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