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