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 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info=$ENV{"PATH_INFO"}; 56if($path_info) { 57if($my_url=~ s,\Q$path_info\E$,, && 58$my_uri=~ s,\Q$path_info\E$,, && 59defined$ENV{'SCRIPT_NAME'}) { 60$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 61} 62} 63 64# target of the home link on top of all pages 65our$home_link=$my_uri||"/"; 66} 67 68# core git executable to use 69# this can just be "git" if your webserver has a sensible PATH 70our$GIT="++GIT_BINDIR++/git"; 71 72# absolute fs-path which will be prepended to the project path 73#our $projectroot = "/pub/scm"; 74our$projectroot="++GITWEB_PROJECTROOT++"; 75 76# fs traversing limit for getting project list 77# the number is relative to the projectroot 78our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 79 80# string of the home link on top of all pages 81our$home_link_str="++GITWEB_HOME_LINK_STR++"; 82 83# name of your site or organization to appear in page titles 84# replace this with something more descriptive for clearer bookmarks 85our$site_name="++GITWEB_SITENAME++" 86|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 87 88# filename of html text to include at top of each page 89our$site_header="++GITWEB_SITE_HEADER++"; 90# html text to include at home page 91our$home_text="++GITWEB_HOMETEXT++"; 92# filename of html text to include at bottom of each page 93our$site_footer="++GITWEB_SITE_FOOTER++"; 94 95# URI of stylesheets 96our@stylesheets= ("++GITWEB_CSS++"); 97# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 98our$stylesheet=undef; 99# URI of GIT logo (72x27 size) 100our$logo="++GITWEB_LOGO++"; 101# URI of GIT favicon, assumed to be image/png type 102our$favicon="++GITWEB_FAVICON++"; 103# URI of gitweb.js (JavaScript code for gitweb) 104our$javascript="++GITWEB_JS++"; 105 106# URI and label (title) of GIT logo link 107#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 108#our $logo_label = "git documentation"; 109our$logo_url="http://git-scm.com/"; 110our$logo_label="git homepage"; 111 112# source of projects list 113our$projects_list="++GITWEB_LIST++"; 114 115# the width (in characters) of the projects list "Description" column 116our$projects_list_description_width=25; 117 118# group projects by category on the projects list 119# (enabled if this variable evaluates to true) 120our$projects_list_group_categories=0; 121 122# default category if none specified 123# (leave the empty string for no category) 124our$project_list_default_category=""; 125 126# default order of projects list 127# valid values are none, project, descr, owner, and age 128our$default_projects_order="project"; 129 130# show repository only if this file exists 131# (only effective if this variable evaluates to true) 132our$export_ok="++GITWEB_EXPORT_OK++"; 133 134# show repository only if this subroutine returns true 135# when given the path to the project, for example: 136# sub { return -e "$_[0]/git-daemon-export-ok"; } 137our$export_auth_hook=undef; 138 139# only allow viewing of repositories also shown on the overview page 140our$strict_export="++GITWEB_STRICT_EXPORT++"; 141 142# list of git base URLs used for URL to where fetch project from, 143# i.e. full URL is "$git_base_url/$project" 144our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 145 146# default blob_plain mimetype and default charset for text/plain blob 147our$default_blob_plain_mimetype='text/plain'; 148our$default_text_plain_charset=undef; 149 150# file to use for guessing MIME types before trying /etc/mime.types 151# (relative to the current git repository) 152our$mimetypes_file=undef; 153 154# assume this charset if line contains non-UTF-8 characters; 155# it should be valid encoding (see Encoding::Supported(3pm) for list), 156# for which encoding all byte sequences are valid, for example 157# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 158# could be even 'utf-8' for the old behavior) 159our$fallback_encoding='latin1'; 160 161# rename detection options for git-diff and git-diff-tree 162# - default is '-M', with the cost proportional to 163# (number of removed files) * (number of new files). 164# - more costly is '-C' (which implies '-M'), with the cost proportional to 165# (number of changed files + number of removed files) * (number of new files) 166# - even more costly is '-C', '--find-copies-harder' with cost 167# (number of files in the original tree) * (number of new files) 168# - one might want to include '-B' option, e.g. '-B', '-M' 169our@diff_opts= ('-M');# taken from git_commit 170 171# Disables features that would allow repository owners to inject script into 172# the gitweb domain. 173our$prevent_xss=0; 174 175# Path to the highlight executable to use (must be the one from 176# http://www.andre-simon.de due to assumptions about parameters and output). 177# Useful if highlight is not installed on your webserver's PATH. 178# [Default: highlight] 179our$highlight_bin="++HIGHLIGHT_BIN++"; 180 181# information about snapshot formats that gitweb is capable of serving 182our%known_snapshot_formats= ( 183# name => { 184# 'display' => display name, 185# 'type' => mime type, 186# 'suffix' => filename suffix, 187# 'format' => --format for git-archive, 188# 'compressor' => [compressor command and arguments] 189# (array reference, optional) 190# 'disabled' => boolean (optional)} 191# 192'tgz'=> { 193'display'=>'tar.gz', 194'type'=>'application/x-gzip', 195'suffix'=>'.tar.gz', 196'format'=>'tar', 197'compressor'=> ['gzip','-n']}, 198 199'tbz2'=> { 200'display'=>'tar.bz2', 201'type'=>'application/x-bzip2', 202'suffix'=>'.tar.bz2', 203'format'=>'tar', 204'compressor'=> ['bzip2']}, 205 206'txz'=> { 207'display'=>'tar.xz', 208'type'=>'application/x-xz', 209'suffix'=>'.tar.xz', 210'format'=>'tar', 211'compressor'=> ['xz'], 212'disabled'=>1}, 213 214'zip'=> { 215'display'=>'zip', 216'type'=>'application/x-zip', 217'suffix'=>'.zip', 218'format'=>'zip'}, 219); 220 221# Aliases so we understand old gitweb.snapshot values in repository 222# configuration. 223our%known_snapshot_format_aliases= ( 224'gzip'=>'tgz', 225'bzip2'=>'tbz2', 226'xz'=>'txz', 227 228# backward compatibility: legacy gitweb config support 229'x-gzip'=>undef,'gz'=>undef, 230'x-bzip2'=>undef,'bz2'=>undef, 231'x-zip'=>undef,''=>undef, 232); 233 234# Pixel sizes for icons and avatars. If the default font sizes or lineheights 235# are changed, it may be appropriate to change these values too via 236# $GITWEB_CONFIG. 237our%avatar_size= ( 238'default'=>16, 239'double'=>32 240); 241 242# Used to set the maximum load that we will still respond to gitweb queries. 243# If server load exceed this value then return "503 server busy" error. 244# If gitweb cannot determined server load, it is taken to be 0. 245# Leave it undefined (or set to 'undef') to turn off load checking. 246our$maxload=300; 247 248# configuration for 'highlight' (http://www.andre-simon.de/) 249# match by basename 250our%highlight_basename= ( 251#'Program' => 'py', 252#'Library' => 'py', 253'SConstruct'=>'py',# SCons equivalent of Makefile 254'Makefile'=>'make', 255); 256# match by extension 257our%highlight_ext= ( 258# main extensions, defining name of syntax; 259# see files in /usr/share/highlight/langDefs/ directory 260map{$_=>$_} 261qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 262# alternate extensions, see /etc/highlight/filetypes.conf 263'h'=>'c', 264map{$_=>'sh'}qw(bash zsh ksh), 265map{$_=>'cpp'}qw(cxx c++ cc), 266map{$_=>'php'}qw(php3 php4 php5 phps), 267map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 268map{$_=>'make'}qw(mak mk), 269map{$_=>'xml'}qw(xhtml html htm), 270); 271 272# You define site-wide feature defaults here; override them with 273# $GITWEB_CONFIG as necessary. 274our%feature= ( 275# feature => { 276# 'sub' => feature-sub (subroutine), 277# 'override' => allow-override (boolean), 278# 'default' => [ default options...] (array reference)} 279# 280# if feature is overridable (it means that allow-override has true value), 281# then feature-sub will be called with default options as parameters; 282# return value of feature-sub indicates if to enable specified feature 283# 284# if there is no 'sub' key (no feature-sub), then feature cannot be 285# overridden 286# 287# use gitweb_get_feature(<feature>) to retrieve the <feature> value 288# (an array) or gitweb_check_feature(<feature>) to check if <feature> 289# is enabled 290 291# Enable the 'blame' blob view, showing the last commit that modified 292# each line in the file. This can be very CPU-intensive. 293 294# To enable system wide have in $GITWEB_CONFIG 295# $feature{'blame'}{'default'} = [1]; 296# To have project specific config enable override in $GITWEB_CONFIG 297# $feature{'blame'}{'override'} = 1; 298# and in project config gitweb.blame = 0|1; 299'blame'=> { 300'sub'=>sub{ feature_bool('blame',@_) }, 301'override'=>0, 302'default'=> [0]}, 303 304# Enable the 'snapshot' link, providing a compressed archive of any 305# tree. This can potentially generate high traffic if you have large 306# project. 307 308# Value is a list of formats defined in %known_snapshot_formats that 309# you wish to offer. 310# To disable system wide have in $GITWEB_CONFIG 311# $feature{'snapshot'}{'default'} = []; 312# To have project specific config enable override in $GITWEB_CONFIG 313# $feature{'snapshot'}{'override'} = 1; 314# and in project config, a comma-separated list of formats or "none" 315# to disable. Example: gitweb.snapshot = tbz2,zip; 316'snapshot'=> { 317'sub'=> \&feature_snapshot, 318'override'=>0, 319'default'=> ['tgz']}, 320 321# Enable text search, which will list the commits which match author, 322# committer or commit text to a given string. Enabled by default. 323# Project specific override is not supported. 324# 325# Note that this controls all search features, which means that if 326# it is disabled, then 'grep' and 'pickaxe' search would also be 327# disabled. 328'search'=> { 329'override'=>0, 330'default'=> [1]}, 331 332# Enable grep search, which will list the files in currently selected 333# tree containing the given string. Enabled by default. This can be 334# potentially CPU-intensive, of course. 335# Note that you need to have 'search' feature enabled too. 336 337# To enable system wide have in $GITWEB_CONFIG 338# $feature{'grep'}{'default'} = [1]; 339# To have project specific config enable override in $GITWEB_CONFIG 340# $feature{'grep'}{'override'} = 1; 341# and in project config gitweb.grep = 0|1; 342'grep'=> { 343'sub'=>sub{ feature_bool('grep',@_) }, 344'override'=>0, 345'default'=> [1]}, 346 347# Enable the pickaxe search, which will list the commits that modified 348# a given string in a file. This can be practical and quite faster 349# alternative to 'blame', but still potentially CPU-intensive. 350# Note that you need to have 'search' feature enabled too. 351 352# To enable system wide have in $GITWEB_CONFIG 353# $feature{'pickaxe'}{'default'} = [1]; 354# To have project specific config enable override in $GITWEB_CONFIG 355# $feature{'pickaxe'}{'override'} = 1; 356# and in project config gitweb.pickaxe = 0|1; 357'pickaxe'=> { 358'sub'=>sub{ feature_bool('pickaxe',@_) }, 359'override'=>0, 360'default'=> [1]}, 361 362# Enable showing size of blobs in a 'tree' view, in a separate 363# column, similar to what 'ls -l' does. This cost a bit of IO. 364 365# To disable system wide have in $GITWEB_CONFIG 366# $feature{'show-sizes'}{'default'} = [0]; 367# To have project specific config enable override in $GITWEB_CONFIG 368# $feature{'show-sizes'}{'override'} = 1; 369# and in project config gitweb.showsizes = 0|1; 370'show-sizes'=> { 371'sub'=>sub{ feature_bool('showsizes',@_) }, 372'override'=>0, 373'default'=> [1]}, 374 375# Make gitweb use an alternative format of the URLs which can be 376# more readable and natural-looking: project name is embedded 377# directly in the path and the query string contains other 378# auxiliary information. All gitweb installations recognize 379# URL in either format; this configures in which formats gitweb 380# generates links. 381 382# To enable system wide have in $GITWEB_CONFIG 383# $feature{'pathinfo'}{'default'} = [1]; 384# Project specific override is not supported. 385 386# Note that you will need to change the default location of CSS, 387# favicon, logo and possibly other files to an absolute URL. Also, 388# if gitweb.cgi serves as your indexfile, you will need to force 389# $my_uri to contain the script name in your $GITWEB_CONFIG. 390'pathinfo'=> { 391'override'=>0, 392'default'=> [0]}, 393 394# Make gitweb consider projects in project root subdirectories 395# to be forks of existing projects. Given project $projname.git, 396# projects matching $projname/*.git will not be shown in the main 397# projects list, instead a '+' mark will be added to $projname 398# there and a 'forks' view will be enabled for the project, listing 399# all the forks. If project list is taken from a file, forks have 400# to be listed after the main project. 401 402# To enable system wide have in $GITWEB_CONFIG 403# $feature{'forks'}{'default'} = [1]; 404# Project specific override is not supported. 405'forks'=> { 406'override'=>0, 407'default'=> [0]}, 408 409# Insert custom links to the action bar of all project pages. 410# This enables you mainly to link to third-party scripts integrating 411# into gitweb; e.g. git-browser for graphical history representation 412# or custom web-based repository administration interface. 413 414# The 'default' value consists of a list of triplets in the form 415# (label, link, position) where position is the label after which 416# to insert the link and link is a format string where %n expands 417# to the project name, %f to the project path within the filesystem, 418# %h to the current hash (h gitweb parameter) and %b to the current 419# hash base (hb gitweb parameter); %% expands to %. 420 421# To enable system wide have in $GITWEB_CONFIG e.g. 422# $feature{'actions'}{'default'} = [('graphiclog', 423# '/git-browser/by-commit.html?r=%n', 'summary')]; 424# Project specific override is not supported. 425'actions'=> { 426'override'=>0, 427'default'=> []}, 428 429# Allow gitweb scan project content tags of project repository, 430# and display the popular Web 2.0-ish "tag cloud" near the projects 431# list. Note that this is something COMPLETELY different from the 432# normal Git tags. 433 434# gitweb by itself can show existing tags, but it does not handle 435# tagging itself; you need to do it externally, outside gitweb. 436# The format is described in git_get_project_ctags() subroutine. 437# You may want to install the HTML::TagCloud Perl module to get 438# a pretty tag cloud instead of just a list of tags. 439 440# To enable system wide have in $GITWEB_CONFIG 441# $feature{'ctags'}{'default'} = [1]; 442# Project specific override is not supported. 443 444# In the future whether ctags editing is enabled might depend 445# on the value, but using 1 should always mean no editing of ctags. 446'ctags'=> { 447'override'=>0, 448'default'=> [0]}, 449 450# The maximum number of patches in a patchset generated in patch 451# view. Set this to 0 or undef to disable patch view, or to a 452# negative number to remove any limit. 453 454# To disable system wide have in $GITWEB_CONFIG 455# $feature{'patches'}{'default'} = [0]; 456# To have project specific config enable override in $GITWEB_CONFIG 457# $feature{'patches'}{'override'} = 1; 458# and in project config gitweb.patches = 0|n; 459# where n is the maximum number of patches allowed in a patchset. 460'patches'=> { 461'sub'=> \&feature_patches, 462'override'=>0, 463'default'=> [16]}, 464 465# Avatar support. When this feature is enabled, views such as 466# shortlog or commit will display an avatar associated with 467# the email of the committer(s) and/or author(s). 468 469# Currently available providers are gravatar and picon. 470# If an unknown provider is specified, the feature is disabled. 471 472# Gravatar depends on Digest::MD5. 473# Picon currently relies on the indiana.edu database. 474 475# To enable system wide have in $GITWEB_CONFIG 476# $feature{'avatar'}{'default'} = ['<provider>']; 477# where <provider> is either gravatar or picon. 478# To have project specific config enable override in $GITWEB_CONFIG 479# $feature{'avatar'}{'override'} = 1; 480# and in project config gitweb.avatar = <provider>; 481'avatar'=> { 482'sub'=> \&feature_avatar, 483'override'=>0, 484'default'=> ['']}, 485 486# Enable displaying how much time and how many git commands 487# it took to generate and display page. Disabled by default. 488# Project specific override is not supported. 489'timed'=> { 490'override'=>0, 491'default'=> [0]}, 492 493# Enable turning some links into links to actions which require 494# JavaScript to run (like 'blame_incremental'). Not enabled by 495# default. Project specific override is currently not supported. 496'javascript-actions'=> { 497'override'=>0, 498'default'=> [0]}, 499 500# Enable and configure ability to change common timezone for dates 501# in gitweb output via JavaScript. Enabled by default. 502# Project specific override is not supported. 503'javascript-timezone'=> { 504'override'=>0, 505'default'=> [ 506'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 507# or undef to turn off this feature 508'gitweb_tz',# name of cookie where to store selected timezone 509'datetime',# CSS class used to mark up dates for manipulation 510]}, 511 512# Syntax highlighting support. This is based on Daniel Svensson's 513# and Sham Chukoury's work in gitweb-xmms2.git. 514# It requires the 'highlight' program present in $PATH, 515# and therefore is disabled by default. 516 517# To enable system wide have in $GITWEB_CONFIG 518# $feature{'highlight'}{'default'} = [1]; 519 520'highlight'=> { 521'sub'=>sub{ feature_bool('highlight',@_) }, 522'override'=>0, 523'default'=> [0]}, 524 525# Enable displaying of remote heads in the heads list 526 527# To enable system wide have in $GITWEB_CONFIG 528# $feature{'remote_heads'}{'default'} = [1]; 529# To have project specific config enable override in $GITWEB_CONFIG 530# $feature{'remote_heads'}{'override'} = 1; 531# and in project config gitweb.remote_heads = 0|1; 532'remote_heads'=> { 533'sub'=>sub{ feature_bool('remote_heads',@_) }, 534'override'=>0, 535'default'=> [0]}, 536); 537 538sub gitweb_get_feature { 539my($name) =@_; 540return unlessexists$feature{$name}; 541my($sub,$override,@defaults) = ( 542$feature{$name}{'sub'}, 543$feature{$name}{'override'}, 544@{$feature{$name}{'default'}}); 545# project specific override is possible only if we have project 546our$git_dir;# global variable, declared later 547if(!$override|| !defined$git_dir) { 548return@defaults; 549} 550if(!defined$sub) { 551warn"feature$nameis not overridable"; 552return@defaults; 553} 554return$sub->(@defaults); 555} 556 557# A wrapper to check if a given feature is enabled. 558# With this, you can say 559# 560# my $bool_feat = gitweb_check_feature('bool_feat'); 561# gitweb_check_feature('bool_feat') or somecode; 562# 563# instead of 564# 565# my ($bool_feat) = gitweb_get_feature('bool_feat'); 566# (gitweb_get_feature('bool_feat'))[0] or somecode; 567# 568sub gitweb_check_feature { 569return(gitweb_get_feature(@_))[0]; 570} 571 572 573sub feature_bool { 574my$key=shift; 575my($val) = git_get_project_config($key,'--bool'); 576 577if(!defined$val) { 578return($_[0]); 579}elsif($valeq'true') { 580return(1); 581}elsif($valeq'false') { 582return(0); 583} 584} 585 586sub feature_snapshot { 587my(@fmts) =@_; 588 589my($val) = git_get_project_config('snapshot'); 590 591if($val) { 592@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 593} 594 595return@fmts; 596} 597 598sub feature_patches { 599my@val= (git_get_project_config('patches','--int')); 600 601if(@val) { 602return@val; 603} 604 605return($_[0]); 606} 607 608sub feature_avatar { 609my@val= (git_get_project_config('avatar')); 610 611return@val?@val:@_; 612} 613 614# checking HEAD file with -e is fragile if the repository was 615# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 616# and then pruned. 617sub check_head_link { 618my($dir) =@_; 619my$headfile="$dir/HEAD"; 620return((-e $headfile) || 621(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 622} 623 624sub check_export_ok { 625my($dir) =@_; 626return(check_head_link($dir) && 627(!$export_ok|| -e "$dir/$export_ok") && 628(!$export_auth_hook||$export_auth_hook->($dir))); 629} 630 631# process alternate names for backward compatibility 632# filter out unsupported (unknown) snapshot formats 633sub filter_snapshot_fmts { 634my@fmts=@_; 635 636@fmts=map{ 637exists$known_snapshot_format_aliases{$_} ? 638$known_snapshot_format_aliases{$_} :$_}@fmts; 639@fmts=grep{ 640exists$known_snapshot_formats{$_} && 641!$known_snapshot_formats{$_}{'disabled'}}@fmts; 642} 643 644# If it is set to code reference, it is code that it is to be run once per 645# request, allowing updating configurations that change with each request, 646# while running other code in config file only once. 647# 648# Otherwise, if it is false then gitweb would process config file only once; 649# if it is true then gitweb config would be run for each request. 650our$per_request_config=1; 651 652# read and parse gitweb config file given by its parameter. 653# returns true on success, false on recoverable error, allowing 654# to chain this subroutine, using first file that exists. 655# dies on errors during parsing config file, as it is unrecoverable. 656sub read_config_file { 657my$filename=shift; 658return unlessdefined$filename; 659# die if there are errors parsing config file 660if(-e $filename) { 661do$filename; 662die$@if$@; 663return1; 664} 665return; 666} 667 668our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 669sub evaluate_gitweb_config { 670our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 671our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 672our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 673 674# Protect agains duplications of file names, to not read config twice. 675# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 676# there possibility of duplication of filename there doesn't matter. 677$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 678$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 679 680# Common system-wide settings for convenience. 681# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 682 read_config_file($GITWEB_CONFIG_COMMON); 683 684# Use first config file that exists. This means use the per-instance 685# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 686 read_config_file($GITWEB_CONFIG)andreturn; 687 read_config_file($GITWEB_CONFIG_SYSTEM); 688} 689 690# Get loadavg of system, to compare against $maxload. 691# Currently it requires '/proc/loadavg' present to get loadavg; 692# if it is not present it returns 0, which means no load checking. 693sub get_loadavg { 694if( -e '/proc/loadavg'){ 695open my$fd,'<','/proc/loadavg' 696orreturn0; 697my@load=split(/\s+/,scalar<$fd>); 698close$fd; 699 700# The first three columns measure CPU and IO utilization of the last one, 701# five, and 10 minute periods. The fourth column shows the number of 702# currently running processes and the total number of processes in the m/n 703# format. The last column displays the last process ID used. 704return$load[0] ||0; 705} 706# additional checks for load average should go here for things that don't export 707# /proc/loadavg 708 709return0; 710} 711 712# version of the core git binary 713our$git_version; 714sub evaluate_git_version { 715our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 716$number_of_git_cmds++; 717} 718 719sub check_loadavg { 720if(defined$maxload&& get_loadavg() >$maxload) { 721 die_error(503,"The load average on the server is too high"); 722} 723} 724 725# ====================================================================== 726# input validation and dispatch 727 728# input parameters can be collected from a variety of sources (presently, CGI 729# and PATH_INFO), so we define an %input_params hash that collects them all 730# together during validation: this allows subsequent uses (e.g. href()) to be 731# agnostic of the parameter origin 732 733our%input_params= (); 734 735# input parameters are stored with the long parameter name as key. This will 736# also be used in the href subroutine to convert parameters to their CGI 737# equivalent, and since the href() usage is the most frequent one, we store 738# the name -> CGI key mapping here, instead of the reverse. 739# 740# XXX: Warning: If you touch this, check the search form for updating, 741# too. 742 743our@cgi_param_mapping= ( 744 project =>"p", 745 action =>"a", 746 file_name =>"f", 747 file_parent =>"fp", 748 hash =>"h", 749 hash_parent =>"hp", 750 hash_base =>"hb", 751 hash_parent_base =>"hpb", 752 page =>"pg", 753 order =>"o", 754 searchtext =>"s", 755 searchtype =>"st", 756 snapshot_format =>"sf", 757 extra_options =>"opt", 758 search_use_regexp =>"sr", 759 ctag =>"by_tag", 760# this must be last entry (for manipulation from JavaScript) 761 javascript =>"js" 762); 763our%cgi_param_mapping=@cgi_param_mapping; 764 765# we will also need to know the possible actions, for validation 766our%actions= ( 767"blame"=> \&git_blame, 768"blame_incremental"=> \&git_blame_incremental, 769"blame_data"=> \&git_blame_data, 770"blobdiff"=> \&git_blobdiff, 771"blobdiff_plain"=> \&git_blobdiff_plain, 772"blob"=> \&git_blob, 773"blob_plain"=> \&git_blob_plain, 774"commitdiff"=> \&git_commitdiff, 775"commitdiff_plain"=> \&git_commitdiff_plain, 776"commit"=> \&git_commit, 777"forks"=> \&git_forks, 778"heads"=> \&git_heads, 779"history"=> \&git_history, 780"log"=> \&git_log, 781"patch"=> \&git_patch, 782"patches"=> \&git_patches, 783"remotes"=> \&git_remotes, 784"rss"=> \&git_rss, 785"atom"=> \&git_atom, 786"search"=> \&git_search, 787"search_help"=> \&git_search_help, 788"shortlog"=> \&git_shortlog, 789"summary"=> \&git_summary, 790"tag"=> \&git_tag, 791"tags"=> \&git_tags, 792"tree"=> \&git_tree, 793"snapshot"=> \&git_snapshot, 794"object"=> \&git_object, 795# those below don't need $project 796"opml"=> \&git_opml, 797"project_list"=> \&git_project_list, 798"project_index"=> \&git_project_index, 799); 800 801# finally, we have the hash of allowed extra_options for the commands that 802# allow them 803our%allowed_options= ( 804"--no-merges"=> [qw(rss atom log shortlog history)], 805); 806 807# fill %input_params with the CGI parameters. All values except for 'opt' 808# should be single values, but opt can be an array. We should probably 809# build an array of parameters that can be multi-valued, but since for the time 810# being it's only this one, we just single it out 811sub evaluate_query_params { 812our$cgi; 813 814while(my($name,$symbol) =each%cgi_param_mapping) { 815if($symboleq'opt') { 816$input_params{$name} = [$cgi->param($symbol) ]; 817}else{ 818$input_params{$name} =$cgi->param($symbol); 819} 820} 821} 822 823# now read PATH_INFO and update the parameter list for missing parameters 824sub evaluate_path_info { 825return ifdefined$input_params{'project'}; 826return if!$path_info; 827$path_info=~ s,^/+,,; 828return if!$path_info; 829 830# find which part of PATH_INFO is project 831my$project=$path_info; 832$project=~ s,/+$,,; 833while($project&& !check_head_link("$projectroot/$project")) { 834$project=~ s,/*[^/]*$,,; 835} 836return unless$project; 837$input_params{'project'} =$project; 838 839# do not change any parameters if an action is given using the query string 840return if$input_params{'action'}; 841$path_info=~ s,^\Q$project\E/*,,; 842 843# next, check if we have an action 844my$action=$path_info; 845$action=~ s,/.*$,,; 846if(exists$actions{$action}) { 847$path_info=~ s,^$action/*,,; 848$input_params{'action'} =$action; 849} 850 851# list of actions that want hash_base instead of hash, but can have no 852# pathname (f) parameter 853my@wants_base= ( 854'tree', 855'history', 856); 857 858# we want to catch, among others 859# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 860my($parentrefname,$parentpathname,$refname,$pathname) = 861($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 862 863# first, analyze the 'current' part 864if(defined$pathname) { 865# we got "branch:filename" or "branch:dir/" 866# we could use git_get_type(branch:pathname), but: 867# - it needs $git_dir 868# - it does a git() call 869# - the convention of terminating directories with a slash 870# makes it superfluous 871# - embedding the action in the PATH_INFO would make it even 872# more superfluous 873$pathname=~ s,^/+,,; 874if(!$pathname||substr($pathname, -1)eq"/") { 875$input_params{'action'} ||="tree"; 876$pathname=~ s,/$,,; 877}else{ 878# the default action depends on whether we had parent info 879# or not 880if($parentrefname) { 881$input_params{'action'} ||="blobdiff_plain"; 882}else{ 883$input_params{'action'} ||="blob_plain"; 884} 885} 886$input_params{'hash_base'} ||=$refname; 887$input_params{'file_name'} ||=$pathname; 888}elsif(defined$refname) { 889# we got "branch". In this case we have to choose if we have to 890# set hash or hash_base. 891# 892# Most of the actions without a pathname only want hash to be 893# set, except for the ones specified in @wants_base that want 894# hash_base instead. It should also be noted that hand-crafted 895# links having 'history' as an action and no pathname or hash 896# set will fail, but that happens regardless of PATH_INFO. 897if(defined$parentrefname) { 898# if there is parent let the default be 'shortlog' action 899# (for http://git.example.com/repo.git/A..B links); if there 900# is no parent, dispatch will detect type of object and set 901# action appropriately if required (if action is not set) 902$input_params{'action'} ||="shortlog"; 903} 904if($input_params{'action'} && 905grep{$_eq$input_params{'action'} }@wants_base) { 906$input_params{'hash_base'} ||=$refname; 907}else{ 908$input_params{'hash'} ||=$refname; 909} 910} 911 912# next, handle the 'parent' part, if present 913if(defined$parentrefname) { 914# a missing pathspec defaults to the 'current' filename, allowing e.g. 915# someproject/blobdiff/oldrev..newrev:/filename 916if($parentpathname) { 917$parentpathname=~ s,^/+,,; 918$parentpathname=~ s,/$,,; 919$input_params{'file_parent'} ||=$parentpathname; 920}else{ 921$input_params{'file_parent'} ||=$input_params{'file_name'}; 922} 923# we assume that hash_parent_base is wanted if a path was specified, 924# or if the action wants hash_base instead of hash 925if(defined$input_params{'file_parent'} || 926grep{$_eq$input_params{'action'} }@wants_base) { 927$input_params{'hash_parent_base'} ||=$parentrefname; 928}else{ 929$input_params{'hash_parent'} ||=$parentrefname; 930} 931} 932 933# for the snapshot action, we allow URLs in the form 934# $project/snapshot/$hash.ext 935# where .ext determines the snapshot and gets removed from the 936# passed $refname to provide the $hash. 937# 938# To be able to tell that $refname includes the format extension, we 939# require the following two conditions to be satisfied: 940# - the hash input parameter MUST have been set from the $refname part 941# of the URL (i.e. they must be equal) 942# - the snapshot format MUST NOT have been defined already (e.g. from 943# CGI parameter sf) 944# It's also useless to try any matching unless $refname has a dot, 945# so we check for that too 946if(defined$input_params{'action'} && 947$input_params{'action'}eq'snapshot'&& 948defined$refname&&index($refname,'.') != -1&& 949$refnameeq$input_params{'hash'} && 950!defined$input_params{'snapshot_format'}) { 951# We loop over the known snapshot formats, checking for 952# extensions. Allowed extensions are both the defined suffix 953# (which includes the initial dot already) and the snapshot 954# format key itself, with a prepended dot 955while(my($fmt,$opt) =each%known_snapshot_formats) { 956my$hash=$refname; 957unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 958next; 959} 960my$sfx=$1; 961# a valid suffix was found, so set the snapshot format 962# and reset the hash parameter 963$input_params{'snapshot_format'} =$fmt; 964$input_params{'hash'} =$hash; 965# we also set the format suffix to the one requested 966# in the URL: this way a request for e.g. .tgz returns 967# a .tgz instead of a .tar.gz 968$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 969last; 970} 971} 972} 973 974our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 975$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 976$searchtext,$search_regexp); 977sub evaluate_and_validate_params { 978our$action=$input_params{'action'}; 979if(defined$action) { 980if(!validate_action($action)) { 981 die_error(400,"Invalid action parameter"); 982} 983} 984 985# parameters which are pathnames 986our$project=$input_params{'project'}; 987if(defined$project) { 988if(!validate_project($project)) { 989undef$project; 990 die_error(404,"No such project"); 991} 992} 993 994our$file_name=$input_params{'file_name'}; 995if(defined$file_name) { 996if(!validate_pathname($file_name)) { 997 die_error(400,"Invalid file parameter"); 998} 999}10001001our$file_parent=$input_params{'file_parent'};1002if(defined$file_parent) {1003if(!validate_pathname($file_parent)) {1004 die_error(400,"Invalid file parent parameter");1005}1006}10071008# parameters which are refnames1009our$hash=$input_params{'hash'};1010if(defined$hash) {1011if(!validate_refname($hash)) {1012 die_error(400,"Invalid hash parameter");1013}1014}10151016our$hash_parent=$input_params{'hash_parent'};1017if(defined$hash_parent) {1018if(!validate_refname($hash_parent)) {1019 die_error(400,"Invalid hash parent parameter");1020}1021}10221023our$hash_base=$input_params{'hash_base'};1024if(defined$hash_base) {1025if(!validate_refname($hash_base)) {1026 die_error(400,"Invalid hash base parameter");1027}1028}10291030our@extra_options= @{$input_params{'extra_options'}};1031# @extra_options is always defined, since it can only be (currently) set from1032# CGI, and $cgi->param() returns the empty array in array context if the param1033# is not set1034foreachmy$opt(@extra_options) {1035if(not exists$allowed_options{$opt}) {1036 die_error(400,"Invalid option parameter");1037}1038if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1039 die_error(400,"Invalid option parameter for this action");1040}1041}10421043our$hash_parent_base=$input_params{'hash_parent_base'};1044if(defined$hash_parent_base) {1045if(!validate_refname($hash_parent_base)) {1046 die_error(400,"Invalid hash parent base parameter");1047}1048}10491050# other parameters1051our$page=$input_params{'page'};1052if(defined$page) {1053if($page=~m/[^0-9]/) {1054 die_error(400,"Invalid page parameter");1055}1056}10571058our$searchtype=$input_params{'searchtype'};1059if(defined$searchtype) {1060if($searchtype=~m/[^a-z]/) {1061 die_error(400,"Invalid searchtype parameter");1062}1063}10641065our$search_use_regexp=$input_params{'search_use_regexp'};10661067our$searchtext=$input_params{'searchtext'};1068our$search_regexp;1069if(defined$searchtext) {1070if(length($searchtext) <2) {1071 die_error(403,"At least two characters are required for search parameter");1072}1073$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext;1074}1075}10761077# path to the current git repository1078our$git_dir;1079sub evaluate_git_dir {1080our$git_dir="$projectroot/$project"if$project;1081}10821083our(@snapshot_fmts,$git_avatar);1084sub configure_gitweb_features {1085# list of supported snapshot formats1086our@snapshot_fmts= gitweb_get_feature('snapshot');1087@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10881089# check that the avatar feature is set to a known provider name,1090# and for each provider check if the dependencies are satisfied.1091# if the provider name is invalid or the dependencies are not met,1092# reset $git_avatar to the empty string.1093our($git_avatar) = gitweb_get_feature('avatar');1094if($git_avatareq'gravatar') {1095$git_avatar=''unless(eval{require Digest::MD5;1; });1096}elsif($git_avatareq'picon') {1097# no dependencies1098}else{1099$git_avatar='';1100}1101}11021103# custom error handler: 'die <message>' is Internal Server Error1104sub handle_errors_html {1105my$msg=shift;# it is already HTML escaped11061107# to avoid infinite loop where error occurs in die_error,1108# change handler to default handler, disabling handle_errors_html1109 set_message("Error occured when inside die_error:\n$msg");11101111# you cannot jump out of die_error when called as error handler;1112# the subroutine set via CGI::Carp::set_message is called _after_1113# HTTP headers are already written, so it cannot write them itself1114 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1115}1116set_message(\&handle_errors_html);11171118# dispatch1119sub dispatch {1120if(!defined$action) {1121if(defined$hash) {1122$action= git_get_type($hash);1123}elsif(defined$hash_base&&defined$file_name) {1124$action= git_get_type("$hash_base:$file_name");1125}elsif(defined$project) {1126$action='summary';1127}else{1128$action='project_list';1129}1130}1131if(!defined($actions{$action})) {1132 die_error(400,"Unknown action");1133}1134if($action!~m/^(?:opml|project_list|project_index)$/&&1135!$project) {1136 die_error(400,"Project needed");1137}1138$actions{$action}->();1139}11401141sub reset_timer {1142our$t0= [ gettimeofday() ]1143ifdefined$t0;1144our$number_of_git_cmds=0;1145}11461147our$first_request=1;1148sub run_request {1149 reset_timer();11501151 evaluate_uri();1152if($first_request) {1153 evaluate_gitweb_config();1154 evaluate_git_version();1155}1156if($per_request_config) {1157if(ref($per_request_config)eq'CODE') {1158$per_request_config->();1159}elsif(!$first_request) {1160 evaluate_gitweb_config();1161}1162}1163 check_loadavg();11641165# $projectroot and $projects_list might be set in gitweb config file1166$projects_list||=$projectroot;11671168 evaluate_query_params();1169 evaluate_path_info();1170 evaluate_and_validate_params();1171 evaluate_git_dir();11721173 configure_gitweb_features();11741175 dispatch();1176}11771178our$is_last_request=sub{1};1179our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1180our$CGI='CGI';1181our$cgi;1182sub configure_as_fcgi {1183require CGI::Fast;1184our$CGI='CGI::Fast';11851186my$request_number=0;1187# let each child service 100 requests1188our$is_last_request=sub{ ++$request_number>100};1189}1190sub evaluate_argv {1191my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1192 configure_as_fcgi()1193if$script_name=~/\.fcgi$/;11941195return unless(@ARGV);11961197require Getopt::Long;1198 Getopt::Long::GetOptions(1199'fastcgi|fcgi|f'=> \&configure_as_fcgi,1200'nproc|n=i'=>sub{1201my($arg,$val) =@_;1202return unlesseval{require FCGI::ProcManager;1; };1203my$proc_manager= FCGI::ProcManager->new({1204 n_processes =>$val,1205});1206our$pre_listen_hook=sub{$proc_manager->pm_manage() };1207our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1208our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1209},1210);1211}12121213sub run {1214 evaluate_argv();12151216$first_request=1;1217$pre_listen_hook->()1218if$pre_listen_hook;12191220 REQUEST:1221while($cgi=$CGI->new()) {1222$pre_dispatch_hook->()1223if$pre_dispatch_hook;12241225 run_request();12261227$post_dispatch_hook->()1228if$post_dispatch_hook;1229$first_request=0;12301231last REQUEST if($is_last_request->());1232}12331234 DONE_GITWEB:12351;1236}12371238run();12391240if(defined caller) {1241# wrapped in a subroutine processing requests,1242# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1243return;1244}else{1245# pure CGI script, serving single request1246exit;1247}12481249## ======================================================================1250## action links12511252# possible values of extra options1253# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1254# -replay => 1 - start from a current view (replay with modifications)1255# -path_info => 0|1 - don't use/use path_info URL (if possible)1256# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1257sub href {1258my%params=@_;1259# default is to use -absolute url() i.e. $my_uri1260my$href=$params{-full} ?$my_url:$my_uri;12611262# implicit -replay, must be first of implicit params1263$params{-replay} =1if(keys%params==1&&$params{-anchor});12641265$params{'project'} =$projectunlessexists$params{'project'};12661267if($params{-replay}) {1268while(my($name,$symbol) =each%cgi_param_mapping) {1269if(!exists$params{$name}) {1270$params{$name} =$input_params{$name};1271}1272}1273}12741275my$use_pathinfo= gitweb_check_feature('pathinfo');1276if(defined$params{'project'} &&1277(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1278# try to put as many parameters as possible in PATH_INFO:1279# - project name1280# - action1281# - hash_parent or hash_parent_base:/file_parent1282# - hash or hash_base:/filename1283# - the snapshot_format as an appropriate suffix12841285# When the script is the root DirectoryIndex for the domain,1286# $href here would be something like http://gitweb.example.com/1287# Thus, we strip any trailing / from $href, to spare us double1288# slashes in the final URL1289$href=~ s,/$,,;12901291# Then add the project name, if present1292$href.="/".esc_path_info($params{'project'});1293delete$params{'project'};12941295# since we destructively absorb parameters, we keep this1296# boolean that remembers if we're handling a snapshot1297my$is_snapshot=$params{'action'}eq'snapshot';12981299# Summary just uses the project path URL, any other action is1300# added to the URL1301if(defined$params{'action'}) {1302$href.="/".esc_path_info($params{'action'})1303unless$params{'action'}eq'summary';1304delete$params{'action'};1305}13061307# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1308# stripping nonexistent or useless pieces1309$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1310||$params{'hash_parent'} ||$params{'hash'});1311if(defined$params{'hash_base'}) {1312if(defined$params{'hash_parent_base'}) {1313$href.= esc_path_info($params{'hash_parent_base'});1314# skip the file_parent if it's the same as the file_name1315if(defined$params{'file_parent'}) {1316if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1317delete$params{'file_parent'};1318}elsif($params{'file_parent'} !~/\.\./) {1319$href.=":/".esc_path_info($params{'file_parent'});1320delete$params{'file_parent'};1321}1322}1323$href.="..";1324delete$params{'hash_parent'};1325delete$params{'hash_parent_base'};1326}elsif(defined$params{'hash_parent'}) {1327$href.= esc_path_info($params{'hash_parent'})."..";1328delete$params{'hash_parent'};1329}13301331$href.= esc_path_info($params{'hash_base'});1332if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1333$href.=":/".esc_path_info($params{'file_name'});1334delete$params{'file_name'};1335}1336delete$params{'hash'};1337delete$params{'hash_base'};1338}elsif(defined$params{'hash'}) {1339$href.= esc_path_info($params{'hash'});1340delete$params{'hash'};1341}13421343# If the action was a snapshot, we can absorb the1344# snapshot_format parameter too1345if($is_snapshot) {1346my$fmt=$params{'snapshot_format'};1347# snapshot_format should always be defined when href()1348# is called, but just in case some code forgets, we1349# fall back to the default1350$fmt||=$snapshot_fmts[0];1351$href.=$known_snapshot_formats{$fmt}{'suffix'};1352delete$params{'snapshot_format'};1353}1354}13551356# now encode the parameters explicitly1357my@result= ();1358for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1359my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1360if(defined$params{$name}) {1361if(ref($params{$name})eq"ARRAY") {1362foreachmy$par(@{$params{$name}}) {1363push@result,$symbol."=". esc_param($par);1364}1365}else{1366push@result,$symbol."=". esc_param($params{$name});1367}1368}1369}1370$href.="?".join(';',@result)ifscalar@result;13711372# final transformation: trailing spaces must be escaped (URI-encoded)1373$href=~s/(\s+)$/CGI::escape($1)/e;13741375if($params{-anchor}) {1376$href.="#".esc_param($params{-anchor});1377}13781379return$href;1380}138113821383## ======================================================================1384## validation, quoting/unquoting and escaping13851386sub validate_action {1387my$input=shift||returnundef;1388returnundefunlessexists$actions{$input};1389return$input;1390}13911392sub validate_project {1393my$input=shift||returnundef;1394if(!validate_pathname($input) ||1395!(-d "$projectroot/$input") ||1396!check_export_ok("$projectroot/$input") ||1397($strict_export&& !project_in_list($input))) {1398returnundef;1399}else{1400return$input;1401}1402}14031404sub validate_pathname {1405my$input=shift||returnundef;14061407# no '.' or '..' as elements of path, i.e. no '.' nor '..'1408# at the beginning, at the end, and between slashes.1409# also this catches doubled slashes1410if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1411returnundef;1412}1413# no null characters1414if($input=~m!\0!) {1415returnundef;1416}1417return$input;1418}14191420sub validate_refname {1421my$input=shift||returnundef;14221423# textual hashes are O.K.1424if($input=~m/^[0-9a-fA-F]{40}$/) {1425return$input;1426}1427# it must be correct pathname1428$input= validate_pathname($input)1429orreturnundef;1430# restrictions on ref name according to git-check-ref-format1431if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1432returnundef;1433}1434return$input;1435}14361437# decode sequences of octets in utf8 into Perl's internal form,1438# which is utf-8 with utf8 flag set if needed. gitweb writes out1439# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1440sub to_utf8 {1441my$str=shift;1442returnundefunlessdefined$str;1443if(utf8::valid($str)) {1444 utf8::decode($str);1445return$str;1446}else{1447return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1448}1449}14501451# quote unsafe chars, but keep the slash, even when it's not1452# correct, but quoted slashes look too horrible in bookmarks1453sub esc_param {1454my$str=shift;1455returnundefunlessdefined$str;1456$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1457$str=~s/ /\+/g;1458return$str;1459}14601461# the quoting rules for path_info fragment are slightly different1462sub esc_path_info {1463my$str=shift;1464returnundefunlessdefined$str;14651466# path_info doesn't treat '+' as space (specially), but '?' must be escaped1467$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;14681469return$str;1470}14711472# quote unsafe chars in whole URL, so some characters cannot be quoted1473sub esc_url {1474my$str=shift;1475returnundefunlessdefined$str;1476$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1477$str=~s/ /\+/g;1478return$str;1479}14801481# quote unsafe characters in HTML attributes1482sub esc_attr {14831484# for XHTML conformance escaping '"' to '"' is not enough1485return esc_html(@_);1486}14871488# replace invalid utf8 character with SUBSTITUTION sequence1489sub esc_html {1490my$str=shift;1491my%opts=@_;14921493returnundefunlessdefined$str;14941495$str= to_utf8($str);1496$str=$cgi->escapeHTML($str);1497if($opts{'-nbsp'}) {1498$str=~s/ / /g;1499}1500$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1501return$str;1502}15031504# quote control characters and escape filename to HTML1505sub esc_path {1506my$str=shift;1507my%opts=@_;15081509returnundefunlessdefined$str;15101511$str= to_utf8($str);1512$str=$cgi->escapeHTML($str);1513if($opts{'-nbsp'}) {1514$str=~s/ / /g;1515}1516$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1517return$str;1518}15191520# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1521sub sanitize {1522my$str=shift;15231524returnundefunlessdefined$str;15251526$str= to_utf8($str);1527$str=~ s|([[:cntrl:]])|($1=~/[\t\n\r]/?$1: quot_cec($1))|eg;1528return$str;1529}15301531# Make control characters "printable", using character escape codes (CEC)1532sub quot_cec {1533my$cntrl=shift;1534my%opts=@_;1535my%es= (# character escape codes, aka escape sequences1536"\t"=>'\t',# tab (HT)1537"\n"=>'\n',# line feed (LF)1538"\r"=>'\r',# carrige return (CR)1539"\f"=>'\f',# form feed (FF)1540"\b"=>'\b',# backspace (BS)1541"\a"=>'\a',# alarm (bell) (BEL)1542"\e"=>'\e',# escape (ESC)1543"\013"=>'\v',# vertical tab (VT)1544"\000"=>'\0',# nul character (NUL)1545);1546my$chr= ( (exists$es{$cntrl})1547?$es{$cntrl}1548:sprintf('\%2x',ord($cntrl)) );1549if($opts{-nohtml}) {1550return$chr;1551}else{1552return"<span class=\"cntrl\">$chr</span>";1553}1554}15551556# Alternatively use unicode control pictures codepoints,1557# Unicode "printable representation" (PR)1558sub quot_upr {1559my$cntrl=shift;1560my%opts=@_;15611562my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1563if($opts{-nohtml}) {1564return$chr;1565}else{1566return"<span class=\"cntrl\">$chr</span>";1567}1568}15691570# git may return quoted and escaped filenames1571sub unquote {1572my$str=shift;15731574sub unq {1575my$seq=shift;1576my%es= (# character escape codes, aka escape sequences1577't'=>"\t",# tab (HT, TAB)1578'n'=>"\n",# newline (NL)1579'r'=>"\r",# return (CR)1580'f'=>"\f",# form feed (FF)1581'b'=>"\b",# backspace (BS)1582'a'=>"\a",# alarm (bell) (BEL)1583'e'=>"\e",# escape (ESC)1584'v'=>"\013",# vertical tab (VT)1585);15861587if($seq=~m/^[0-7]{1,3}$/) {1588# octal char sequence1589returnchr(oct($seq));1590}elsif(exists$es{$seq}) {1591# C escape sequence, aka character escape code1592return$es{$seq};1593}1594# quoted ordinary character1595return$seq;1596}15971598if($str=~m/^"(.*)"$/) {1599# needs unquoting1600$str=$1;1601$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1602}1603return$str;1604}16051606# escape tabs (convert tabs to spaces)1607sub untabify {1608my$line=shift;16091610while((my$pos=index($line,"\t")) != -1) {1611if(my$count= (8- ($pos%8))) {1612my$spaces=' ' x $count;1613$line=~s/\t/$spaces/;1614}1615}16161617return$line;1618}16191620sub project_in_list {1621my$project=shift;1622my@list= git_get_projects_list();1623return@list&&scalar(grep{$_->{'path'}eq$project}@list);1624}16251626## ----------------------------------------------------------------------1627## HTML aware string manipulation16281629# Try to chop given string on a word boundary between position1630# $len and $len+$add_len. If there is no word boundary there,1631# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1632# (marking chopped part) would be longer than given string.1633sub chop_str {1634my$str=shift;1635my$len=shift;1636my$add_len=shift||10;1637my$where=shift||'right';# 'left' | 'center' | 'right'16381639# Make sure perl knows it is utf8 encoded so we don't1640# cut in the middle of a utf8 multibyte char.1641$str= to_utf8($str);16421643# allow only $len chars, but don't cut a word if it would fit in $add_len1644# if it doesn't fit, cut it if it's still longer than the dots we would add1645# remove chopped character entities entirely16461647# when chopping in the middle, distribute $len into left and right part1648# return early if chopping wouldn't make string shorter1649if($whereeq'center') {1650return$strif($len+5>=length($str));# filler is length 51651$len=int($len/2);1652}else{1653return$strif($len+4>=length($str));# filler is length 41654}16551656# regexps: ending and beginning with word part up to $add_len1657my$endre=qr/.{$len}\w{0,$add_len}/;1658my$begre=qr/\w{0,$add_len}.{$len}/;16591660if($whereeq'left') {1661$str=~m/^(.*?)($begre)$/;1662my($lead,$body) = ($1,$2);1663if(length($lead) >4) {1664$lead=" ...";1665}1666return"$lead$body";16671668}elsif($whereeq'center') {1669$str=~m/^($endre)(.*)$/;1670my($left,$str) = ($1,$2);1671$str=~m/^(.*?)($begre)$/;1672my($mid,$right) = ($1,$2);1673if(length($mid) >5) {1674$mid=" ... ";1675}1676return"$left$mid$right";16771678}else{1679$str=~m/^($endre)(.*)$/;1680my$body=$1;1681my$tail=$2;1682if(length($tail) >4) {1683$tail="... ";1684}1685return"$body$tail";1686}1687}16881689# takes the same arguments as chop_str, but also wraps a <span> around the1690# result with a title attribute if it does get chopped. Additionally, the1691# string is HTML-escaped.1692sub chop_and_escape_str {1693my($str) =@_;16941695my$chopped= chop_str(@_);1696if($choppedeq$str) {1697return esc_html($chopped);1698}else{1699$str=~s/[[:cntrl:]]/?/g;1700return$cgi->span({-title=>$str}, esc_html($chopped));1701}1702}17031704## ----------------------------------------------------------------------1705## functions returning short strings17061707# CSS class for given age value (in seconds)1708sub age_class {1709my$age=shift;17101711if(!defined$age) {1712return"noage";1713}elsif($age<60*60*2) {1714return"age0";1715}elsif($age<60*60*24*2) {1716return"age1";1717}else{1718return"age2";1719}1720}17211722# convert age in seconds to "nn units ago" string1723sub age_string {1724my$age=shift;1725my$age_str;17261727if($age>60*60*24*365*2) {1728$age_str= (int$age/60/60/24/365);1729$age_str.=" years ago";1730}elsif($age>60*60*24*(365/12)*2) {1731$age_str=int$age/60/60/24/(365/12);1732$age_str.=" months ago";1733}elsif($age>60*60*24*7*2) {1734$age_str=int$age/60/60/24/7;1735$age_str.=" weeks ago";1736}elsif($age>60*60*24*2) {1737$age_str=int$age/60/60/24;1738$age_str.=" days ago";1739}elsif($age>60*60*2) {1740$age_str=int$age/60/60;1741$age_str.=" hours ago";1742}elsif($age>60*2) {1743$age_str=int$age/60;1744$age_str.=" min ago";1745}elsif($age>2) {1746$age_str=int$age;1747$age_str.=" sec ago";1748}else{1749$age_str.=" right now";1750}1751return$age_str;1752}17531754useconstant{1755 S_IFINVALID =>0030000,1756 S_IFGITLINK =>0160000,1757};17581759# submodule/subproject, a commit object reference1760sub S_ISGITLINK {1761my$mode=shift;17621763return(($mode& S_IFMT) == S_IFGITLINK)1764}17651766# convert file mode in octal to symbolic file mode string1767sub mode_str {1768my$mode=oct shift;17691770if(S_ISGITLINK($mode)) {1771return'm---------';1772}elsif(S_ISDIR($mode& S_IFMT)) {1773return'drwxr-xr-x';1774}elsif(S_ISLNK($mode)) {1775return'lrwxrwxrwx';1776}elsif(S_ISREG($mode)) {1777# git cares only about the executable bit1778if($mode& S_IXUSR) {1779return'-rwxr-xr-x';1780}else{1781return'-rw-r--r--';1782};1783}else{1784return'----------';1785}1786}17871788# convert file mode in octal to file type string1789sub file_type {1790my$mode=shift;17911792if($mode!~m/^[0-7]+$/) {1793return$mode;1794}else{1795$mode=oct$mode;1796}17971798if(S_ISGITLINK($mode)) {1799return"submodule";1800}elsif(S_ISDIR($mode& S_IFMT)) {1801return"directory";1802}elsif(S_ISLNK($mode)) {1803return"symlink";1804}elsif(S_ISREG($mode)) {1805return"file";1806}else{1807return"unknown";1808}1809}18101811# convert file mode in octal to file type description string1812sub file_type_long {1813my$mode=shift;18141815if($mode!~m/^[0-7]+$/) {1816return$mode;1817}else{1818$mode=oct$mode;1819}18201821if(S_ISGITLINK($mode)) {1822return"submodule";1823}elsif(S_ISDIR($mode& S_IFMT)) {1824return"directory";1825}elsif(S_ISLNK($mode)) {1826return"symlink";1827}elsif(S_ISREG($mode)) {1828if($mode& S_IXUSR) {1829return"executable";1830}else{1831return"file";1832};1833}else{1834return"unknown";1835}1836}183718381839## ----------------------------------------------------------------------1840## functions returning short HTML fragments, or transforming HTML fragments1841## which don't belong to other sections18421843# format line of commit message.1844sub format_log_line_html {1845my$line=shift;18461847$line= esc_html($line, -nbsp=>1);1848$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1849$cgi->a({-href => href(action=>"object", hash=>$1),1850-class=>"text"},$1);1851}eg;18521853return$line;1854}18551856# format marker of refs pointing to given object18571858# the destination action is chosen based on object type and current context:1859# - for annotated tags, we choose the tag view unless it's the current view1860# already, in which case we go to shortlog view1861# - for other refs, we keep the current view if we're in history, shortlog or1862# log view, and select shortlog otherwise1863sub format_ref_marker {1864my($refs,$id) =@_;1865my$markers='';18661867if(defined$refs->{$id}) {1868foreachmy$ref(@{$refs->{$id}}) {1869# this code exploits the fact that non-lightweight tags are the1870# only indirect objects, and that they are the only objects for which1871# we want to use tag instead of shortlog as action1872my($type,$name) =qw();1873my$indirect= ($ref=~s/\^\{\}$//);1874# e.g. tags/v2.6.11 or heads/next1875if($ref=~m!^(.*?)s?/(.*)$!) {1876$type=$1;1877$name=$2;1878}else{1879$type="ref";1880$name=$ref;1881}18821883my$class=$type;1884$class.=" indirect"if$indirect;18851886my$dest_action="shortlog";18871888if($indirect) {1889$dest_action="tag"unless$actioneq"tag";1890}elsif($action=~/^(history|(short)?log)$/) {1891$dest_action=$action;1892}18931894my$dest="";1895$dest.="refs/"unless$ref=~ m!^refs/!;1896$dest.=$ref;18971898my$link=$cgi->a({1899-href => href(1900 action=>$dest_action,1901 hash=>$dest1902)},$name);19031904$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1905$link."</span>";1906}1907}19081909if($markers) {1910return' <span class="refs">'.$markers.'</span>';1911}else{1912return"";1913}1914}19151916# format, perhaps shortened and with markers, title line1917sub format_subject_html {1918my($long,$short,$href,$extra) =@_;1919$extra=''unlessdefined($extra);19201921if(length($short) <length($long)) {1922$long=~s/[[:cntrl:]]/?/g;1923return$cgi->a({-href =>$href, -class=>"list subject",1924-title => to_utf8($long)},1925 esc_html($short)) .$extra;1926}else{1927return$cgi->a({-href =>$href, -class=>"list subject"},1928 esc_html($long)) .$extra;1929}1930}19311932# Rather than recomputing the url for an email multiple times, we cache it1933# after the first hit. This gives a visible benefit in views where the avatar1934# for the same email is used repeatedly (e.g. shortlog).1935# The cache is shared by all avatar engines (currently gravatar only), which1936# are free to use it as preferred. Since only one avatar engine is used for any1937# given page, there's no risk for cache conflicts.1938our%avatar_cache= ();19391940# Compute the picon url for a given email, by using the picon search service over at1941# http://www.cs.indiana.edu/picons/search.html1942sub picon_url {1943my$email=lc shift;1944if(!$avatar_cache{$email}) {1945my($user,$domain) =split('@',$email);1946$avatar_cache{$email} =1947"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1948"$domain/$user/".1949"users+domains+unknown/up/single";1950}1951return$avatar_cache{$email};1952}19531954# Compute the gravatar url for a given email, if it's not in the cache already.1955# Gravatar stores only the part of the URL before the size, since that's the1956# one computationally more expensive. This also allows reuse of the cache for1957# different sizes (for this particular engine).1958sub gravatar_url {1959my$email=lc shift;1960my$size=shift;1961$avatar_cache{$email} ||=1962"http://www.gravatar.com/avatar/".1963 Digest::MD5::md5_hex($email) ."?s=";1964return$avatar_cache{$email} .$size;1965}19661967# Insert an avatar for the given $email at the given $size if the feature1968# is enabled.1969sub git_get_avatar {1970my($email,%opts) =@_;1971my$pre_white= ($opts{-pad_before} ?" ":"");1972my$post_white= ($opts{-pad_after} ?" ":"");1973$opts{-size} ||='default';1974my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1975my$url="";1976if($git_avatareq'gravatar') {1977$url= gravatar_url($email,$size);1978}elsif($git_avatareq'picon') {1979$url= picon_url($email);1980}1981# Other providers can be added by extending the if chain, defining $url1982# as needed. If no variant puts something in $url, we assume avatars1983# are completely disabled/unavailable.1984if($url) {1985return$pre_white.1986"<img width=\"$size\"".1987"class=\"avatar\"".1988"src=\"".esc_url($url)."\"".1989"alt=\"\"".1990"/>".$post_white;1991}else{1992return"";1993}1994}19951996sub format_search_author {1997my($author,$searchtype,$displaytext) =@_;1998my$have_search= gitweb_check_feature('search');19992000if($have_search) {2001my$performed="";2002if($searchtypeeq'author') {2003$performed="authored";2004}elsif($searchtypeeq'committer') {2005$performed="committed";2006}20072008return$cgi->a({-href => href(action=>"search", hash=>$hash,2009 searchtext=>$author,2010 searchtype=>$searchtype),class=>"list",2011 title=>"Search for commits$performedby$author"},2012$displaytext);20132014}else{2015return$displaytext;2016}2017}20182019# format the author name of the given commit with the given tag2020# the author name is chopped and escaped according to the other2021# optional parameters (see chop_str).2022sub format_author_html {2023my$tag=shift;2024my$co=shift;2025my$author= chop_and_escape_str($co->{'author_name'},@_);2026return"<$tagclass=\"author\">".2027 format_search_author($co->{'author_name'},"author",2028 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2029$author) .2030"</$tag>";2031}20322033# format git diff header line, i.e. "diff --(git|combined|cc) ..."2034sub format_git_diff_header_line {2035my$line=shift;2036my$diffinfo=shift;2037my($from,$to) =@_;20382039if($diffinfo->{'nparents'}) {2040# combined diff2041$line=~s!^(diff (.*?) )"?.*$!$1!;2042if($to->{'href'}) {2043$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2044 esc_path($to->{'file'}));2045}else{# file was deleted (no href)2046$line.= esc_path($to->{'file'});2047}2048}else{2049# "ordinary" diff2050$line=~s!^(diff (.*?) )"?a/.*$!$1!;2051if($from->{'href'}) {2052$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2053'a/'. esc_path($from->{'file'}));2054}else{# file was added (no href)2055$line.='a/'. esc_path($from->{'file'});2056}2057$line.=' ';2058if($to->{'href'}) {2059$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2060'b/'. esc_path($to->{'file'}));2061}else{# file was deleted2062$line.='b/'. esc_path($to->{'file'});2063}2064}20652066return"<div class=\"diff header\">$line</div>\n";2067}20682069# format extended diff header line, before patch itself2070sub format_extended_diff_header_line {2071my$line=shift;2072my$diffinfo=shift;2073my($from,$to) =@_;20742075# match <path>2076if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2077$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2078 esc_path($from->{'file'}));2079}2080if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2081$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2082 esc_path($to->{'file'}));2083}2084# match single <mode>2085if($line=~m/\s(\d{6})$/) {2086$line.='<span class="info"> ('.2087 file_type_long($1) .2088')</span>';2089}2090# match <hash>2091if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2092# can match only for combined diff2093$line='index ';2094for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2095if($from->{'href'}[$i]) {2096$line.=$cgi->a({-href=>$from->{'href'}[$i],2097-class=>"hash"},2098substr($diffinfo->{'from_id'}[$i],0,7));2099}else{2100$line.='0' x 7;2101}2102# separator2103$line.=','if($i<$diffinfo->{'nparents'} -1);2104}2105$line.='..';2106if($to->{'href'}) {2107$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2108substr($diffinfo->{'to_id'},0,7));2109}else{2110$line.='0' x 7;2111}21122113}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2114# can match only for ordinary diff2115my($from_link,$to_link);2116if($from->{'href'}) {2117$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2118substr($diffinfo->{'from_id'},0,7));2119}else{2120$from_link='0' x 7;2121}2122if($to->{'href'}) {2123$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2124substr($diffinfo->{'to_id'},0,7));2125}else{2126$to_link='0' x 7;2127}2128my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2129$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2130}21312132return$line."<br/>\n";2133}21342135# format from-file/to-file diff header2136sub format_diff_from_to_header {2137my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2138my$line;2139my$result='';21402141$line=$from_line;2142#assert($line =~ m/^---/) if DEBUG;2143# no extra formatting for "^--- /dev/null"2144if(!$diffinfo->{'nparents'}) {2145# ordinary (single parent) diff2146if($line=~m!^--- "?a/!) {2147if($from->{'href'}) {2148$line='--- a/'.2149$cgi->a({-href=>$from->{'href'}, -class=>"path"},2150 esc_path($from->{'file'}));2151}else{2152$line='--- a/'.2153 esc_path($from->{'file'});2154}2155}2156$result.= qq!<div class="diff from_file">$line</div>\n!;21572158}else{2159# combined diff (merge commit)2160for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2161if($from->{'href'}[$i]) {2162$line='--- '.2163$cgi->a({-href=>href(action=>"blobdiff",2164 hash_parent=>$diffinfo->{'from_id'}[$i],2165 hash_parent_base=>$parents[$i],2166 file_parent=>$from->{'file'}[$i],2167 hash=>$diffinfo->{'to_id'},2168 hash_base=>$hash,2169 file_name=>$to->{'file'}),2170-class=>"path",2171-title=>"diff". ($i+1)},2172$i+1) .2173'/'.2174$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2175 esc_path($from->{'file'}[$i]));2176}else{2177$line='--- /dev/null';2178}2179$result.= qq!<div class="diff from_file">$line</div>\n!;2180}2181}21822183$line=$to_line;2184#assert($line =~ m/^\+\+\+/) if DEBUG;2185# no extra formatting for "^+++ /dev/null"2186if($line=~m!^\+\+\+ "?b/!) {2187if($to->{'href'}) {2188$line='+++ b/'.2189$cgi->a({-href=>$to->{'href'}, -class=>"path"},2190 esc_path($to->{'file'}));2191}else{2192$line='+++ b/'.2193 esc_path($to->{'file'});2194}2195}2196$result.= qq!<div class="diff to_file">$line</div>\n!;21972198return$result;2199}22002201# create note for patch simplified by combined diff2202sub format_diff_cc_simplified {2203my($diffinfo,@parents) =@_;2204my$result='';22052206$result.="<div class=\"diff header\">".2207"diff --cc ";2208if(!is_deleted($diffinfo)) {2209$result.=$cgi->a({-href => href(action=>"blob",2210 hash_base=>$hash,2211 hash=>$diffinfo->{'to_id'},2212 file_name=>$diffinfo->{'to_file'}),2213-class=>"path"},2214 esc_path($diffinfo->{'to_file'}));2215}else{2216$result.= esc_path($diffinfo->{'to_file'});2217}2218$result.="</div>\n".# class="diff header"2219"<div class=\"diff nodifferences\">".2220"Simple merge".2221"</div>\n";# class="diff nodifferences"22222223return$result;2224}22252226# format patch (diff) line (not to be used for diff headers)2227sub format_diff_line {2228my$line=shift;2229my($from,$to) =@_;2230my$diff_class="";22312232chomp$line;22332234if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2235# combined diff2236my$prefix=substr($line,0,scalar@{$from->{'href'}});2237if($line=~m/^\@{3}/) {2238$diff_class=" chunk_header";2239}elsif($line=~m/^\\/) {2240$diff_class=" incomplete";2241}elsif($prefix=~tr/+/+/) {2242$diff_class=" add";2243}elsif($prefix=~tr/-/-/) {2244$diff_class=" rem";2245}2246}else{2247# assume ordinary diff2248my$char=substr($line,0,1);2249if($chareq'+') {2250$diff_class=" add";2251}elsif($chareq'-') {2252$diff_class=" rem";2253}elsif($chareq'@') {2254$diff_class=" chunk_header";2255}elsif($chareq"\\") {2256$diff_class=" incomplete";2257}2258}2259$line= untabify($line);2260if($from&&$to&&$line=~m/^\@{2} /) {2261my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2262$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;22632264$from_lines=0unlessdefined$from_lines;2265$to_lines=0unlessdefined$to_lines;22662267if($from->{'href'}) {2268$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2269-class=>"list"},$from_text);2270}2271if($to->{'href'}) {2272$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2273-class=>"list"},$to_text);2274}2275$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2276"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2277return"<div class=\"diff$diff_class\">$line</div>\n";2278}elsif($from&&$to&&$line=~m/^\@{3}/) {2279my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2280my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);22812282@from_text=split(' ',$ranges);2283for(my$i=0;$i<@from_text; ++$i) {2284($from_start[$i],$from_nlines[$i]) =2285(split(',',substr($from_text[$i],1)),0);2286}22872288$to_text=pop@from_text;2289$to_start=pop@from_start;2290$to_nlines=pop@from_nlines;22912292$line="<span class=\"chunk_info\">$prefix";2293for(my$i=0;$i<@from_text; ++$i) {2294if($from->{'href'}[$i]) {2295$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2296-class=>"list"},$from_text[$i]);2297}else{2298$line.=$from_text[$i];2299}2300$line.=" ";2301}2302if($to->{'href'}) {2303$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2304-class=>"list"},$to_text);2305}else{2306$line.=$to_text;2307}2308$line.="$prefix</span>".2309"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2310return"<div class=\"diff$diff_class\">$line</div>\n";2311}2312return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2313}23142315# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2316# linked. Pass the hash of the tree/commit to snapshot.2317sub format_snapshot_links {2318my($hash) =@_;2319my$num_fmts=@snapshot_fmts;2320if($num_fmts>1) {2321# A parenthesized list of links bearing format names.2322# e.g. "snapshot (_tar.gz_ _zip_)"2323return"snapshot (".join(' ',map2324$cgi->a({2325-href => href(2326 action=>"snapshot",2327 hash=>$hash,2328 snapshot_format=>$_2329)2330},$known_snapshot_formats{$_}{'display'})2331,@snapshot_fmts) .")";2332}elsif($num_fmts==1) {2333# A single "snapshot" link whose tooltip bears the format name.2334# i.e. "_snapshot_"2335my($fmt) =@snapshot_fmts;2336return2337$cgi->a({2338-href => href(2339 action=>"snapshot",2340 hash=>$hash,2341 snapshot_format=>$fmt2342),2343-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2344},"snapshot");2345}else{# $num_fmts == 02346returnundef;2347}2348}23492350## ......................................................................2351## functions returning values to be passed, perhaps after some2352## transformation, to other functions; e.g. returning arguments to href()23532354# returns hash to be passed to href to generate gitweb URL2355# in -title key it returns description of link2356sub get_feed_info {2357my$format=shift||'Atom';2358my%res= (action =>lc($format));23592360# feed links are possible only for project views2361return unless(defined$project);2362# some views should link to OPML, or to generic project feed,2363# or don't have specific feed yet (so they should use generic)2364return if($action=~/^(?:tags|heads|forks|tag|search)$/x);23652366my$branch;2367# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2368# from tag links; this also makes possible to detect branch links2369if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2370(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2371$branch=$1;2372}2373# find log type for feed description (title)2374my$type='log';2375if(defined$file_name) {2376$type="history of$file_name";2377$type.="/"if($actioneq'tree');2378$type.=" on '$branch'"if(defined$branch);2379}else{2380$type="log of$branch"if(defined$branch);2381}23822383$res{-title} =$type;2384$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2385$res{'file_name'} =$file_name;23862387return%res;2388}23892390## ----------------------------------------------------------------------2391## git utility subroutines, invoking git commands23922393# returns path to the core git executable and the --git-dir parameter as list2394sub git_cmd {2395$number_of_git_cmds++;2396return$GIT,'--git-dir='.$git_dir;2397}23982399# quote the given arguments for passing them to the shell2400# quote_command("command", "arg 1", "arg with ' and ! characters")2401# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2402# Try to avoid using this function wherever possible.2403sub quote_command {2404returnjoin(' ',2405map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2406}24072408# get HEAD ref of given project as hash2409sub git_get_head_hash {2410return git_get_full_hash(shift,'HEAD');2411}24122413sub git_get_full_hash {2414return git_get_hash(@_);2415}24162417sub git_get_short_hash {2418return git_get_hash(@_,'--short=7');2419}24202421sub git_get_hash {2422my($project,$hash,@options) =@_;2423my$o_git_dir=$git_dir;2424my$retval=undef;2425$git_dir="$projectroot/$project";2426if(open my$fd,'-|', git_cmd(),'rev-parse',2427'--verify','-q',@options,$hash) {2428$retval= <$fd>;2429chomp$retvalifdefined$retval;2430close$fd;2431}2432if(defined$o_git_dir) {2433$git_dir=$o_git_dir;2434}2435return$retval;2436}24372438# get type of given object2439sub git_get_type {2440my$hash=shift;24412442open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2443my$type= <$fd>;2444close$fdorreturn;2445chomp$type;2446return$type;2447}24482449# repository configuration2450our$config_file='';2451our%config;24522453# store multiple values for single key as anonymous array reference2454# single values stored directly in the hash, not as [ <value> ]2455sub hash_set_multi {2456my($hash,$key,$value) =@_;24572458if(!exists$hash->{$key}) {2459$hash->{$key} =$value;2460}elsif(!ref$hash->{$key}) {2461$hash->{$key} = [$hash->{$key},$value];2462}else{2463push@{$hash->{$key}},$value;2464}2465}24662467# return hash of git project configuration2468# optionally limited to some section, e.g. 'gitweb'2469sub git_parse_project_config {2470my$section_regexp=shift;2471my%config;24722473local$/="\0";24742475open my$fh,"-|", git_cmd(),"config",'-z','-l',2476orreturn;24772478while(my$keyval= <$fh>) {2479chomp$keyval;2480my($key,$value) =split(/\n/,$keyval,2);24812482 hash_set_multi(\%config,$key,$value)2483if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2484}2485close$fh;24862487return%config;2488}24892490# convert config value to boolean: 'true' or 'false'2491# no value, number > 0, 'true' and 'yes' values are true2492# rest of values are treated as false (never as error)2493sub config_to_bool {2494my$val=shift;24952496return1if!defined$val;# section.key24972498# strip leading and trailing whitespace2499$val=~s/^\s+//;2500$val=~s/\s+$//;25012502return(($val=~/^\d+$/&&$val) ||# section.key = 12503($val=~/^(?:true|yes)$/i));# section.key = true2504}25052506# convert config value to simple decimal number2507# an optional value suffix of 'k', 'm', or 'g' will cause the value2508# to be multiplied by 1024, 1048576, or 10737418242509sub config_to_int {2510my$val=shift;25112512# strip leading and trailing whitespace2513$val=~s/^\s+//;2514$val=~s/\s+$//;25152516if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2517$unit=lc($unit);2518# unknown unit is treated as 12519return$num* ($uniteq'g'?1073741824:2520$uniteq'm'?1048576:2521$uniteq'k'?1024:1);2522}2523return$val;2524}25252526# convert config value to array reference, if needed2527sub config_to_multi {2528my$val=shift;25292530returnref($val) ?$val: (defined($val) ? [$val] : []);2531}25322533sub git_get_project_config {2534my($key,$type) =@_;25352536return unlessdefined$git_dir;25372538# key sanity check2539return unless($key);2540# only subsection, if exists, is case sensitive,2541# and not lowercased by 'git config -z -l'2542if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2543$key=join(".",lc($hi),$mi,lc($lo));2544}else{2545$key=lc($key);2546}2547$key=~s/^gitweb\.//;2548return if($key=~m/\W/);25492550# type sanity check2551if(defined$type) {2552$type=~s/^--//;2553$type=undef2554unless($typeeq'bool'||$typeeq'int');2555}25562557# get config2558if(!defined$config_file||2559$config_filene"$git_dir/config") {2560%config= git_parse_project_config('gitweb');2561$config_file="$git_dir/config";2562}25632564# check if config variable (key) exists2565return unlessexists$config{"gitweb.$key"};25662567# ensure given type2568if(!defined$type) {2569return$config{"gitweb.$key"};2570}elsif($typeeq'bool') {2571# backward compatibility: 'git config --bool' returns true/false2572return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2573}elsif($typeeq'int') {2574return config_to_int($config{"gitweb.$key"});2575}2576return$config{"gitweb.$key"};2577}25782579# get hash of given path at given ref2580sub git_get_hash_by_path {2581my$base=shift;2582my$path=shift||returnundef;2583my$type=shift;25842585$path=~ s,/+$,,;25862587open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2588or die_error(500,"Open git-ls-tree failed");2589my$line= <$fd>;2590close$fdorreturnundef;25912592if(!defined$line) {2593# there is no tree or hash given by $path at $base2594returnundef;2595}25962597#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2598$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2599if(defined$type&&$typene$2) {2600# type doesn't match2601returnundef;2602}2603return$3;2604}26052606# get path of entry with given hash at given tree-ish (ref)2607# used to get 'from' filename for combined diff (merge commit) for renames2608sub git_get_path_by_hash {2609my$base=shift||return;2610my$hash=shift||return;26112612local$/="\0";26132614open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2615orreturnundef;2616while(my$line= <$fd>) {2617chomp$line;26182619#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2620#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2621if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2622close$fd;2623return$1;2624}2625}2626close$fd;2627returnundef;2628}26292630## ......................................................................2631## git utility functions, directly accessing git repository26322633# get the value of config variable either from file named as the variable2634# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2635# configuration variable in the repository config file.2636sub git_get_file_or_project_config {2637my($path,$name) =@_;26382639$git_dir="$projectroot/$path";2640open my$fd,'<',"$git_dir/$name"2641orreturn git_get_project_config($name);2642my$conf= <$fd>;2643close$fd;2644if(defined$conf) {2645chomp$conf;2646}2647return$conf;2648}26492650sub git_get_project_description {2651my$path=shift;2652return git_get_file_or_project_config($path,'description');2653}26542655sub git_get_project_category {2656my$path=shift;2657return git_get_file_or_project_config($path,'category');2658}265926602661# supported formats:2662# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2663# - if its contents is a number, use it as tag weight,2664# - otherwise add a tag with weight 12665# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2666# the same value multiple times increases tag weight2667# * `gitweb.ctag' multi-valued repo config variable2668sub git_get_project_ctags {2669my$project=shift;2670my$ctags= {};26712672$git_dir="$projectroot/$project";2673if(opendir my$dh,"$git_dir/ctags") {2674my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2675foreachmy$tagfile(@files) {2676open my$ct,'<',$tagfile2677ornext;2678my$val= <$ct>;2679chomp$valif$val;2680close$ct;26812682(my$ctag=$tagfile) =~ s#.*/##;2683if($val=~/^\d+$/) {2684$ctags->{$ctag} =$val;2685}else{2686$ctags->{$ctag} =1;2687}2688}2689closedir$dh;26902691}elsif(open my$fh,'<',"$git_dir/ctags") {2692while(my$line= <$fh>) {2693chomp$line;2694$ctags->{$line}++if$line;2695}2696close$fh;26972698}else{2699my$taglist= config_to_multi(git_get_project_config('ctag'));2700foreachmy$tag(@$taglist) {2701$ctags->{$tag}++;2702}2703}27042705return$ctags;2706}27072708# return hash, where keys are content tags ('ctags'),2709# and values are sum of weights of given tag in every project2710sub git_gather_all_ctags {2711my$projects=shift;2712my$ctags= {};27132714foreachmy$p(@$projects) {2715foreachmy$ct(keys%{$p->{'ctags'}}) {2716$ctags->{$ct} +=$p->{'ctags'}->{$ct};2717}2718}27192720return$ctags;2721}27222723sub git_populate_project_tagcloud {2724my$ctags=shift;27252726# First, merge different-cased tags; tags vote on casing2727my%ctags_lc;2728foreach(keys%$ctags) {2729$ctags_lc{lc$_}->{count} +=$ctags->{$_};2730if(not$ctags_lc{lc$_}->{topcount}2731or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2732$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2733$ctags_lc{lc$_}->{topname} =$_;2734}2735}27362737my$cloud;2738my$matched=$cgi->param('by_tag');2739if(eval{require HTML::TagCloud;1; }) {2740$cloud= HTML::TagCloud->new;2741foreachmy$ctag(sort keys%ctags_lc) {2742# Pad the title with spaces so that the cloud looks2743# less crammed.2744my$title= esc_html($ctags_lc{$ctag}->{topname});2745$title=~s/ / /g;2746$title=~s/^/ /g;2747$title=~s/$/ /g;2748if(defined$matched&&$matchedeq$ctag) {2749$title=qq(<span class="match">$title</span>);2750}2751$cloud->add($title, href(project=>undef, ctag=>$ctag),2752$ctags_lc{$ctag}->{count});2753}2754}else{2755$cloud= {};2756foreachmy$ctag(keys%ctags_lc) {2757my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2758if(defined$matched&&$matchedeq$ctag) {2759$title=qq(<span class="match">$title</span>);2760}2761$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2762$cloud->{$ctag}{ctag} =2763$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2764}2765}2766return$cloud;2767}27682769sub git_show_project_tagcloud {2770my($cloud,$count) =@_;2771if(ref$cloudeq'HTML::TagCloud') {2772return$cloud->html_and_css($count);2773}else{2774my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2775return2776'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2777join(', ',map{2778$cloud->{$_}->{'ctag'}2779}splice(@tags,0,$count)) .2780'</div>';2781}2782}27832784sub git_get_project_url_list {2785my$path=shift;27862787$git_dir="$projectroot/$path";2788open my$fd,'<',"$git_dir/cloneurl"2789orreturnwantarray?2790@{ config_to_multi(git_get_project_config('url')) } :2791 config_to_multi(git_get_project_config('url'));2792my@git_project_url_list=map{chomp;$_} <$fd>;2793close$fd;27942795returnwantarray?@git_project_url_list: \@git_project_url_list;2796}27972798sub git_get_projects_list {2799my$filter=shift||'';2800my@list;28012802$filter=~s/\.git$//;28032804if(-d $projects_list) {2805# search in directory2806my$dir=$projects_list;2807# remove the trailing "/"2808$dir=~s!/+$!!;2809my$pfxlen=length("$projects_list");2810my$pfxdepth= ($projects_list=~tr!/!!);2811# when filtering, search only given subdirectory2812if($filter) {2813$dir.="/$filter";2814$dir=~s!/+$!!;2815}28162817 File::Find::find({2818 follow_fast =>1,# follow symbolic links2819 follow_skip =>2,# ignore duplicates2820 dangling_symlinks =>0,# ignore dangling symlinks, silently2821 wanted =>sub{2822# global variables2823our$project_maxdepth;2824our$projectroot;2825# skip project-list toplevel, if we get it.2826return if(m!^[/.]$!);2827# only directories can be git repositories2828return unless(-d $_);2829# don't traverse too deep (Find is super slow on os x)2830# $project_maxdepth excludes depth of $projectroot2831if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2832$File::Find::prune =1;2833return;2834}28352836my$path=substr($File::Find::name,$pfxlen+1);2837# we check related file in $projectroot2838if(check_export_ok("$projectroot/$path")) {2839push@list, { path =>$path};2840$File::Find::prune =1;2841}2842},2843},"$dir");28442845}elsif(-f $projects_list) {2846# read from file(url-encoded):2847# 'git%2Fgit.git Linus+Torvalds'2848# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2849# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2850open my$fd,'<',$projects_listorreturn;2851 PROJECT:2852while(my$line= <$fd>) {2853chomp$line;2854my($path,$owner) =split' ',$line;2855$path= unescape($path);2856$owner= unescape($owner);2857if(!defined$path) {2858next;2859}2860# if $filter is rpovided, check if $path begins with $filter2861if($filter&&$path!~m!^\Q$filter\E/!) {2862next;2863}2864if(check_export_ok("$projectroot/$path")) {2865my$pr= {2866 path =>$path,2867 owner => to_utf8($owner),2868};2869push@list,$pr;2870}2871}2872close$fd;2873}2874return@list;2875}28762877# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)2878# as side effects it sets 'forks' field to list of forks for forked projects2879sub filter_forks_from_projects_list {2880my$projects=shift;28812882my%trie;# prefix tree of directories (path components)2883# generate trie out of those directories that might contain forks2884foreachmy$pr(@$projects) {2885my$path=$pr->{'path'};2886$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory2887next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'2888next unless($path);# skip '.git' repository: tests, git-instaweb2889next unless(-d $path);# containing directory exists2890$pr->{'forks'} = [];# there can be 0 or more forks of project28912892# add to trie2893my@dirs=split('/',$path);2894# walk the trie, until either runs out of components or out of trie2895my$ref= \%trie;2896while(scalar@dirs&&2897exists($ref->{$dirs[0]})) {2898$ref=$ref->{shift@dirs};2899}2900# create rest of trie structure from rest of components2901foreachmy$dir(@dirs) {2902$ref=$ref->{$dir} = {};2903}2904# create end marker, store $pr as a data2905$ref->{''} =$prif(!exists$ref->{''});2906}29072908# filter out forks, by finding shortest prefix match for paths2909my@filtered;2910 PROJECT:2911foreachmy$pr(@$projects) {2912# trie lookup2913my$ref= \%trie;2914 DIR:2915foreachmy$dir(split('/',$pr->{'path'})) {2916if(exists$ref->{''}) {2917# found [shortest] prefix, is a fork - skip it2918push@{$ref->{''}{'forks'}},$pr;2919next PROJECT;2920}2921if(!exists$ref->{$dir}) {2922# not in trie, cannot have prefix, not a fork2923push@filtered,$pr;2924next PROJECT;2925}2926# If the dir is there, we just walk one step down the trie.2927$ref=$ref->{$dir};2928}2929# we ran out of trie2930# (shouldn't happen: it's either no match, or end marker)2931push@filtered,$pr;2932}29332934return@filtered;2935}29362937# note: fill_project_list_info must be run first,2938# for 'descr_long' and 'ctags' to be filled2939sub search_projects_list {2940my($projlist,%opts) =@_;2941my$tagfilter=$opts{'tagfilter'};2942my$searchtext=$opts{'searchtext'};29432944return@$projlist2945unless($tagfilter||$searchtext);29462947my@projects;2948 PROJECT:2949foreachmy$pr(@$projlist) {29502951if($tagfilter) {2952next unlessref($pr->{'ctags'})eq'HASH';2953next unless2954grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};2955}29562957if($searchtext) {2958next unless2959$pr->{'path'} =~/$searchtext/||2960$pr->{'descr_long'} =~/$searchtext/;2961}29622963push@projects,$pr;2964}29652966return@projects;2967}29682969our$gitweb_project_owner=undef;2970sub git_get_project_list_from_file {29712972return if(defined$gitweb_project_owner);29732974$gitweb_project_owner= {};2975# read from file (url-encoded):2976# 'git%2Fgit.git Linus+Torvalds'2977# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2978# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2979if(-f $projects_list) {2980open(my$fd,'<',$projects_list);2981while(my$line= <$fd>) {2982chomp$line;2983my($pr,$ow) =split' ',$line;2984$pr= unescape($pr);2985$ow= unescape($ow);2986$gitweb_project_owner->{$pr} = to_utf8($ow);2987}2988close$fd;2989}2990}29912992sub git_get_project_owner {2993my$project=shift;2994my$owner;29952996returnundefunless$project;2997$git_dir="$projectroot/$project";29982999if(!defined$gitweb_project_owner) {3000 git_get_project_list_from_file();3001}30023003if(exists$gitweb_project_owner->{$project}) {3004$owner=$gitweb_project_owner->{$project};3005}3006if(!defined$owner){3007$owner= git_get_project_config('owner');3008}3009if(!defined$owner) {3010$owner= get_file_owner("$git_dir");3011}30123013return$owner;3014}30153016sub git_get_last_activity {3017my($path) =@_;3018my$fd;30193020$git_dir="$projectroot/$path";3021open($fd,"-|", git_cmd(),'for-each-ref',3022'--format=%(committer)',3023'--sort=-committerdate',3024'--count=1',3025'refs/heads')orreturn;3026my$most_recent= <$fd>;3027close$fdorreturn;3028if(defined$most_recent&&3029$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3030my$timestamp=$1;3031my$age=time-$timestamp;3032return($age, age_string($age));3033}3034return(undef,undef);3035}30363037# Implementation note: when a single remote is wanted, we cannot use 'git3038# remote show -n' because that command always work (assuming it's a remote URL3039# if it's not defined), and we cannot use 'git remote show' because that would3040# try to make a network roundtrip. So the only way to find if that particular3041# remote is defined is to walk the list provided by 'git remote -v' and stop if3042# and when we find what we want.3043sub git_get_remotes_list {3044my$wanted=shift;3045my%remotes= ();30463047open my$fd,'-|', git_cmd(),'remote','-v';3048return unless$fd;3049while(my$remote= <$fd>) {3050chomp$remote;3051$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3052next if$wantedand not$remoteeq$wanted;3053my($url,$key) = ($1,$2);30543055$remotes{$remote} ||= {'heads'=> () };3056$remotes{$remote}{$key} =$url;3057}3058close$fdorreturn;3059returnwantarray?%remotes: \%remotes;3060}30613062# Takes a hash of remotes as first parameter and fills it by adding the3063# available remote heads for each of the indicated remotes.3064sub fill_remote_heads {3065my$remotes=shift;3066my@heads=map{"remotes/$_"}keys%$remotes;3067my@remoteheads= git_get_heads_list(undef,@heads);3068foreachmy$remote(keys%$remotes) {3069$remotes->{$remote}{'heads'} = [grep{3070$_->{'name'} =~s!^$remote/!!3071}@remoteheads];3072}3073}30743075sub git_get_references {3076my$type=shift||"";3077my%refs;3078# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113079# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3080open my$fd,"-|", git_cmd(),"show-ref","--dereference",3081($type? ("--","refs/$type") : ())# use -- <pattern> if $type3082orreturn;30833084while(my$line= <$fd>) {3085chomp$line;3086if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3087if(defined$refs{$1}) {3088push@{$refs{$1}},$2;3089}else{3090$refs{$1} = [$2];3091}3092}3093}3094close$fdorreturn;3095return \%refs;3096}30973098sub git_get_rev_name_tags {3099my$hash=shift||returnundef;31003101open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3102orreturn;3103my$name_rev= <$fd>;3104close$fd;31053106if($name_rev=~ m|^$hash tags/(.*)$|) {3107return$1;3108}else{3109# catches also '$hash undefined' output3110returnundef;3111}3112}31133114## ----------------------------------------------------------------------3115## parse to hash functions31163117sub parse_date {3118my$epoch=shift;3119my$tz=shift||"-0000";31203121my%date;3122my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3123my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3124my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3125$date{'hour'} =$hour;3126$date{'minute'} =$min;3127$date{'mday'} =$mday;3128$date{'day'} =$days[$wday];3129$date{'month'} =$months[$mon];3130$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3131$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3132$date{'mday-time'} =sprintf"%d%s%02d:%02d",3133$mday,$months[$mon],$hour,$min;3134$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",31351900+$year,1+$mon,$mday,$hour,$min,$sec;31363137my($tz_sign,$tz_hour,$tz_min) =3138($tz=~m/^([-+])(\d\d)(\d\d)$/);3139$tz_sign= ($tz_signeq'-'? -1: +1);3140my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3141($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3142$date{'hour_local'} =$hour;3143$date{'minute_local'} =$min;3144$date{'tz_local'} =$tz;3145$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",31461900+$year,$mon+1,$mday,3147$hour,$min,$sec,$tz);3148return%date;3149}31503151sub parse_tag {3152my$tag_id=shift;3153my%tag;3154my@comment;31553156open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3157$tag{'id'} =$tag_id;3158while(my$line= <$fd>) {3159chomp$line;3160if($line=~m/^object ([0-9a-fA-F]{40})$/) {3161$tag{'object'} =$1;3162}elsif($line=~m/^type (.+)$/) {3163$tag{'type'} =$1;3164}elsif($line=~m/^tag (.+)$/) {3165$tag{'name'} =$1;3166}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3167$tag{'author'} =$1;3168$tag{'author_epoch'} =$2;3169$tag{'author_tz'} =$3;3170if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3171$tag{'author_name'} =$1;3172$tag{'author_email'} =$2;3173}else{3174$tag{'author_name'} =$tag{'author'};3175}3176}elsif($line=~m/--BEGIN/) {3177push@comment,$line;3178last;3179}elsif($lineeq"") {3180last;3181}3182}3183push@comment, <$fd>;3184$tag{'comment'} = \@comment;3185close$fdorreturn;3186if(!defined$tag{'name'}) {3187return3188};3189return%tag3190}31913192sub parse_commit_text {3193my($commit_text,$withparents) =@_;3194my@commit_lines=split'\n',$commit_text;3195my%co;31963197pop@commit_lines;# Remove '\0'31983199if(!@commit_lines) {3200return;3201}32023203my$header=shift@commit_lines;3204if($header!~m/^[0-9a-fA-F]{40}/) {3205return;3206}3207($co{'id'},my@parents) =split' ',$header;3208while(my$line=shift@commit_lines) {3209last if$lineeq"\n";3210if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3211$co{'tree'} =$1;3212}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3213push@parents,$1;3214}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3215$co{'author'} = to_utf8($1);3216$co{'author_epoch'} =$2;3217$co{'author_tz'} =$3;3218if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3219$co{'author_name'} =$1;3220$co{'author_email'} =$2;3221}else{3222$co{'author_name'} =$co{'author'};3223}3224}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3225$co{'committer'} = to_utf8($1);3226$co{'committer_epoch'} =$2;3227$co{'committer_tz'} =$3;3228if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3229$co{'committer_name'} =$1;3230$co{'committer_email'} =$2;3231}else{3232$co{'committer_name'} =$co{'committer'};3233}3234}3235}3236if(!defined$co{'tree'}) {3237return;3238};3239$co{'parents'} = \@parents;3240$co{'parent'} =$parents[0];32413242foreachmy$title(@commit_lines) {3243$title=~s/^ //;3244if($titlene"") {3245$co{'title'} = chop_str($title,80,5);3246# remove leading stuff of merges to make the interesting part visible3247if(length($title) >50) {3248$title=~s/^Automatic //;3249$title=~s/^merge (of|with) /Merge ... /i;3250if(length($title) >50) {3251$title=~s/(http|rsync):\/\///;3252}3253if(length($title) >50) {3254$title=~s/(master|www|rsync)\.//;3255}3256if(length($title) >50) {3257$title=~s/kernel.org:?//;3258}3259if(length($title) >50) {3260$title=~s/\/pub\/scm//;3261}3262}3263$co{'title_short'} = chop_str($title,50,5);3264last;3265}3266}3267if(!defined$co{'title'} ||$co{'title'}eq"") {3268$co{'title'} =$co{'title_short'} ='(no commit message)';3269}3270# remove added spaces3271foreachmy$line(@commit_lines) {3272$line=~s/^ //;3273}3274$co{'comment'} = \@commit_lines;32753276my$age=time-$co{'committer_epoch'};3277$co{'age'} =$age;3278$co{'age_string'} = age_string($age);3279my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3280if($age>60*60*24*7*2) {3281$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3282$co{'age_string_age'} =$co{'age_string'};3283}else{3284$co{'age_string_date'} =$co{'age_string'};3285$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3286}3287return%co;3288}32893290sub parse_commit {3291my($commit_id) =@_;3292my%co;32933294local$/="\0";32953296open my$fd,"-|", git_cmd(),"rev-list",3297"--parents",3298"--header",3299"--max-count=1",3300$commit_id,3301"--",3302or die_error(500,"Open git-rev-list failed");3303%co= parse_commit_text(<$fd>,1);3304close$fd;33053306return%co;3307}33083309sub parse_commits {3310my($commit_id,$maxcount,$skip,$filename,@args) =@_;3311my@cos;33123313$maxcount||=1;3314$skip||=0;33153316local$/="\0";33173318open my$fd,"-|", git_cmd(),"rev-list",3319"--header",3320@args,3321("--max-count=".$maxcount),3322("--skip=".$skip),3323@extra_options,3324$commit_id,3325"--",3326($filename? ($filename) : ())3327or die_error(500,"Open git-rev-list failed");3328while(my$line= <$fd>) {3329my%co= parse_commit_text($line);3330push@cos, \%co;3331}3332close$fd;33333334returnwantarray?@cos: \@cos;3335}33363337# parse line of git-diff-tree "raw" output3338sub parse_difftree_raw_line {3339my$line=shift;3340my%res;33413342# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3343# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3344if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3345$res{'from_mode'} =$1;3346$res{'to_mode'} =$2;3347$res{'from_id'} =$3;3348$res{'to_id'} =$4;3349$res{'status'} =$5;3350$res{'similarity'} =$6;3351if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3352($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3353}else{3354$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3355}3356}3357# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3358# combined diff (for merge commit)3359elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3360$res{'nparents'} =length($1);3361$res{'from_mode'} = [split(' ',$2) ];3362$res{'to_mode'} =pop@{$res{'from_mode'}};3363$res{'from_id'} = [split(' ',$3) ];3364$res{'to_id'} =pop@{$res{'from_id'}};3365$res{'status'} = [split('',$4) ];3366$res{'to_file'} = unquote($5);3367}3368# 'c512b523472485aef4fff9e57b229d9d243c967f'3369elsif($line=~m/^([0-9a-fA-F]{40})$/) {3370$res{'commit'} =$1;3371}33723373returnwantarray?%res: \%res;3374}33753376# wrapper: return parsed line of git-diff-tree "raw" output3377# (the argument might be raw line, or parsed info)3378sub parsed_difftree_line {3379my$line_or_ref=shift;33803381if(ref($line_or_ref)eq"HASH") {3382# pre-parsed (or generated by hand)3383return$line_or_ref;3384}else{3385return parse_difftree_raw_line($line_or_ref);3386}3387}33883389# parse line of git-ls-tree output3390sub parse_ls_tree_line {3391my$line=shift;3392my%opts=@_;3393my%res;33943395if($opts{'-l'}) {3396#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3397$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;33983399$res{'mode'} =$1;3400$res{'type'} =$2;3401$res{'hash'} =$3;3402$res{'size'} =$4;3403if($opts{'-z'}) {3404$res{'name'} =$5;3405}else{3406$res{'name'} = unquote($5);3407}3408}else{3409#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3410$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;34113412$res{'mode'} =$1;3413$res{'type'} =$2;3414$res{'hash'} =$3;3415if($opts{'-z'}) {3416$res{'name'} =$4;3417}else{3418$res{'name'} = unquote($4);3419}3420}34213422returnwantarray?%res: \%res;3423}34243425# generates _two_ hashes, references to which are passed as 2 and 3 argument3426sub parse_from_to_diffinfo {3427my($diffinfo,$from,$to,@parents) =@_;34283429if($diffinfo->{'nparents'}) {3430# combined diff3431$from->{'file'} = [];3432$from->{'href'} = [];3433 fill_from_file_info($diffinfo,@parents)3434unlessexists$diffinfo->{'from_file'};3435for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3436$from->{'file'}[$i] =3437defined$diffinfo->{'from_file'}[$i] ?3438$diffinfo->{'from_file'}[$i] :3439$diffinfo->{'to_file'};3440if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3441$from->{'href'}[$i] = href(action=>"blob",3442 hash_base=>$parents[$i],3443 hash=>$diffinfo->{'from_id'}[$i],3444 file_name=>$from->{'file'}[$i]);3445}else{3446$from->{'href'}[$i] =undef;3447}3448}3449}else{3450# ordinary (not combined) diff3451$from->{'file'} =$diffinfo->{'from_file'};3452if($diffinfo->{'status'}ne"A") {# not new (added) file3453$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3454 hash=>$diffinfo->{'from_id'},3455 file_name=>$from->{'file'});3456}else{3457delete$from->{'href'};3458}3459}34603461$to->{'file'} =$diffinfo->{'to_file'};3462if(!is_deleted($diffinfo)) {# file exists in result3463$to->{'href'} = href(action=>"blob", hash_base=>$hash,3464 hash=>$diffinfo->{'to_id'},3465 file_name=>$to->{'file'});3466}else{3467delete$to->{'href'};3468}3469}34703471## ......................................................................3472## parse to array of hashes functions34733474sub git_get_heads_list {3475my($limit,@classes) =@_;3476@classes= ('heads')unless@classes;3477my@patterns=map{"refs/$_"}@classes;3478my@headslist;34793480open my$fd,'-|', git_cmd(),'for-each-ref',3481($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3482'--format=%(objectname) %(refname) %(subject)%00%(committer)',3483@patterns3484orreturn;3485while(my$line= <$fd>) {3486my%ref_item;34873488chomp$line;3489my($refinfo,$committerinfo) =split(/\0/,$line);3490my($hash,$name,$title) =split(' ',$refinfo,3);3491my($committer,$epoch,$tz) =3492($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3493$ref_item{'fullname'} =$name;3494$name=~s!^refs/(?:head|remote)s/!!;34953496$ref_item{'name'} =$name;3497$ref_item{'id'} =$hash;3498$ref_item{'title'} =$title||'(no commit message)';3499$ref_item{'epoch'} =$epoch;3500if($epoch) {3501$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3502}else{3503$ref_item{'age'} ="unknown";3504}35053506push@headslist, \%ref_item;3507}3508close$fd;35093510returnwantarray?@headslist: \@headslist;3511}35123513sub git_get_tags_list {3514my$limit=shift;3515my@tagslist;35163517open my$fd,'-|', git_cmd(),'for-each-ref',3518($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3519'--format=%(objectname) %(objecttype) %(refname) '.3520'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3521'refs/tags'3522orreturn;3523while(my$line= <$fd>) {3524my%ref_item;35253526chomp$line;3527my($refinfo,$creatorinfo) =split(/\0/,$line);3528my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3529my($creator,$epoch,$tz) =3530($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3531$ref_item{'fullname'} =$name;3532$name=~s!^refs/tags/!!;35333534$ref_item{'type'} =$type;3535$ref_item{'id'} =$id;3536$ref_item{'name'} =$name;3537if($typeeq"tag") {3538$ref_item{'subject'} =$title;3539$ref_item{'reftype'} =$reftype;3540$ref_item{'refid'} =$refid;3541}else{3542$ref_item{'reftype'} =$type;3543$ref_item{'refid'} =$id;3544}35453546if($typeeq"tag"||$typeeq"commit") {3547$ref_item{'epoch'} =$epoch;3548if($epoch) {3549$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3550}else{3551$ref_item{'age'} ="unknown";3552}3553}35543555push@tagslist, \%ref_item;3556}3557close$fd;35583559returnwantarray?@tagslist: \@tagslist;3560}35613562## ----------------------------------------------------------------------3563## filesystem-related functions35643565sub get_file_owner {3566my$path=shift;35673568my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3569my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3570if(!defined$gcos) {3571returnundef;3572}3573my$owner=$gcos;3574$owner=~s/[,;].*$//;3575return to_utf8($owner);3576}35773578# assume that file exists3579sub insert_file {3580my$filename=shift;35813582open my$fd,'<',$filename;3583print map{ to_utf8($_) } <$fd>;3584close$fd;3585}35863587## ......................................................................3588## mimetype related functions35893590sub mimetype_guess_file {3591my$filename=shift;3592my$mimemap=shift;3593-r $mimemaporreturnundef;35943595my%mimemap;3596open(my$mh,'<',$mimemap)orreturnundef;3597while(<$mh>) {3598next ifm/^#/;# skip comments3599my($mimetype,@exts) =split(/\s+/);3600foreachmy$ext(@exts) {3601$mimemap{$ext} =$mimetype;3602}3603}3604close($mh);36053606$filename=~/\.([^.]*)$/;3607return$mimemap{$1};3608}36093610sub mimetype_guess {3611my$filename=shift;3612my$mime;3613$filename=~/\./orreturnundef;36143615if($mimetypes_file) {3616my$file=$mimetypes_file;3617if($file!~m!^/!) {# if it is relative path3618# it is relative to project3619$file="$projectroot/$project/$file";3620}3621$mime= mimetype_guess_file($filename,$file);3622}3623$mime||= mimetype_guess_file($filename,'/etc/mime.types');3624return$mime;3625}36263627sub blob_mimetype {3628my$fd=shift;3629my$filename=shift;36303631if($filename) {3632my$mime= mimetype_guess($filename);3633$mimeandreturn$mime;3634}36353636# just in case3637return$default_blob_plain_mimetypeunless$fd;36383639if(-T $fd) {3640return'text/plain';3641}elsif(!$filename) {3642return'application/octet-stream';3643}elsif($filename=~m/\.png$/i) {3644return'image/png';3645}elsif($filename=~m/\.gif$/i) {3646return'image/gif';3647}elsif($filename=~m/\.jpe?g$/i) {3648return'image/jpeg';3649}else{3650return'application/octet-stream';3651}3652}36533654sub blob_contenttype {3655my($fd,$file_name,$type) =@_;36563657$type||= blob_mimetype($fd,$file_name);3658if($typeeq'text/plain'&&defined$default_text_plain_charset) {3659$type.="; charset=$default_text_plain_charset";3660}36613662return$type;3663}36643665# guess file syntax for syntax highlighting; return undef if no highlighting3666# the name of syntax can (in the future) depend on syntax highlighter used3667sub guess_file_syntax {3668my($highlight,$mimetype,$file_name) =@_;3669returnundefunless($highlight&&defined$file_name);3670my$basename= basename($file_name,'.in');3671return$highlight_basename{$basename}3672ifexists$highlight_basename{$basename};36733674$basename=~/\.([^.]*)$/;3675my$ext=$1orreturnundef;3676return$highlight_ext{$ext}3677ifexists$highlight_ext{$ext};36783679returnundef;3680}36813682# run highlighter and return FD of its output,3683# or return original FD if no highlighting3684sub run_highlighter {3685my($fd,$highlight,$syntax) =@_;3686return$fdunless($highlight&&defined$syntax);36873688close$fd;3689open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3690 quote_command($highlight_bin).3691" --replace-tabs=8 --fragment --syntax$syntax|"3692or die_error(500,"Couldn't open file or run syntax highlighter");3693return$fd;3694}36953696## ======================================================================3697## functions printing HTML: header, footer, error page36983699sub get_page_title {3700my$title= to_utf8($site_name);37013702return$titleunless(defined$project);3703$title.=" - ". to_utf8($project);37043705return$titleunless(defined$action);3706$title.="/$action";# $action is US-ASCII (7bit ASCII)37073708return$titleunless(defined$file_name);3709$title.=" - ". esc_path($file_name);3710if($actioneq"tree"&&$file_name!~ m|/$|) {3711$title.="/";3712}37133714return$title;3715}37163717sub get_content_type_html {3718# require explicit support from the UA if we are to send the page as3719# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3720# we have to do this because MSIE sometimes globs '*/*', pretending to3721# support xhtml+xml but choking when it gets what it asked for.3722if(defined$cgi->http('HTTP_ACCEPT') &&3723$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3724$cgi->Accept('application/xhtml+xml') !=0) {3725return'application/xhtml+xml';3726}else{3727return'text/html';3728}3729}37303731sub print_feed_meta {3732if(defined$project) {3733my%href_params= get_feed_info();3734if(!exists$href_params{'-title'}) {3735$href_params{'-title'} ='log';3736}37373738foreachmy$format(qw(RSS Atom)) {3739my$type=lc($format);3740my%link_attr= (3741'-rel'=>'alternate',3742'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3743'-type'=>"application/$type+xml"3744);37453746$href_params{'action'} =$type;3747$link_attr{'-href'} = href(%href_params);3748print"<link ".3749"rel=\"$link_attr{'-rel'}\"".3750"title=\"$link_attr{'-title'}\"".3751"href=\"$link_attr{'-href'}\"".3752"type=\"$link_attr{'-type'}\"".3753"/>\n";37543755$href_params{'extra_options'} ='--no-merges';3756$link_attr{'-href'} = href(%href_params);3757$link_attr{'-title'} .=' (no merges)';3758print"<link ".3759"rel=\"$link_attr{'-rel'}\"".3760"title=\"$link_attr{'-title'}\"".3761"href=\"$link_attr{'-href'}\"".3762"type=\"$link_attr{'-type'}\"".3763"/>\n";3764}37653766}else{3767printf('<link rel="alternate" title="%sprojects list" '.3768'href="%s" type="text/plain; charset=utf-8" />'."\n",3769 esc_attr($site_name), href(project=>undef, action=>"project_index"));3770printf('<link rel="alternate" title="%sprojects feeds" '.3771'href="%s" type="text/x-opml" />'."\n",3772 esc_attr($site_name), href(project=>undef, action=>"opml"));3773}3774}37753776sub print_header_links {3777my$status=shift;37783779# print out each stylesheet that exist, providing backwards capability3780# for those people who defined $stylesheet in a config file3781if(defined$stylesheet) {3782print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3783}else{3784foreachmy$stylesheet(@stylesheets) {3785next unless$stylesheet;3786print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3787}3788}3789 print_feed_meta()3790if($statuseq'200 OK');3791if(defined$favicon) {3792printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3793}3794}37953796sub print_nav_breadcrumbs {3797my%opts=@_;37983799print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3800if(defined$project) {3801print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3802if(defined$action) {3803my$action_print=$action;3804if(defined$opts{-action_extra}) {3805$action_print=$cgi->a({-href => href(action=>$action)},3806$action);3807}3808print" /$action_print";3809}3810if(defined$opts{-action_extra}) {3811print" /$opts{-action_extra}";3812}3813print"\n";3814}3815}38163817sub print_search_form {3818if(!defined$searchtext) {3819$searchtext="";3820}3821my$search_hash;3822if(defined$hash_base) {3823$search_hash=$hash_base;3824}elsif(defined$hash) {3825$search_hash=$hash;3826}else{3827$search_hash="HEAD";3828}3829my$action=$my_uri;3830my$use_pathinfo= gitweb_check_feature('pathinfo');3831if($use_pathinfo) {3832$action.="/".esc_url($project);3833}3834print$cgi->startform(-method=>"get", -action =>$action) .3835"<div class=\"search\">\n".3836(!$use_pathinfo&&3837$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3838$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3839$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3840$cgi->popup_menu(-name =>'st', -default=>'commit',3841-values=> ['commit','grep','author','committer','pickaxe']) .3842$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3843" search:\n",3844$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3845"<span title=\"Extended regular expression\">".3846$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3847-checked =>$search_use_regexp) .3848"</span>".3849"</div>".3850$cgi->end_form() ."\n";3851}38523853sub git_header_html {3854my$status=shift||"200 OK";3855my$expires=shift;3856my%opts=@_;38573858my$title= get_page_title();3859my$content_type= get_content_type_html();3860print$cgi->header(-type=>$content_type, -charset =>'utf-8',3861-status=>$status, -expires =>$expires)3862unless($opts{'-no_http_header'});3863my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3864print<<EOF;3865<?xml version="1.0" encoding="utf-8"?>3866<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3867<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3868<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3869<!-- git core binaries version$git_version-->3870<head>3871<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3872<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3873<meta name="robots" content="index, nofollow"/>3874<title>$title</title>3875EOF3876# the stylesheet, favicon etc urls won't work correctly with path_info3877# unless we set the appropriate base URL3878if($ENV{'PATH_INFO'}) {3879print"<base href=\"".esc_url($base_url)."\"/>\n";3880}3881 print_header_links($status);3882print"</head>\n".3883"<body>\n";38843885if(defined$site_header&& -f $site_header) {3886 insert_file($site_header);3887}38883889print"<div class=\"page_header\">\n";3890if(defined$logo) {3891print$cgi->a({-href => esc_url($logo_url),3892-title =>$logo_label},3893$cgi->img({-src => esc_url($logo),3894-width =>72, -height =>27,3895-alt =>"git",3896-class=>"logo"}));3897}3898 print_nav_breadcrumbs(%opts);3899print"</div>\n";39003901my$have_search= gitweb_check_feature('search');3902if(defined$project&&$have_search) {3903 print_search_form();3904}3905}39063907sub git_footer_html {3908my$feed_class='rss_logo';39093910print"<div class=\"page_footer\">\n";3911if(defined$project) {3912my$descr= git_get_project_description($project);3913if(defined$descr) {3914print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3915}39163917my%href_params= get_feed_info();3918if(!%href_params) {3919$feed_class.=' generic';3920}3921$href_params{'-title'} ||='log';39223923foreachmy$format(qw(RSS Atom)) {3924$href_params{'action'} =lc($format);3925print$cgi->a({-href => href(%href_params),3926-title =>"$href_params{'-title'}$formatfeed",3927-class=>$feed_class},$format)."\n";3928}39293930}else{3931print$cgi->a({-href => href(project=>undef, action=>"opml"),3932-class=>$feed_class},"OPML") ." ";3933print$cgi->a({-href => href(project=>undef, action=>"project_index"),3934-class=>$feed_class},"TXT") ."\n";3935}3936print"</div>\n";# class="page_footer"39373938if(defined$t0&& gitweb_check_feature('timed')) {3939print"<div id=\"generating_info\">\n";3940print'This page took '.3941'<span id="generating_time" class="time_span">'.3942 tv_interval($t0, [ gettimeofday() ]).3943' seconds </span>'.3944' and '.3945'<span id="generating_cmd">'.3946$number_of_git_cmds.3947'</span> git commands '.3948" to generate.\n";3949print"</div>\n";# class="page_footer"3950}39513952if(defined$site_footer&& -f $site_footer) {3953 insert_file($site_footer);3954}39553956print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3957if(defined$action&&3958$actioneq'blame_incremental') {3959print qq!<script type="text/javascript">\n!.3960 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3961 qq!"!. href() .qq!");\n!.3962 qq!</script>\n!;3963}else{3964my($jstimezone,$tz_cookie,$datetime_class) =3965 gitweb_get_feature('javascript-timezone');39663967print qq!<script type="text/javascript">\n!.3968 qq!window.onload = function () {\n!;3969if(gitweb_check_feature('javascript-actions')) {3970print qq! fixLinks();\n!;3971}3972if($jstimezone&&$tz_cookie&&$datetime_class) {3973print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days3974 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;3975}3976print qq!};\n!.3977 qq!</script>\n!;3978}39793980print"</body>\n".3981"</html>";3982}39833984# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3985# Example: die_error(404, 'Hash not found')3986# By convention, use the following status codes (as defined in RFC 2616):3987# 400: Invalid or missing CGI parameters, or3988# requested object exists but has wrong type.3989# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3990# this server or project.3991# 404: Requested object/revision/project doesn't exist.3992# 500: The server isn't configured properly, or3993# an internal error occurred (e.g. failed assertions caused by bugs), or3994# an unknown error occurred (e.g. the git binary died unexpectedly).3995# 503: The server is currently unavailable (because it is overloaded,3996# or down for maintenance). Generally, this is a temporary state.3997sub die_error {3998my$status=shift||500;3999my$error= esc_html(shift) ||"Internal Server Error";4000my$extra=shift;4001my%opts=@_;40024003my%http_responses= (4004400=>'400 Bad Request',4005403=>'403 Forbidden',4006404=>'404 Not Found',4007500=>'500 Internal Server Error',4008503=>'503 Service Unavailable',4009);4010 git_header_html($http_responses{$status},undef,%opts);4011print<<EOF;4012<div class="page_body">4013<br /><br />4014$status-$error4015<br />4016EOF4017if(defined$extra) {4018print"<hr />\n".4019"$extra\n";4020}4021print"</div>\n";40224023 git_footer_html();4024goto DONE_GITWEB4025unless($opts{'-error_handler'});4026}40274028## ----------------------------------------------------------------------4029## functions printing or outputting HTML: navigation40304031sub git_print_page_nav {4032my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4033$extra=''if!defined$extra;# pager or formats40344035my@navs=qw(summary shortlog log commit commitdiff tree);4036if($suppress) {4037@navs=grep{$_ne$suppress}@navs;4038}40394040my%arg=map{$_=> {action=>$_} }@navs;4041if(defined$head) {4042for(qw(commit commitdiff)) {4043$arg{$_}{'hash'} =$head;4044}4045if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4046for(qw(shortlog log)) {4047$arg{$_}{'hash'} =$head;4048}4049}4050}40514052$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4053$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;40544055my@actions= gitweb_get_feature('actions');4056my%repl= (4057'%'=>'%',4058'n'=>$project,# project name4059'f'=>$git_dir,# project path within filesystem4060'h'=>$treehead||'',# current hash ('h' parameter)4061'b'=>$treebase||'',# hash base ('hb' parameter)4062);4063while(@actions) {4064my($label,$link,$pos) =splice(@actions,0,3);4065# insert4066@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4067# munch munch4068$link=~s/%([%nfhb])/$repl{$1}/g;4069$arg{$label}{'_href'} =$link;4070}40714072print"<div class=\"page_nav\">\n".4073(join" | ",4074map{$_eq$current?4075$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4076}@navs);4077print"<br/>\n$extra<br/>\n".4078"</div>\n";4079}40804081# returns a submenu for the nagivation of the refs views (tags, heads,4082# remotes) with the current view disabled and the remotes view only4083# available if the feature is enabled4084sub format_ref_views {4085my($current) =@_;4086my@ref_views=qw{tags heads};4087push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4088returnjoin" | ",map{4089$_eq$current?$_:4090$cgi->a({-href => href(action=>$_)},$_)4091}@ref_views4092}40934094sub format_paging_nav {4095my($action,$page,$has_next_link) =@_;4096my$paging_nav;409740984099if($page>0) {4100$paging_nav.=4101$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4102" ⋅ ".4103$cgi->a({-href => href(-replay=>1, page=>$page-1),4104-accesskey =>"p", -title =>"Alt-p"},"prev");4105}else{4106$paging_nav.="first ⋅ prev";4107}41084109if($has_next_link) {4110$paging_nav.=" ⋅ ".4111$cgi->a({-href => href(-replay=>1, page=>$page+1),4112-accesskey =>"n", -title =>"Alt-n"},"next");4113}else{4114$paging_nav.=" ⋅ next";4115}41164117return$paging_nav;4118}41194120## ......................................................................4121## functions printing or outputting HTML: div41224123sub git_print_header_div {4124my($action,$title,$hash,$hash_base) =@_;4125my%args= ();41264127$args{'action'} =$action;4128$args{'hash'} =$hashif$hash;4129$args{'hash_base'} =$hash_baseif$hash_base;41304131print"<div class=\"header\">\n".4132$cgi->a({-href => href(%args), -class=>"title"},4133$title?$title:$action) .4134"\n</div>\n";4135}41364137sub format_repo_url {4138my($name,$url) =@_;4139return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4140}41414142# Group output by placing it in a DIV element and adding a header.4143# Options for start_div() can be provided by passing a hash reference as the4144# first parameter to the function.4145# Options to git_print_header_div() can be provided by passing an array4146# reference. This must follow the options to start_div if they are present.4147# The content can be a scalar, which is output as-is, a scalar reference, which4148# is output after html escaping, an IO handle passed either as *handle or4149# *handle{IO}, or a function reference. In the latter case all following4150# parameters will be taken as argument to the content function call.4151sub git_print_section {4152my($div_args,$header_args,$content);4153my$arg=shift;4154if(ref($arg)eq'HASH') {4155$div_args=$arg;4156$arg=shift;4157}4158if(ref($arg)eq'ARRAY') {4159$header_args=$arg;4160$arg=shift;4161}4162$content=$arg;41634164print$cgi->start_div($div_args);4165 git_print_header_div(@$header_args);41664167if(ref($content)eq'CODE') {4168$content->(@_);4169}elsif(ref($content)eq'SCALAR') {4170print esc_html($$content);4171}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4172print<$content>;4173}elsif(!ref($content) &&defined($content)) {4174print$content;4175}41764177print$cgi->end_div;4178}41794180sub format_timestamp_html {4181my$date=shift;4182my$strtime=$date->{'rfc2822'};41834184my(undef,undef,$datetime_class) =4185 gitweb_get_feature('javascript-timezone');4186if($datetime_class) {4187$strtime= qq!<span class="$datetime_class">$strtime</span>!;4188}41894190my$localtime_format='(%02d:%02d%s)';4191if($date->{'hour_local'} <6) {4192$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4193}4194$strtime.=' '.4195sprintf($localtime_format,4196$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});41974198return$strtime;4199}42004201# Outputs the author name and date in long form4202sub git_print_authorship {4203my$co=shift;4204my%opts=@_;4205my$tag=$opts{-tag} ||'div';4206my$author=$co->{'author_name'};42074208my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4209print"<$tagclass=\"author_date\">".4210 format_search_author($author,"author", esc_html($author)) .4211" [".format_timestamp_html(\%ad)."]".4212 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4213"</$tag>\n";4214}42154216# Outputs table rows containing the full author or committer information,4217# in the format expected for 'commit' view (& similar).4218# Parameters are a commit hash reference, followed by the list of people4219# to output information for. If the list is empty it defaults to both4220# author and committer.4221sub git_print_authorship_rows {4222my$co=shift;4223# too bad we can't use @people = @_ || ('author', 'committer')4224my@people=@_;4225@people= ('author','committer')unless@people;4226foreachmy$who(@people) {4227my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4228print"<tr><td>$who</td><td>".4229 format_search_author($co->{"${who}_name"},$who,4230 esc_html($co->{"${who}_name"})) ." ".4231 format_search_author($co->{"${who}_email"},$who,4232 esc_html("<".$co->{"${who}_email"} .">")) .4233"</td><td rowspan=\"2\">".4234 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4235"</td></tr>\n".4236"<tr>".4237"<td></td><td>".4238 format_timestamp_html(\%wd) .4239"</td>".4240"</tr>\n";4241}4242}42434244sub git_print_page_path {4245my$name=shift;4246my$type=shift;4247my$hb=shift;424842494250print"<div class=\"page_path\">";4251print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4252-title =>'tree root'}, to_utf8("[$project]"));4253print" / ";4254if(defined$name) {4255my@dirname=split'/',$name;4256my$basename=pop@dirname;4257my$fullname='';42584259foreachmy$dir(@dirname) {4260$fullname.= ($fullname?'/':'') .$dir;4261print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4262 hash_base=>$hb),4263-title =>$fullname}, esc_path($dir));4264print" / ";4265}4266if(defined$type&&$typeeq'blob') {4267print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4268 hash_base=>$hb),4269-title =>$name}, esc_path($basename));4270}elsif(defined$type&&$typeeq'tree') {4271print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4272 hash_base=>$hb),4273-title =>$name}, esc_path($basename));4274print" / ";4275}else{4276print esc_path($basename);4277}4278}4279print"<br/></div>\n";4280}42814282sub git_print_log {4283my$log=shift;4284my%opts=@_;42854286if($opts{'-remove_title'}) {4287# remove title, i.e. first line of log4288shift@$log;4289}4290# remove leading empty lines4291while(defined$log->[0] &&$log->[0]eq"") {4292shift@$log;4293}42944295# print log4296my$signoff=0;4297my$empty=0;4298foreachmy$line(@$log) {4299if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {4300$signoff=1;4301$empty=0;4302if(!$opts{'-remove_signoff'}) {4303print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4304next;4305}else{4306# remove signoff lines4307next;4308}4309}else{4310$signoff=0;4311}43124313# print only one empty line4314# do not print empty line after signoff4315if($lineeq"") {4316next if($empty||$signoff);4317$empty=1;4318}else{4319$empty=0;4320}43214322print format_log_line_html($line) ."<br/>\n";4323}43244325if($opts{'-final_empty_line'}) {4326# end with single empty line4327print"<br/>\n"unless$empty;4328}4329}43304331# return link target (what link points to)4332sub git_get_link_target {4333my$hash=shift;4334my$link_target;43354336# read link4337open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4338orreturn;4339{4340local$/=undef;4341$link_target= <$fd>;4342}4343close$fd4344orreturn;43454346return$link_target;4347}43484349# given link target, and the directory (basedir) the link is in,4350# return target of link relative to top directory (top tree);4351# return undef if it is not possible (including absolute links).4352sub normalize_link_target {4353my($link_target,$basedir) =@_;43544355# absolute symlinks (beginning with '/') cannot be normalized4356return if(substr($link_target,0,1)eq'/');43574358# normalize link target to path from top (root) tree (dir)4359my$path;4360if($basedir) {4361$path=$basedir.'/'.$link_target;4362}else{4363# we are in top (root) tree (dir)4364$path=$link_target;4365}43664367# remove //, /./, and /../4368my@path_parts;4369foreachmy$part(split('/',$path)) {4370# discard '.' and ''4371next if(!$part||$parteq'.');4372# handle '..'4373if($parteq'..') {4374if(@path_parts) {4375pop@path_parts;4376}else{4377# link leads outside repository (outside top dir)4378return;4379}4380}else{4381push@path_parts,$part;4382}4383}4384$path=join('/',@path_parts);43854386return$path;4387}43884389# print tree entry (row of git_tree), but without encompassing <tr> element4390sub git_print_tree_entry {4391my($t,$basedir,$hash_base,$have_blame) =@_;43924393my%base_key= ();4394$base_key{'hash_base'} =$hash_baseifdefined$hash_base;43954396# The format of a table row is: mode list link. Where mode is4397# the mode of the entry, list is the name of the entry, an href,4398# and link is the action links of the entry.43994400print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4401if(exists$t->{'size'}) {4402print"<td class=\"size\">$t->{'size'}</td>\n";4403}4404if($t->{'type'}eq"blob") {4405print"<td class=\"list\">".4406$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4407 file_name=>"$basedir$t->{'name'}",%base_key),4408-class=>"list"}, esc_path($t->{'name'}));4409if(S_ISLNK(oct$t->{'mode'})) {4410my$link_target= git_get_link_target($t->{'hash'});4411if($link_target) {4412my$norm_target= normalize_link_target($link_target,$basedir);4413if(defined$norm_target) {4414print" -> ".4415$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4416 file_name=>$norm_target),4417-title =>$norm_target}, esc_path($link_target));4418}else{4419print" -> ". esc_path($link_target);4420}4421}4422}4423print"</td>\n";4424print"<td class=\"link\">";4425print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4426 file_name=>"$basedir$t->{'name'}",%base_key)},4427"blob");4428if($have_blame) {4429print" | ".4430$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4431 file_name=>"$basedir$t->{'name'}",%base_key)},4432"blame");4433}4434if(defined$hash_base) {4435print" | ".4436$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4437 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4438"history");4439}4440print" | ".4441$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4442 file_name=>"$basedir$t->{'name'}")},4443"raw");4444print"</td>\n";44454446}elsif($t->{'type'}eq"tree") {4447print"<td class=\"list\">";4448print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4449 file_name=>"$basedir$t->{'name'}",4450%base_key)},4451 esc_path($t->{'name'}));4452print"</td>\n";4453print"<td class=\"link\">";4454print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4455 file_name=>"$basedir$t->{'name'}",4456%base_key)},4457"tree");4458if(defined$hash_base) {4459print" | ".4460$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4461 file_name=>"$basedir$t->{'name'}")},4462"history");4463}4464print"</td>\n";4465}else{4466# unknown object: we can only present history for it4467# (this includes 'commit' object, i.e. submodule support)4468print"<td class=\"list\">".4469 esc_path($t->{'name'}) .4470"</td>\n";4471print"<td class=\"link\">";4472if(defined$hash_base) {4473print$cgi->a({-href => href(action=>"history",4474 hash_base=>$hash_base,4475 file_name=>"$basedir$t->{'name'}")},4476"history");4477}4478print"</td>\n";4479}4480}44814482## ......................................................................4483## functions printing large fragments of HTML44844485# get pre-image filenames for merge (combined) diff4486sub fill_from_file_info {4487my($diff,@parents) =@_;44884489$diff->{'from_file'} = [ ];4490$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4491for(my$i=0;$i<$diff->{'nparents'};$i++) {4492if($diff->{'status'}[$i]eq'R'||4493$diff->{'status'}[$i]eq'C') {4494$diff->{'from_file'}[$i] =4495 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4496}4497}44984499return$diff;4500}45014502# is current raw difftree line of file deletion4503sub is_deleted {4504my$diffinfo=shift;45054506return$diffinfo->{'to_id'}eq('0' x 40);4507}45084509# does patch correspond to [previous] difftree raw line4510# $diffinfo - hashref of parsed raw diff format4511# $patchinfo - hashref of parsed patch diff format4512# (the same keys as in $diffinfo)4513sub is_patch_split {4514my($diffinfo,$patchinfo) =@_;45154516returndefined$diffinfo&&defined$patchinfo4517&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4518}451945204521sub git_difftree_body {4522my($difftree,$hash,@parents) =@_;4523my($parent) =$parents[0];4524my$have_blame= gitweb_check_feature('blame');4525print"<div class=\"list_head\">\n";4526if($#{$difftree} >10) {4527print(($#{$difftree} +1) ." files changed:\n");4528}4529print"</div>\n";45304531print"<table class=\"".4532(@parents>1?"combined ":"") .4533"diff_tree\">\n";45344535# header only for combined diff in 'commitdiff' view4536my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4537if($has_header) {4538# table header4539print"<thead><tr>\n".4540"<th></th><th></th>\n";# filename, patchN link4541for(my$i=0;$i<@parents;$i++) {4542my$par=$parents[$i];4543print"<th>".4544$cgi->a({-href => href(action=>"commitdiff",4545 hash=>$hash, hash_parent=>$par),4546-title =>'commitdiff to parent number '.4547($i+1) .': '.substr($par,0,7)},4548$i+1) .4549" </th>\n";4550}4551print"</tr></thead>\n<tbody>\n";4552}45534554my$alternate=1;4555my$patchno=0;4556foreachmy$line(@{$difftree}) {4557my$diff= parsed_difftree_line($line);45584559if($alternate) {4560print"<tr class=\"dark\">\n";4561}else{4562print"<tr class=\"light\">\n";4563}4564$alternate^=1;45654566if(exists$diff->{'nparents'}) {# combined diff45674568 fill_from_file_info($diff,@parents)4569unlessexists$diff->{'from_file'};45704571if(!is_deleted($diff)) {4572# file exists in the result (child) commit4573print"<td>".4574$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4575 file_name=>$diff->{'to_file'},4576 hash_base=>$hash),4577-class=>"list"}, esc_path($diff->{'to_file'})) .4578"</td>\n";4579}else{4580print"<td>".4581 esc_path($diff->{'to_file'}) .4582"</td>\n";4583}45844585if($actioneq'commitdiff') {4586# link to patch4587$patchno++;4588print"<td class=\"link\">".4589$cgi->a({-href => href(-anchor=>"patch$patchno")},4590"patch") .4591" | ".4592"</td>\n";4593}45944595my$has_history=0;4596my$not_deleted=0;4597for(my$i=0;$i<$diff->{'nparents'};$i++) {4598my$hash_parent=$parents[$i];4599my$from_hash=$diff->{'from_id'}[$i];4600my$from_path=$diff->{'from_file'}[$i];4601my$status=$diff->{'status'}[$i];46024603$has_history||= ($statusne'A');4604$not_deleted||= ($statusne'D');46054606if($statuseq'A') {4607print"<td class=\"link\"align=\"right\"> | </td>\n";4608}elsif($statuseq'D') {4609print"<td class=\"link\">".4610$cgi->a({-href => href(action=>"blob",4611 hash_base=>$hash,4612 hash=>$from_hash,4613 file_name=>$from_path)},4614"blob". ($i+1)) .4615" | </td>\n";4616}else{4617if($diff->{'to_id'}eq$from_hash) {4618print"<td class=\"link nochange\">";4619}else{4620print"<td class=\"link\">";4621}4622print$cgi->a({-href => href(action=>"blobdiff",4623 hash=>$diff->{'to_id'},4624 hash_parent=>$from_hash,4625 hash_base=>$hash,4626 hash_parent_base=>$hash_parent,4627 file_name=>$diff->{'to_file'},4628 file_parent=>$from_path)},4629"diff". ($i+1)) .4630" | </td>\n";4631}4632}46334634print"<td class=\"link\">";4635if($not_deleted) {4636print$cgi->a({-href => href(action=>"blob",4637 hash=>$diff->{'to_id'},4638 file_name=>$diff->{'to_file'},4639 hash_base=>$hash)},4640"blob");4641print" | "if($has_history);4642}4643if($has_history) {4644print$cgi->a({-href => href(action=>"history",4645 file_name=>$diff->{'to_file'},4646 hash_base=>$hash)},4647"history");4648}4649print"</td>\n";46504651print"</tr>\n";4652next;# instead of 'else' clause, to avoid extra indent4653}4654# else ordinary diff46554656my($to_mode_oct,$to_mode_str,$to_file_type);4657my($from_mode_oct,$from_mode_str,$from_file_type);4658if($diff->{'to_mode'}ne('0' x 6)) {4659$to_mode_oct=oct$diff->{'to_mode'};4660if(S_ISREG($to_mode_oct)) {# only for regular file4661$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4662}4663$to_file_type= file_type($diff->{'to_mode'});4664}4665if($diff->{'from_mode'}ne('0' x 6)) {4666$from_mode_oct=oct$diff->{'from_mode'};4667if(S_ISREG($from_mode_oct)) {# only for regular file4668$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4669}4670$from_file_type= file_type($diff->{'from_mode'});4671}46724673if($diff->{'status'}eq"A") {# created4674my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4675$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4676$mode_chng.="]</span>";4677print"<td>";4678print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4679 hash_base=>$hash, file_name=>$diff->{'file'}),4680-class=>"list"}, esc_path($diff->{'file'}));4681print"</td>\n";4682print"<td>$mode_chng</td>\n";4683print"<td class=\"link\">";4684if($actioneq'commitdiff') {4685# link to patch4686$patchno++;4687print$cgi->a({-href => href(-anchor=>"patch$patchno")},4688"patch") .4689" | ";4690}4691print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4692 hash_base=>$hash, file_name=>$diff->{'file'})},4693"blob");4694print"</td>\n";46954696}elsif($diff->{'status'}eq"D") {# deleted4697my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4698print"<td>";4699print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4700 hash_base=>$parent, file_name=>$diff->{'file'}),4701-class=>"list"}, esc_path($diff->{'file'}));4702print"</td>\n";4703print"<td>$mode_chng</td>\n";4704print"<td class=\"link\">";4705if($actioneq'commitdiff') {4706# link to patch4707$patchno++;4708print$cgi->a({-href => href(-anchor=>"patch$patchno")},4709"patch") .4710" | ";4711}4712print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4713 hash_base=>$parent, file_name=>$diff->{'file'})},4714"blob") ." | ";4715if($have_blame) {4716print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4717 file_name=>$diff->{'file'})},4718"blame") ." | ";4719}4720print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4721 file_name=>$diff->{'file'})},4722"history");4723print"</td>\n";47244725}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4726my$mode_chnge="";4727if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4728$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4729if($from_file_typene$to_file_type) {4730$mode_chnge.=" from$from_file_typeto$to_file_type";4731}4732if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4733if($from_mode_str&&$to_mode_str) {4734$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4735}elsif($to_mode_str) {4736$mode_chnge.=" mode:$to_mode_str";4737}4738}4739$mode_chnge.="]</span>\n";4740}4741print"<td>";4742print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4743 hash_base=>$hash, file_name=>$diff->{'file'}),4744-class=>"list"}, esc_path($diff->{'file'}));4745print"</td>\n";4746print"<td>$mode_chnge</td>\n";4747print"<td class=\"link\">";4748if($actioneq'commitdiff') {4749# link to patch4750$patchno++;4751print$cgi->a({-href => href(-anchor=>"patch$patchno")},4752"patch") .4753" | ";4754}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4755# "commit" view and modified file (not onlu mode changed)4756print$cgi->a({-href => href(action=>"blobdiff",4757 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4758 hash_base=>$hash, hash_parent_base=>$parent,4759 file_name=>$diff->{'file'})},4760"diff") .4761" | ";4762}4763print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4764 hash_base=>$hash, file_name=>$diff->{'file'})},4765"blob") ." | ";4766if($have_blame) {4767print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4768 file_name=>$diff->{'file'})},4769"blame") ." | ";4770}4771print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4772 file_name=>$diff->{'file'})},4773"history");4774print"</td>\n";47754776}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4777my%status_name= ('R'=>'moved','C'=>'copied');4778my$nstatus=$status_name{$diff->{'status'}};4779my$mode_chng="";4780if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4781# mode also for directories, so we cannot use $to_mode_str4782$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4783}4784print"<td>".4785$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4786 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4787-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4788"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4789$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4790 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4791-class=>"list"}, esc_path($diff->{'from_file'})) .4792" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4793"<td class=\"link\">";4794if($actioneq'commitdiff') {4795# link to patch4796$patchno++;4797print$cgi->a({-href => href(-anchor=>"patch$patchno")},4798"patch") .4799" | ";4800}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4801# "commit" view and modified file (not only pure rename or copy)4802print$cgi->a({-href => href(action=>"blobdiff",4803 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4804 hash_base=>$hash, hash_parent_base=>$parent,4805 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4806"diff") .4807" | ";4808}4809print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4810 hash_base=>$parent, file_name=>$diff->{'to_file'})},4811"blob") ." | ";4812if($have_blame) {4813print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4814 file_name=>$diff->{'to_file'})},4815"blame") ." | ";4816}4817print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4818 file_name=>$diff->{'to_file'})},4819"history");4820print"</td>\n";48214822}# we should not encounter Unmerged (U) or Unknown (X) status4823print"</tr>\n";4824}4825print"</tbody>"if$has_header;4826print"</table>\n";4827}48284829sub git_patchset_body {4830my($fd,$difftree,$hash,@hash_parents) =@_;4831my($hash_parent) =$hash_parents[0];48324833my$is_combined= (@hash_parents>1);4834my$patch_idx=0;4835my$patch_number=0;4836my$patch_line;4837my$diffinfo;4838my$to_name;4839my(%from,%to);48404841print"<div class=\"patchset\">\n";48424843# skip to first patch4844while($patch_line= <$fd>) {4845chomp$patch_line;48464847last if($patch_line=~m/^diff /);4848}48494850 PATCH:4851while($patch_line) {48524853# parse "git diff" header line4854if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4855# $1 is from_name, which we do not use4856$to_name= unquote($2);4857$to_name=~s!^b/!!;4858}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4859# $1 is 'cc' or 'combined', which we do not use4860$to_name= unquote($2);4861}else{4862$to_name=undef;4863}48644865# check if current patch belong to current raw line4866# and parse raw git-diff line if needed4867if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4868# this is continuation of a split patch4869print"<div class=\"patch cont\">\n";4870}else{4871# advance raw git-diff output if needed4872$patch_idx++ifdefined$diffinfo;48734874# read and prepare patch information4875$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);48764877# compact combined diff output can have some patches skipped4878# find which patch (using pathname of result) we are at now;4879if($is_combined) {4880while($to_namene$diffinfo->{'to_file'}) {4881print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4882 format_diff_cc_simplified($diffinfo,@hash_parents) .4883"</div>\n";# class="patch"48844885$patch_idx++;4886$patch_number++;48874888last if$patch_idx>$#$difftree;4889$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4890}4891}48924893# modifies %from, %to hashes4894 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);48954896# this is first patch for raw difftree line with $patch_idx index4897# we index @$difftree array from 0, but number patches from 14898print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4899}49004901# git diff header4902#assert($patch_line =~ m/^diff /) if DEBUG;4903#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4904$patch_number++;4905# print "git diff" header4906print format_git_diff_header_line($patch_line,$diffinfo,4907 \%from, \%to);49084909# print extended diff header4910print"<div class=\"diff extended_header\">\n";4911 EXTENDED_HEADER:4912while($patch_line= <$fd>) {4913chomp$patch_line;49144915last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);49164917print format_extended_diff_header_line($patch_line,$diffinfo,4918 \%from, \%to);4919}4920print"</div>\n";# class="diff extended_header"49214922# from-file/to-file diff header4923if(!$patch_line) {4924print"</div>\n";# class="patch"4925last PATCH;4926}4927next PATCH if($patch_line=~m/^diff /);4928#assert($patch_line =~ m/^---/) if DEBUG;49294930my$last_patch_line=$patch_line;4931$patch_line= <$fd>;4932chomp$patch_line;4933#assert($patch_line =~ m/^\+\+\+/) if DEBUG;49344935print format_diff_from_to_header($last_patch_line,$patch_line,4936$diffinfo, \%from, \%to,4937@hash_parents);49384939# the patch itself4940 LINE:4941while($patch_line= <$fd>) {4942chomp$patch_line;49434944next PATCH if($patch_line=~m/^diff /);49454946print format_diff_line($patch_line, \%from, \%to);4947}49484949}continue{4950print"</div>\n";# class="patch"4951}49524953# for compact combined (--cc) format, with chunk and patch simplification4954# the patchset might be empty, but there might be unprocessed raw lines4955for(++$patch_idxif$patch_number>0;4956$patch_idx<@$difftree;4957++$patch_idx) {4958# read and prepare patch information4959$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);49604961# generate anchor for "patch" links in difftree / whatchanged part4962print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4963 format_diff_cc_simplified($diffinfo,@hash_parents) .4964"</div>\n";# class="patch"49654966$patch_number++;4967}49684969if($patch_number==0) {4970if(@hash_parents>1) {4971print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4972}else{4973print"<div class=\"diff nodifferences\">No differences found</div>\n";4974}4975}49764977print"</div>\n";# class="patchset"4978}49794980# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49814982# fills project list info (age, description, owner, category, forks)4983# for each project in the list, removing invalid projects from4984# returned list4985# NOTE: modifies $projlist, but does not remove entries from it4986sub fill_project_list_info {4987my$projlist=shift;4988my@projects;49894990my$show_ctags= gitweb_check_feature('ctags');4991 PROJECT:4992foreachmy$pr(@$projlist) {4993my(@activity) = git_get_last_activity($pr->{'path'});4994unless(@activity) {4995next PROJECT;4996}4997($pr->{'age'},$pr->{'age_string'}) =@activity;4998if(!defined$pr->{'descr'}) {4999my$descr= git_get_project_description($pr->{'path'}) ||"";5000$descr= to_utf8($descr);5001$pr->{'descr_long'} =$descr;5002$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5003}5004if(!defined$pr->{'owner'}) {5005$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5006}5007if($show_ctags) {5008$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5009}5010if($projects_list_group_categories&& !defined$pr->{'category'}) {5011my$cat= git_get_project_category($pr->{'path'}) ||5012$project_list_default_category;5013$pr->{'category'} = to_utf8($cat);5014}50155016push@projects,$pr;5017}50185019return@projects;5020}50215022sub sort_projects_list {5023my($projlist,$order) =@_;5024my@projects;50255026my%order_info= (5027 project => { key =>'path', type =>'str'},5028 descr => { key =>'descr_long', type =>'str'},5029 owner => { key =>'owner', type =>'str'},5030 age => { key =>'age', type =>'num'}5031);5032my$oi=$order_info{$order};5033return@$projlistunlessdefined$oi;5034if($oi->{'type'}eq'str') {5035@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5036}else{5037@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5038}50395040return@projects;5041}50425043# returns a hash of categories, containing the list of project5044# belonging to each category5045sub build_projlist_by_category {5046my($projlist,$from,$to) =@_;5047my%categories;50485049$from=0unlessdefined$from;5050$to=$#$projlistif(!defined$to||$#$projlist<$to);50515052for(my$i=$from;$i<=$to;$i++) {5053my$pr=$projlist->[$i];5054push@{$categories{$pr->{'category'} }},$pr;5055}50565057returnwantarray?%categories: \%categories;5058}50595060# print 'sort by' <th> element, generating 'sort by $name' replay link5061# if that order is not selected5062sub print_sort_th {5063print format_sort_th(@_);5064}50655066sub format_sort_th {5067my($name,$order,$header) =@_;5068my$sort_th="";5069$header||=ucfirst($name);50705071if($ordereq$name) {5072$sort_th.="<th>$header</th>\n";5073}else{5074$sort_th.="<th>".5075$cgi->a({-href => href(-replay=>1, order=>$name),5076-class=>"header"},$header) .5077"</th>\n";5078}50795080return$sort_th;5081}50825083sub git_project_list_rows {5084my($projlist,$from,$to,$check_forks) =@_;50855086$from=0unlessdefined$from;5087$to=$#$projlistif(!defined$to||$#$projlist<$to);50885089my$alternate=1;5090for(my$i=$from;$i<=$to;$i++) {5091my$pr=$projlist->[$i];50925093if($alternate) {5094print"<tr class=\"dark\">\n";5095}else{5096print"<tr class=\"light\">\n";5097}5098$alternate^=1;50995100if($check_forks) {5101print"<td>";5102if($pr->{'forks'}) {5103my$nforks=scalar@{$pr->{'forks'}};5104if($nforks>0) {5105print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5106-title =>"$nforksforks"},"+");5107}else{5108print$cgi->span({-title =>"$nforksforks"},"+");5109}5110}5111print"</td>\n";5112}5113print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5114-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".5115"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5116-class=>"list", -title =>$pr->{'descr_long'}},5117 esc_html($pr->{'descr'})) ."</td>\n".5118"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5119print"<td class=\"". age_class($pr->{'age'}) ."\">".5120(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".5121"<td class=\"link\">".5122$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5123$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5124$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5125$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5126($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5127"</td>\n".5128"</tr>\n";5129}5130}51315132sub git_project_list_body {5133# actually uses global variable $project5134my($projlist,$order,$from,$to,$extra,$no_header) =@_;5135my@projects=@$projlist;51365137my$check_forks= gitweb_check_feature('forks');5138my$show_ctags= gitweb_check_feature('ctags');5139my$tagfilter=$show_ctags?$cgi->param('by_tag') :undef;5140$check_forks=undef5141if($tagfilter||$searchtext);51425143# filtering out forks before filling info allows to do less work5144@projects= filter_forks_from_projects_list(\@projects)5145if($check_forks);5146@projects= fill_project_list_info(\@projects);5147# searching projects require filling to be run before it5148@projects= search_projects_list(\@projects,5149'searchtext'=>$searchtext,5150'tagfilter'=>$tagfilter)5151if($tagfilter||$searchtext);51525153$order||=$default_projects_order;5154$from=0unlessdefined$from;5155$to=$#projectsif(!defined$to||$#projects<$to);51565157# short circuit5158if($from>$to) {5159print"<center>\n".5160"<b>No such projects found</b><br />\n".5161"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5162"</center>\n<br />\n";5163return;5164}51655166@projects= sort_projects_list(\@projects,$order);51675168if($show_ctags) {5169my$ctags= git_gather_all_ctags(\@projects);5170my$cloud= git_populate_project_tagcloud($ctags);5171print git_show_project_tagcloud($cloud,64);5172}51735174print"<table class=\"project_list\">\n";5175unless($no_header) {5176print"<tr>\n";5177if($check_forks) {5178print"<th></th>\n";5179}5180 print_sort_th('project',$order,'Project');5181 print_sort_th('descr',$order,'Description');5182 print_sort_th('owner',$order,'Owner');5183 print_sort_th('age',$order,'Last Change');5184print"<th></th>\n".# for links5185"</tr>\n";5186}51875188if($projects_list_group_categories) {5189# only display categories with projects in the $from-$to window5190@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5191my%categories= build_projlist_by_category(\@projects,$from,$to);5192foreachmy$cat(sort keys%categories) {5193unless($cateq"") {5194print"<tr>\n";5195if($check_forks) {5196print"<td></td>\n";5197}5198print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5199print"</tr>\n";5200}52015202 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5203}5204}else{5205 git_project_list_rows(\@projects,$from,$to,$check_forks);5206}52075208if(defined$extra) {5209print"<tr>\n";5210if($check_forks) {5211print"<td></td>\n";5212}5213print"<td colspan=\"5\">$extra</td>\n".5214"</tr>\n";5215}5216print"</table>\n";5217}52185219sub git_log_body {5220# uses global variable $project5221my($commitlist,$from,$to,$refs,$extra) =@_;52225223$from=0unlessdefined$from;5224$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52255226for(my$i=0;$i<=$to;$i++) {5227my%co= %{$commitlist->[$i]};5228next if!%co;5229my$commit=$co{'id'};5230my$ref= format_ref_marker($refs,$commit);5231 git_print_header_div('commit',5232"<span class=\"age\">$co{'age_string'}</span>".5233 esc_html($co{'title'}) .$ref,5234$commit);5235print"<div class=\"title_text\">\n".5236"<div class=\"log_link\">\n".5237$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5238" | ".5239$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5240" | ".5241$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5242"<br/>\n".5243"</div>\n";5244 git_print_authorship(\%co, -tag =>'span');5245print"<br/>\n</div>\n";52465247print"<div class=\"log_body\">\n";5248 git_print_log($co{'comment'}, -final_empty_line=>1);5249print"</div>\n";5250}5251if($extra) {5252print"<div class=\"page_nav\">\n";5253print"$extra\n";5254print"</div>\n";5255}5256}52575258sub git_shortlog_body {5259# uses global variable $project5260my($commitlist,$from,$to,$refs,$extra) =@_;52615262$from=0unlessdefined$from;5263$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);52645265print"<table class=\"shortlog\">\n";5266my$alternate=1;5267for(my$i=$from;$i<=$to;$i++) {5268my%co= %{$commitlist->[$i]};5269my$commit=$co{'id'};5270my$ref= format_ref_marker($refs,$commit);5271if($alternate) {5272print"<tr class=\"dark\">\n";5273}else{5274print"<tr class=\"light\">\n";5275}5276$alternate^=1;5277# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5278print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5279 format_author_html('td', \%co,10) ."<td>";5280print format_subject_html($co{'title'},$co{'title_short'},5281 href(action=>"commit", hash=>$commit),$ref);5282print"</td>\n".5283"<td class=\"link\">".5284$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5285$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5286$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5287my$snapshot_links= format_snapshot_links($commit);5288if(defined$snapshot_links) {5289print" | ".$snapshot_links;5290}5291print"</td>\n".5292"</tr>\n";5293}5294if(defined$extra) {5295print"<tr>\n".5296"<td colspan=\"4\">$extra</td>\n".5297"</tr>\n";5298}5299print"</table>\n";5300}53015302sub git_history_body {5303# Warning: assumes constant type (blob or tree) during history5304my($commitlist,$from,$to,$refs,$extra,5305$file_name,$file_hash,$ftype) =@_;53065307$from=0unlessdefined$from;5308$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});53095310print"<table class=\"history\">\n";5311my$alternate=1;5312for(my$i=$from;$i<=$to;$i++) {5313my%co= %{$commitlist->[$i]};5314if(!%co) {5315next;5316}5317my$commit=$co{'id'};53185319my$ref= format_ref_marker($refs,$commit);53205321if($alternate) {5322print"<tr class=\"dark\">\n";5323}else{5324print"<tr class=\"light\">\n";5325}5326$alternate^=1;5327print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5328# shortlog: format_author_html('td', \%co, 10)5329 format_author_html('td', \%co,15,3) ."<td>";5330# originally git_history used chop_str($co{'title'}, 50)5331print format_subject_html($co{'title'},$co{'title_short'},5332 href(action=>"commit", hash=>$commit),$ref);5333print"</td>\n".5334"<td class=\"link\">".5335$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5336$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");53375338if($ftypeeq'blob') {5339my$blob_current=$file_hash;5340my$blob_parent= git_get_hash_by_path($commit,$file_name);5341if(defined$blob_current&&defined$blob_parent&&5342$blob_currentne$blob_parent) {5343print" | ".5344$cgi->a({-href => href(action=>"blobdiff",5345 hash=>$blob_current, hash_parent=>$blob_parent,5346 hash_base=>$hash_base, hash_parent_base=>$commit,5347 file_name=>$file_name)},5348"diff to current");5349}5350}5351print"</td>\n".5352"</tr>\n";5353}5354if(defined$extra) {5355print"<tr>\n".5356"<td colspan=\"4\">$extra</td>\n".5357"</tr>\n";5358}5359print"</table>\n";5360}53615362sub git_tags_body {5363# uses global variable $project5364my($taglist,$from,$to,$extra) =@_;5365$from=0unlessdefined$from;5366$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);53675368print"<table class=\"tags\">\n";5369my$alternate=1;5370for(my$i=$from;$i<=$to;$i++) {5371my$entry=$taglist->[$i];5372my%tag=%$entry;5373my$comment=$tag{'subject'};5374my$comment_short;5375if(defined$comment) {5376$comment_short= chop_str($comment,30,5);5377}5378if($alternate) {5379print"<tr class=\"dark\">\n";5380}else{5381print"<tr class=\"light\">\n";5382}5383$alternate^=1;5384if(defined$tag{'age'}) {5385print"<td><i>$tag{'age'}</i></td>\n";5386}else{5387print"<td></td>\n";5388}5389print"<td>".5390$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5391-class=>"list name"}, esc_html($tag{'name'})) .5392"</td>\n".5393"<td>";5394if(defined$comment) {5395print format_subject_html($comment,$comment_short,5396 href(action=>"tag", hash=>$tag{'id'}));5397}5398print"</td>\n".5399"<td class=\"selflink\">";5400if($tag{'type'}eq"tag") {5401print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5402}else{5403print" ";5404}5405print"</td>\n".5406"<td class=\"link\">"." | ".5407$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5408if($tag{'reftype'}eq"commit") {5409print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5410" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5411}elsif($tag{'reftype'}eq"blob") {5412print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5413}5414print"</td>\n".5415"</tr>";5416}5417if(defined$extra) {5418print"<tr>\n".5419"<td colspan=\"5\">$extra</td>\n".5420"</tr>\n";5421}5422print"</table>\n";5423}54245425sub git_heads_body {5426# uses global variable $project5427my($headlist,$head,$from,$to,$extra) =@_;5428$from=0unlessdefined$from;5429$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);54305431print"<table class=\"heads\">\n";5432my$alternate=1;5433for(my$i=$from;$i<=$to;$i++) {5434my$entry=$headlist->[$i];5435my%ref=%$entry;5436my$curr=$ref{'id'}eq$head;5437if($alternate) {5438print"<tr class=\"dark\">\n";5439}else{5440print"<tr class=\"light\">\n";5441}5442$alternate^=1;5443print"<td><i>$ref{'age'}</i></td>\n".5444($curr?"<td class=\"current_head\">":"<td>") .5445$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5446-class=>"list name"},esc_html($ref{'name'})) .5447"</td>\n".5448"<td class=\"link\">".5449$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5450$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5451$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5452"</td>\n".5453"</tr>";5454}5455if(defined$extra) {5456print"<tr>\n".5457"<td colspan=\"3\">$extra</td>\n".5458"</tr>\n";5459}5460print"</table>\n";5461}54625463# Display a single remote block5464sub git_remote_block {5465my($remote,$rdata,$limit,$head) =@_;54665467my$heads=$rdata->{'heads'};5468my$fetch=$rdata->{'fetch'};5469my$push=$rdata->{'push'};54705471my$urls_table="<table class=\"projects_list\">\n";54725473if(defined$fetch) {5474if($fetcheq$push) {5475$urls_table.= format_repo_url("URL",$fetch);5476}else{5477$urls_table.= format_repo_url("Fetch URL",$fetch);5478$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5479}5480}elsif(defined$push) {5481$urls_table.= format_repo_url("Push URL",$push);5482}else{5483$urls_table.= format_repo_url("","No remote URL");5484}54855486$urls_table.="</table>\n";54875488my$dots;5489if(defined$limit&&$limit<@$heads) {5490$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");5491}54925493print$urls_table;5494 git_heads_body($heads,$head,0,$limit,$dots);5495}54965497# Display a list of remote names with the respective fetch and push URLs5498sub git_remotes_list {5499my($remotedata,$limit) =@_;5500print"<table class=\"heads\">\n";5501my$alternate=1;5502my@remotes=sort keys%$remotedata;55035504my$limited=$limit&&$limit<@remotes;55055506$#remotes=$limit-1if$limited;55075508while(my$remote=shift@remotes) {5509my$rdata=$remotedata->{$remote};5510my$fetch=$rdata->{'fetch'};5511my$push=$rdata->{'push'};5512if($alternate) {5513print"<tr class=\"dark\">\n";5514}else{5515print"<tr class=\"light\">\n";5516}5517$alternate^=1;5518print"<td>".5519$cgi->a({-href=> href(action=>'remotes', hash=>$remote),5520-class=>"list name"},esc_html($remote)) .5521"</td>";5522print"<td class=\"link\">".5523(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .5524" | ".5525(defined$push?$cgi->a({-href=>$push},"push") :"push") .5526"</td>";55275528print"</tr>\n";5529}55305531if($limited) {5532print"<tr>\n".5533"<td colspan=\"3\">".5534$cgi->a({-href => href(action=>"remotes")},"...") .5535"</td>\n"."</tr>\n";5536}55375538print"</table>";5539}55405541# Display remote heads grouped by remote, unless there are too many5542# remotes, in which case we only display the remote names5543sub git_remotes_body {5544my($remotedata,$limit,$head) =@_;5545if($limitand$limit<keys%$remotedata) {5546 git_remotes_list($remotedata,$limit);5547}else{5548 fill_remote_heads($remotedata);5549while(my($remote,$rdata) =each%$remotedata) {5550 git_print_section({-class=>"remote", -id=>$remote},5551["remotes",$remote,$remote],sub{5552 git_remote_block($remote,$rdata,$limit,$head);5553});5554}5555}5556}55575558sub git_search_message {5559my%co=@_;55605561my$greptype;5562if($searchtypeeq'commit') {5563$greptype="--grep=";5564}elsif($searchtypeeq'author') {5565$greptype="--author=";5566}elsif($searchtypeeq'committer') {5567$greptype="--committer=";5568}5569$greptype.=$searchtext;5570my@commitlist= parse_commits($hash,101, (100*$page),undef,5571$greptype,'--regexp-ignore-case',5572$search_use_regexp?'--extended-regexp':'--fixed-strings');55735574my$paging_nav='';5575if($page>0) {5576$paging_nav.=5577$cgi->a({-href => href(-replay=>1, page=>undef)},5578"first") .5579" ⋅ ".5580$cgi->a({-href => href(-replay=>1, page=>$page-1),5581-accesskey =>"p", -title =>"Alt-p"},"prev");5582}else{5583$paging_nav.="first ⋅ prev";5584}5585my$next_link='';5586if($#commitlist>=100) {5587$next_link=5588$cgi->a({-href => href(-replay=>1, page=>$page+1),5589-accesskey =>"n", -title =>"Alt-n"},"next");5590$paging_nav.=" ⋅$next_link";5591}else{5592$paging_nav.=" ⋅ next";5593}55945595 git_header_html();55965597 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5598 git_print_header_div('commit', esc_html($co{'title'}),$hash);5599if($page==0&& !@commitlist) {5600print"<p>No match.</p>\n";5601}else{5602 git_search_grep_body(\@commitlist,0,99,$next_link);5603}56045605 git_footer_html();5606}56075608sub git_search_changes {5609my%co=@_;56105611local$/="\n";5612open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5613'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5614($search_use_regexp?'--pickaxe-regex': ())5615or die_error(500,"Open git-log failed");56165617 git_header_html();56185619 git_print_page_nav('','',$hash,$co{'tree'},$hash);5620 git_print_header_div('commit', esc_html($co{'title'}),$hash);56215622print"<table class=\"pickaxe search\">\n";5623my$alternate=1;5624undef%co;5625my@files;5626while(my$line= <$fd>) {5627chomp$line;5628next unless$line;56295630my%set= parse_difftree_raw_line($line);5631if(defined$set{'commit'}) {5632# finish previous commit5633if(%co) {5634print"</td>\n".5635"<td class=\"link\">".5636$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5637"commit") .5638" | ".5639$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5640 hash_base=>$co{'id'})},5641"tree") .5642"</td>\n".5643"</tr>\n";5644}56455646if($alternate) {5647print"<tr class=\"dark\">\n";5648}else{5649print"<tr class=\"light\">\n";5650}5651$alternate^=1;5652%co= parse_commit($set{'commit'});5653my$author= chop_and_escape_str($co{'author_name'},15,5);5654print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5655"<td><i>$author</i></td>\n".5656"<td>".5657$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5658-class=>"list subject"},5659 chop_and_escape_str($co{'title'},50) ."<br/>");5660}elsif(defined$set{'to_id'}) {5661next if($set{'to_id'} =~m/^0{40}$/);56625663print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5664 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5665-class=>"list"},5666"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5667"<br/>\n";5668}5669}5670close$fd;56715672# finish last commit (warning: repetition!)5673if(%co) {5674print"</td>\n".5675"<td class=\"link\">".5676$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},5677"commit") .5678" | ".5679$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},5680 hash_base=>$co{'id'})},5681"tree") .5682"</td>\n".5683"</tr>\n";5684}56855686print"</table>\n";56875688 git_footer_html();5689}56905691sub git_search_files {5692my%co=@_;56935694local$/="\n";5695open my$fd,"-|", git_cmd(),'grep','-n',5696$search_use_regexp? ('-E','-i') :'-F',5697$searchtext,$co{'tree'}5698or die_error(500,"Open git-grep failed");56995700 git_header_html();57015702 git_print_page_nav('','',$hash,$co{'tree'},$hash);5703 git_print_header_div('commit', esc_html($co{'title'}),$hash);57045705print"<table class=\"grep_search\">\n";5706my$alternate=1;5707my$matches=0;5708my$lastfile='';5709while(my$line= <$fd>) {5710chomp$line;5711my($file,$lno,$ltext,$binary);5712last if($matches++>1000);5713if($line=~/^Binary file (.+) matches$/) {5714$file=$1;5715$binary=1;5716}else{5717(undef,$file,$lno,$ltext) =split(/:/,$line,4);5718}5719if($filene$lastfile) {5720$lastfileand print"</td></tr>\n";5721if($alternate++) {5722print"<tr class=\"dark\">\n";5723}else{5724print"<tr class=\"light\">\n";5725}5726print"<td class=\"list\">".5727$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5728 file_name=>"$file"),5729-class=>"list"}, esc_path($file));5730print"</td><td>\n";5731$lastfile=$file;5732}5733if($binary) {5734print"<div class=\"binary\">Binary file</div>\n";5735}else{5736$ltext= untabify($ltext);5737if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {5738$ltext= esc_html($1, -nbsp=>1);5739$ltext.='<span class="match">';5740$ltext.= esc_html($2, -nbsp=>1);5741$ltext.='</span>';5742$ltext.= esc_html($3, -nbsp=>1);5743}else{5744$ltext= esc_html($ltext, -nbsp=>1);5745}5746print"<div class=\"pre\">".5747$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},5748 file_name=>"$file").'#l'.$lno,5749-class=>"linenr"},sprintf('%4i',$lno))5750.' '.$ltext."</div>\n";5751}5752}5753if($lastfile) {5754print"</td></tr>\n";5755if($matches>1000) {5756print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";5757}5758}else{5759print"<div class=\"diff nodifferences\">No matches found</div>\n";5760}5761close$fd;57625763print"</table>\n";57645765 git_footer_html();5766}57675768sub git_search_grep_body {5769my($commitlist,$from,$to,$extra) =@_;5770$from=0unlessdefined$from;5771$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57725773print"<table class=\"commit_search\">\n";5774my$alternate=1;5775for(my$i=$from;$i<=$to;$i++) {5776my%co= %{$commitlist->[$i]};5777if(!%co) {5778next;5779}5780my$commit=$co{'id'};5781if($alternate) {5782print"<tr class=\"dark\">\n";5783}else{5784print"<tr class=\"light\">\n";5785}5786$alternate^=1;5787print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5788 format_author_html('td', \%co,15,5) .5789"<td>".5790$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5791-class=>"list subject"},5792 chop_and_escape_str($co{'title'},50) ."<br/>");5793my$comment=$co{'comment'};5794foreachmy$line(@$comment) {5795if($line=~m/^(.*?)($search_regexp)(.*)$/i) {5796my($lead,$match,$trail) = ($1,$2,$3);5797$match= chop_str($match,70,5,'center');5798my$contextlen=int((80-length($match))/2);5799$contextlen=30if($contextlen>30);5800$lead= chop_str($lead,$contextlen,10,'left');5801$trail= chop_str($trail,$contextlen,10,'right');58025803$lead= esc_html($lead);5804$match= esc_html($match);5805$trail= esc_html($trail);58065807print"$lead<span class=\"match\">$match</span>$trail<br />";5808}5809}5810print"</td>\n".5811"<td class=\"link\">".5812$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5813" | ".5814$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5815" | ".5816$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5817print"</td>\n".5818"</tr>\n";5819}5820if(defined$extra) {5821print"<tr>\n".5822"<td colspan=\"3\">$extra</td>\n".5823"</tr>\n";5824}5825print"</table>\n";5826}58275828## ======================================================================5829## ======================================================================5830## actions58315832sub git_project_list {5833my$order=$input_params{'order'};5834if(defined$order&&$order!~m/none|project|descr|owner|age/) {5835 die_error(400,"Unknown order parameter");5836}58375838my@list= git_get_projects_list();5839if(!@list) {5840 die_error(404,"No projects found");5841}58425843 git_header_html();5844if(defined$home_text&& -f $home_text) {5845print"<div class=\"index_include\">\n";5846 insert_file($home_text);5847print"</div>\n";5848}5849print$cgi->startform(-method=>"get") .5850"<p class=\"projsearch\">Search:\n".5851$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5852"</p>".5853$cgi->end_form() ."\n";5854 git_project_list_body(\@list,$order);5855 git_footer_html();5856}58575858sub git_forks {5859my$order=$input_params{'order'};5860if(defined$order&&$order!~m/none|project|descr|owner|age/) {5861 die_error(400,"Unknown order parameter");5862}58635864my@list= git_get_projects_list($project);5865if(!@list) {5866 die_error(404,"No forks found");5867}58685869 git_header_html();5870 git_print_page_nav('','');5871 git_print_header_div('summary',"$projectforks");5872 git_project_list_body(\@list,$order);5873 git_footer_html();5874}58755876sub git_project_index {5877my@projects= git_get_projects_list();5878if(!@projects) {5879 die_error(404,"No projects found");5880}58815882print$cgi->header(5883-type =>'text/plain',5884-charset =>'utf-8',5885-content_disposition =>'inline; filename="index.aux"');58865887foreachmy$pr(@projects) {5888if(!exists$pr->{'owner'}) {5889$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5890}58915892my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5893# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5894$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5895$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5896$path=~s/ /\+/g;5897$owner=~s/ /\+/g;58985899print"$path$owner\n";5900}5901}59025903sub git_summary {5904my$descr= git_get_project_description($project) ||"none";5905my%co= parse_commit("HEAD");5906my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5907my$head=$co{'id'};5908my$remote_heads= gitweb_check_feature('remote_heads');59095910my$owner= git_get_project_owner($project);59115912my$refs= git_get_references();5913# These get_*_list functions return one more to allow us to see if5914# there are more ...5915my@taglist= git_get_tags_list(16);5916my@headlist= git_get_heads_list(16);5917my%remotedata=$remote_heads? git_get_remotes_list() : ();5918my@forklist;5919my$check_forks= gitweb_check_feature('forks');59205921if($check_forks) {5922# find forks of a project5923@forklist= git_get_projects_list($project);5924# filter out forks of forks5925@forklist= filter_forks_from_projects_list(\@forklist)5926if(@forklist);5927}59285929 git_header_html();5930 git_print_page_nav('summary','',$head);59315932print"<div class=\"title\"> </div>\n";5933print"<table class=\"projects_list\">\n".5934"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5935"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5936if(defined$cd{'rfc2822'}) {5937print"<tr id=\"metadata_lchange\"><td>last change</td>".5938"<td>".format_timestamp_html(\%cd)."</td></tr>\n";5939}59405941# use per project git URL list in $projectroot/$project/cloneurl5942# or make project git URL from git base URL and project name5943my$url_tag="URL";5944my@url_list= git_get_project_url_list($project);5945@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5946foreachmy$git_url(@url_list) {5947next unless$git_url;5948print format_repo_url($url_tag,$git_url);5949$url_tag="";5950}59515952# Tag cloud5953my$show_ctags= gitweb_check_feature('ctags');5954if($show_ctags) {5955my$ctags= git_get_project_ctags($project);5956if(%$ctags) {5957# without ability to add tags, don't show if there are none5958my$cloud= git_populate_project_tagcloud($ctags);5959print"<tr id=\"metadata_ctags\">".5960"<td>content tags</td>".5961"<td>".git_show_project_tagcloud($cloud,48)."</td>".5962"</tr>\n";5963}5964}59655966print"</table>\n";59675968# If XSS prevention is on, we don't include README.html.5969# TODO: Allow a readme in some safe format.5970if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5971print"<div class=\"title\">readme</div>\n".5972"<div class=\"readme\">\n";5973 insert_file("$projectroot/$project/README.html");5974print"\n</div>\n";# class="readme"5975}59765977# we need to request one more than 16 (0..15) to check if5978# those 16 are all5979my@commitlist=$head? parse_commits($head,17) : ();5980if(@commitlist) {5981 git_print_header_div('shortlog');5982 git_shortlog_body(\@commitlist,0,15,$refs,5983$#commitlist<=15?undef:5984$cgi->a({-href => href(action=>"shortlog")},"..."));5985}59865987if(@taglist) {5988 git_print_header_div('tags');5989 git_tags_body(\@taglist,0,15,5990$#taglist<=15?undef:5991$cgi->a({-href => href(action=>"tags")},"..."));5992}59935994if(@headlist) {5995 git_print_header_div('heads');5996 git_heads_body(\@headlist,$head,0,15,5997$#headlist<=15?undef:5998$cgi->a({-href => href(action=>"heads")},"..."));5999}60006001if(%remotedata) {6002 git_print_header_div('remotes');6003 git_remotes_body(\%remotedata,15,$head);6004}60056006if(@forklist) {6007 git_print_header_div('forks');6008 git_project_list_body(\@forklist,'age',0,15,6009$#forklist<=15?undef:6010$cgi->a({-href => href(action=>"forks")},"..."),6011'no_header');6012}60136014 git_footer_html();6015}60166017sub git_tag {6018my%tag= parse_tag($hash);60196020if(!%tag) {6021 die_error(404,"Unknown tag object");6022}60236024my$head= git_get_head_hash($project);6025 git_header_html();6026 git_print_page_nav('','',$head,undef,$head);6027 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6028print"<div class=\"title_text\">\n".6029"<table class=\"object_header\">\n".6030"<tr>\n".6031"<td>object</td>\n".6032"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6033$tag{'object'}) ."</td>\n".6034"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6035$tag{'type'}) ."</td>\n".6036"</tr>\n";6037if(defined($tag{'author'})) {6038 git_print_authorship_rows(\%tag,'author');6039}6040print"</table>\n\n".6041"</div>\n";6042print"<div class=\"page_body\">";6043my$comment=$tag{'comment'};6044foreachmy$line(@$comment) {6045chomp$line;6046print esc_html($line, -nbsp=>1) ."<br/>\n";6047}6048print"</div>\n";6049 git_footer_html();6050}60516052sub git_blame_common {6053my$format=shift||'porcelain';6054if($formateq'porcelain'&&$cgi->param('js')) {6055$format='incremental';6056$action='blame_incremental';# for page title etc6057}60586059# permissions6060 gitweb_check_feature('blame')6061or die_error(403,"Blame view not allowed");60626063# error checking6064 die_error(400,"No file name given")unless$file_name;6065$hash_base||= git_get_head_hash($project);6066 die_error(404,"Couldn't find base commit")unless$hash_base;6067my%co= parse_commit($hash_base)6068or die_error(404,"Commit not found");6069my$ftype="blob";6070if(!defined$hash) {6071$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6072or die_error(404,"Error looking up file");6073}else{6074$ftype= git_get_type($hash);6075if($ftype!~"blob") {6076 die_error(400,"Object is not a blob");6077}6078}60796080my$fd;6081if($formateq'incremental') {6082# get file contents (as base)6083open$fd,"-|", git_cmd(),'cat-file','blob',$hash6084or die_error(500,"Open git-cat-file failed");6085}elsif($formateq'data') {6086# run git-blame --incremental6087open$fd,"-|", git_cmd(),"blame","--incremental",6088$hash_base,"--",$file_name6089or die_error(500,"Open git-blame --incremental failed");6090}else{6091# run git-blame --porcelain6092open$fd,"-|", git_cmd(),"blame",'-p',6093$hash_base,'--',$file_name6094or die_error(500,"Open git-blame --porcelain failed");6095}60966097# incremental blame data returns early6098if($formateq'data') {6099print$cgi->header(6100-type=>"text/plain", -charset =>"utf-8",6101-status=>"200 OK");6102local$| =1;# output autoflush6103printwhile<$fd>;6104close$fd6105or print"ERROR$!\n";61066107print'END';6108if(defined$t0&& gitweb_check_feature('timed')) {6109print' '.6110 tv_interval($t0, [ gettimeofday() ]).6111' '.$number_of_git_cmds;6112}6113print"\n";61146115return;6116}61176118# page header6119 git_header_html();6120my$formats_nav=6121$cgi->a({-href => href(action=>"blob", -replay=>1)},6122"blob") .6123" | ";6124if($formateq'incremental') {6125$formats_nav.=6126$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6127"blame") ." (non-incremental)";6128}else{6129$formats_nav.=6130$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6131"blame") ." (incremental)";6132}6133$formats_nav.=6134" | ".6135$cgi->a({-href => href(action=>"history", -replay=>1)},6136"history") .6137" | ".6138$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6139"HEAD");6140 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6141 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6142 git_print_page_path($file_name,$ftype,$hash_base);61436144# page body6145if($formateq'incremental') {6146print"<noscript>\n<div class=\"error\"><center><b>\n".6147"This page requires JavaScript to run.\nUse ".6148$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6149'this page').6150" instead.\n".6151"</b></center></div>\n</noscript>\n";61526153print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6154}61556156print qq!<div class="page_body">\n!;6157print qq!<div id="progress_info">.../ ...</div>\n!6158if($formateq'incremental');6159print qq!<table id="blame_table"class="blame" width="100%">\n!.6160#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6161 qq!<thead>\n!.6162 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6163 qq!</thead>\n!.6164 qq!<tbody>\n!;61656166my@rev_color=qw(light dark);6167my$num_colors=scalar(@rev_color);6168my$current_color=0;61696170if($formateq'incremental') {6171my$color_class=$rev_color[$current_color];61726173#contents of a file6174my$linenr=0;6175 LINE:6176while(my$line= <$fd>) {6177chomp$line;6178$linenr++;61796180print qq!<tr id="l$linenr"class="$color_class">!.6181 qq!<td class="sha1"><a href=""> </a></td>!.6182 qq!<td class="linenr">!.6183 qq!<a class="linenr" href="">$linenr</a></td>!;6184print qq!<td class="pre">! . esc_html($line) ."</td>\n";6185print qq!</tr>\n!;6186}61876188}else{# porcelain, i.e. ordinary blame6189my%metainfo= ();# saves information about commits61906191# blame data6192 LINE:6193while(my$line= <$fd>) {6194chomp$line;6195# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6196# no <lines in group> for subsequent lines in group of lines6197my($full_rev,$orig_lineno,$lineno,$group_size) =6198($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6199if(!exists$metainfo{$full_rev}) {6200$metainfo{$full_rev} = {'nprevious'=>0};6201}6202my$meta=$metainfo{$full_rev};6203my$data;6204while($data= <$fd>) {6205chomp$data;6206last if($data=~s/^\t//);# contents of line6207if($data=~/^(\S+)(?: (.*))?$/) {6208$meta->{$1} =$2unlessexists$meta->{$1};6209}6210if($data=~/^previous /) {6211$meta->{'nprevious'}++;6212}6213}6214my$short_rev=substr($full_rev,0,8);6215my$author=$meta->{'author'};6216my%date=6217 parse_date($meta->{'author-time'},$meta->{'author-tz'});6218my$date=$date{'iso-tz'};6219if($group_size) {6220$current_color= ($current_color+1) %$num_colors;6221}6222my$tr_class=$rev_color[$current_color];6223$tr_class.=' boundary'if(exists$meta->{'boundary'});6224$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6225$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6226print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6227if($group_size) {6228print"<td class=\"sha1\"";6229print" title=\"". esc_html($author) .",$date\"";6230print" rowspan=\"$group_size\""if($group_size>1);6231print">";6232print$cgi->a({-href => href(action=>"commit",6233 hash=>$full_rev,6234 file_name=>$file_name)},6235 esc_html($short_rev));6236if($group_size>=2) {6237my@author_initials= ($author=~/\b([[:upper:]])\B/g);6238if(@author_initials) {6239print"<br />".6240 esc_html(join('',@author_initials));6241# or join('.', ...)6242}6243}6244print"</td>\n";6245}6246# 'previous' <sha1 of parent commit> <filename at commit>6247if(exists$meta->{'previous'} &&6248$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6249$meta->{'parent'} =$1;6250$meta->{'file_parent'} = unquote($2);6251}6252my$linenr_commit=6253exists($meta->{'parent'}) ?6254$meta->{'parent'} :$full_rev;6255my$linenr_filename=6256exists($meta->{'file_parent'}) ?6257$meta->{'file_parent'} : unquote($meta->{'filename'});6258my$blamed= href(action =>'blame',6259 file_name =>$linenr_filename,6260 hash_base =>$linenr_commit);6261print"<td class=\"linenr\">";6262print$cgi->a({ -href =>"$blamed#l$orig_lineno",6263-class=>"linenr"},6264 esc_html($lineno));6265print"</td>";6266print"<td class=\"pre\">". esc_html($data) ."</td>\n";6267print"</tr>\n";6268}# end while62696270}62716272# footer6273print"</tbody>\n".6274"</table>\n";# class="blame"6275print"</div>\n";# class="blame_body"6276close$fd6277or print"Reading blob failed\n";62786279 git_footer_html();6280}62816282sub git_blame {6283 git_blame_common();6284}62856286sub git_blame_incremental {6287 git_blame_common('incremental');6288}62896290sub git_blame_data {6291 git_blame_common('data');6292}62936294sub git_tags {6295my$head= git_get_head_hash($project);6296 git_header_html();6297 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6298 git_print_header_div('summary',$project);62996300my@tagslist= git_get_tags_list();6301if(@tagslist) {6302 git_tags_body(\@tagslist);6303}6304 git_footer_html();6305}63066307sub git_heads {6308my$head= git_get_head_hash($project);6309 git_header_html();6310 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6311 git_print_header_div('summary',$project);63126313my@headslist= git_get_heads_list();6314if(@headslist) {6315 git_heads_body(\@headslist,$head);6316}6317 git_footer_html();6318}63196320# used both for single remote view and for list of all the remotes6321sub git_remotes {6322 gitweb_check_feature('remote_heads')6323or die_error(403,"Remote heads view is disabled");63246325my$head= git_get_head_hash($project);6326my$remote=$input_params{'hash'};63276328my$remotedata= git_get_remotes_list($remote);6329 die_error(500,"Unable to get remote information")unlessdefined$remotedata;63306331unless(%$remotedata) {6332 die_error(404,defined$remote?6333"Remote$remotenot found":6334"No remotes found");6335}63366337 git_header_html(undef,undef, -action_extra =>$remote);6338 git_print_page_nav('','',$head,undef,$head,6339 format_ref_views($remote?'':'remotes'));63406341 fill_remote_heads($remotedata);6342if(defined$remote) {6343 git_print_header_div('remotes',"$remoteremote for$project");6344 git_remote_block($remote,$remotedata->{$remote},undef,$head);6345}else{6346 git_print_header_div('summary',"$projectremotes");6347 git_remotes_body($remotedata,undef,$head);6348}63496350 git_footer_html();6351}63526353sub git_blob_plain {6354my$type=shift;6355my$expires;63566357if(!defined$hash) {6358if(defined$file_name) {6359my$base=$hash_base|| git_get_head_hash($project);6360$hash= git_get_hash_by_path($base,$file_name,"blob")6361or die_error(404,"Cannot find file");6362}else{6363 die_error(400,"No file name defined");6364}6365}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6366# blobs defined by non-textual hash id's can be cached6367$expires="+1d";6368}63696370open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6371or die_error(500,"Open git-cat-file blob '$hash' failed");63726373# content-type (can include charset)6374$type= blob_contenttype($fd,$file_name,$type);63756376# "save as" filename, even when no $file_name is given6377my$save_as="$hash";6378if(defined$file_name) {6379$save_as=$file_name;6380}elsif($type=~m/^text\//) {6381$save_as.='.txt';6382}63836384# With XSS prevention on, blobs of all types except a few known safe6385# ones are served with "Content-Disposition: attachment" to make sure6386# they don't run in our security domain. For certain image types,6387# blob view writes an <img> tag referring to blob_plain view, and we6388# want to be sure not to break that by serving the image as an6389# attachment (though Firefox 3 doesn't seem to care).6390my$sandbox=$prevent_xss&&6391$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;63926393# serve text/* as text/plain6394if($prevent_xss&&6395($type=~m!^text/[a-z]+\b(.*)$!||6396($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6397my$rest=$1;6398$rest=defined$rest?$rest:'';6399$type="text/plain$rest";6400}64016402print$cgi->header(6403-type =>$type,6404-expires =>$expires,6405-content_disposition =>6406($sandbox?'attachment':'inline')6407.'; filename="'.$save_as.'"');6408local$/=undef;6409binmode STDOUT,':raw';6410print<$fd>;6411binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6412close$fd;6413}64146415sub git_blob {6416my$expires;64176418if(!defined$hash) {6419if(defined$file_name) {6420my$base=$hash_base|| git_get_head_hash($project);6421$hash= git_get_hash_by_path($base,$file_name,"blob")6422or die_error(404,"Cannot find file");6423}else{6424 die_error(400,"No file name defined");6425}6426}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6427# blobs defined by non-textual hash id's can be cached6428$expires="+1d";6429}64306431my$have_blame= gitweb_check_feature('blame');6432open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6433or die_error(500,"Couldn't cat$file_name,$hash");6434my$mimetype= blob_mimetype($fd,$file_name);6435# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6436if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6437close$fd;6438return git_blob_plain($mimetype);6439}6440# we can have blame only for text/* mimetype6441$have_blame&&= ($mimetype=~m!^text/!);64426443my$highlight= gitweb_check_feature('highlight');6444my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6445$fd= run_highlighter($fd,$highlight,$syntax)6446if$syntax;64476448 git_header_html(undef,$expires);6449my$formats_nav='';6450if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6451if(defined$file_name) {6452if($have_blame) {6453$formats_nav.=6454$cgi->a({-href => href(action=>"blame", -replay=>1)},6455"blame") .6456" | ";6457}6458$formats_nav.=6459$cgi->a({-href => href(action=>"history", -replay=>1)},6460"history") .6461" | ".6462$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6463"raw") .6464" | ".6465$cgi->a({-href => href(action=>"blob",6466 hash_base=>"HEAD", file_name=>$file_name)},6467"HEAD");6468}else{6469$formats_nav.=6470$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6471"raw");6472}6473 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6474 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6475}else{6476print"<div class=\"page_nav\">\n".6477"<br/><br/></div>\n".6478"<div class=\"title\">".esc_html($hash)."</div>\n";6479}6480 git_print_page_path($file_name,"blob",$hash_base);6481print"<div class=\"page_body\">\n";6482if($mimetype=~m!^image/!) {6483print qq!<img type="!.esc_attr($mimetype).qq!"!;6484if($file_name) {6485print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;6486}6487print qq! src="! .6488 href(action=>"blob_plain", hash=>$hash,6489 hash_base=>$hash_base, file_name=>$file_name) .6490 qq!"/>\n!;6491}else{6492my$nr;6493while(my$line= <$fd>) {6494chomp$line;6495$nr++;6496$line= untabify($line);6497printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,6498$nr, esc_attr(href(-replay =>1)),$nr,$nr,6499$syntax? sanitize($line) : esc_html($line, -nbsp=>1);6500}6501}6502close$fd6503or print"Reading blob failed.\n";6504print"</div>";6505 git_footer_html();6506}65076508sub git_tree {6509if(!defined$hash_base) {6510$hash_base="HEAD";6511}6512if(!defined$hash) {6513if(defined$file_name) {6514$hash= git_get_hash_by_path($hash_base,$file_name,"tree");6515}else{6516$hash=$hash_base;6517}6518}6519 die_error(404,"No such tree")unlessdefined($hash);65206521my$show_sizes= gitweb_check_feature('show-sizes');6522my$have_blame= gitweb_check_feature('blame');65236524my@entries= ();6525{6526local$/="\0";6527open my$fd,"-|", git_cmd(),"ls-tree",'-z',6528($show_sizes?'-l': ()),@extra_options,$hash6529or die_error(500,"Open git-ls-tree failed");6530@entries=map{chomp;$_} <$fd>;6531close$fd6532or die_error(404,"Reading tree failed");6533}65346535my$refs= git_get_references();6536my$ref= format_ref_marker($refs,$hash_base);6537 git_header_html();6538my$basedir='';6539if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6540my@views_nav= ();6541if(defined$file_name) {6542push@views_nav,6543$cgi->a({-href => href(action=>"history", -replay=>1)},6544"history"),6545$cgi->a({-href => href(action=>"tree",6546 hash_base=>"HEAD", file_name=>$file_name)},6547"HEAD"),6548}6549my$snapshot_links= format_snapshot_links($hash);6550if(defined$snapshot_links) {6551# FIXME: Should be available when we have no hash base as well.6552push@views_nav,$snapshot_links;6553}6554 git_print_page_nav('tree','',$hash_base,undef,undef,6555join(' | ',@views_nav));6556 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);6557}else{6558undef$hash_base;6559print"<div class=\"page_nav\">\n";6560print"<br/><br/></div>\n";6561print"<div class=\"title\">".esc_html($hash)."</div>\n";6562}6563if(defined$file_name) {6564$basedir=$file_name;6565if($basedirne''&&substr($basedir, -1)ne'/') {6566$basedir.='/';6567}6568 git_print_page_path($file_name,'tree',$hash_base);6569}6570print"<div class=\"page_body\">\n";6571print"<table class=\"tree\">\n";6572my$alternate=1;6573# '..' (top directory) link if possible6574if(defined$hash_base&&6575defined$file_name&&$file_name=~m![^/]+$!) {6576if($alternate) {6577print"<tr class=\"dark\">\n";6578}else{6579print"<tr class=\"light\">\n";6580}6581$alternate^=1;65826583my$up=$file_name;6584$up=~s!/?[^/]+$!!;6585undef$upunless$up;6586# based on git_print_tree_entry6587print'<td class="mode">'. mode_str('040000') ."</td>\n";6588print'<td class="size"> </td>'."\n"if$show_sizes;6589print'<td class="list">';6590print$cgi->a({-href => href(action=>"tree",6591 hash_base=>$hash_base,6592 file_name=>$up)},6593"..");6594print"</td>\n";6595print"<td class=\"link\"></td>\n";65966597print"</tr>\n";6598}6599foreachmy$line(@entries) {6600my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);66016602if($alternate) {6603print"<tr class=\"dark\">\n";6604}else{6605print"<tr class=\"light\">\n";6606}6607$alternate^=1;66086609 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);66106611print"</tr>\n";6612}6613print"</table>\n".6614"</div>";6615 git_footer_html();6616}66176618sub snapshot_name {6619my($project,$hash) =@_;66206621# path/to/project.git -> project6622# path/to/project/.git -> project6623my$name= to_utf8($project);6624$name=~ s,([^/])/*\.git$,$1,;6625$name= basename($name);6626# sanitize name6627$name=~s/[[:cntrl:]]/?/g;66286629my$ver=$hash;6630if($hash=~/^[0-9a-fA-F]+$/) {6631# shorten SHA-1 hash6632my$full_hash= git_get_full_hash($project,$hash);6633if($full_hash=~/^$hash/&&length($hash) >7) {6634$ver= git_get_short_hash($project,$hash);6635}6636}elsif($hash=~m!^refs/tags/(.*)$!) {6637# tags don't need shortened SHA-1 hash6638$ver=$1;6639}else{6640# branches and other need shortened SHA-1 hash6641if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {6642$ver=$1;6643}6644$ver.='-'. git_get_short_hash($project,$hash);6645}6646# in case of hierarchical branch names6647$ver=~s!/!.!g;66486649# name = project-version_string6650$name="$name-$ver";66516652returnwantarray? ($name,$name) :$name;6653}66546655sub git_snapshot {6656my$format=$input_params{'snapshot_format'};6657if(!@snapshot_fmts) {6658 die_error(403,"Snapshots not allowed");6659}6660# default to first supported snapshot format6661$format||=$snapshot_fmts[0];6662if($format!~m/^[a-z0-9]+$/) {6663 die_error(400,"Invalid snapshot format parameter");6664}elsif(!exists($known_snapshot_formats{$format})) {6665 die_error(400,"Unknown snapshot format");6666}elsif($known_snapshot_formats{$format}{'disabled'}) {6667 die_error(403,"Snapshot format not allowed");6668}elsif(!grep($_eq$format,@snapshot_fmts)) {6669 die_error(403,"Unsupported snapshot format");6670}66716672my$type= git_get_type("$hash^{}");6673if(!$type) {6674 die_error(404,'Object does not exist');6675}elsif($typeeq'blob') {6676 die_error(400,'Object is not a tree-ish');6677}66786679my($name,$prefix) = snapshot_name($project,$hash);6680my$filename="$name$known_snapshot_formats{$format}{'suffix'}";6681my$cmd= quote_command(6682 git_cmd(),'archive',6683"--format=$known_snapshot_formats{$format}{'format'}",6684"--prefix=$prefix/",$hash);6685if(exists$known_snapshot_formats{$format}{'compressor'}) {6686$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});6687}66886689$filename=~s/(["\\])/\\$1/g;6690print$cgi->header(6691-type =>$known_snapshot_formats{$format}{'type'},6692-content_disposition =>'inline; filename="'.$filename.'"',6693-status =>'200 OK');66946695open my$fd,"-|",$cmd6696or die_error(500,"Execute git-archive failed");6697binmode STDOUT,':raw';6698print<$fd>;6699binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6700close$fd;6701}67026703sub git_log_generic {6704my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;67056706my$head= git_get_head_hash($project);6707if(!defined$base) {6708$base=$head;6709}6710if(!defined$page) {6711$page=0;6712}6713my$refs= git_get_references();67146715my$commit_hash=$base;6716if(defined$parent) {6717$commit_hash="$parent..$base";6718}6719my@commitlist=6720 parse_commits($commit_hash,101, (100*$page),6721defined$file_name? ($file_name,"--full-history") : ());67226723my$ftype;6724if(!defined$file_hash&&defined$file_name) {6725# some commits could have deleted file in question,6726# and not have it in tree, but one of them has to have it6727for(my$i=0;$i<@commitlist;$i++) {6728$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);6729last ifdefined$file_hash;6730}6731}6732if(defined$file_hash) {6733$ftype= git_get_type($file_hash);6734}6735if(defined$file_name&& !defined$ftype) {6736 die_error(500,"Unknown type of object");6737}6738my%co;6739if(defined$file_name) {6740%co= parse_commit($base)6741or die_error(404,"Unknown commit object");6742}674367446745my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);6746my$next_link='';6747if($#commitlist>=100) {6748$next_link=6749$cgi->a({-href => href(-replay=>1, page=>$page+1),6750-accesskey =>"n", -title =>"Alt-n"},"next");6751}6752my$patch_max= gitweb_get_feature('patches');6753if($patch_max&& !defined$file_name) {6754if($patch_max<0||@commitlist<=$patch_max) {6755$paging_nav.=" ⋅ ".6756$cgi->a({-href => href(action=>"patches", -replay=>1)},6757"patches");6758}6759}67606761 git_header_html();6762 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);6763if(defined$file_name) {6764 git_print_header_div('commit', esc_html($co{'title'}),$base);6765}else{6766 git_print_header_div('summary',$project)6767}6768 git_print_page_path($file_name,$ftype,$hash_base)6769if(defined$file_name);67706771$body_subr->(\@commitlist,0,99,$refs,$next_link,6772$file_name,$file_hash,$ftype);67736774 git_footer_html();6775}67766777sub git_log {6778 git_log_generic('log', \&git_log_body,6779$hash,$hash_parent);6780}67816782sub git_commit {6783$hash||=$hash_base||"HEAD";6784my%co= parse_commit($hash)6785or die_error(404,"Unknown commit object");67866787my$parent=$co{'parent'};6788my$parents=$co{'parents'};# listref67896790# we need to prepare $formats_nav before any parameter munging6791my$formats_nav;6792if(!defined$parent) {6793# --root commitdiff6794$formats_nav.='(initial)';6795}elsif(@$parents==1) {6796# single parent commit6797$formats_nav.=6798'(parent: '.6799$cgi->a({-href => href(action=>"commit",6800 hash=>$parent)},6801 esc_html(substr($parent,0,7))) .6802')';6803}else{6804# merge commit6805$formats_nav.=6806'(merge: '.6807join(' ',map{6808$cgi->a({-href => href(action=>"commit",6809 hash=>$_)},6810 esc_html(substr($_,0,7)));6811}@$parents) .6812')';6813}6814if(gitweb_check_feature('patches') &&@$parents<=1) {6815$formats_nav.=" | ".6816$cgi->a({-href => href(action=>"patch", -replay=>1)},6817"patch");6818}68196820if(!defined$parent) {6821$parent="--root";6822}6823my@difftree;6824open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",6825@diff_opts,6826(@$parents<=1?$parent:'-c'),6827$hash,"--"6828or die_error(500,"Open git-diff-tree failed");6829@difftree=map{chomp;$_} <$fd>;6830close$fdor die_error(404,"Reading git-diff-tree failed");68316832# non-textual hash id's can be cached6833my$expires;6834if($hash=~m/^[0-9a-fA-F]{40}$/) {6835$expires="+1d";6836}6837my$refs= git_get_references();6838my$ref= format_ref_marker($refs,$co{'id'});68396840 git_header_html(undef,$expires);6841 git_print_page_nav('commit','',6842$hash,$co{'tree'},$hash,6843$formats_nav);68446845if(defined$co{'parent'}) {6846 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);6847}else{6848 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);6849}6850print"<div class=\"title_text\">\n".6851"<table class=\"object_header\">\n";6852 git_print_authorship_rows(\%co);6853print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";6854print"<tr>".6855"<td>tree</td>".6856"<td class=\"sha1\">".6857$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),6858class=>"list"},$co{'tree'}) .6859"</td>".6860"<td class=\"link\">".6861$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6862"tree");6863my$snapshot_links= format_snapshot_links($hash);6864if(defined$snapshot_links) {6865print" | ".$snapshot_links;6866}6867print"</td>".6868"</tr>\n";68696870foreachmy$par(@$parents) {6871print"<tr>".6872"<td>parent</td>".6873"<td class=\"sha1\">".6874$cgi->a({-href => href(action=>"commit", hash=>$par),6875class=>"list"},$par) .6876"</td>".6877"<td class=\"link\">".6878$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6879" | ".6880$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6881"</td>".6882"</tr>\n";6883}6884print"</table>".6885"</div>\n";68866887print"<div class=\"page_body\">\n";6888 git_print_log($co{'comment'});6889print"</div>\n";68906891 git_difftree_body(\@difftree,$hash,@$parents);68926893 git_footer_html();6894}68956896sub git_object {6897# object is defined by:6898# - hash or hash_base alone6899# - hash_base and file_name6900my$type;69016902# - hash or hash_base alone6903if($hash|| ($hash_base&& !defined$file_name)) {6904my$object_id=$hash||$hash_base;69056906open my$fd,"-|", quote_command(6907 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6908or die_error(404,"Object does not exist");6909$type= <$fd>;6910chomp$type;6911close$fd6912or die_error(404,"Object does not exist");69136914# - hash_base and file_name6915}elsif($hash_base&&defined$file_name) {6916$file_name=~ s,/+$,,;69176918system(git_cmd(),"cat-file",'-e',$hash_base) ==06919or die_error(404,"Base object does not exist");69206921# here errors should not hapen6922open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6923or die_error(500,"Open git-ls-tree failed");6924my$line= <$fd>;6925close$fd;69266927#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6928unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6929 die_error(404,"File or directory for given base does not exist");6930}6931$type=$2;6932$hash=$3;6933}else{6934 die_error(400,"Not enough information to find object");6935}69366937print$cgi->redirect(-uri => href(action=>$type, -full=>1,6938 hash=>$hash, hash_base=>$hash_base,6939 file_name=>$file_name),6940-status =>'302 Found');6941}69426943sub git_blobdiff {6944my$format=shift||'html';69456946my$fd;6947my@difftree;6948my%diffinfo;6949my$expires;69506951# preparing $fd and %diffinfo for git_patchset_body6952# new style URI6953if(defined$hash_base&&defined$hash_parent_base) {6954if(defined$file_name) {6955# read raw output6956open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6957$hash_parent_base,$hash_base,6958"--", (defined$file_parent?$file_parent: ()),$file_name6959or die_error(500,"Open git-diff-tree failed");6960@difftree=map{chomp;$_} <$fd>;6961close$fd6962or die_error(404,"Reading git-diff-tree failed");6963@difftree6964or die_error(404,"Blob diff not found");69656966}elsif(defined$hash&&6967$hash=~/[0-9a-fA-F]{40}/) {6968# try to find filename from $hash69696970# read filtered raw output6971open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6972$hash_parent_base,$hash_base,"--"6973or die_error(500,"Open git-diff-tree failed");6974@difftree=6975# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6976# $hash == to_id6977grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6978map{chomp;$_} <$fd>;6979close$fd6980or die_error(404,"Reading git-diff-tree failed");6981@difftree6982or die_error(404,"Blob diff not found");69836984}else{6985 die_error(400,"Missing one of the blob diff parameters");6986}69876988if(@difftree>1) {6989 die_error(400,"Ambiguous blob diff specification");6990}69916992%diffinfo= parse_difftree_raw_line($difftree[0]);6993$file_parent||=$diffinfo{'from_file'} ||$file_name;6994$file_name||=$diffinfo{'to_file'};69956996$hash_parent||=$diffinfo{'from_id'};6997$hash||=$diffinfo{'to_id'};69986999# non-textual hash id's can be cached7000if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7001$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7002$expires='+1d';7003}70047005# open patch output7006open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7007'-p', ($formateq'html'?"--full-index": ()),7008$hash_parent_base,$hash_base,7009"--", (defined$file_parent?$file_parent: ()),$file_name7010or die_error(500,"Open git-diff-tree failed");7011}70127013# old/legacy style URI -- not generated anymore since 1.4.3.7014if(!%diffinfo) {7015 die_error('404 Not Found',"Missing one of the blob diff parameters")7016}70177018# header7019if($formateq'html') {7020my$formats_nav=7021$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7022"raw");7023 git_header_html(undef,$expires);7024if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7025 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7026 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7027}else{7028print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7029print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7030}7031if(defined$file_name) {7032 git_print_page_path($file_name,"blob",$hash_base);7033}else{7034print"<div class=\"page_path\"></div>\n";7035}70367037}elsif($formateq'plain') {7038print$cgi->header(7039-type =>'text/plain',7040-charset =>'utf-8',7041-expires =>$expires,7042-content_disposition =>'inline; filename="'."$file_name".'.patch"');70437044print"X-Git-Url: ".$cgi->self_url() ."\n\n";70457046}else{7047 die_error(400,"Unknown blobdiff format");7048}70497050# patch7051if($formateq'html') {7052print"<div class=\"page_body\">\n";70537054 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);7055close$fd;70567057print"</div>\n";# class="page_body"7058 git_footer_html();70597060}else{7061while(my$line= <$fd>) {7062$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7063$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;70647065print$line;70667067last if$line=~m!^\+\+\+!;7068}7069local$/=undef;7070print<$fd>;7071close$fd;7072}7073}70747075sub git_blobdiff_plain {7076 git_blobdiff('plain');7077}70787079sub git_commitdiff {7080my%params=@_;7081my$format=$params{-format} ||'html';70827083my($patch_max) = gitweb_get_feature('patches');7084if($formateq'patch') {7085 die_error(403,"Patch view not allowed")unless$patch_max;7086}70877088$hash||=$hash_base||"HEAD";7089my%co= parse_commit($hash)7090or die_error(404,"Unknown commit object");70917092# choose format for commitdiff for merge7093if(!defined$hash_parent&& @{$co{'parents'}} >1) {7094$hash_parent='--cc';7095}7096# we need to prepare $formats_nav before almost any parameter munging7097my$formats_nav;7098if($formateq'html') {7099$formats_nav=7100$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7101"raw");7102if($patch_max&& @{$co{'parents'}} <=1) {7103$formats_nav.=" | ".7104$cgi->a({-href => href(action=>"patch", -replay=>1)},7105"patch");7106}71077108if(defined$hash_parent&&7109$hash_parentne'-c'&&$hash_parentne'--cc') {7110# commitdiff with two commits given7111my$hash_parent_short=$hash_parent;7112if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7113$hash_parent_short=substr($hash_parent,0,7);7114}7115$formats_nav.=7116' (from';7117for(my$i=0;$i< @{$co{'parents'}};$i++) {7118if($co{'parents'}[$i]eq$hash_parent) {7119$formats_nav.=' parent '. ($i+1);7120last;7121}7122}7123$formats_nav.=': '.7124$cgi->a({-href => href(action=>"commitdiff",7125 hash=>$hash_parent)},7126 esc_html($hash_parent_short)) .7127')';7128}elsif(!$co{'parent'}) {7129# --root commitdiff7130$formats_nav.=' (initial)';7131}elsif(scalar@{$co{'parents'}} ==1) {7132# single parent commit7133$formats_nav.=7134' (parent: '.7135$cgi->a({-href => href(action=>"commitdiff",7136 hash=>$co{'parent'})},7137 esc_html(substr($co{'parent'},0,7))) .7138')';7139}else{7140# merge commit7141if($hash_parenteq'--cc') {7142$formats_nav.=' | '.7143$cgi->a({-href => href(action=>"commitdiff",7144 hash=>$hash, hash_parent=>'-c')},7145'combined');7146}else{# $hash_parent eq '-c'7147$formats_nav.=' | '.7148$cgi->a({-href => href(action=>"commitdiff",7149 hash=>$hash, hash_parent=>'--cc')},7150'compact');7151}7152$formats_nav.=7153' (merge: '.7154join(' ',map{7155$cgi->a({-href => href(action=>"commitdiff",7156 hash=>$_)},7157 esc_html(substr($_,0,7)));7158} @{$co{'parents'}} ) .7159')';7160}7161}71627163my$hash_parent_param=$hash_parent;7164if(!defined$hash_parent_param) {7165# --cc for multiple parents, --root for parentless7166$hash_parent_param=7167@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7168}71697170# read commitdiff7171my$fd;7172my@difftree;7173if($formateq'html') {7174open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7175"--no-commit-id","--patch-with-raw","--full-index",7176$hash_parent_param,$hash,"--"7177or die_error(500,"Open git-diff-tree failed");71787179while(my$line= <$fd>) {7180chomp$line;7181# empty line ends raw part of diff-tree output7182last unless$line;7183push@difftree,scalar parse_difftree_raw_line($line);7184}71857186}elsif($formateq'plain') {7187open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7188'-p',$hash_parent_param,$hash,"--"7189or die_error(500,"Open git-diff-tree failed");7190}elsif($formateq'patch') {7191# For commit ranges, we limit the output to the number of7192# patches specified in the 'patches' feature.7193# For single commits, we limit the output to a single patch,7194# diverging from the git-format-patch default.7195my@commit_spec= ();7196if($hash_parent) {7197if($patch_max>0) {7198push@commit_spec,"-$patch_max";7199}7200push@commit_spec,'-n',"$hash_parent..$hash";7201}else{7202if($params{-single}) {7203push@commit_spec,'-1';7204}else{7205if($patch_max>0) {7206push@commit_spec,"-$patch_max";7207}7208push@commit_spec,"-n";7209}7210push@commit_spec,'--root',$hash;7211}7212open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7213'--encoding=utf8','--stdout',@commit_spec7214or die_error(500,"Open git-format-patch failed");7215}else{7216 die_error(400,"Unknown commitdiff format");7217}72187219# non-textual hash id's can be cached7220my$expires;7221if($hash=~m/^[0-9a-fA-F]{40}$/) {7222$expires="+1d";7223}72247225# write commit message7226if($formateq'html') {7227my$refs= git_get_references();7228my$ref= format_ref_marker($refs,$co{'id'});72297230 git_header_html(undef,$expires);7231 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7232 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7233print"<div class=\"title_text\">\n".7234"<table class=\"object_header\">\n";7235 git_print_authorship_rows(\%co);7236print"</table>".7237"</div>\n";7238print"<div class=\"page_body\">\n";7239if(@{$co{'comment'}} >1) {7240print"<div class=\"log\">\n";7241 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7242print"</div>\n";# class="log"7243}72447245}elsif($formateq'plain') {7246my$refs= git_get_references("tags");7247my$tagname= git_get_rev_name_tags($hash);7248my$filename= basename($project) ."-$hash.patch";72497250print$cgi->header(7251-type =>'text/plain',7252-charset =>'utf-8',7253-expires =>$expires,7254-content_disposition =>'inline; filename="'."$filename".'"');7255my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7256print"From: ". to_utf8($co{'author'}) ."\n";7257print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7258print"Subject: ". to_utf8($co{'title'}) ."\n";72597260print"X-Git-Tag:$tagname\n"if$tagname;7261print"X-Git-Url: ".$cgi->self_url() ."\n\n";72627263foreachmy$line(@{$co{'comment'}}) {7264print to_utf8($line) ."\n";7265}7266print"---\n\n";7267}elsif($formateq'patch') {7268my$filename= basename($project) ."-$hash.patch";72697270print$cgi->header(7271-type =>'text/plain',7272-charset =>'utf-8',7273-expires =>$expires,7274-content_disposition =>'inline; filename="'."$filename".'"');7275}72767277# write patch7278if($formateq'html') {7279my$use_parents= !defined$hash_parent||7280$hash_parenteq'-c'||$hash_parenteq'--cc';7281 git_difftree_body(\@difftree,$hash,7282$use_parents? @{$co{'parents'}} :$hash_parent);7283print"<br/>\n";72847285 git_patchset_body($fd, \@difftree,$hash,7286$use_parents? @{$co{'parents'}} :$hash_parent);7287close$fd;7288print"</div>\n";# class="page_body"7289 git_footer_html();72907291}elsif($formateq'plain') {7292local$/=undef;7293print<$fd>;7294close$fd7295or print"Reading git-diff-tree failed\n";7296}elsif($formateq'patch') {7297local$/=undef;7298print<$fd>;7299close$fd7300or print"Reading git-format-patch failed\n";7301}7302}73037304sub git_commitdiff_plain {7305 git_commitdiff(-format =>'plain');7306}73077308# format-patch-style patches7309sub git_patch {7310 git_commitdiff(-format =>'patch', -single =>1);7311}73127313sub git_patches {7314 git_commitdiff(-format =>'patch');7315}73167317sub git_history {7318 git_log_generic('history', \&git_history_body,7319$hash_base,$hash_parent_base,7320$file_name,$hash);7321}73227323sub git_search {7324$searchtype||='commit';73257326# check if appropriate features are enabled7327 gitweb_check_feature('search')7328or die_error(403,"Search is disabled");7329if($searchtypeeq'pickaxe') {7330# pickaxe may take all resources of your box and run for several minutes7331# with every query - so decide by yourself how public you make this feature7332 gitweb_check_feature('pickaxe')7333or die_error(403,"Pickaxe search is disabled");7334}7335if($searchtypeeq'grep') {7336# grep search might be potentially CPU-intensive, too7337 gitweb_check_feature('grep')7338or die_error(403,"Grep search is disabled");7339}73407341if(!defined$searchtext) {7342 die_error(400,"Text field is empty");7343}7344if(!defined$hash) {7345$hash= git_get_head_hash($project);7346}7347my%co= parse_commit($hash);7348if(!%co) {7349 die_error(404,"Unknown commit object");7350}7351if(!defined$page) {7352$page=0;7353}73547355if($searchtypeeq'commit'||7356$searchtypeeq'author'||7357$searchtypeeq'committer') {7358 git_search_message(%co);7359}elsif($searchtypeeq'pickaxe') {7360 git_search_changes(%co);7361}elsif($searchtypeeq'grep') {7362 git_search_files(%co);7363}else{7364 die_error(400,"Unknown search type");7365}7366}73677368sub git_search_help {7369 git_header_html();7370 git_print_page_nav('','',$hash,$hash,$hash);7371print<<EOT;7372<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7373regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7374the pattern entered is recognized as the POSIX extended7375<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7376insensitive).</p>7377<dl>7378<dt><b>commit</b></dt>7379<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7380EOT7381my$have_grep= gitweb_check_feature('grep');7382if($have_grep) {7383print<<EOT;7384<dt><b>grep</b></dt>7385<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7386 a different one) are searched for the given pattern. On large trees, this search can take7387a while and put some strain on the server, so please use it with some consideration. Note that7388due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7389case-sensitive.</dd>7390EOT7391}7392print<<EOT;7393<dt><b>author</b></dt>7394<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7395<dt><b>committer</b></dt>7396<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7397EOT7398my$have_pickaxe= gitweb_check_feature('pickaxe');7399if($have_pickaxe) {7400print<<EOT;7401<dt><b>pickaxe</b></dt>7402<dd>All commits that caused the string to appear or disappear from any file (changes that7403added, removed or "modified" the string) will be listed. This search can take a while and7404takes a lot of strain on the server, so please use it wisely. Note that since you may be7405interested even in changes just changing the case as well, this search is case sensitive.</dd>7406EOT7407}7408print"</dl>\n";7409 git_footer_html();7410}74117412sub git_shortlog {7413 git_log_generic('shortlog', \&git_shortlog_body,7414$hash,$hash_parent);7415}74167417## ......................................................................7418## feeds (RSS, Atom; OPML)74197420sub git_feed {7421my$format=shift||'atom';7422my$have_blame= gitweb_check_feature('blame');74237424# Atom: http://www.atomenabled.org/developers/syndication/7425# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ7426if($formatne'rss'&&$formatne'atom') {7427 die_error(400,"Unknown web feed format");7428}74297430# log/feed of current (HEAD) branch, log of given branch, history of file/directory7431my$head=$hash||'HEAD';7432my@commitlist= parse_commits($head,150,0,$file_name);74337434my%latest_commit;7435my%latest_date;7436my$content_type="application/$format+xml";7437if(defined$cgi->http('HTTP_ACCEPT') &&7438$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {7439# browser (feed reader) prefers text/xml7440$content_type='text/xml';7441}7442if(defined($commitlist[0])) {7443%latest_commit= %{$commitlist[0]};7444my$latest_epoch=$latest_commit{'committer_epoch'};7445%latest_date= parse_date($latest_epoch,$latest_commit{'comitter_tz'});7446my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7447if(defined$if_modified) {7448my$since;7449if(eval{require HTTP::Date;1; }) {7450$since= HTTP::Date::str2time($if_modified);7451}elsif(eval{require Time::ParseDate;1; }) {7452$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7453}7454if(defined$since&&$latest_epoch<=$since) {7455print$cgi->header(7456-type =>$content_type,7457-charset =>'utf-8',7458-last_modified =>$latest_date{'rfc2822'},7459-status =>'304 Not Modified');7460return;7461}7462}7463print$cgi->header(7464-type =>$content_type,7465-charset =>'utf-8',7466-last_modified =>$latest_date{'rfc2822'});7467}else{7468print$cgi->header(7469-type =>$content_type,7470-charset =>'utf-8');7471}74727473# Optimization: skip generating the body if client asks only7474# for Last-Modified date.7475return if($cgi->request_method()eq'HEAD');74767477# header variables7478my$title="$site_name-$project/$action";7479my$feed_type='log';7480if(defined$hash) {7481$title.=" - '$hash'";7482$feed_type='branch log';7483if(defined$file_name) {7484$title.=" ::$file_name";7485$feed_type='history';7486}7487}elsif(defined$file_name) {7488$title.=" -$file_name";7489$feed_type='history';7490}7491$title.="$feed_type";7492my$descr= git_get_project_description($project);7493if(defined$descr) {7494$descr= esc_html($descr);7495}else{7496$descr="$project".7497($formateq'rss'?'RSS':'Atom') .7498" feed";7499}7500my$owner= git_get_project_owner($project);7501$owner= esc_html($owner);75027503#header7504my$alt_url;7505if(defined$file_name) {7506$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);7507}elsif(defined$hash) {7508$alt_url= href(-full=>1, action=>"log", hash=>$hash);7509}else{7510$alt_url= href(-full=>1, action=>"summary");7511}7512print qq!<?xml version="1.0" encoding="utf-8"?>\n!;7513if($formateq'rss') {7514print<<XML;7515<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">7516<channel>7517XML7518print"<title>$title</title>\n".7519"<link>$alt_url</link>\n".7520"<description>$descr</description>\n".7521"<language>en</language>\n".7522# project owner is responsible for 'editorial' content7523"<managingEditor>$owner</managingEditor>\n";7524if(defined$logo||defined$favicon) {7525# prefer the logo to the favicon, since RSS7526# doesn't allow both7527my$img= esc_url($logo||$favicon);7528print"<image>\n".7529"<url>$img</url>\n".7530"<title>$title</title>\n".7531"<link>$alt_url</link>\n".7532"</image>\n";7533}7534if(%latest_date) {7535print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";7536print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";7537}7538print"<generator>gitweb v.$version/$git_version</generator>\n";7539}elsif($formateq'atom') {7540print<<XML;7541<feed xmlns="http://www.w3.org/2005/Atom">7542XML7543print"<title>$title</title>\n".7544"<subtitle>$descr</subtitle>\n".7545'<link rel="alternate" type="text/html" href="'.7546$alt_url.'" />'."\n".7547'<link rel="self" type="'.$content_type.'" href="'.7548$cgi->self_url() .'" />'."\n".7549"<id>". href(-full=>1) ."</id>\n".7550# use project owner for feed author7551"<author><name>$owner</name></author>\n";7552if(defined$favicon) {7553print"<icon>". esc_url($favicon) ."</icon>\n";7554}7555if(defined$logo) {7556# not twice as wide as tall: 72 x 27 pixels7557print"<logo>". esc_url($logo) ."</logo>\n";7558}7559if(!%latest_date) {7560# dummy date to keep the feed valid until commits trickle in:7561print"<updated>1970-01-01T00:00:00Z</updated>\n";7562}else{7563print"<updated>$latest_date{'iso-8601'}</updated>\n";7564}7565print"<generator version='$version/$git_version'>gitweb</generator>\n";7566}75677568# contents7569for(my$i=0;$i<=$#commitlist;$i++) {7570my%co= %{$commitlist[$i]};7571my$commit=$co{'id'};7572# we read 150, we always show 30 and the ones more recent than 48 hours7573if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {7574last;7575}7576my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});75777578# get list of changed files7579open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7580$co{'parent'} ||"--root",7581$co{'id'},"--", (defined$file_name?$file_name: ())7582ornext;7583my@difftree=map{chomp;$_} <$fd>;7584close$fd7585ornext;75867587# print element (entry, item)7588my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);7589if($formateq'rss') {7590print"<item>\n".7591"<title>". esc_html($co{'title'}) ."</title>\n".7592"<author>". esc_html($co{'author'}) ."</author>\n".7593"<pubDate>$cd{'rfc2822'}</pubDate>\n".7594"<guid isPermaLink=\"true\">$co_url</guid>\n".7595"<link>$co_url</link>\n".7596"<description>". esc_html($co{'title'}) ."</description>\n".7597"<content:encoded>".7598"<![CDATA[\n";7599}elsif($formateq'atom') {7600print"<entry>\n".7601"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".7602"<updated>$cd{'iso-8601'}</updated>\n".7603"<author>\n".7604" <name>". esc_html($co{'author_name'}) ."</name>\n";7605if($co{'author_email'}) {7606print" <email>". esc_html($co{'author_email'}) ."</email>\n";7607}7608print"</author>\n".7609# use committer for contributor7610"<contributor>\n".7611" <name>". esc_html($co{'committer_name'}) ."</name>\n";7612if($co{'committer_email'}) {7613print" <email>". esc_html($co{'committer_email'}) ."</email>\n";7614}7615print"</contributor>\n".7616"<published>$cd{'iso-8601'}</published>\n".7617"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".7618"<id>$co_url</id>\n".7619"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".7620"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";7621}7622my$comment=$co{'comment'};7623print"<pre>\n";7624foreachmy$line(@$comment) {7625$line= esc_html($line);7626print"$line\n";7627}7628print"</pre><ul>\n";7629foreachmy$difftree_line(@difftree) {7630my%difftree= parse_difftree_raw_line($difftree_line);7631next if!$difftree{'from_id'};76327633my$file=$difftree{'file'} ||$difftree{'to_file'};76347635print"<li>".7636"[".7637$cgi->a({-href => href(-full=>1, action=>"blobdiff",7638 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},7639 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},7640 file_name=>$file, file_parent=>$difftree{'from_file'}),7641-title =>"diff"},'D');7642if($have_blame) {7643print$cgi->a({-href => href(-full=>1, action=>"blame",7644 file_name=>$file, hash_base=>$commit),7645-title =>"blame"},'B');7646}7647# if this is not a feed of a file history7648if(!defined$file_name||$file_namene$file) {7649print$cgi->a({-href => href(-full=>1, action=>"history",7650 file_name=>$file, hash=>$commit),7651-title =>"history"},'H');7652}7653$file= esc_path($file);7654print"] ".7655"$file</li>\n";7656}7657if($formateq'rss') {7658print"</ul>]]>\n".7659"</content:encoded>\n".7660"</item>\n";7661}elsif($formateq'atom') {7662print"</ul>\n</div>\n".7663"</content>\n".7664"</entry>\n";7665}7666}76677668# end of feed7669if($formateq'rss') {7670print"</channel>\n</rss>\n";7671}elsif($formateq'atom') {7672print"</feed>\n";7673}7674}76757676sub git_rss {7677 git_feed('rss');7678}76797680sub git_atom {7681 git_feed('atom');7682}76837684sub git_opml {7685my@list= git_get_projects_list();7686if(!@list) {7687 die_error(404,"No projects found");7688}76897690print$cgi->header(7691-type =>'text/xml',7692-charset =>'utf-8',7693-content_disposition =>'inline; filename="opml.xml"');76947695print<<XML;7696<?xml version="1.0" encoding="utf-8"?>7697<opml version="1.0">7698<head>7699 <title>$site_nameOPML Export</title>7700</head>7701<body>7702<outline text="git RSS feeds">7703XML77047705foreachmy$pr(@list) {7706my%proj=%$pr;7707my$head= git_get_head_hash($proj{'path'});7708if(!defined$head) {7709next;7710}7711$git_dir="$projectroot/$proj{'path'}";7712my%co= parse_commit($head);7713if(!%co) {7714next;7715}77167717my$path= esc_html(chop_str($proj{'path'},25,5));7718my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7719my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7720print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7721}7722print<<XML;7723</outline>7724</body>7725</opml>7726XML7727}