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