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