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