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