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