gitweb / gitweb.perlon commit Merge branch 'js/maint-cvsexport' (6fe870f)
   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        $params{'project'} = $project unless exists $params{'project'};
 615
 616        if ($params{-replay}) {
 617                while (my ($name, $symbol) = each %mapping) {
 618                        if (!exists $params{$name}) {
 619                                # to allow for multivalued params we use arrayref form
 620                                $params{$name} = [ $cgi->param($symbol) ];
 621                        }
 622                }
 623        }
 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        $git_dir = "$projectroot/$project";
1774
1775        if (!defined $gitweb_project_owner) {
1776                git_get_project_list_from_file();
1777        }
1778
1779        if (exists $gitweb_project_owner->{$project}) {
1780                $owner = $gitweb_project_owner->{$project};
1781        }
1782        if (!defined $owner){
1783                $owner = git_get_project_config('owner');
1784        }
1785        if (!defined $owner) {
1786                $owner = get_file_owner("$git_dir");
1787        }
1788
1789        return $owner;
1790}
1791
1792sub git_get_last_activity {
1793        my ($path) = @_;
1794        my $fd;
1795
1796        $git_dir = "$projectroot/$path";
1797        open($fd, "-|", git_cmd(), 'for-each-ref',
1798             '--format=%(committer)',
1799             '--sort=-committerdate',
1800             '--count=1',
1801             'refs/heads') or return;
1802        my $most_recent = <$fd>;
1803        close $fd or return;
1804        if (defined $most_recent &&
1805            $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1806                my $timestamp = $1;
1807                my $age = time - $timestamp;
1808                return ($age, age_string($age));
1809        }
1810        return (undef, undef);
1811}
1812
1813sub git_get_references {
1814        my $type = shift || "";
1815        my %refs;
1816        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1817        # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1818        open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1819                ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1820                or return;
1821
1822        while (my $line = <$fd>) {
1823                chomp $line;
1824                if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1825                        if (defined $refs{$1}) {
1826                                push @{$refs{$1}}, $2;
1827                        } else {
1828                                $refs{$1} = [ $2 ];
1829                        }
1830                }
1831        }
1832        close $fd or return;
1833        return \%refs;
1834}
1835
1836sub git_get_rev_name_tags {
1837        my $hash = shift || return undef;
1838
1839        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1840                or return;
1841        my $name_rev = <$fd>;
1842        close $fd;
1843
1844        if ($name_rev =~ m|^$hash tags/(.*)$|) {
1845                return $1;
1846        } else {
1847                # catches also '$hash undefined' output
1848                return undef;
1849        }
1850}
1851
1852## ----------------------------------------------------------------------
1853## parse to hash functions
1854
1855sub parse_date {
1856        my $epoch = shift;
1857        my $tz = shift || "-0000";
1858
1859        my %date;
1860        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1861        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1862        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1863        $date{'hour'} = $hour;
1864        $date{'minute'} = $min;
1865        $date{'mday'} = $mday;
1866        $date{'day'} = $days[$wday];
1867        $date{'month'} = $months[$mon];
1868        $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1869                             $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1870        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1871                             $mday, $months[$mon], $hour ,$min;
1872        $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1873                             1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
1874
1875        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1876        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1877        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1878        $date{'hour_local'} = $hour;
1879        $date{'minute_local'} = $min;
1880        $date{'tz_local'} = $tz;
1881        $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1882                                  1900+$year, $mon+1, $mday,
1883                                  $hour, $min, $sec, $tz);
1884        return %date;
1885}
1886
1887sub parse_tag {
1888        my $tag_id = shift;
1889        my %tag;
1890        my @comment;
1891
1892        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1893        $tag{'id'} = $tag_id;
1894        while (my $line = <$fd>) {
1895                chomp $line;
1896                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1897                        $tag{'object'} = $1;
1898                } elsif ($line =~ m/^type (.+)$/) {
1899                        $tag{'type'} = $1;
1900                } elsif ($line =~ m/^tag (.+)$/) {
1901                        $tag{'name'} = $1;
1902                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1903                        $tag{'author'} = $1;
1904                        $tag{'epoch'} = $2;
1905                        $tag{'tz'} = $3;
1906                } elsif ($line =~ m/--BEGIN/) {
1907                        push @comment, $line;
1908                        last;
1909                } elsif ($line eq "") {
1910                        last;
1911                }
1912        }
1913        push @comment, <$fd>;
1914        $tag{'comment'} = \@comment;
1915        close $fd or return;
1916        if (!defined $tag{'name'}) {
1917                return
1918        };
1919        return %tag
1920}
1921
1922sub parse_commit_text {
1923        my ($commit_text, $withparents) = @_;
1924        my @commit_lines = split '\n', $commit_text;
1925        my %co;
1926
1927        pop @commit_lines; # Remove '\0'
1928
1929        if (! @commit_lines) {
1930                return;
1931        }
1932
1933        my $header = shift @commit_lines;
1934        if ($header !~ m/^[0-9a-fA-F]{40}/) {
1935                return;
1936        }
1937        ($co{'id'}, my @parents) = split ' ', $header;
1938        while (my $line = shift @commit_lines) {
1939                last if $line eq "\n";
1940                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1941                        $co{'tree'} = $1;
1942                } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1943                        push @parents, $1;
1944                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1945                        $co{'author'} = $1;
1946                        $co{'author_epoch'} = $2;
1947                        $co{'author_tz'} = $3;
1948                        if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1949                                $co{'author_name'}  = $1;
1950                                $co{'author_email'} = $2;
1951                        } else {
1952                                $co{'author_name'} = $co{'author'};
1953                        }
1954                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1955                        $co{'committer'} = $1;
1956                        $co{'committer_epoch'} = $2;
1957                        $co{'committer_tz'} = $3;
1958                        $co{'committer_name'} = $co{'committer'};
1959                        if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1960                                $co{'committer_name'}  = $1;
1961                                $co{'committer_email'} = $2;
1962                        } else {
1963                                $co{'committer_name'} = $co{'committer'};
1964                        }
1965                }
1966        }
1967        if (!defined $co{'tree'}) {
1968                return;
1969        };
1970        $co{'parents'} = \@parents;
1971        $co{'parent'} = $parents[0];
1972
1973        foreach my $title (@commit_lines) {
1974                $title =~ s/^    //;
1975                if ($title ne "") {
1976                        $co{'title'} = chop_str($title, 80, 5);
1977                        # remove leading stuff of merges to make the interesting part visible
1978                        if (length($title) > 50) {
1979                                $title =~ s/^Automatic //;
1980                                $title =~ s/^merge (of|with) /Merge ... /i;
1981                                if (length($title) > 50) {
1982                                        $title =~ s/(http|rsync):\/\///;
1983                                }
1984                                if (length($title) > 50) {
1985                                        $title =~ s/(master|www|rsync)\.//;
1986                                }
1987                                if (length($title) > 50) {
1988                                        $title =~ s/kernel.org:?//;
1989                                }
1990                                if (length($title) > 50) {
1991                                        $title =~ s/\/pub\/scm//;
1992                                }
1993                        }
1994                        $co{'title_short'} = chop_str($title, 50, 5);
1995                        last;
1996                }
1997        }
1998        if ($co{'title'} eq "") {
1999                $co{'title'} = $co{'title_short'} = '(no commit message)';
2000        }
2001        # remove added spaces
2002        foreach my $line (@commit_lines) {
2003                $line =~ s/^    //;
2004        }
2005        $co{'comment'} = \@commit_lines;
2006
2007        my $age = time - $co{'committer_epoch'};
2008        $co{'age'} = $age;
2009        $co{'age_string'} = age_string($age);
2010        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2011        if ($age > 60*60*24*7*2) {
2012                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2013                $co{'age_string_age'} = $co{'age_string'};
2014        } else {
2015                $co{'age_string_date'} = $co{'age_string'};
2016                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2017        }
2018        return %co;
2019}
2020
2021sub parse_commit {
2022        my ($commit_id) = @_;
2023        my %co;
2024
2025        local $/ = "\0";
2026
2027        open my $fd, "-|", git_cmd(), "rev-list",
2028                "--parents",
2029                "--header",
2030                "--max-count=1",
2031                $commit_id,
2032                "--",
2033                or die_error(undef, "Open git-rev-list failed");
2034        %co = parse_commit_text(<$fd>, 1);
2035        close $fd;
2036
2037        return %co;
2038}
2039
2040sub parse_commits {
2041        my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
2042        my @cos;
2043
2044        $maxcount ||= 1;
2045        $skip ||= 0;
2046
2047        local $/ = "\0";
2048
2049        open my $fd, "-|", git_cmd(), "rev-list",
2050                "--header",
2051                ($arg ? ($arg) : ()),
2052                ("--max-count=" . $maxcount),
2053                ("--skip=" . $skip),
2054                @extra_options,
2055                $commit_id,
2056                "--",
2057                ($filename ? ($filename) : ())
2058                or die_error(undef, "Open git-rev-list failed");
2059        while (my $line = <$fd>) {
2060                my %co = parse_commit_text($line);
2061                push @cos, \%co;
2062        }
2063        close $fd;
2064
2065        return wantarray ? @cos : \@cos;
2066}
2067
2068# parse ref from ref_file, given by ref_id, with given type
2069sub parse_ref {
2070        my $ref_file = shift;
2071        my $ref_id = shift;
2072        my $type = shift || git_get_type($ref_id);
2073        my %ref_item;
2074
2075        $ref_item{'type'} = $type;
2076        $ref_item{'id'} = $ref_id;
2077        $ref_item{'epoch'} = 0;
2078        $ref_item{'age'} = "unknown";
2079        if ($type eq "tag") {
2080                my %tag = parse_tag($ref_id);
2081                $ref_item{'comment'} = $tag{'comment'};
2082                if ($tag{'type'} eq "commit") {
2083                        my %co = parse_commit($tag{'object'});
2084                        $ref_item{'epoch'} = $co{'committer_epoch'};
2085                        $ref_item{'age'} = $co{'age_string'};
2086                } elsif (defined($tag{'epoch'})) {
2087                        my $age = time - $tag{'epoch'};
2088                        $ref_item{'epoch'} = $tag{'epoch'};
2089                        $ref_item{'age'} = age_string($age);
2090                }
2091                $ref_item{'reftype'} = $tag{'type'};
2092                $ref_item{'name'} = $tag{'name'};
2093                $ref_item{'refid'} = $tag{'object'};
2094        } elsif ($type eq "commit"){
2095                my %co = parse_commit($ref_id);
2096                $ref_item{'reftype'} = "commit";
2097                $ref_item{'name'} = $ref_file;
2098                $ref_item{'title'} = $co{'title'};
2099                $ref_item{'refid'} = $ref_id;
2100                $ref_item{'epoch'} = $co{'committer_epoch'};
2101                $ref_item{'age'} = $co{'age_string'};
2102        } else {
2103                $ref_item{'reftype'} = $type;
2104                $ref_item{'name'} = $ref_file;
2105                $ref_item{'refid'} = $ref_id;
2106        }
2107
2108        return %ref_item;
2109}
2110
2111# parse line of git-diff-tree "raw" output
2112sub parse_difftree_raw_line {
2113        my $line = shift;
2114        my %res;
2115
2116        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
2117        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
2118        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2119                $res{'from_mode'} = $1;
2120                $res{'to_mode'} = $2;
2121                $res{'from_id'} = $3;
2122                $res{'to_id'} = $4;
2123                $res{'status'} = $res{'status_str'} = $5;
2124                $res{'similarity'} = $6;
2125                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2126                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2127                } else {
2128                        $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2129                }
2130        }
2131        # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2132        # combined diff (for merge commit)
2133        elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2134                $res{'nparents'}  = length($1);
2135                $res{'from_mode'} = [ split(' ', $2) ];
2136                $res{'to_mode'} = pop @{$res{'from_mode'}};
2137                $res{'from_id'} = [ split(' ', $3) ];
2138                $res{'to_id'} = pop @{$res{'from_id'}};
2139                $res{'status_str'} = $4;
2140                $res{'status'} = [ split('', $4) ];
2141                $res{'to_file'} = unquote($5);
2142        }
2143        # 'c512b523472485aef4fff9e57b229d9d243c967f'
2144        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2145                $res{'commit'} = $1;
2146        }
2147
2148        return wantarray ? %res : \%res;
2149}
2150
2151# wrapper: return parsed line of git-diff-tree "raw" output
2152# (the argument might be raw line, or parsed info)
2153sub parsed_difftree_line {
2154        my $line_or_ref = shift;
2155
2156        if (ref($line_or_ref) eq "HASH") {
2157                # pre-parsed (or generated by hand)
2158                return $line_or_ref;
2159        } else {
2160                return parse_difftree_raw_line($line_or_ref);
2161        }
2162}
2163
2164# parse line of git-ls-tree output
2165sub parse_ls_tree_line ($;%) {
2166        my $line = shift;
2167        my %opts = @_;
2168        my %res;
2169
2170        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
2171        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2172
2173        $res{'mode'} = $1;
2174        $res{'type'} = $2;
2175        $res{'hash'} = $3;
2176        if ($opts{'-z'}) {
2177                $res{'name'} = $4;
2178        } else {
2179                $res{'name'} = unquote($4);
2180        }
2181
2182        return wantarray ? %res : \%res;
2183}
2184
2185# generates _two_ hashes, references to which are passed as 2 and 3 argument
2186sub parse_from_to_diffinfo {
2187        my ($diffinfo, $from, $to, @parents) = @_;
2188
2189        if ($diffinfo->{'nparents'}) {
2190                # combined diff
2191                $from->{'file'} = [];
2192                $from->{'href'} = [];
2193                fill_from_file_info($diffinfo, @parents)
2194                        unless exists $diffinfo->{'from_file'};
2195                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2196                        $from->{'file'}[$i] =
2197                                defined $diffinfo->{'from_file'}[$i] ?
2198                                        $diffinfo->{'from_file'}[$i] :
2199                                        $diffinfo->{'to_file'};
2200                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2201                                $from->{'href'}[$i] = href(action=>"blob",
2202                                                           hash_base=>$parents[$i],
2203                                                           hash=>$diffinfo->{'from_id'}[$i],
2204                                                           file_name=>$from->{'file'}[$i]);
2205                        } else {
2206                                $from->{'href'}[$i] = undef;
2207                        }
2208                }
2209        } else {
2210                # ordinary (not combined) diff
2211                $from->{'file'} = $diffinfo->{'from_file'};
2212                if ($diffinfo->{'status'} ne "A") { # not new (added) file
2213                        $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2214                                               hash=>$diffinfo->{'from_id'},
2215                                               file_name=>$from->{'file'});
2216                } else {
2217                        delete $from->{'href'};
2218                }
2219        }
2220
2221        $to->{'file'} = $diffinfo->{'to_file'};
2222        if (!is_deleted($diffinfo)) { # file exists in result
2223                $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2224                                     hash=>$diffinfo->{'to_id'},
2225                                     file_name=>$to->{'file'});
2226        } else {
2227                delete $to->{'href'};
2228        }
2229}
2230
2231## ......................................................................
2232## parse to array of hashes functions
2233
2234sub git_get_heads_list {
2235        my $limit = shift;
2236        my @headslist;
2237
2238        open my $fd, '-|', git_cmd(), 'for-each-ref',
2239                ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2240                '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2241                'refs/heads'
2242                or return;
2243        while (my $line = <$fd>) {
2244                my %ref_item;
2245
2246                chomp $line;
2247                my ($refinfo, $committerinfo) = split(/\0/, $line);
2248                my ($hash, $name, $title) = split(' ', $refinfo, 3);
2249                my ($committer, $epoch, $tz) =
2250                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2251                $ref_item{'fullname'}  = $name;
2252                $name =~ s!^refs/heads/!!;
2253
2254                $ref_item{'name'}  = $name;
2255                $ref_item{'id'}    = $hash;
2256                $ref_item{'title'} = $title || '(no commit message)';
2257                $ref_item{'epoch'} = $epoch;
2258                if ($epoch) {
2259                        $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2260                } else {
2261                        $ref_item{'age'} = "unknown";
2262                }
2263
2264                push @headslist, \%ref_item;
2265        }
2266        close $fd;
2267
2268        return wantarray ? @headslist : \@headslist;
2269}
2270
2271sub git_get_tags_list {
2272        my $limit = shift;
2273        my @tagslist;
2274
2275        open my $fd, '-|', git_cmd(), 'for-each-ref',
2276                ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2277                '--format=%(objectname) %(objecttype) %(refname) '.
2278                '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2279                'refs/tags'
2280                or return;
2281        while (my $line = <$fd>) {
2282                my %ref_item;
2283
2284                chomp $line;
2285                my ($refinfo, $creatorinfo) = split(/\0/, $line);
2286                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2287                my ($creator, $epoch, $tz) =
2288                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2289                $ref_item{'fullname'} = $name;
2290                $name =~ s!^refs/tags/!!;
2291
2292                $ref_item{'type'} = $type;
2293                $ref_item{'id'} = $id;
2294                $ref_item{'name'} = $name;
2295                if ($type eq "tag") {
2296                        $ref_item{'subject'} = $title;
2297                        $ref_item{'reftype'} = $reftype;
2298                        $ref_item{'refid'}   = $refid;
2299                } else {
2300                        $ref_item{'reftype'} = $type;
2301                        $ref_item{'refid'}   = $id;
2302                }
2303
2304                if ($type eq "tag" || $type eq "commit") {
2305                        $ref_item{'epoch'} = $epoch;
2306                        if ($epoch) {
2307                                $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2308                        } else {
2309                                $ref_item{'age'} = "unknown";
2310                        }
2311                }
2312
2313                push @tagslist, \%ref_item;
2314        }
2315        close $fd;
2316
2317        return wantarray ? @tagslist : \@tagslist;
2318}
2319
2320## ----------------------------------------------------------------------
2321## filesystem-related functions
2322
2323sub get_file_owner {
2324        my $path = shift;
2325
2326        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2327        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2328        if (!defined $gcos) {
2329                return undef;
2330        }
2331        my $owner = $gcos;
2332        $owner =~ s/[,;].*$//;
2333        return to_utf8($owner);
2334}
2335
2336## ......................................................................
2337## mimetype related functions
2338
2339sub mimetype_guess_file {
2340        my $filename = shift;
2341        my $mimemap = shift;
2342        -r $mimemap or return undef;
2343
2344        my %mimemap;
2345        open(MIME, $mimemap) or return undef;
2346        while (<MIME>) {
2347                next if m/^#/; # skip comments
2348                my ($mime, $exts) = split(/\t+/);
2349                if (defined $exts) {
2350                        my @exts = split(/\s+/, $exts);
2351                        foreach my $ext (@exts) {
2352                                $mimemap{$ext} = $mime;
2353                        }
2354                }
2355        }
2356        close(MIME);
2357
2358        $filename =~ /\.([^.]*)$/;
2359        return $mimemap{$1};
2360}
2361
2362sub mimetype_guess {
2363        my $filename = shift;
2364        my $mime;
2365        $filename =~ /\./ or return undef;
2366
2367        if ($mimetypes_file) {
2368                my $file = $mimetypes_file;
2369                if ($file !~ m!^/!) { # if it is relative path
2370                        # it is relative to project
2371                        $file = "$projectroot/$project/$file";
2372                }
2373                $mime = mimetype_guess_file($filename, $file);
2374        }
2375        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2376        return $mime;
2377}
2378
2379sub blob_mimetype {
2380        my $fd = shift;
2381        my $filename = shift;
2382
2383        if ($filename) {
2384                my $mime = mimetype_guess($filename);
2385                $mime and return $mime;
2386        }
2387
2388        # just in case
2389        return $default_blob_plain_mimetype unless $fd;
2390
2391        if (-T $fd) {
2392                return 'text/plain' .
2393                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2394        } elsif (! $filename) {
2395                return 'application/octet-stream';
2396        } elsif ($filename =~ m/\.png$/i) {
2397                return 'image/png';
2398        } elsif ($filename =~ m/\.gif$/i) {
2399                return 'image/gif';
2400        } elsif ($filename =~ m/\.jpe?g$/i) {
2401                return 'image/jpeg';
2402        } else {
2403                return 'application/octet-stream';
2404        }
2405}
2406
2407## ======================================================================
2408## functions printing HTML: header, footer, error page
2409
2410sub git_header_html {
2411        my $status = shift || "200 OK";
2412        my $expires = shift;
2413
2414        my $title = "$site_name";
2415        if (defined $project) {
2416                $title .= " - " . to_utf8($project);
2417                if (defined $action) {
2418                        $title .= "/$action";
2419                        if (defined $file_name) {
2420                                $title .= " - " . esc_path($file_name);
2421                                if ($action eq "tree" && $file_name !~ m|/$|) {
2422                                        $title .= "/";
2423                                }
2424                        }
2425                }
2426        }
2427        my $content_type;
2428        # require explicit support from the UA if we are to send the page as
2429        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2430        # we have to do this because MSIE sometimes globs '*/*', pretending to
2431        # support xhtml+xml but choking when it gets what it asked for.
2432        if (defined $cgi->http('HTTP_ACCEPT') &&
2433            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2434            $cgi->Accept('application/xhtml+xml') != 0) {
2435                $content_type = 'application/xhtml+xml';
2436        } else {
2437                $content_type = 'text/html';
2438        }
2439        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2440                           -status=> $status, -expires => $expires);
2441        my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2442        print <<EOF;
2443<?xml version="1.0" encoding="utf-8"?>
2444<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2445<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2446<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2447<!-- git core binaries version $git_version -->
2448<head>
2449<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2450<meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2451<meta name="robots" content="index, nofollow"/>
2452<title>$title</title>
2453EOF
2454# print out each stylesheet that exist
2455        if (defined $stylesheet) {
2456#provides backwards capability for those people who define style sheet in a config file
2457                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2458        } else {
2459                foreach my $stylesheet (@stylesheets) {
2460                        next unless $stylesheet;
2461                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2462                }
2463        }
2464        if (defined $project) {
2465                printf('<link rel="alternate" title="%s log RSS feed" '.
2466                       'href="%s" type="application/rss+xml" />'."\n",
2467                       esc_param($project), href(action=>"rss"));
2468                printf('<link rel="alternate" title="%s log RSS feed (no merges)" '.
2469                       'href="%s" type="application/rss+xml" />'."\n",
2470                       esc_param($project), href(action=>"rss",
2471                                                 extra_options=>"--no-merges"));
2472                printf('<link rel="alternate" title="%s log Atom feed" '.
2473                       'href="%s" type="application/atom+xml" />'."\n",
2474                       esc_param($project), href(action=>"atom"));
2475                printf('<link rel="alternate" title="%s log Atom feed (no merges)" '.
2476                       'href="%s" type="application/atom+xml" />'."\n",
2477                       esc_param($project), href(action=>"atom",
2478                                                 extra_options=>"--no-merges"));
2479        } else {
2480                printf('<link rel="alternate" title="%s projects list" '.
2481                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2482                       $site_name, href(project=>undef, action=>"project_index"));
2483                printf('<link rel="alternate" title="%s projects feeds" '.
2484                       'href="%s" type="text/x-opml"/>'."\n",
2485                       $site_name, href(project=>undef, action=>"opml"));
2486        }
2487        if (defined $favicon) {
2488                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2489        }
2490
2491        print "</head>\n" .
2492              "<body>\n";
2493
2494        if (-f $site_header) {
2495                open (my $fd, $site_header);
2496                print <$fd>;
2497                close $fd;
2498        }
2499
2500        print "<div class=\"page_header\">\n" .
2501              $cgi->a({-href => esc_url($logo_url),
2502                       -title => $logo_label},
2503                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2504        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2505        if (defined $project) {
2506                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2507                if (defined $action) {
2508                        print " / $action";
2509                }
2510                print "\n";
2511        }
2512        print "</div>\n";
2513
2514        my ($have_search) = gitweb_check_feature('search');
2515        if ((defined $project) && ($have_search)) {
2516                if (!defined $searchtext) {
2517                        $searchtext = "";
2518                }
2519                my $search_hash;
2520                if (defined $hash_base) {
2521                        $search_hash = $hash_base;
2522                } elsif (defined $hash) {
2523                        $search_hash = $hash;
2524                } else {
2525                        $search_hash = "HEAD";
2526                }
2527                my $action = $my_uri;
2528                my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2529                if ($use_pathinfo) {
2530                        $action .= "/$project";
2531                } else {
2532                        $cgi->param("p", $project);
2533                }
2534                $cgi->param("a", "search");
2535                $cgi->param("h", $search_hash);
2536                print $cgi->startform(-method => "get", -action => $action) .
2537                      "<div class=\"search\">\n" .
2538                      (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2539                      $cgi->hidden(-name => "a") . "\n" .
2540                      $cgi->hidden(-name => "h") . "\n" .
2541                      $cgi->popup_menu(-name => 'st', -default => 'commit',
2542                                       -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2543                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2544                      " search:\n",
2545                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2546                      "</div>" .
2547                      $cgi->end_form() . "\n";
2548        }
2549}
2550
2551sub git_footer_html {
2552        print "<div class=\"page_footer\">\n";
2553        if (defined $project) {
2554                my $descr = git_get_project_description($project);
2555                if (defined $descr) {
2556                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2557                }
2558                print $cgi->a({-href => href(action=>"rss"),
2559                              -class => "rss_logo"}, "RSS") . " ";
2560                print $cgi->a({-href => href(action=>"atom"),
2561                              -class => "rss_logo"}, "Atom") . "\n";
2562        } else {
2563                print $cgi->a({-href => href(project=>undef, action=>"opml"),
2564                              -class => "rss_logo"}, "OPML") . " ";
2565                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2566                              -class => "rss_logo"}, "TXT") . "\n";
2567        }
2568        print "</div>\n" ;
2569
2570        if (-f $site_footer) {
2571                open (my $fd, $site_footer);
2572                print <$fd>;
2573                close $fd;
2574        }
2575
2576        print "</body>\n" .
2577              "</html>";
2578}
2579
2580sub die_error {
2581        my $status = shift || "403 Forbidden";
2582        my $error = shift || "Malformed query, file missing or permission denied";
2583
2584        git_header_html($status);
2585        print <<EOF;
2586<div class="page_body">
2587<br /><br />
2588$status - $error
2589<br />
2590</div>
2591EOF
2592        git_footer_html();
2593        exit;
2594}
2595
2596## ----------------------------------------------------------------------
2597## functions printing or outputting HTML: navigation
2598
2599sub git_print_page_nav {
2600        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2601        $extra = '' if !defined $extra; # pager or formats
2602
2603        my @navs = qw(summary shortlog log commit commitdiff tree);
2604        if ($suppress) {
2605                @navs = grep { $_ ne $suppress } @navs;
2606        }
2607
2608        my %arg = map { $_ => {action=>$_} } @navs;
2609        if (defined $head) {
2610                for (qw(commit commitdiff)) {
2611                        $arg{$_}{'hash'} = $head;
2612                }
2613                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2614                        for (qw(shortlog log)) {
2615                                $arg{$_}{'hash'} = $head;
2616                        }
2617                }
2618        }
2619        $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2620        $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2621
2622        print "<div class=\"page_nav\">\n" .
2623                (join " | ",
2624                 map { $_ eq $current ?
2625                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2626                 } @navs);
2627        print "<br/>\n$extra<br/>\n" .
2628              "</div>\n";
2629}
2630
2631sub format_paging_nav {
2632        my ($action, $hash, $head, $page, $nrevs) = @_;
2633        my $paging_nav;
2634
2635
2636        if ($hash ne $head || $page) {
2637                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2638        } else {
2639                $paging_nav .= "HEAD";
2640        }
2641
2642        if ($page > 0) {
2643                $paging_nav .= " &sdot; " .
2644                        $cgi->a({-href => href(-replay=>1, page=>$page-1),
2645                                 -accesskey => "p", -title => "Alt-p"}, "prev");
2646        } else {
2647                $paging_nav .= " &sdot; prev";
2648        }
2649
2650        if ($nrevs >= (100 * ($page+1)-1)) {
2651                $paging_nav .= " &sdot; " .
2652                        $cgi->a({-href => href(-replay=>1, page=>$page+1),
2653                                 -accesskey => "n", -title => "Alt-n"}, "next");
2654        } else {
2655                $paging_nav .= " &sdot; next";
2656        }
2657
2658        return $paging_nav;
2659}
2660
2661## ......................................................................
2662## functions printing or outputting HTML: div
2663
2664sub git_print_header_div {
2665        my ($action, $title, $hash, $hash_base) = @_;
2666        my %args = ();
2667
2668        $args{'action'} = $action;
2669        $args{'hash'} = $hash if $hash;
2670        $args{'hash_base'} = $hash_base if $hash_base;
2671
2672        print "<div class=\"header\">\n" .
2673              $cgi->a({-href => href(%args), -class => "title"},
2674              $title ? $title : $action) .
2675              "\n</div>\n";
2676}
2677
2678#sub git_print_authorship (\%) {
2679sub git_print_authorship {
2680        my $co = shift;
2681
2682        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2683        print "<div class=\"author_date\">" .
2684              esc_html($co->{'author_name'}) .
2685              " [$ad{'rfc2822'}";
2686        if ($ad{'hour_local'} < 6) {
2687                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2688                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2689        } else {
2690                printf(" (%02d:%02d %s)",
2691                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2692        }
2693        print "]</div>\n";
2694}
2695
2696sub git_print_page_path {
2697        my $name = shift;
2698        my $type = shift;
2699        my $hb = shift;
2700
2701
2702        print "<div class=\"page_path\">";
2703        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2704                      -title => 'tree root'}, to_utf8("[$project]"));
2705        print " / ";
2706        if (defined $name) {
2707                my @dirname = split '/', $name;
2708                my $basename = pop @dirname;
2709                my $fullname = '';
2710
2711                foreach my $dir (@dirname) {
2712                        $fullname .= ($fullname ? '/' : '') . $dir;
2713                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2714                                                     hash_base=>$hb),
2715                                      -title => $fullname}, esc_path($dir));
2716                        print " / ";
2717                }
2718                if (defined $type && $type eq 'blob') {
2719                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2720                                                     hash_base=>$hb),
2721                                      -title => $name}, esc_path($basename));
2722                } elsif (defined $type && $type eq 'tree') {
2723                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2724                                                     hash_base=>$hb),
2725                                      -title => $name}, esc_path($basename));
2726                        print " / ";
2727                } else {
2728                        print esc_path($basename);
2729                }
2730        }
2731        print "<br/></div>\n";
2732}
2733
2734# sub git_print_log (\@;%) {
2735sub git_print_log ($;%) {
2736        my $log = shift;
2737        my %opts = @_;
2738
2739        if ($opts{'-remove_title'}) {
2740                # remove title, i.e. first line of log
2741                shift @$log;
2742        }
2743        # remove leading empty lines
2744        while (defined $log->[0] && $log->[0] eq "") {
2745                shift @$log;
2746        }
2747
2748        # print log
2749        my $signoff = 0;
2750        my $empty = 0;
2751        foreach my $line (@$log) {
2752                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2753                        $signoff = 1;
2754                        $empty = 0;
2755                        if (! $opts{'-remove_signoff'}) {
2756                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2757                                next;
2758                        } else {
2759                                # remove signoff lines
2760                                next;
2761                        }
2762                } else {
2763                        $signoff = 0;
2764                }
2765
2766                # print only one empty line
2767                # do not print empty line after signoff
2768                if ($line eq "") {
2769                        next if ($empty || $signoff);
2770                        $empty = 1;
2771                } else {
2772                        $empty = 0;
2773                }
2774
2775                print format_log_line_html($line) . "<br/>\n";
2776        }
2777
2778        if ($opts{'-final_empty_line'}) {
2779                # end with single empty line
2780                print "<br/>\n" unless $empty;
2781        }
2782}
2783
2784# return link target (what link points to)
2785sub git_get_link_target {
2786        my $hash = shift;
2787        my $link_target;
2788
2789        # read link
2790        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2791                or return;
2792        {
2793                local $/;
2794                $link_target = <$fd>;
2795        }
2796        close $fd
2797                or return;
2798
2799        return $link_target;
2800}
2801
2802# given link target, and the directory (basedir) the link is in,
2803# return target of link relative to top directory (top tree);
2804# return undef if it is not possible (including absolute links).
2805sub normalize_link_target {
2806        my ($link_target, $basedir, $hash_base) = @_;
2807
2808        # we can normalize symlink target only if $hash_base is provided
2809        return unless $hash_base;
2810
2811        # absolute symlinks (beginning with '/') cannot be normalized
2812        return if (substr($link_target, 0, 1) eq '/');
2813
2814        # normalize link target to path from top (root) tree (dir)
2815        my $path;
2816        if ($basedir) {
2817                $path = $basedir . '/' . $link_target;
2818        } else {
2819                # we are in top (root) tree (dir)
2820                $path = $link_target;
2821        }
2822
2823        # remove //, /./, and /../
2824        my @path_parts;
2825        foreach my $part (split('/', $path)) {
2826                # discard '.' and ''
2827                next if (!$part || $part eq '.');
2828                # handle '..'
2829                if ($part eq '..') {
2830                        if (@path_parts) {
2831                                pop @path_parts;
2832                        } else {
2833                                # link leads outside repository (outside top dir)
2834                                return;
2835                        }
2836                } else {
2837                        push @path_parts, $part;
2838                }
2839        }
2840        $path = join('/', @path_parts);
2841
2842        return $path;
2843}
2844
2845# print tree entry (row of git_tree), but without encompassing <tr> element
2846sub git_print_tree_entry {
2847        my ($t, $basedir, $hash_base, $have_blame) = @_;
2848
2849        my %base_key = ();
2850        $base_key{'hash_base'} = $hash_base if defined $hash_base;
2851
2852        # The format of a table row is: mode list link.  Where mode is
2853        # the mode of the entry, list is the name of the entry, an href,
2854        # and link is the action links of the entry.
2855
2856        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2857        if ($t->{'type'} eq "blob") {
2858                print "<td class=\"list\">" .
2859                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2860                                               file_name=>"$basedir$t->{'name'}", %base_key),
2861                                -class => "list"}, esc_path($t->{'name'}));
2862                if (S_ISLNK(oct $t->{'mode'})) {
2863                        my $link_target = git_get_link_target($t->{'hash'});
2864                        if ($link_target) {
2865                                my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2866                                if (defined $norm_target) {
2867                                        print " -> " .
2868                                              $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2869                                                                     file_name=>$norm_target),
2870                                                       -title => $norm_target}, esc_path($link_target));
2871                                } else {
2872                                        print " -> " . esc_path($link_target);
2873                                }
2874                        }
2875                }
2876                print "</td>\n";
2877                print "<td class=\"link\">";
2878                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2879                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2880                              "blob");
2881                if ($have_blame) {
2882                        print " | " .
2883                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2884                                                     file_name=>"$basedir$t->{'name'}", %base_key)},
2885                                      "blame");
2886                }
2887                if (defined $hash_base) {
2888                        print " | " .
2889                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2890                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2891                                      "history");
2892                }
2893                print " | " .
2894                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2895                                               file_name=>"$basedir$t->{'name'}")},
2896                                "raw");
2897                print "</td>\n";
2898
2899        } elsif ($t->{'type'} eq "tree") {
2900                print "<td class=\"list\">";
2901                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2902                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2903                              esc_path($t->{'name'}));
2904                print "</td>\n";
2905                print "<td class=\"link\">";
2906                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2907                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2908                              "tree");
2909                if (defined $hash_base) {
2910                        print " | " .
2911                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2912                                                     file_name=>"$basedir$t->{'name'}")},
2913                                      "history");
2914                }
2915                print "</td>\n";
2916        } else {
2917                # unknown object: we can only present history for it
2918                # (this includes 'commit' object, i.e. submodule support)
2919                print "<td class=\"list\">" .
2920                      esc_path($t->{'name'}) .
2921                      "</td>\n";
2922                print "<td class=\"link\">";
2923                if (defined $hash_base) {
2924                        print $cgi->a({-href => href(action=>"history",
2925                                                     hash_base=>$hash_base,
2926                                                     file_name=>"$basedir$t->{'name'}")},
2927                                      "history");
2928                }
2929                print "</td>\n";
2930        }
2931}
2932
2933## ......................................................................
2934## functions printing large fragments of HTML
2935
2936# get pre-image filenames for merge (combined) diff
2937sub fill_from_file_info {
2938        my ($diff, @parents) = @_;
2939
2940        $diff->{'from_file'} = [ ];
2941        $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2942        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2943                if ($diff->{'status'}[$i] eq 'R' ||
2944                    $diff->{'status'}[$i] eq 'C') {
2945                        $diff->{'from_file'}[$i] =
2946                                git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2947                }
2948        }
2949
2950        return $diff;
2951}
2952
2953# is current raw difftree line of file deletion
2954sub is_deleted {
2955        my $diffinfo = shift;
2956
2957        return $diffinfo->{'status_str'} =~ /D/;
2958}
2959
2960# does patch correspond to [previous] difftree raw line
2961# $diffinfo  - hashref of parsed raw diff format
2962# $patchinfo - hashref of parsed patch diff format
2963#              (the same keys as in $diffinfo)
2964sub is_patch_split {
2965        my ($diffinfo, $patchinfo) = @_;
2966
2967        return defined $diffinfo && defined $patchinfo
2968                && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
2969}
2970
2971
2972sub git_difftree_body {
2973        my ($difftree, $hash, @parents) = @_;
2974        my ($parent) = $parents[0];
2975        my ($have_blame) = gitweb_check_feature('blame');
2976        print "<div class=\"list_head\">\n";
2977        if ($#{$difftree} > 10) {
2978                print(($#{$difftree} + 1) . " files changed:\n");
2979        }
2980        print "</div>\n";
2981
2982        print "<table class=\"" .
2983              (@parents > 1 ? "combined " : "") .
2984              "diff_tree\">\n";
2985
2986        # header only for combined diff in 'commitdiff' view
2987        my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
2988        if ($has_header) {
2989                # table header
2990                print "<thead><tr>\n" .
2991                       "<th></th><th></th>\n"; # filename, patchN link
2992                for (my $i = 0; $i < @parents; $i++) {
2993                        my $par = $parents[$i];
2994                        print "<th>" .
2995                              $cgi->a({-href => href(action=>"commitdiff",
2996                                                     hash=>$hash, hash_parent=>$par),
2997                                       -title => 'commitdiff to parent number ' .
2998                                                  ($i+1) . ': ' . substr($par,0,7)},
2999                                      $i+1) .
3000                              "&nbsp;</th>\n";
3001                }
3002                print "</tr></thead>\n<tbody>\n";
3003        }
3004
3005        my $alternate = 1;
3006        my $patchno = 0;
3007        foreach my $line (@{$difftree}) {
3008                my $diff = parsed_difftree_line($line);
3009
3010                if ($alternate) {
3011                        print "<tr class=\"dark\">\n";
3012                } else {
3013                        print "<tr class=\"light\">\n";
3014                }
3015                $alternate ^= 1;
3016
3017                if (exists $diff->{'nparents'}) { # combined diff
3018
3019                        fill_from_file_info($diff, @parents)
3020                                unless exists $diff->{'from_file'};
3021
3022                        if (!is_deleted($diff)) {
3023                                # file exists in the result (child) commit
3024                                print "<td>" .
3025                                      $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3026                                                             file_name=>$diff->{'to_file'},
3027                                                             hash_base=>$hash),
3028                                              -class => "list"}, esc_path($diff->{'to_file'})) .
3029                                      "</td>\n";
3030                        } else {
3031                                print "<td>" .
3032                                      esc_path($diff->{'to_file'}) .
3033                                      "</td>\n";
3034                        }
3035
3036                        if ($action eq 'commitdiff') {
3037                                # link to patch
3038                                $patchno++;
3039                                print "<td class=\"link\">" .
3040                                      $cgi->a({-href => "#patch$patchno"}, "patch") .
3041                                      " | " .
3042                                      "</td>\n";
3043                        }
3044
3045                        my $has_history = 0;
3046                        my $not_deleted = 0;
3047                        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3048                                my $hash_parent = $parents[$i];
3049                                my $from_hash = $diff->{'from_id'}[$i];
3050                                my $from_path = $diff->{'from_file'}[$i];
3051                                my $status = $diff->{'status'}[$i];
3052
3053                                $has_history ||= ($status ne 'A');
3054                                $not_deleted ||= ($status ne 'D');
3055
3056                                if ($status eq 'A') {
3057                                        print "<td  class=\"link\" align=\"right\"> | </td>\n";
3058                                } elsif ($status eq 'D') {
3059                                        print "<td class=\"link\">" .
3060                                              $cgi->a({-href => href(action=>"blob",
3061                                                                     hash_base=>$hash,
3062                                                                     hash=>$from_hash,
3063                                                                     file_name=>$from_path)},
3064                                                      "blob" . ($i+1)) .
3065                                              " | </td>\n";
3066                                } else {
3067                                        if ($diff->{'to_id'} eq $from_hash) {
3068                                                print "<td class=\"link nochange\">";
3069                                        } else {
3070                                                print "<td class=\"link\">";
3071                                        }
3072                                        print $cgi->a({-href => href(action=>"blobdiff",
3073                                                                     hash=>$diff->{'to_id'},
3074                                                                     hash_parent=>$from_hash,
3075                                                                     hash_base=>$hash,
3076                                                                     hash_parent_base=>$hash_parent,
3077                                                                     file_name=>$diff->{'to_file'},
3078                                                                     file_parent=>$from_path)},
3079                                                      "diff" . ($i+1)) .
3080                                              " | </td>\n";
3081                                }
3082                        }
3083
3084                        print "<td class=\"link\">";
3085                        if ($not_deleted) {
3086                                print $cgi->a({-href => href(action=>"blob",
3087                                                             hash=>$diff->{'to_id'},
3088                                                             file_name=>$diff->{'to_file'},
3089                                                             hash_base=>$hash)},
3090                                              "blob");
3091                                print " | " if ($has_history);
3092                        }
3093                        if ($has_history) {
3094                                print $cgi->a({-href => href(action=>"history",
3095                                                             file_name=>$diff->{'to_file'},
3096                                                             hash_base=>$hash)},
3097                                              "history");
3098                        }
3099                        print "</td>\n";
3100
3101                        print "</tr>\n";
3102                        next; # instead of 'else' clause, to avoid extra indent
3103                }
3104                # else ordinary diff
3105
3106                my ($to_mode_oct, $to_mode_str, $to_file_type);
3107                my ($from_mode_oct, $from_mode_str, $from_file_type);
3108                if ($diff->{'to_mode'} ne ('0' x 6)) {
3109                        $to_mode_oct = oct $diff->{'to_mode'};
3110                        if (S_ISREG($to_mode_oct)) { # only for regular file
3111                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3112                        }
3113                        $to_file_type = file_type($diff->{'to_mode'});
3114                }
3115                if ($diff->{'from_mode'} ne ('0' x 6)) {
3116                        $from_mode_oct = oct $diff->{'from_mode'};
3117                        if (S_ISREG($to_mode_oct)) { # only for regular file
3118                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3119                        }
3120                        $from_file_type = file_type($diff->{'from_mode'});
3121                }
3122
3123                if ($diff->{'status'} eq "A") { # created
3124                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3125                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
3126                        $mode_chng   .= "]</span>";
3127                        print "<td>";
3128                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3129                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
3130                                      -class => "list"}, esc_path($diff->{'file'}));
3131                        print "</td>\n";
3132                        print "<td>$mode_chng</td>\n";
3133                        print "<td class=\"link\">";
3134                        if ($action eq 'commitdiff') {
3135                                # link to patch
3136                                $patchno++;
3137                                print $cgi->a({-href => "#patch$patchno"}, "patch");
3138                                print " | ";
3139                        }
3140                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3141                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
3142                                      "blob");
3143                        print "</td>\n";
3144
3145                } elsif ($diff->{'status'} eq "D") { # deleted
3146                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3147                        print "<td>";
3148                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3149                                                     hash_base=>$parent, file_name=>$diff->{'file'}),
3150                                       -class => "list"}, esc_path($diff->{'file'}));
3151                        print "</td>\n";
3152                        print "<td>$mode_chng</td>\n";
3153                        print "<td class=\"link\">";
3154                        if ($action eq 'commitdiff') {
3155                                # link to patch
3156                                $patchno++;
3157                                print $cgi->a({-href => "#patch$patchno"}, "patch");
3158                                print " | ";
3159                        }
3160                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3161                                                     hash_base=>$parent, file_name=>$diff->{'file'})},
3162                                      "blob") . " | ";
3163                        if ($have_blame) {
3164                                print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3165                                                             file_name=>$diff->{'file'})},
3166                                              "blame") . " | ";
3167                        }
3168                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3169                                                     file_name=>$diff->{'file'})},
3170                                      "history");
3171                        print "</td>\n";
3172
3173                } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3174                        my $mode_chnge = "";
3175                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3176                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3177                                if ($from_file_type ne $to_file_type) {
3178                                        $mode_chnge .= " from $from_file_type to $to_file_type";
3179                                }
3180                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3181                                        if ($from_mode_str && $to_mode_str) {
3182                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3183                                        } elsif ($to_mode_str) {
3184                                                $mode_chnge .= " mode: $to_mode_str";
3185                                        }
3186                                }
3187                                $mode_chnge .= "]</span>\n";
3188                        }
3189                        print "<td>";
3190                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3191                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
3192                                      -class => "list"}, esc_path($diff->{'file'}));
3193                        print "</td>\n";
3194                        print "<td>$mode_chnge</td>\n";
3195                        print "<td class=\"link\">";
3196                        if ($action eq 'commitdiff') {
3197                                # link to patch
3198                                $patchno++;
3199                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
3200                                      " | ";
3201                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3202                                # "commit" view and modified file (not onlu mode changed)
3203                                print $cgi->a({-href => href(action=>"blobdiff",
3204                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3205                                                             hash_base=>$hash, hash_parent_base=>$parent,
3206                                                             file_name=>$diff->{'file'})},
3207                                              "diff") .
3208                                      " | ";
3209                        }
3210                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3211                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
3212                                       "blob") . " | ";
3213                        if ($have_blame) {
3214                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3215                                                             file_name=>$diff->{'file'})},
3216                                              "blame") . " | ";
3217                        }
3218                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3219                                                     file_name=>$diff->{'file'})},
3220                                      "history");
3221                        print "</td>\n";
3222
3223                } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3224                        my %status_name = ('R' => 'moved', 'C' => 'copied');
3225                        my $nstatus = $status_name{$diff->{'status'}};
3226                        my $mode_chng = "";
3227                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3228                                # mode also for directories, so we cannot use $to_mode_str
3229                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3230                        }
3231                        print "<td>" .
3232                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3233                                                     hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3234                                      -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3235                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3236                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3237                                                     hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3238                                      -class => "list"}, esc_path($diff->{'from_file'})) .
3239                              " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3240                              "<td class=\"link\">";
3241                        if ($action eq 'commitdiff') {
3242                                # link to patch
3243                                $patchno++;
3244                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
3245                                      " | ";
3246                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3247                                # "commit" view and modified file (not only pure rename or copy)
3248                                print $cgi->a({-href => href(action=>"blobdiff",
3249                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3250                                                             hash_base=>$hash, hash_parent_base=>$parent,
3251                                                             file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3252                                              "diff") .
3253                                      " | ";
3254                        }
3255                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3256                                                     hash_base=>$parent, file_name=>$diff->{'to_file'})},
3257                                      "blob") . " | ";
3258                        if ($have_blame) {
3259                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3260                                                             file_name=>$diff->{'to_file'})},
3261                                              "blame") . " | ";
3262                        }
3263                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3264                                                    file_name=>$diff->{'to_file'})},
3265                                      "history");
3266                        print "</td>\n";
3267
3268                } # we should not encounter Unmerged (U) or Unknown (X) status
3269                print "</tr>\n";
3270        }
3271        print "</tbody>" if $has_header;
3272        print "</table>\n";
3273}
3274
3275sub git_patchset_body {
3276        my ($fd, $difftree, $hash, @hash_parents) = @_;
3277        my ($hash_parent) = $hash_parents[0];
3278
3279        my $is_combined = (@hash_parents > 1);
3280        my $patch_idx = 0;
3281        my $patch_number = 0;
3282        my $patch_line;
3283        my $diffinfo;
3284        my $to_name;
3285        my (%from, %to);
3286
3287        print "<div class=\"patchset\">\n";
3288
3289        # skip to first patch
3290        while ($patch_line = <$fd>) {
3291                chomp $patch_line;
3292
3293                last if ($patch_line =~ m/^diff /);
3294        }
3295
3296 PATCH:
3297        while ($patch_line) {
3298
3299                # parse "git diff" header line
3300                if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3301                        # $1 is from_name, which we do not use
3302                        $to_name = unquote($2);
3303                        $to_name =~ s!^b/!!;
3304                } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3305                        # $1 is 'cc' or 'combined', which we do not use
3306                        $to_name = unquote($2);
3307                } else {
3308                        $to_name = undef;
3309                }
3310
3311                # check if current patch belong to current raw line
3312                # and parse raw git-diff line if needed
3313                if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3314                        # this is continuation of a split patch
3315                        print "<div class=\"patch cont\">\n";
3316                } else {
3317                        # advance raw git-diff output if needed
3318                        $patch_idx++ if defined $diffinfo;
3319
3320                        # read and prepare patch information
3321                        $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3322
3323                        # compact combined diff output can have some patches skipped
3324                        # find which patch (using pathname of result) we are at now;
3325                        if ($is_combined) {
3326                                while ($to_name ne $diffinfo->{'to_file'}) {
3327                                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3328                                              format_diff_cc_simplified($diffinfo, @hash_parents) .
3329                                              "</div>\n";  # class="patch"
3330
3331                                        $patch_idx++;
3332                                        $patch_number++;
3333
3334                                        last if $patch_idx > $#$difftree;
3335                                        $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3336                                }
3337                        }
3338
3339                        # modifies %from, %to hashes
3340                        parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3341
3342                        # this is first patch for raw difftree line with $patch_idx index
3343                        # we index @$difftree array from 0, but number patches from 1
3344                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3345                }
3346
3347                # git diff header
3348                #assert($patch_line =~ m/^diff /) if DEBUG;
3349                #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3350                $patch_number++;
3351                # print "git diff" header
3352                print format_git_diff_header_line($patch_line, $diffinfo,
3353                                                  \%from, \%to);
3354
3355                # print extended diff header
3356                print "<div class=\"diff extended_header\">\n";
3357        EXTENDED_HEADER:
3358                while ($patch_line = <$fd>) {
3359                        chomp $patch_line;
3360
3361                        last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3362
3363                        print format_extended_diff_header_line($patch_line, $diffinfo,
3364                                                               \%from, \%to);
3365                }
3366                print "</div>\n"; # class="diff extended_header"
3367
3368                # from-file/to-file diff header
3369                if (! $patch_line) {
3370                        print "</div>\n"; # class="patch"
3371                        last PATCH;
3372                }
3373                next PATCH if ($patch_line =~ m/^diff /);
3374                #assert($patch_line =~ m/^---/) if DEBUG;
3375
3376                my $last_patch_line = $patch_line;
3377                $patch_line = <$fd>;
3378                chomp $patch_line;
3379                #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3380
3381                print format_diff_from_to_header($last_patch_line, $patch_line,
3382                                                 $diffinfo, \%from, \%to,
3383                                                 @hash_parents);
3384
3385                # the patch itself
3386        LINE:
3387                while ($patch_line = <$fd>) {
3388                        chomp $patch_line;
3389
3390                        next PATCH if ($patch_line =~ m/^diff /);
3391
3392                        print format_diff_line($patch_line, \%from, \%to);
3393                }
3394
3395        } continue {
3396                print "</div>\n"; # class="patch"
3397        }
3398
3399        # for compact combined (--cc) format, with chunk and patch simpliciaction
3400        # patchset might be empty, but there might be unprocessed raw lines
3401        for (++$patch_idx if $patch_number > 0;
3402             $patch_idx < @$difftree;
3403             ++$patch_idx) {
3404                # read and prepare patch information
3405                $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3406
3407                # generate anchor for "patch" links in difftree / whatchanged part
3408                print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3409                      format_diff_cc_simplified($diffinfo, @hash_parents) .
3410                      "</div>\n";  # class="patch"
3411
3412                $patch_number++;
3413        }
3414
3415        if ($patch_number == 0) {
3416                if (@hash_parents > 1) {
3417                        print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3418                } else {
3419                        print "<div class=\"diff nodifferences\">No differences found</div>\n";
3420                }
3421        }
3422
3423        print "</div>\n"; # class="patchset"
3424}
3425
3426# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3427
3428sub git_project_list_body {
3429        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3430
3431        my ($check_forks) = gitweb_check_feature('forks');
3432
3433        my @projects;
3434        foreach my $pr (@$projlist) {
3435                my (@aa) = git_get_last_activity($pr->{'path'});
3436                unless (@aa) {
3437                        next;
3438                }
3439                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3440                if (!defined $pr->{'descr'}) {
3441                        my $descr = git_get_project_description($pr->{'path'}) || "";
3442                        $pr->{'descr_long'} = to_utf8($descr);
3443                        $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3444                }
3445                if (!defined $pr->{'owner'}) {
3446                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3447                }
3448                if ($check_forks) {
3449                        my $pname = $pr->{'path'};
3450                        if (($pname =~ s/\.git$//) &&
3451                            ($pname !~ /\/$/) &&
3452                            (-d "$projectroot/$pname")) {
3453                                $pr->{'forks'} = "-d $projectroot/$pname";
3454                        }
3455                        else {
3456                                $pr->{'forks'} = 0;
3457                        }
3458                }
3459                push @projects, $pr;
3460        }
3461
3462        $order ||= $default_projects_order;
3463        $from = 0 unless defined $from;
3464        $to = $#projects if (!defined $to || $#projects < $to);
3465
3466        print "<table class=\"project_list\">\n";
3467        unless ($no_header) {
3468                print "<tr>\n";
3469                if ($check_forks) {
3470                        print "<th></th>\n";
3471                }
3472                if ($order eq "project") {
3473                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3474                        print "<th>Project</th>\n";
3475                } else {
3476                        print "<th>" .
3477                              $cgi->a({-href => href(project=>undef, order=>'project'),
3478                                       -class => "header"}, "Project") .
3479                              "</th>\n";
3480                }
3481                if ($order eq "descr") {
3482                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3483                        print "<th>Description</th>\n";
3484                } else {
3485                        print "<th>" .
3486                              $cgi->a({-href => href(project=>undef, order=>'descr'),
3487                                       -class => "header"}, "Description") .
3488                              "</th>\n";
3489                }
3490                if ($order eq "owner") {
3491                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3492                        print "<th>Owner</th>\n";
3493                } else {
3494                        print "<th>" .
3495                              $cgi->a({-href => href(project=>undef, order=>'owner'),
3496                                       -class => "header"}, "Owner") .
3497                              "</th>\n";
3498                }
3499                if ($order eq "age") {
3500                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3501                        print "<th>Last Change</th>\n";
3502                } else {
3503                        print "<th>" .
3504                              $cgi->a({-href => href(project=>undef, order=>'age'),
3505                                       -class => "header"}, "Last Change") .
3506                              "</th>\n";
3507                }
3508                print "<th></th>\n" .
3509                      "</tr>\n";
3510        }
3511        my $alternate = 1;
3512        for (my $i = $from; $i <= $to; $i++) {
3513                my $pr = $projects[$i];
3514                if ($alternate) {
3515                        print "<tr class=\"dark\">\n";
3516                } else {
3517                        print "<tr class=\"light\">\n";
3518                }
3519                $alternate ^= 1;
3520                if ($check_forks) {
3521                        print "<td>";
3522                        if ($pr->{'forks'}) {
3523                                print "<!-- $pr->{'forks'} -->\n";
3524                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3525                        }
3526                        print "</td>\n";
3527                }
3528                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3529                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3530                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3531                                        -class => "list", -title => $pr->{'descr_long'}},
3532                                        esc_html($pr->{'descr'})) . "</td>\n" .
3533                      "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
3534                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3535                      (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3536                      "<td class=\"link\">" .
3537                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3538                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3539                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3540                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3541                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3542                      "</td>\n" .
3543                      "</tr>\n";
3544        }
3545        if (defined $extra) {
3546                print "<tr>\n";
3547                if ($check_forks) {
3548                        print "<td></td>\n";
3549                }
3550                print "<td colspan=\"5\">$extra</td>\n" .
3551                      "</tr>\n";
3552        }
3553        print "</table>\n";
3554}
3555
3556sub git_shortlog_body {
3557        # uses global variable $project
3558        my ($commitlist, $from, $to, $refs, $extra) = @_;
3559
3560        $from = 0 unless defined $from;
3561        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3562
3563        print "<table class=\"shortlog\">\n";
3564        my $alternate = 1;
3565        for (my $i = $from; $i <= $to; $i++) {
3566                my %co = %{$commitlist->[$i]};
3567                my $commit = $co{'id'};
3568                my $ref = format_ref_marker($refs, $commit);
3569                if ($alternate) {
3570                        print "<tr class=\"dark\">\n";
3571                } else {
3572                        print "<tr class=\"light\">\n";
3573                }
3574                $alternate ^= 1;
3575                my $author = chop_and_escape_str($co{'author_name'}, 10);
3576                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3577                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3578                      "<td><i>" . $author . "</i></td>\n" .
3579                      "<td>";
3580                print format_subject_html($co{'title'}, $co{'title_short'},
3581                                          href(action=>"commit", hash=>$commit), $ref);
3582                print "</td>\n" .
3583                      "<td class=\"link\">" .
3584                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3585                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3586                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3587                my $snapshot_links = format_snapshot_links($commit);
3588                if (defined $snapshot_links) {
3589                        print " | " . $snapshot_links;
3590                }
3591                print "</td>\n" .
3592                      "</tr>\n";
3593        }
3594        if (defined $extra) {
3595                print "<tr>\n" .
3596                      "<td colspan=\"4\">$extra</td>\n" .
3597                      "</tr>\n";
3598        }
3599        print "</table>\n";
3600}
3601
3602sub git_history_body {
3603        # Warning: assumes constant type (blob or tree) during history
3604        my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3605
3606        $from = 0 unless defined $from;
3607        $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3608
3609        print "<table class=\"history\">\n";
3610        my $alternate = 1;
3611        for (my $i = $from; $i <= $to; $i++) {
3612                my %co = %{$commitlist->[$i]};
3613                if (!%co) {
3614                        next;
3615                }
3616                my $commit = $co{'id'};
3617
3618                my $ref = format_ref_marker($refs, $commit);
3619
3620                if ($alternate) {
3621                        print "<tr class=\"dark\">\n";
3622                } else {
3623                        print "<tr class=\"light\">\n";
3624                }
3625                $alternate ^= 1;
3626        # shortlog uses      chop_str($co{'author_name'}, 10)
3627                my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
3628                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3629                      "<td><i>" . $author . "</i></td>\n" .
3630                      "<td>";
3631                # originally git_history used chop_str($co{'title'}, 50)
3632                print format_subject_html($co{'title'}, $co{'title_short'},
3633                                          href(action=>"commit", hash=>$commit), $ref);
3634                print "</td>\n" .
3635                      "<td class=\"link\">" .
3636                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3637                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3638
3639                if ($ftype eq 'blob') {
3640                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3641                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3642                        if (defined $blob_current && defined $blob_parent &&
3643                                        $blob_current ne $blob_parent) {
3644                                print " | " .
3645                                        $cgi->a({-href => href(action=>"blobdiff",
3646                                                               hash=>$blob_current, hash_parent=>$blob_parent,
3647                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
3648                                                               file_name=>$file_name)},
3649                                                "diff to current");
3650                        }
3651                }
3652                print "</td>\n" .
3653                      "</tr>\n";
3654        }
3655        if (defined $extra) {
3656                print "<tr>\n" .
3657                      "<td colspan=\"4\">$extra</td>\n" .
3658                      "</tr>\n";
3659        }
3660        print "</table>\n";
3661}
3662
3663sub git_tags_body {
3664        # uses global variable $project
3665        my ($taglist, $from, $to, $extra) = @_;
3666        $from = 0 unless defined $from;
3667        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3668
3669        print "<table class=\"tags\">\n";
3670        my $alternate = 1;
3671        for (my $i = $from; $i <= $to; $i++) {
3672                my $entry = $taglist->[$i];
3673                my %tag = %$entry;
3674                my $comment = $tag{'subject'};
3675                my $comment_short;
3676                if (defined $comment) {
3677                        $comment_short = chop_str($comment, 30, 5);
3678                }
3679                if ($alternate) {
3680                        print "<tr class=\"dark\">\n";
3681                } else {
3682                        print "<tr class=\"light\">\n";
3683                }
3684                $alternate ^= 1;
3685                if (defined $tag{'age'}) {
3686                        print "<td><i>$tag{'age'}</i></td>\n";
3687                } else {
3688                        print "<td></td>\n";
3689                }
3690                print "<td>" .
3691                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3692                               -class => "list name"}, esc_html($tag{'name'})) .
3693                      "</td>\n" .
3694                      "<td>";
3695                if (defined $comment) {
3696                        print format_subject_html($comment, $comment_short,
3697                                                  href(action=>"tag", hash=>$tag{'id'}));
3698                }
3699                print "</td>\n" .
3700                      "<td class=\"selflink\">";
3701                if ($tag{'type'} eq "tag") {
3702                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3703                } else {
3704                        print "&nbsp;";
3705                }
3706                print "</td>\n" .
3707                      "<td class=\"link\">" . " | " .
3708                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3709                if ($tag{'reftype'} eq "commit") {
3710                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
3711                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
3712                } elsif ($tag{'reftype'} eq "blob") {
3713                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3714                }
3715                print "</td>\n" .
3716                      "</tr>";
3717        }
3718        if (defined $extra) {
3719                print "<tr>\n" .
3720                      "<td colspan=\"5\">$extra</td>\n" .
3721                      "</tr>\n";
3722        }
3723        print "</table>\n";
3724}
3725
3726sub git_heads_body {
3727        # uses global variable $project
3728        my ($headlist, $head, $from, $to, $extra) = @_;
3729        $from = 0 unless defined $from;
3730        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3731
3732        print "<table class=\"heads\">\n";
3733        my $alternate = 1;
3734        for (my $i = $from; $i <= $to; $i++) {
3735                my $entry = $headlist->[$i];
3736                my %ref = %$entry;
3737                my $curr = $ref{'id'} eq $head;
3738                if ($alternate) {
3739                        print "<tr class=\"dark\">\n";
3740                } else {
3741                        print "<tr class=\"light\">\n";
3742                }
3743                $alternate ^= 1;
3744                print "<td><i>$ref{'age'}</i></td>\n" .
3745                      ($curr ? "<td class=\"current_head\">" : "<td>") .
3746                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
3747                               -class => "list name"},esc_html($ref{'name'})) .
3748                      "</td>\n" .
3749                      "<td class=\"link\">" .
3750                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
3751                      $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
3752                      $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
3753                      "</td>\n" .
3754                      "</tr>";
3755        }
3756        if (defined $extra) {
3757                print "<tr>\n" .
3758                      "<td colspan=\"3\">$extra</td>\n" .
3759                      "</tr>\n";
3760        }
3761        print "</table>\n";
3762}
3763
3764sub git_search_grep_body {
3765        my ($commitlist, $from, $to, $extra) = @_;
3766        $from = 0 unless defined $from;
3767        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3768
3769        print "<table class=\"commit_search\">\n";
3770        my $alternate = 1;
3771        for (my $i = $from; $i <= $to; $i++) {
3772                my %co = %{$commitlist->[$i]};
3773                if (!%co) {
3774                        next;
3775                }
3776                my $commit = $co{'id'};
3777                if ($alternate) {
3778                        print "<tr class=\"dark\">\n";
3779                } else {
3780                        print "<tr class=\"light\">\n";
3781                }
3782                $alternate ^= 1;
3783                my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
3784                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3785                      "<td><i>" . $author . "</i></td>\n" .
3786                      "<td>" .
3787                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3788                               chop_and_escape_str($co{'title'}, 50) . "<br/>");
3789                my $comment = $co{'comment'};
3790                foreach my $line (@$comment) {
3791                        if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3792                                my $lead = esc_html($1) || "";
3793                                $lead = chop_str($lead, 30, 10);
3794                                my $match = esc_html($2) || "";
3795                                my $trail = esc_html($3) || "";
3796                                $trail = chop_str($trail, 30, 10);
3797                                my $text = "$lead<span class=\"match\">$match</span>$trail";
3798                                print chop_str($text, 80, 5) . "<br/>\n";
3799                        }
3800                }
3801                print "</td>\n" .
3802                      "<td class=\"link\">" .
3803                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3804                      " | " .
3805                      $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
3806                      " | " .
3807                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3808                print "</td>\n" .
3809                      "</tr>\n";
3810        }
3811        if (defined $extra) {
3812                print "<tr>\n" .
3813                      "<td colspan=\"3\">$extra</td>\n" .
3814                      "</tr>\n";
3815        }
3816        print "</table>\n";
3817}
3818
3819## ======================================================================
3820## ======================================================================
3821## actions
3822
3823sub git_project_list {
3824        my $order = $cgi->param('o');
3825        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3826                die_error(undef, "Unknown order parameter");
3827        }
3828
3829        my @list = git_get_projects_list();
3830        if (!@list) {
3831                die_error(undef, "No projects found");
3832        }
3833
3834        git_header_html();
3835        if (-f $home_text) {
3836                print "<div class=\"index_include\">\n";
3837                open (my $fd, $home_text);
3838                print <$fd>;
3839                close $fd;
3840                print "</div>\n";
3841        }
3842        git_project_list_body(\@list, $order);
3843        git_footer_html();
3844}
3845
3846sub git_forks {
3847        my $order = $cgi->param('o');
3848        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3849                die_error(undef, "Unknown order parameter");
3850        }
3851
3852        my @list = git_get_projects_list($project);
3853        if (!@list) {
3854                die_error(undef, "No forks found");
3855        }
3856
3857        git_header_html();
3858        git_print_page_nav('','');
3859        git_print_header_div('summary', "$project forks");
3860        git_project_list_body(\@list, $order);
3861        git_footer_html();
3862}
3863
3864sub git_project_index {
3865        my @projects = git_get_projects_list($project);
3866
3867        print $cgi->header(
3868                -type => 'text/plain',
3869                -charset => 'utf-8',
3870                -content_disposition => 'inline; filename="index.aux"');
3871
3872        foreach my $pr (@projects) {
3873                if (!exists $pr->{'owner'}) {
3874                        $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3875                }
3876
3877                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3878                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3879                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3880                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3881                $path  =~ s/ /\+/g;
3882                $owner =~ s/ /\+/g;
3883
3884                print "$path $owner\n";
3885        }
3886}
3887
3888sub git_summary {
3889        my $descr = git_get_project_description($project) || "none";
3890        my %co = parse_commit("HEAD");
3891        my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3892        my $head = $co{'id'};
3893
3894        my $owner = git_get_project_owner($project);
3895
3896        my $refs = git_get_references();
3897        # These get_*_list functions return one more to allow us to see if
3898        # there are more ...
3899        my @taglist  = git_get_tags_list(16);
3900        my @headlist = git_get_heads_list(16);
3901        my @forklist;
3902        my ($check_forks) = gitweb_check_feature('forks');
3903
3904        if ($check_forks) {
3905                @forklist = git_get_projects_list($project);
3906        }
3907
3908        git_header_html();
3909        git_print_page_nav('summary','', $head);
3910
3911        print "<div class=\"title\">&nbsp;</div>\n";
3912        print "<table class=\"projects_list\">\n" .
3913              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3914              "<tr><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
3915        if (defined $cd{'rfc2822'}) {
3916                print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3917        }
3918
3919        # use per project git URL list in $projectroot/$project/cloneurl
3920        # or make project git URL from git base URL and project name
3921        my $url_tag = "URL";
3922        my @url_list = git_get_project_url_list($project);
3923        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3924        foreach my $git_url (@url_list) {
3925                next unless $git_url;
3926                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3927                $url_tag = "";
3928        }
3929        print "</table>\n";
3930
3931        if (-s "$projectroot/$project/README.html") {
3932                if (open my $fd, "$projectroot/$project/README.html") {
3933                        print "<div class=\"title\">readme</div>\n" .
3934                              "<div class=\"readme\">\n";
3935                        print $_ while (<$fd>);
3936                        print "\n</div>\n"; # class="readme"
3937                        close $fd;
3938                }
3939        }
3940
3941        # we need to request one more than 16 (0..15) to check if
3942        # those 16 are all
3943        my @commitlist = $head ? parse_commits($head, 17) : ();
3944        if (@commitlist) {
3945                git_print_header_div('shortlog');
3946                git_shortlog_body(\@commitlist, 0, 15, $refs,
3947                                  $#commitlist <=  15 ? undef :
3948                                  $cgi->a({-href => href(action=>"shortlog")}, "..."));
3949        }
3950
3951        if (@taglist) {
3952                git_print_header_div('tags');
3953                git_tags_body(\@taglist, 0, 15,
3954                              $#taglist <=  15 ? undef :
3955                              $cgi->a({-href => href(action=>"tags")}, "..."));
3956        }
3957
3958        if (@headlist) {
3959                git_print_header_div('heads');
3960                git_heads_body(\@headlist, $head, 0, 15,
3961                               $#headlist <= 15 ? undef :
3962                               $cgi->a({-href => href(action=>"heads")}, "..."));
3963        }
3964
3965        if (@forklist) {
3966                git_print_header_div('forks');
3967                git_project_list_body(\@forklist, undef, 0, 15,
3968                                      $#forklist <= 15 ? undef :
3969                                      $cgi->a({-href => href(action=>"forks")}, "..."),
3970                                      'noheader');
3971        }
3972
3973        git_footer_html();
3974}
3975
3976sub git_tag {
3977        my $head = git_get_head_hash($project);
3978        git_header_html();
3979        git_print_page_nav('','', $head,undef,$head);
3980        my %tag = parse_tag($hash);
3981
3982        if (! %tag) {
3983                die_error(undef, "Unknown tag object");
3984        }
3985
3986        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3987        print "<div class=\"title_text\">\n" .
3988              "<table class=\"object_header\">\n" .
3989              "<tr>\n" .
3990              "<td>object</td>\n" .
3991              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3992                               $tag{'object'}) . "</td>\n" .
3993              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3994                                              $tag{'type'}) . "</td>\n" .
3995              "</tr>\n";
3996        if (defined($tag{'author'})) {
3997                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3998                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3999                print "<tr><td></td><td>" . $ad{'rfc2822'} .
4000                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4001                        "</td></tr>\n";
4002        }
4003        print "</table>\n\n" .
4004              "</div>\n";
4005        print "<div class=\"page_body\">";
4006        my $comment = $tag{'comment'};
4007        foreach my $line (@$comment) {
4008                chomp $line;
4009                print esc_html($line, -nbsp=>1) . "<br/>\n";
4010        }
4011        print "</div>\n";
4012        git_footer_html();
4013}
4014
4015sub git_blame2 {
4016        my $fd;
4017        my $ftype;
4018
4019        my ($have_blame) = gitweb_check_feature('blame');
4020        if (!$have_blame) {
4021                die_error('403 Permission denied', "Permission denied");
4022        }
4023        die_error('404 Not Found', "File name not defined") if (!$file_name);
4024        $hash_base ||= git_get_head_hash($project);
4025        die_error(undef, "Couldn't find base commit") unless ($hash_base);
4026        my %co = parse_commit($hash_base)
4027                or die_error(undef, "Reading commit failed");
4028        if (!defined $hash) {
4029                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4030                        or die_error(undef, "Error looking up file");
4031        }
4032        $ftype = git_get_type($hash);
4033        if ($ftype !~ "blob") {
4034                die_error('400 Bad Request', "Object is not a blob");
4035        }
4036        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
4037              $file_name, $hash_base)
4038                or die_error(undef, "Open git-blame failed");
4039        git_header_html();
4040        my $formats_nav =
4041                $cgi->a({-href => href(action=>"blob", -replay=>1)},
4042                        "blob") .
4043                " | " .
4044                $cgi->a({-href => href(action=>"history", -replay=>1)},
4045                        "history") .
4046                " | " .
4047                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4048                        "HEAD");
4049        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4050        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4051        git_print_page_path($file_name, $ftype, $hash_base);
4052        my @rev_color = (qw(light2 dark2));
4053        my $num_colors = scalar(@rev_color);
4054        my $current_color = 0;
4055        my $last_rev;
4056        print <<HTML;
4057<div class="page_body">
4058<table class="blame">
4059<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4060HTML
4061        my %metainfo = ();
4062        while (1) {
4063                $_ = <$fd>;
4064                last unless defined $_;
4065                my ($full_rev, $orig_lineno, $lineno, $group_size) =
4066                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4067                if (!exists $metainfo{$full_rev}) {
4068                        $metainfo{$full_rev} = {};
4069                }
4070                my $meta = $metainfo{$full_rev};
4071                while (<$fd>) {
4072                        last if (s/^\t//);
4073                        if (/^(\S+) (.*)$/) {
4074                                $meta->{$1} = $2;
4075                        }
4076                }
4077                my $data = $_;
4078                chomp $data;
4079                my $rev = substr($full_rev, 0, 8);
4080                my $author = $meta->{'author'};
4081                my %date = parse_date($meta->{'author-time'},
4082                                      $meta->{'author-tz'});
4083                my $date = $date{'iso-tz'};
4084                if ($group_size) {
4085                        $current_color = ++$current_color % $num_colors;
4086                }
4087                print "<tr class=\"$rev_color[$current_color]\">\n";
4088                if ($group_size) {
4089                        print "<td class=\"sha1\"";
4090                        print " title=\"". esc_html($author) . ", $date\"";
4091                        print " rowspan=\"$group_size\"" if ($group_size > 1);
4092                        print ">";
4093                        print $cgi->a({-href => href(action=>"commit",
4094                                                     hash=>$full_rev,
4095                                                     file_name=>$file_name)},
4096                                      esc_html($rev));
4097                        print "</td>\n";
4098                }
4099                open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4100                        or die_error(undef, "Open git-rev-parse failed");
4101                my $parent_commit = <$dd>;
4102                close $dd;
4103                chomp($parent_commit);
4104                my $blamed = href(action => 'blame',
4105                                  file_name => $meta->{'filename'},
4106                                  hash_base => $parent_commit);
4107                print "<td class=\"linenr\">";
4108                print $cgi->a({ -href => "$blamed#l$orig_lineno",
4109                                -id => "l$lineno",
4110                                -class => "linenr" },
4111                              esc_html($lineno));
4112                print "</td>";
4113                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4114                print "</tr>\n";
4115        }
4116        print "</table>\n";
4117        print "</div>";
4118        close $fd
4119                or print "Reading blob failed\n";
4120        git_footer_html();
4121}
4122
4123sub git_blame {
4124        my $fd;
4125
4126        my ($have_blame) = gitweb_check_feature('blame');
4127        if (!$have_blame) {
4128                die_error('403 Permission denied', "Permission denied");
4129        }
4130        die_error('404 Not Found', "File name not defined") if (!$file_name);
4131        $hash_base ||= git_get_head_hash($project);
4132        die_error(undef, "Couldn't find base commit") unless ($hash_base);
4133        my %co = parse_commit($hash_base)
4134                or die_error(undef, "Reading commit failed");
4135        if (!defined $hash) {
4136                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4137                        or die_error(undef, "Error lookup file");
4138        }
4139        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
4140                or die_error(undef, "Open git-annotate failed");
4141        git_header_html();
4142        my $formats_nav =
4143                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4144                        "blob") .
4145                " | " .
4146                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4147                        "history") .
4148                " | " .
4149                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4150                        "HEAD");
4151        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4152        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4153        git_print_page_path($file_name, 'blob', $hash_base);
4154        print "<div class=\"page_body\">\n";
4155        print <<HTML;
4156<table class="blame">
4157  <tr>
4158    <th>Commit</th>
4159    <th>Age</th>
4160    <th>Author</th>
4161    <th>Line</th>
4162    <th>Data</th>
4163  </tr>
4164HTML
4165        my @line_class = (qw(light dark));
4166        my $line_class_len = scalar (@line_class);
4167        my $line_class_num = $#line_class;
4168        while (my $line = <$fd>) {
4169                my $long_rev;
4170                my $short_rev;
4171                my $author;
4172                my $time;
4173                my $lineno;
4174                my $data;
4175                my $age;
4176                my $age_str;
4177                my $age_class;
4178
4179                chomp $line;
4180                $line_class_num = ($line_class_num + 1) % $line_class_len;
4181
4182                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
4183                        $long_rev = $1;
4184                        $author   = $2;
4185                        $time     = $3;
4186                        $lineno   = $4;
4187                        $data     = $5;
4188                } else {
4189                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
4190                        next;
4191                }
4192                $short_rev  = substr ($long_rev, 0, 8);
4193                $age        = time () - $time;
4194                $age_str    = age_string ($age);
4195                $age_str    =~ s/ /&nbsp;/g;
4196                $age_class  = age_class($age);
4197                $author     = esc_html ($author);
4198                $author     =~ s/ /&nbsp;/g;
4199
4200                $data = untabify($data);
4201                $data = esc_html ($data);
4202
4203                print <<HTML;
4204  <tr class="$line_class[$line_class_num]">
4205    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
4206    <td class="$age_class">$age_str</td>
4207    <td>$author</td>
4208    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
4209    <td class="pre">$data</td>
4210  </tr>
4211HTML
4212        } # while (my $line = <$fd>)
4213        print "</table>\n\n";
4214        close $fd
4215                or print "Reading blob failed.\n";
4216        print "</div>";
4217        git_footer_html();
4218}
4219
4220sub git_tags {
4221        my $head = git_get_head_hash($project);
4222        git_header_html();
4223        git_print_page_nav('','', $head,undef,$head);
4224        git_print_header_div('summary', $project);
4225
4226        my @tagslist = git_get_tags_list();
4227        if (@tagslist) {
4228                git_tags_body(\@tagslist);
4229        }
4230        git_footer_html();
4231}
4232
4233sub git_heads {
4234        my $head = git_get_head_hash($project);
4235        git_header_html();
4236        git_print_page_nav('','', $head,undef,$head);
4237        git_print_header_div('summary', $project);
4238
4239        my @headslist = git_get_heads_list();
4240        if (@headslist) {
4241                git_heads_body(\@headslist, $head);
4242        }
4243        git_footer_html();
4244}
4245
4246sub git_blob_plain {
4247        my $expires;
4248
4249        if (!defined $hash) {
4250                if (defined $file_name) {
4251                        my $base = $hash_base || git_get_head_hash($project);
4252                        $hash = git_get_hash_by_path($base, $file_name, "blob")
4253                                or die_error(undef, "Error lookup file");
4254                } else {
4255                        die_error(undef, "No file name defined");
4256                }
4257        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4258                # blobs defined by non-textual hash id's can be cached
4259                $expires = "+1d";
4260        }
4261
4262        my $type = shift;
4263        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4264                or die_error(undef, "Couldn't cat $file_name, $hash");
4265
4266        $type ||= blob_mimetype($fd, $file_name);
4267
4268        # save as filename, even when no $file_name is given
4269        my $save_as = "$hash";
4270        if (defined $file_name) {
4271                $save_as = $file_name;
4272        } elsif ($type =~ m/^text\//) {
4273                $save_as .= '.txt';
4274        }
4275
4276        print $cgi->header(
4277                -type => "$type",
4278                -expires=>$expires,
4279                -content_disposition => 'inline; filename="' . "$save_as" . '"');
4280        undef $/;
4281        binmode STDOUT, ':raw';
4282        print <$fd>;
4283        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4284        $/ = "\n";
4285        close $fd;
4286}
4287
4288sub git_blob {
4289        my $expires;
4290
4291        if (!defined $hash) {
4292                if (defined $file_name) {
4293                        my $base = $hash_base || git_get_head_hash($project);
4294                        $hash = git_get_hash_by_path($base, $file_name, "blob")
4295                                or die_error(undef, "Error lookup file");
4296                } else {
4297                        die_error(undef, "No file name defined");
4298                }
4299        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4300                # blobs defined by non-textual hash id's can be cached
4301                $expires = "+1d";
4302        }
4303
4304        my ($have_blame) = gitweb_check_feature('blame');
4305        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4306                or die_error(undef, "Couldn't cat $file_name, $hash");
4307        my $mimetype = blob_mimetype($fd, $file_name);
4308        if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4309                close $fd;
4310                return git_blob_plain($mimetype);
4311        }
4312        # we can have blame only for text/* mimetype
4313        $have_blame &&= ($mimetype =~ m!^text/!);
4314
4315        git_header_html(undef, $expires);
4316        my $formats_nav = '';
4317        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4318                if (defined $file_name) {
4319                        if ($have_blame) {
4320                                $formats_nav .=
4321                                        $cgi->a({-href => href(action=>"blame", -replay=>1)},
4322                                                "blame") .
4323                                        " | ";
4324                        }
4325                        $formats_nav .=
4326                                $cgi->a({-href => href(action=>"history", -replay=>1)},
4327                                        "history") .
4328                                " | " .
4329                                $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4330                                        "raw") .
4331                                " | " .
4332                                $cgi->a({-href => href(action=>"blob",
4333                                                       hash_base=>"HEAD", file_name=>$file_name)},
4334                                        "HEAD");
4335                } else {
4336                        $formats_nav .=
4337                                $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4338                                        "raw");
4339                }
4340                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4341                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4342        } else {
4343                print "<div class=\"page_nav\">\n" .
4344                      "<br/><br/></div>\n" .
4345                      "<div class=\"title\">$hash</div>\n";
4346        }
4347        git_print_page_path($file_name, "blob", $hash_base);
4348        print "<div class=\"page_body\">\n";
4349        if ($mimetype =~ m!^image/!) {
4350                print qq!<img type="$mimetype"!;
4351                if ($file_name) {
4352                        print qq! alt="$file_name" title="$file_name"!;
4353                }
4354                print qq! src="! .
4355                      href(action=>"blob_plain", hash=>$hash,
4356                           hash_base=>$hash_base, file_name=>$file_name) .
4357                      qq!" />\n!;
4358        } else {
4359                my $nr;
4360                while (my $line = <$fd>) {
4361                        chomp $line;
4362                        $nr++;
4363                        $line = untabify($line);
4364                        printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4365                               $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4366                }
4367        }
4368        close $fd
4369                or print "Reading blob failed.\n";
4370        print "</div>";
4371        git_footer_html();
4372}
4373
4374sub git_tree {
4375        if (!defined $hash_base) {
4376                $hash_base = "HEAD";
4377        }
4378        if (!defined $hash) {
4379                if (defined $file_name) {
4380                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4381                } else {
4382                        $hash = $hash_base;
4383                }
4384        }
4385        $/ = "\0";
4386        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4387                or die_error(undef, "Open git-ls-tree failed");
4388        my @entries = map { chomp; $_ } <$fd>;
4389        close $fd or die_error(undef, "Reading tree failed");
4390        $/ = "\n";
4391
4392        my $refs = git_get_references();
4393        my $ref = format_ref_marker($refs, $hash_base);
4394        git_header_html();
4395        my $basedir = '';
4396        my ($have_blame) = gitweb_check_feature('blame');
4397        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4398                my @views_nav = ();
4399                if (defined $file_name) {
4400                        push @views_nav,
4401                                $cgi->a({-href => href(action=>"history", -replay=>1)},
4402                                        "history"),
4403                                $cgi->a({-href => href(action=>"tree",
4404                                                       hash_base=>"HEAD", file_name=>$file_name)},
4405                                        "HEAD"),
4406                }
4407                my $snapshot_links = format_snapshot_links($hash);
4408                if (defined $snapshot_links) {
4409                        # FIXME: Should be available when we have no hash base as well.
4410                        push @views_nav, $snapshot_links;
4411                }
4412                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4413                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4414        } else {
4415                undef $hash_base;
4416                print "<div class=\"page_nav\">\n";
4417                print "<br/><br/></div>\n";
4418                print "<div class=\"title\">$hash</div>\n";
4419        }
4420        if (defined $file_name) {
4421                $basedir = $file_name;
4422                if ($basedir ne '' && substr($basedir, -1) ne '/') {
4423                        $basedir .= '/';
4424                }
4425        }
4426        git_print_page_path($file_name, 'tree', $hash_base);
4427        print "<div class=\"page_body\">\n";
4428        print "<table class=\"tree\">\n";
4429        my $alternate = 1;
4430        # '..' (top directory) link if possible
4431        if (defined $hash_base &&
4432            defined $file_name && $file_name =~ m![^/]+$!) {
4433                if ($alternate) {
4434                        print "<tr class=\"dark\">\n";
4435                } else {
4436                        print "<tr class=\"light\">\n";
4437                }
4438                $alternate ^= 1;
4439
4440                my $up = $file_name;
4441                $up =~ s!/?[^/]+$!!;
4442                undef $up unless $up;
4443                # based on git_print_tree_entry
4444                print '<td class="mode">' . mode_str('040000') . "</td>\n";
4445                print '<td class="list">';
4446                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4447                                             file_name=>$up)},
4448                              "..");
4449                print "</td>\n";
4450                print "<td class=\"link\"></td>\n";
4451
4452                print "</tr>\n";
4453        }
4454        foreach my $line (@entries) {
4455                my %t = parse_ls_tree_line($line, -z => 1);
4456
4457                if ($alternate) {
4458                        print "<tr class=\"dark\">\n";
4459                } else {
4460                        print "<tr class=\"light\">\n";
4461                }
4462                $alternate ^= 1;
4463
4464                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4465
4466                print "</tr>\n";
4467        }
4468        print "</table>\n" .
4469              "</div>";
4470        git_footer_html();
4471}
4472
4473sub git_snapshot {
4474        my @supported_fmts = gitweb_check_feature('snapshot');
4475        @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4476
4477        my $format = $cgi->param('sf');
4478        if (!@supported_fmts) {
4479                die_error('403 Permission denied', "Permission denied");
4480        }
4481        # default to first supported snapshot format
4482        $format ||= $supported_fmts[0];
4483        if ($format !~ m/^[a-z0-9]+$/) {
4484                die_error(undef, "Invalid snapshot format parameter");
4485        } elsif (!exists($known_snapshot_formats{$format})) {
4486                die_error(undef, "Unknown snapshot format");
4487        } elsif (!grep($_ eq $format, @supported_fmts)) {
4488                die_error(undef, "Unsupported snapshot format");
4489        }
4490
4491        if (!defined $hash) {
4492                $hash = git_get_head_hash($project);
4493        }
4494
4495        my $git_command = git_cmd_str();
4496        my $name = $project;
4497        $name =~ s,([^/])/*\.git$,$1,;
4498        $name = basename($name);
4499        my $filename = to_utf8($name);
4500        $name =~ s/\047/\047\\\047\047/g;
4501        my $cmd;
4502        $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4503        $cmd = "$git_command archive " .
4504                "--format=$known_snapshot_formats{$format}{'format'} " .
4505                "--prefix=\'$name\'/ $hash";
4506        if (exists $known_snapshot_formats{$format}{'compressor'}) {
4507                $cmd .= ' | ' . join ' ', @{$known_snapshot_formats{$format}{'compressor'}};
4508        }
4509
4510        print $cgi->header(
4511                -type => $known_snapshot_formats{$format}{'type'},
4512                -content_disposition => 'inline; filename="' . "$filename" . '"',
4513                -status => '200 OK');
4514
4515        open my $fd, "-|", $cmd
4516                or die_error(undef, "Execute git-archive failed");
4517        binmode STDOUT, ':raw';
4518        print <$fd>;
4519        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4520        close $fd;
4521}
4522
4523sub git_log {
4524        my $head = git_get_head_hash($project);
4525        if (!defined $hash) {
4526                $hash = $head;
4527        }
4528        if (!defined $page) {
4529                $page = 0;
4530        }
4531        my $refs = git_get_references();
4532
4533        my @commitlist = parse_commits($hash, 101, (100 * $page));
4534
4535        my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4536
4537        git_header_html();
4538        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4539
4540        if (!@commitlist) {
4541                my %co = parse_commit($hash);
4542
4543                git_print_header_div('summary', $project);
4544                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4545        }
4546        my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4547        for (my $i = 0; $i <= $to; $i++) {
4548                my %co = %{$commitlist[$i]};
4549                next if !%co;
4550                my $commit = $co{'id'};
4551                my $ref = format_ref_marker($refs, $commit);
4552                my %ad = parse_date($co{'author_epoch'});
4553                git_print_header_div('commit',
4554                               "<span class=\"age\">$co{'age_string'}</span>" .
4555                               esc_html($co{'title'}) . $ref,
4556                               $commit);
4557                print "<div class=\"title_text\">\n" .
4558                      "<div class=\"log_link\">\n" .
4559                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4560                      " | " .
4561                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4562                      " | " .
4563                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4564                      "<br/>\n" .
4565                      "</div>\n" .
4566                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4567                      "</div>\n";
4568
4569                print "<div class=\"log_body\">\n";
4570                git_print_log($co{'comment'}, -final_empty_line=> 1);
4571                print "</div>\n";
4572        }
4573        if ($#commitlist >= 100) {
4574                print "<div class=\"page_nav\">\n";
4575                print $cgi->a({-href => href(-replay=>1, page=>$page+1),
4576                               -accesskey => "n", -title => "Alt-n"}, "next");
4577                print "</div>\n";
4578        }
4579        git_footer_html();
4580}
4581
4582sub git_commit {
4583        $hash ||= $hash_base || "HEAD";
4584        my %co = parse_commit($hash);
4585        if (!%co) {
4586                die_error(undef, "Unknown commit object");
4587        }
4588        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4589        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4590
4591        my $parent  = $co{'parent'};
4592        my $parents = $co{'parents'}; # listref
4593
4594        # we need to prepare $formats_nav before any parameter munging
4595        my $formats_nav;
4596        if (!defined $parent) {
4597                # --root commitdiff
4598                $formats_nav .= '(initial)';
4599        } elsif (@$parents == 1) {
4600                # single parent commit
4601                $formats_nav .=
4602                        '(parent: ' .
4603                        $cgi->a({-href => href(action=>"commit",
4604                                               hash=>$parent)},
4605                                esc_html(substr($parent, 0, 7))) .
4606                        ')';
4607        } else {
4608                # merge commit
4609                $formats_nav .=
4610                        '(merge: ' .
4611                        join(' ', map {
4612                                $cgi->a({-href => href(action=>"commit",
4613                                                       hash=>$_)},
4614                                        esc_html(substr($_, 0, 7)));
4615                        } @$parents ) .
4616                        ')';
4617        }
4618
4619        if (!defined $parent) {
4620                $parent = "--root";
4621        }
4622        my @difftree;
4623        open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4624                @diff_opts,
4625                (@$parents <= 1 ? $parent : '-c'),
4626                $hash, "--"
4627                or die_error(undef, "Open git-diff-tree failed");
4628        @difftree = map { chomp; $_ } <$fd>;
4629        close $fd or die_error(undef, "Reading git-diff-tree failed");
4630
4631        # non-textual hash id's can be cached
4632        my $expires;
4633        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4634                $expires = "+1d";
4635        }
4636        my $refs = git_get_references();
4637        my $ref = format_ref_marker($refs, $co{'id'});
4638
4639        git_header_html(undef, $expires);
4640        git_print_page_nav('commit', '',
4641                           $hash, $co{'tree'}, $hash,
4642                           $formats_nav);
4643
4644        if (defined $co{'parent'}) {
4645                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4646        } else {
4647                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4648        }
4649        print "<div class=\"title_text\">\n" .
4650              "<table class=\"object_header\">\n";
4651        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4652              "<tr>" .
4653              "<td></td><td> $ad{'rfc2822'}";
4654        if ($ad{'hour_local'} < 6) {
4655                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4656                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4657        } else {
4658                printf(" (%02d:%02d %s)",
4659                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4660        }
4661        print "</td>" .
4662              "</tr>\n";
4663        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4664        print "<tr><td></td><td> $cd{'rfc2822'}" .
4665              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4666              "</td></tr>\n";
4667        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4668        print "<tr>" .
4669              "<td>tree</td>" .
4670              "<td class=\"sha1\">" .
4671              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4672                       class => "list"}, $co{'tree'}) .
4673              "</td>" .
4674              "<td class=\"link\">" .
4675              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4676                      "tree");
4677        my $snapshot_links = format_snapshot_links($hash);
4678        if (defined $snapshot_links) {
4679                print " | " . $snapshot_links;
4680        }
4681        print "</td>" .
4682              "</tr>\n";
4683
4684        foreach my $par (@$parents) {
4685                print "<tr>" .
4686                      "<td>parent</td>" .
4687                      "<td class=\"sha1\">" .
4688                      $cgi->a({-href => href(action=>"commit", hash=>$par),
4689                               class => "list"}, $par) .
4690                      "</td>" .
4691                      "<td class=\"link\">" .
4692                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4693                      " | " .
4694                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4695                      "</td>" .
4696                      "</tr>\n";
4697        }
4698        print "</table>".
4699              "</div>\n";
4700
4701        print "<div class=\"page_body\">\n";
4702        git_print_log($co{'comment'});
4703        print "</div>\n";
4704
4705        git_difftree_body(\@difftree, $hash, @$parents);
4706
4707        git_footer_html();
4708}
4709
4710sub git_object {
4711        # object is defined by:
4712        # - hash or hash_base alone
4713        # - hash_base and file_name
4714        my $type;
4715
4716        # - hash or hash_base alone
4717        if ($hash || ($hash_base && !defined $file_name)) {
4718                my $object_id = $hash || $hash_base;
4719
4720                my $git_command = git_cmd_str();
4721                open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4722                        or die_error('404 Not Found', "Object does not exist");
4723                $type = <$fd>;
4724                chomp $type;
4725                close $fd
4726                        or die_error('404 Not Found', "Object does not exist");
4727
4728        # - hash_base and file_name
4729        } elsif ($hash_base && defined $file_name) {
4730                $file_name =~ s,/+$,,;
4731
4732                system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4733                        or die_error('404 Not Found', "Base object does not exist");
4734
4735                # here errors should not hapen
4736                open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4737                        or die_error(undef, "Open git-ls-tree failed");
4738                my $line = <$fd>;
4739                close $fd;
4740
4741                #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4742                unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4743                        die_error('404 Not Found', "File or directory for given base does not exist");
4744                }
4745                $type = $2;
4746                $hash = $3;
4747        } else {
4748                die_error('404 Not Found', "Not enough information to find object");
4749        }
4750
4751        print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4752                                          hash=>$hash, hash_base=>$hash_base,
4753                                          file_name=>$file_name),
4754                             -status => '302 Found');
4755}
4756
4757sub git_blobdiff {
4758        my $format = shift || 'html';
4759
4760        my $fd;
4761        my @difftree;
4762        my %diffinfo;
4763        my $expires;
4764
4765        # preparing $fd and %diffinfo for git_patchset_body
4766        # new style URI
4767        if (defined $hash_base && defined $hash_parent_base) {
4768                if (defined $file_name) {
4769                        # read raw output
4770                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4771                                $hash_parent_base, $hash_base,
4772                                "--", (defined $file_parent ? $file_parent : ()), $file_name
4773                                or die_error(undef, "Open git-diff-tree failed");
4774                        @difftree = map { chomp; $_ } <$fd>;
4775                        close $fd
4776                                or die_error(undef, "Reading git-diff-tree failed");
4777                        @difftree
4778                                or die_error('404 Not Found', "Blob diff not found");
4779
4780                } elsif (defined $hash &&
4781                         $hash =~ /[0-9a-fA-F]{40}/) {
4782                        # try to find filename from $hash
4783
4784                        # read filtered raw output
4785                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4786                                $hash_parent_base, $hash_base, "--"
4787                                or die_error(undef, "Open git-diff-tree failed");
4788                        @difftree =
4789                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4790                                # $hash == to_id
4791                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4792                                map { chomp; $_ } <$fd>;
4793                        close $fd
4794                                or die_error(undef, "Reading git-diff-tree failed");
4795                        @difftree
4796                                or die_error('404 Not Found', "Blob diff not found");
4797
4798                } else {
4799                        die_error('404 Not Found', "Missing one of the blob diff parameters");
4800                }
4801
4802                if (@difftree > 1) {
4803                        die_error('404 Not Found', "Ambiguous blob diff specification");
4804                }
4805
4806                %diffinfo = parse_difftree_raw_line($difftree[0]);
4807                $file_parent ||= $diffinfo{'from_file'} || $file_name;
4808                $file_name   ||= $diffinfo{'to_file'};
4809
4810                $hash_parent ||= $diffinfo{'from_id'};
4811                $hash        ||= $diffinfo{'to_id'};
4812
4813                # non-textual hash id's can be cached
4814                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4815                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4816                        $expires = '+1d';
4817                }
4818
4819                # open patch output
4820                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4821                        '-p', ($format eq 'html' ? "--full-index" : ()),
4822                        $hash_parent_base, $hash_base,
4823                        "--", (defined $file_parent ? $file_parent : ()), $file_name
4824                        or die_error(undef, "Open git-diff-tree failed");
4825        }
4826
4827        # old/legacy style URI
4828        if (!%diffinfo && # if new style URI failed
4829            defined $hash && defined $hash_parent) {
4830                # fake git-diff-tree raw output
4831                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4832                $diffinfo{'from_id'} = $hash_parent;
4833                $diffinfo{'to_id'}   = $hash;
4834                if (defined $file_name) {
4835                        if (defined $file_parent) {
4836                                $diffinfo{'status'} = '2';
4837                                $diffinfo{'from_file'} = $file_parent;
4838                                $diffinfo{'to_file'}   = $file_name;
4839                        } else { # assume not renamed
4840                                $diffinfo{'status'} = '1';
4841                                $diffinfo{'from_file'} = $file_name;
4842                                $diffinfo{'to_file'}   = $file_name;
4843                        }
4844                } else { # no filename given
4845                        $diffinfo{'status'} = '2';
4846                        $diffinfo{'from_file'} = $hash_parent;
4847                        $diffinfo{'to_file'}   = $hash;
4848                }
4849
4850                # non-textual hash id's can be cached
4851                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4852                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4853                        $expires = '+1d';
4854                }
4855
4856                # open patch output
4857                open $fd, "-|", git_cmd(), "diff", @diff_opts,
4858                        '-p', ($format eq 'html' ? "--full-index" : ()),
4859                        $hash_parent, $hash, "--"
4860                        or die_error(undef, "Open git-diff failed");
4861        } else  {
4862                die_error('404 Not Found', "Missing one of the blob diff parameters")
4863                        unless %diffinfo;
4864        }
4865
4866        # header
4867        if ($format eq 'html') {
4868                my $formats_nav =
4869                        $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
4870                                "raw");
4871                git_header_html(undef, $expires);
4872                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4873                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4874                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4875                } else {
4876                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4877                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4878                }
4879                if (defined $file_name) {
4880                        git_print_page_path($file_name, "blob", $hash_base);
4881                } else {
4882                        print "<div class=\"page_path\"></div>\n";
4883                }
4884
4885        } elsif ($format eq 'plain') {
4886                print $cgi->header(
4887                        -type => 'text/plain',
4888                        -charset => 'utf-8',
4889                        -expires => $expires,
4890                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4891
4892                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4893
4894        } else {
4895                die_error(undef, "Unknown blobdiff format");
4896        }
4897
4898        # patch
4899        if ($format eq 'html') {
4900                print "<div class=\"page_body\">\n";
4901
4902                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4903                close $fd;
4904
4905                print "</div>\n"; # class="page_body"
4906                git_footer_html();
4907
4908        } else {
4909                while (my $line = <$fd>) {
4910                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4911                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4912
4913                        print $line;
4914
4915                        last if $line =~ m!^\+\+\+!;
4916                }
4917                local $/ = undef;
4918                print <$fd>;
4919                close $fd;
4920        }
4921}
4922
4923sub git_blobdiff_plain {
4924        git_blobdiff('plain');
4925}
4926
4927sub git_commitdiff {
4928        my $format = shift || 'html';
4929        $hash ||= $hash_base || "HEAD";
4930        my %co = parse_commit($hash);
4931        if (!%co) {
4932                die_error(undef, "Unknown commit object");
4933        }
4934
4935        # choose format for commitdiff for merge
4936        if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4937                $hash_parent = '--cc';
4938        }
4939        # we need to prepare $formats_nav before almost any parameter munging
4940        my $formats_nav;
4941        if ($format eq 'html') {
4942                $formats_nav =
4943                        $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
4944                                "raw");
4945
4946                if (defined $hash_parent &&
4947                    $hash_parent ne '-c' && $hash_parent ne '--cc') {
4948                        # commitdiff with two commits given
4949                        my $hash_parent_short = $hash_parent;
4950                        if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4951                                $hash_parent_short = substr($hash_parent, 0, 7);
4952                        }
4953                        $formats_nav .=
4954                                ' (from';
4955                        for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4956                                if ($co{'parents'}[$i] eq $hash_parent) {
4957                                        $formats_nav .= ' parent ' . ($i+1);
4958                                        last;
4959                                }
4960                        }
4961                        $formats_nav .= ': ' .
4962                                $cgi->a({-href => href(action=>"commitdiff",
4963                                                       hash=>$hash_parent)},
4964                                        esc_html($hash_parent_short)) .
4965                                ')';
4966                } elsif (!$co{'parent'}) {
4967                        # --root commitdiff
4968                        $formats_nav .= ' (initial)';
4969                } elsif (scalar @{$co{'parents'}} == 1) {
4970                        # single parent commit
4971                        $formats_nav .=
4972                                ' (parent: ' .
4973                                $cgi->a({-href => href(action=>"commitdiff",
4974                                                       hash=>$co{'parent'})},
4975                                        esc_html(substr($co{'parent'}, 0, 7))) .
4976                                ')';
4977                } else {
4978                        # merge commit
4979                        if ($hash_parent eq '--cc') {
4980                                $formats_nav .= ' | ' .
4981                                        $cgi->a({-href => href(action=>"commitdiff",
4982                                                               hash=>$hash, hash_parent=>'-c')},
4983                                                'combined');
4984                        } else { # $hash_parent eq '-c'
4985                                $formats_nav .= ' | ' .
4986                                        $cgi->a({-href => href(action=>"commitdiff",
4987                                                               hash=>$hash, hash_parent=>'--cc')},
4988                                                'compact');
4989                        }
4990                        $formats_nav .=
4991                                ' (merge: ' .
4992                                join(' ', map {
4993                                        $cgi->a({-href => href(action=>"commitdiff",
4994                                                               hash=>$_)},
4995                                                esc_html(substr($_, 0, 7)));
4996                                } @{$co{'parents'}} ) .
4997                                ')';
4998                }
4999        }
5000
5001        my $hash_parent_param = $hash_parent;
5002        if (!defined $hash_parent_param) {
5003                # --cc for multiple parents, --root for parentless
5004                $hash_parent_param =
5005                        @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5006        }
5007
5008        # read commitdiff
5009        my $fd;
5010        my @difftree;
5011        if ($format eq 'html') {
5012                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5013                        "--no-commit-id", "--patch-with-raw", "--full-index",
5014                        $hash_parent_param, $hash, "--"
5015                        or die_error(undef, "Open git-diff-tree failed");
5016
5017                while (my $line = <$fd>) {
5018                        chomp $line;
5019                        # empty line ends raw part of diff-tree output
5020                        last unless $line;
5021                        push @difftree, scalar parse_difftree_raw_line($line);
5022                }
5023
5024        } elsif ($format eq 'plain') {
5025                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5026                        '-p', $hash_parent_param, $hash, "--"
5027                        or die_error(undef, "Open git-diff-tree failed");
5028
5029        } else {
5030                die_error(undef, "Unknown commitdiff format");
5031        }
5032
5033        # non-textual hash id's can be cached
5034        my $expires;
5035        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5036                $expires = "+1d";
5037        }
5038
5039        # write commit message
5040        if ($format eq 'html') {
5041                my $refs = git_get_references();
5042                my $ref = format_ref_marker($refs, $co{'id'});
5043
5044                git_header_html(undef, $expires);
5045                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5046                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5047                git_print_authorship(\%co);
5048                print "<div class=\"page_body\">\n";
5049                if (@{$co{'comment'}} > 1) {
5050                        print "<div class=\"log\">\n";
5051                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5052                        print "</div>\n"; # class="log"
5053                }
5054
5055        } elsif ($format eq 'plain') {
5056                my $refs = git_get_references("tags");
5057                my $tagname = git_get_rev_name_tags($hash);
5058                my $filename = basename($project) . "-$hash.patch";
5059
5060                print $cgi->header(
5061                        -type => 'text/plain',
5062                        -charset => 'utf-8',
5063                        -expires => $expires,
5064                        -content_disposition => 'inline; filename="' . "$filename" . '"');
5065                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5066                print "From: " . to_utf8($co{'author'}) . "\n";
5067                print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5068                print "Subject: " . to_utf8($co{'title'}) . "\n";
5069
5070                print "X-Git-Tag: $tagname\n" if $tagname;
5071                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5072
5073                foreach my $line (@{$co{'comment'}}) {
5074                        print to_utf8($line) . "\n";
5075                }
5076                print "---\n\n";
5077        }
5078
5079        # write patch
5080        if ($format eq 'html') {
5081                my $use_parents = !defined $hash_parent ||
5082                        $hash_parent eq '-c' || $hash_parent eq '--cc';
5083                git_difftree_body(\@difftree, $hash,
5084                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
5085                print "<br/>\n";
5086
5087                git_patchset_body($fd, \@difftree, $hash,
5088                                  $use_parents ? @{$co{'parents'}} : $hash_parent);
5089                close $fd;
5090                print "</div>\n"; # class="page_body"
5091                git_footer_html();
5092
5093        } elsif ($format eq 'plain') {
5094                local $/ = undef;
5095                print <$fd>;
5096                close $fd
5097                        or print "Reading git-diff-tree failed\n";
5098        }
5099}
5100
5101sub git_commitdiff_plain {
5102        git_commitdiff('plain');
5103}
5104
5105sub git_history {
5106        if (!defined $hash_base) {
5107                $hash_base = git_get_head_hash($project);
5108        }
5109        if (!defined $page) {
5110                $page = 0;
5111        }
5112        my $ftype;
5113        my %co = parse_commit($hash_base);
5114        if (!%co) {
5115                die_error(undef, "Unknown commit object");
5116        }
5117
5118        my $refs = git_get_references();
5119        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5120
5121        if (!defined $hash && defined $file_name) {
5122                $hash = git_get_hash_by_path($hash_base, $file_name);
5123        }
5124        if (defined $hash) {
5125                $ftype = git_get_type($hash);
5126        }
5127
5128        my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
5129
5130        my $paging_nav = '';
5131        if ($page > 0) {
5132                $paging_nav .=
5133                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5134                                               file_name=>$file_name)},
5135                                "first");
5136                $paging_nav .= " &sdot; " .
5137                        $cgi->a({-href => href(-replay=>1, page=>$page-1),
5138                                 -accesskey => "p", -title => "Alt-p"}, "prev");
5139        } else {
5140                $paging_nav .= "first";
5141                $paging_nav .= " &sdot; prev";
5142        }
5143        my $next_link = '';
5144        if ($#commitlist >= 100) {
5145                $next_link =
5146                        $cgi->a({-href => href(-replay=>1, page=>$page+1),
5147                                 -accesskey => "n", -title => "Alt-n"}, "next");
5148                $paging_nav .= " &sdot; $next_link";
5149        } else {
5150                $paging_nav .= " &sdot; next";
5151        }
5152
5153        git_header_html();
5154        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5155        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5156        git_print_page_path($file_name, $ftype, $hash_base);
5157
5158        git_history_body(\@commitlist, 0, 99,
5159                         $refs, $hash_base, $ftype, $next_link);
5160
5161        git_footer_html();
5162}
5163
5164sub git_search {
5165        my ($have_search) = gitweb_check_feature('search');
5166        if (!$have_search) {
5167                die_error('403 Permission denied', "Permission denied");
5168        }
5169        if (!defined $searchtext) {
5170                die_error(undef, "Text field empty");
5171        }
5172        if (!defined $hash) {
5173                $hash = git_get_head_hash($project);
5174        }
5175        my %co = parse_commit($hash);
5176        if (!%co) {
5177                die_error(undef, "Unknown commit object");
5178        }
5179        if (!defined $page) {
5180                $page = 0;
5181        }
5182
5183        $searchtype ||= 'commit';
5184        if ($searchtype eq 'pickaxe') {
5185                # pickaxe may take all resources of your box and run for several minutes
5186                # with every query - so decide by yourself how public you make this feature
5187                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5188                if (!$have_pickaxe) {
5189                        die_error('403 Permission denied', "Permission denied");
5190                }
5191        }
5192        if ($searchtype eq 'grep') {
5193                my ($have_grep) = gitweb_check_feature('grep');
5194                if (!$have_grep) {
5195                        die_error('403 Permission denied', "Permission denied");
5196                }
5197        }
5198
5199        git_header_html();
5200
5201        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5202                my $greptype;
5203                if ($searchtype eq 'commit') {
5204                        $greptype = "--grep=";
5205                } elsif ($searchtype eq 'author') {
5206                        $greptype = "--author=";
5207                } elsif ($searchtype eq 'committer') {
5208                        $greptype = "--committer=";
5209                }
5210                $greptype .= $search_regexp;
5211                my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
5212
5213                my $paging_nav = '';
5214                if ($page > 0) {
5215                        $paging_nav .=
5216                                $cgi->a({-href => href(action=>"search", hash=>$hash,
5217                                                       searchtext=>$searchtext, searchtype=>$searchtype)},
5218                                        "first");
5219                        $paging_nav .= " &sdot; " .
5220                                $cgi->a({-href => href(-replay=>1, page=>$page-1),
5221                                         -accesskey => "p", -title => "Alt-p"}, "prev");
5222                } else {
5223                        $paging_nav .= "first";
5224                        $paging_nav .= " &sdot; prev";
5225                }
5226                my $next_link = '';
5227                if ($#commitlist >= 100) {
5228                        $next_link =
5229                                $cgi->a({-href => href(-replay=>1, page=>$page+1),
5230                                         -accesskey => "n", -title => "Alt-n"}, "next");
5231                        $paging_nav .= " &sdot; $next_link";
5232                } else {
5233                        $paging_nav .= " &sdot; next";
5234                }
5235
5236                if ($#commitlist >= 100) {
5237                }
5238
5239                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5240                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5241                git_search_grep_body(\@commitlist, 0, 99, $next_link);
5242        }
5243
5244        if ($searchtype eq 'pickaxe') {
5245                git_print_page_nav('','', $hash,$co{'tree'},$hash);
5246                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5247
5248                print "<table class=\"pickaxe search\">\n";
5249                my $alternate = 1;
5250                $/ = "\n";
5251                my $git_command = git_cmd_str();
5252                my $searchqtext = $searchtext;
5253                $searchqtext =~ s/'/'\\''/;
5254                open my $fd, "-|", "$git_command rev-list $hash | " .
5255                        "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5256                undef %co;
5257                my @files;
5258                while (my $line = <$fd>) {
5259                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5260                                my %set;
5261                                $set{'file'} = $6;
5262                                $set{'from_id'} = $3;
5263                                $set{'to_id'} = $4;
5264                                $set{'id'} = $set{'to_id'};
5265                                if ($set{'id'} =~ m/0{40}/) {
5266                                        $set{'id'} = $set{'from_id'};
5267                                }
5268                                if ($set{'id'} =~ m/0{40}/) {
5269                                        next;
5270                                }
5271                                push @files, \%set;
5272                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5273                                if (%co) {
5274                                        if ($alternate) {
5275                                                print "<tr class=\"dark\">\n";
5276                                        } else {
5277                                                print "<tr class=\"light\">\n";
5278                                        }
5279                                        $alternate ^= 1;
5280                                        my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5281                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5282                                              "<td><i>" . $author . "</i></td>\n" .
5283                                              "<td>" .
5284                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5285                                                      -class => "list subject"},
5286                                                      chop_and_escape_str($co{'title'}, 50) . "<br/>");
5287                                        while (my $setref = shift @files) {
5288                                                my %set = %$setref;
5289                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5290                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
5291                                                              -class => "list"},
5292                                                              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5293                                                      "<br/>\n";
5294                                        }
5295                                        print "</td>\n" .
5296                                              "<td class=\"link\">" .
5297                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5298                                              " | " .
5299                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5300                                        print "</td>\n" .
5301                                              "</tr>\n";
5302                                }
5303                                %co = parse_commit($1);
5304                        }
5305                }
5306                close $fd;
5307
5308                print "</table>\n";
5309        }
5310
5311        if ($searchtype eq 'grep') {
5312                git_print_page_nav('','', $hash,$co{'tree'},$hash);
5313                git_print_header_div('commit', esc_html($co{'title'}), $hash);
5314
5315                print "<table class=\"grep_search\">\n";
5316                my $alternate = 1;
5317                my $matches = 0;
5318                $/ = "\n";
5319                open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5320                my $lastfile = '';
5321                while (my $line = <$fd>) {
5322                        chomp $line;
5323                        my ($file, $lno, $ltext, $binary);
5324                        last if ($matches++ > 1000);
5325                        if ($line =~ /^Binary file (.+) matches$/) {
5326                                $file = $1;
5327                                $binary = 1;
5328                        } else {
5329                                (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5330                        }
5331                        if ($file ne $lastfile) {
5332                                $lastfile and print "</td></tr>\n";
5333                                if ($alternate++) {
5334                                        print "<tr class=\"dark\">\n";
5335                                } else {
5336                                        print "<tr class=\"light\">\n";
5337                                }
5338                                print "<td class=\"list\">".
5339                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5340                                                               file_name=>"$file"),
5341                                                -class => "list"}, esc_path($file));
5342                                print "</td><td>\n";
5343                                $lastfile = $file;
5344                        }
5345                        if ($binary) {
5346                                print "<div class=\"binary\">Binary file</div>\n";
5347                        } else {
5348                                $ltext = untabify($ltext);
5349                                if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5350                                        $ltext = esc_html($1, -nbsp=>1);
5351                                        $ltext .= '<span class="match">';
5352                                        $ltext .= esc_html($2, -nbsp=>1);
5353                                        $ltext .= '</span>';
5354                                        $ltext .= esc_html($3, -nbsp=>1);
5355                                } else {
5356                                        $ltext = esc_html($ltext, -nbsp=>1);
5357                                }
5358                                print "<div class=\"pre\">" .
5359                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5360                                                               file_name=>"$file").'#l'.$lno,
5361                                                -class => "linenr"}, sprintf('%4i', $lno))
5362                                        . ' ' .  $ltext . "</div>\n";
5363                        }
5364                }
5365                if ($lastfile) {
5366                        print "</td></tr>\n";
5367                        if ($matches > 1000) {
5368                                print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5369                        }
5370                } else {
5371                        print "<div class=\"diff nodifferences\">No matches found</div>\n";
5372                }
5373                close $fd;
5374
5375                print "</table>\n";
5376        }
5377        git_footer_html();
5378}
5379
5380sub git_search_help {
5381        git_header_html();
5382        git_print_page_nav('','', $hash,$hash,$hash);
5383        print <<EOT;
5384<dl>
5385<dt><b>commit</b></dt>
5386<dd>The commit messages and authorship information will be scanned for the given string.</dd>
5387EOT
5388        my ($have_grep) = gitweb_check_feature('grep');
5389        if ($have_grep) {
5390                print <<EOT;
5391<dt><b>grep</b></dt>
5392<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5393    a different one) are searched for the given
5394<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5395(POSIX extended) and the matches are listed. On large
5396trees, this search can take a while and put some strain on the server, so please use it with
5397some consideration.</dd>
5398EOT
5399        }
5400        print <<EOT;
5401<dt><b>author</b></dt>
5402<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5403<dt><b>committer</b></dt>
5404<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5405EOT
5406        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5407        if ($have_pickaxe) {
5408                print <<EOT;
5409<dt><b>pickaxe</b></dt>
5410<dd>All commits that caused the string to appear or disappear from any file (changes that
5411added, removed or "modified" the string) will be listed. This search can take a while and
5412takes a lot of strain on the server, so please use it wisely.</dd>
5413EOT
5414        }
5415        print "</dl>\n";
5416        git_footer_html();
5417}
5418
5419sub git_shortlog {
5420        my $head = git_get_head_hash($project);
5421        if (!defined $hash) {
5422                $hash = $head;
5423        }
5424        if (!defined $page) {
5425                $page = 0;
5426        }
5427        my $refs = git_get_references();
5428
5429        my @commitlist = parse_commits($hash, 101, (100 * $page));
5430
5431        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5432        my $next_link = '';
5433        if ($#commitlist >= 100) {
5434                $next_link =
5435                        $cgi->a({-href => href(-replay=>1, page=>$page+1),
5436                                 -accesskey => "n", -title => "Alt-n"}, "next");
5437        }
5438
5439        git_header_html();
5440        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5441        git_print_header_div('summary', $project);
5442
5443        git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5444
5445        git_footer_html();
5446}
5447
5448## ......................................................................
5449## feeds (RSS, Atom; OPML)
5450
5451sub git_feed {
5452        my $format = shift || 'atom';
5453        my ($have_blame) = gitweb_check_feature('blame');
5454
5455        # Atom: http://www.atomenabled.org/developers/syndication/
5456        # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5457        if ($format ne 'rss' && $format ne 'atom') {
5458                die_error(undef, "Unknown web feed format");
5459        }
5460
5461        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5462        my $head = $hash || 'HEAD';
5463        my @commitlist = parse_commits($head, 150, 0, undef, $file_name);
5464
5465        my %latest_commit;
5466        my %latest_date;
5467        my $content_type = "application/$format+xml";
5468        if (defined $cgi->http('HTTP_ACCEPT') &&
5469                 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5470                # browser (feed reader) prefers text/xml
5471                $content_type = 'text/xml';
5472        }
5473        if (defined($commitlist[0])) {
5474                %latest_commit = %{$commitlist[0]};
5475                %latest_date   = parse_date($latest_commit{'author_epoch'});
5476                print $cgi->header(
5477                        -type => $content_type,
5478                        -charset => 'utf-8',
5479                        -last_modified => $latest_date{'rfc2822'});
5480        } else {
5481                print $cgi->header(
5482                        -type => $content_type,
5483                        -charset => 'utf-8');
5484        }
5485
5486        # Optimization: skip generating the body if client asks only
5487        # for Last-Modified date.
5488        return if ($cgi->request_method() eq 'HEAD');
5489
5490        # header variables
5491        my $title = "$site_name - $project/$action";
5492        my $feed_type = 'log';
5493        if (defined $hash) {
5494                $title .= " - '$hash'";
5495                $feed_type = 'branch log';
5496                if (defined $file_name) {
5497                        $title .= " :: $file_name";
5498                        $feed_type = 'history';
5499                }
5500        } elsif (defined $file_name) {
5501                $title .= " - $file_name";
5502                $feed_type = 'history';
5503        }
5504        $title .= " $feed_type";
5505        my $descr = git_get_project_description($project);
5506        if (defined $descr) {
5507                $descr = esc_html($descr);
5508        } else {
5509                $descr = "$project " .
5510                         ($format eq 'rss' ? 'RSS' : 'Atom') .
5511                         " feed";
5512        }
5513        my $owner = git_get_project_owner($project);
5514        $owner = esc_html($owner);
5515
5516        #header
5517        my $alt_url;
5518        if (defined $file_name) {
5519                $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5520        } elsif (defined $hash) {
5521                $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5522        } else {
5523                $alt_url = href(-full=>1, action=>"summary");
5524        }
5525        print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5526        if ($format eq 'rss') {
5527                print <<XML;
5528<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5529<channel>
5530XML
5531                print "<title>$title</title>\n" .
5532                      "<link>$alt_url</link>\n" .
5533                      "<description>$descr</description>\n" .
5534                      "<language>en</language>\n";
5535        } elsif ($format eq 'atom') {
5536                print <<XML;
5537<feed xmlns="http://www.w3.org/2005/Atom">
5538XML
5539                print "<title>$title</title>\n" .
5540                      "<subtitle>$descr</subtitle>\n" .
5541                      '<link rel="alternate" type="text/html" href="' .
5542                      $alt_url . '" />' . "\n" .
5543                      '<link rel="self" type="' . $content_type . '" href="' .
5544                      $cgi->self_url() . '" />' . "\n" .
5545                      "<id>" . href(-full=>1) . "</id>\n" .
5546                      # use project owner for feed author
5547                      "<author><name>$owner</name></author>\n";
5548                if (defined $favicon) {
5549                        print "<icon>" . esc_url($favicon) . "</icon>\n";
5550                }
5551                if (defined $logo_url) {
5552                        # not twice as wide as tall: 72 x 27 pixels
5553                        print "<logo>" . esc_url($logo) . "</logo>\n";
5554                }
5555                if (! %latest_date) {
5556                        # dummy date to keep the feed valid until commits trickle in:
5557                        print "<updated>1970-01-01T00:00:00Z</updated>\n";
5558                } else {
5559                        print "<updated>$latest_date{'iso-8601'}</updated>\n";
5560                }
5561        }
5562
5563        # contents
5564        for (my $i = 0; $i <= $#commitlist; $i++) {
5565                my %co = %{$commitlist[$i]};
5566                my $commit = $co{'id'};
5567                # we read 150, we always show 30 and the ones more recent than 48 hours
5568                if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5569                        last;
5570                }
5571                my %cd = parse_date($co{'author_epoch'});
5572
5573                # get list of changed files
5574                open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5575                        $co{'parent'} || "--root",
5576                        $co{'id'}, "--", (defined $file_name ? $file_name : ())
5577                        or next;
5578                my @difftree = map { chomp; $_ } <$fd>;
5579                close $fd
5580                        or next;
5581
5582                # print element (entry, item)
5583                my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
5584                if ($format eq 'rss') {
5585                        print "<item>\n" .
5586                              "<title>" . esc_html($co{'title'}) . "</title>\n" .
5587                              "<author>" . esc_html($co{'author'}) . "</author>\n" .
5588                              "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5589                              "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5590                              "<link>$co_url</link>\n" .
5591                              "<description>" . esc_html($co{'title'}) . "</description>\n" .
5592                              "<content:encoded>" .
5593                              "<![CDATA[\n";
5594                } elsif ($format eq 'atom') {
5595                        print "<entry>\n" .
5596                              "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5597                              "<updated>$cd{'iso-8601'}</updated>\n" .
5598                              "<author>\n" .
5599                              "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5600                        if ($co{'author_email'}) {
5601                                print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5602                        }
5603                        print "</author>\n" .
5604                              # use committer for contributor
5605                              "<contributor>\n" .
5606                              "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5607                        if ($co{'committer_email'}) {
5608                                print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5609                        }
5610                        print "</contributor>\n" .
5611                              "<published>$cd{'iso-8601'}</published>\n" .
5612                              "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5613                              "<id>$co_url</id>\n" .
5614                              "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5615                              "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5616                }
5617                my $comment = $co{'comment'};
5618                print "<pre>\n";
5619                foreach my $line (@$comment) {
5620                        $line = esc_html($line);
5621                        print "$line\n";
5622                }
5623                print "</pre><ul>\n";
5624                foreach my $difftree_line (@difftree) {
5625                        my %difftree = parse_difftree_raw_line($difftree_line);
5626                        next if !$difftree{'from_id'};
5627
5628                        my $file = $difftree{'file'} || $difftree{'to_file'};
5629
5630                        print "<li>" .
5631                              "[" .
5632                              $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5633                                                     hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5634                                                     hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5635                                                     file_name=>$file, file_parent=>$difftree{'from_file'}),
5636                                      -title => "diff"}, 'D');
5637                        if ($have_blame) {
5638                                print $cgi->a({-href => href(-full=>1, action=>"blame",
5639                                                             file_name=>$file, hash_base=>$commit),
5640                                              -title => "blame"}, 'B');
5641                        }
5642                        # if this is not a feed of a file history
5643                        if (!defined $file_name || $file_name ne $file) {
5644                                print $cgi->a({-href => href(-full=>1, action=>"history",
5645                                                             file_name=>$file, hash=>$commit),
5646                                              -title => "history"}, 'H');
5647                        }
5648                        $file = esc_path($file);
5649                        print "] ".
5650                              "$file</li>\n";
5651                }
5652                if ($format eq 'rss') {
5653                        print "</ul>]]>\n" .
5654                              "</content:encoded>\n" .
5655                              "</item>\n";
5656                } elsif ($format eq 'atom') {
5657                        print "</ul>\n</div>\n" .
5658                              "</content>\n" .
5659                              "</entry>\n";
5660                }
5661        }
5662
5663        # end of feed
5664        if ($format eq 'rss') {
5665                print "</channel>\n</rss>\n";
5666        }       elsif ($format eq 'atom') {
5667                print "</feed>\n";
5668        }
5669}
5670
5671sub git_rss {
5672        git_feed('rss');
5673}
5674
5675sub git_atom {
5676        git_feed('atom');
5677}
5678
5679sub git_opml {
5680        my @list = git_get_projects_list();
5681
5682        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5683        print <<XML;
5684<?xml version="1.0" encoding="utf-8"?>
5685<opml version="1.0">
5686<head>
5687  <title>$site_name OPML Export</title>
5688</head>
5689<body>
5690<outline text="git RSS feeds">
5691XML
5692
5693        foreach my $pr (@list) {
5694                my %proj = %$pr;
5695                my $head = git_get_head_hash($proj{'path'});
5696                if (!defined $head) {
5697                        next;
5698                }
5699                $git_dir = "$projectroot/$proj{'path'}";
5700                my %co = parse_commit($head);
5701                if (!%co) {
5702                        next;
5703                }
5704
5705                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5706                my $rss  = "$my_url?p=$proj{'path'};a=rss";
5707                my $html = "$my_url?p=$proj{'path'};a=summary";
5708                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5709        }
5710        print <<XML;
5711</outline>
5712</body>
5713</opml>
5714XML
5715}