Config.pm 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Dawn Endico <endico@mozilla.org>
#                 Dan Mosedale <dmose@mozilla.org>
#                 Joe Robins <jmrobins@tgix.com>
#                 Jake <jake@bugzilla.org>
#                 J. Paul Reed <preed@sigkill.com>
#                 Bradley Baetz <bbaetz@student.usyd.edu.au>
#                 Christopher Aillon <christopher@aillon.com>
28
#                 Erik Stambaugh <erik@dasbistro.com>
29 30 31 32 33 34 35

package Bugzilla::Config;

use strict;

use base qw(Exporter);

36 37 38 39 40 41 42 43 44 45
# Under mod_perl, get this from a .htaccess config variable,
# and/or default from the current 'real' dir
# At some stage after this, it may be possible for these dir locations
# to go into localconfig. localconfig can't be specified in a config file,
# except possibly with mod_perl. If you move localconfig, you need to change
# the define here.
# $libpath is really only for mod_perl; its not yet possible to move the
# .pms elsewhere.
# $webdotdir must be in the webtree somewhere. Even if you use a local dot,
# we output images to there. Also, if $webdot dir is not relative to the
46
# bugzilla root directory, you'll need to change showdependencygraph.cgi to
47 48
# set image_url to the correct location.
# The script should really generate these graphs directly...
49
# Note that if $libpath is changed, some stuff will break, notably dependency
50 51 52 53 54 55
# graphs (since the path will be wrong in the HTML). This will be fixed at
# some point.

our $libpath = '.';
our $localconfig = "$libpath/localconfig";
our $datadir = "$libpath/data";
56
our $attachdir = "$datadir/attachments";
57 58 59
our $templatedir = "$libpath/template";
our $webdotdir = "$datadir/webdot";

60 61 62 63 64 65 66 67
# Module stuff
@Bugzilla::Config::EXPORT = qw(Param);

# Don't export localvars by default - people should have to explicitly
# ask for it, as a (probably futile) attempt to stop code using it
# when it shouldn't
# ChmodDataFile is here until that stuff all moves out of globals.pl
# into this file
68 69
@Bugzilla::Config::EXPORT_OK = qw(ChmodDataFile);

70 71 72
%Bugzilla::Config::EXPORT_TAGS =
  (
   admin => [qw(GetParamList UpdateParams SetParam WriteParams)],
73
   db => [qw($db_driver $db_host $db_port $db_name $db_user $db_pass $db_sock)],
74 75
   locations => [qw($libpath $localconfig $attachdir
                    $datadir $templatedir $webdotdir)],
76
  );
77
Exporter::export_ok_tags('admin', 'db', 'locations');
78 79

# Bugzilla version
80
$Bugzilla::Config::VERSION = "2.19.2+";
81 82 83 84

use Safe;

use vars qw(@param_list);
85 86 87 88 89 90 91 92 93 94 95

# Data::Dumper is required as needed, below. The problem is that then when
# the code locally sets $Data::Dumper::Foo, this triggers 'used only once'
# warnings.
# We can't predeclare another package's vars, though, so just use them
{
    local $Data::Dumper::Sortkeys;
    local $Data::Dumper::Terse;
    local $Data::Dumper::Indent;
}

96 97 98 99 100 101 102
my %param;

# INITIALISATION CODE

# XXX - mod_perl - need to register Apache init handler for params
sub _load_datafiles {
    # read in localconfig variables
103
    do $localconfig;
104

105
    if (-e "$datadir/params") {
106 107 108 109 110
        # Handle reading old param files by munging the symbol table
        # Don't have to do this if we use safe mode, since its evaled
        # in a sandbox where $foo is in the same module as $::foo
        #local *::param = \%param;

111
        # Note that checksetup.pl sets file permissions on '$datadir/params'
112 113 114 115 116 117

        # Using Safe mode is _not_ a guarantee of safety if someone does
        # manage to write to the file. However, it won't hurt...
        # See bug 165144 for not needing to eval this at all
        my $s = new Safe;

118 119 120
        $s->rdo("$datadir/params");
        die "Error reading $datadir/params: $!" if $!;
        die "Error evaluating $datadir/params: $@" if $@;
121 122 123 124 125 126 127 128 129 130

        # Now read the param back out from the sandbox
        %param = %{$s->varglob('param')};
    }
}

# Load in the datafiles
_load_datafiles();

# Load in the param defintions
131 132 133 134 135
unless (my $ret = do 'defparams.pl') {
    die "Couldn't parse defparams.pl: $@" if $@;
    die "Couldn't do defparams.pl: $!" unless defined $ret;
    die "Couldn't run defparams.pl" unless $ret;
}
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

# Stick the params into a hash
my %params;
foreach my $item (@param_list) {
    $params{$item->{'name'}} = $item;
}

# END INIT CODE

# Subroutines go here

sub Param {
    my ($param) = @_;

    # By this stage, the param must be in the hash
151
    die "Can't find param named $param" unless (exists $params{$param});
152

153 154 155 156 157 158 159 160 161
    # When module startup code runs (which is does even via -c, when using
    # |use|), we may try to grab params which don't exist yet. This affects
    # tests, so have this as a fallback for the -c case
    return $params{$param}->{default} if ($^C && not exists $param{$param});

    # If we have a value for the param, return it
    return $param{$param} if exists $param{$param};

    # Else error out
162
    die "No value for param $param (try running checksetup.pl again)";
163 164 165 166 167 168 169 170 171 172 173 174 175 176
}

sub GetParamList {
    return @param_list;
}

sub SetParam {
    my ($name, $value) = @_;

    die "Unknown param $name" unless (exists $params{$name});

    my $entry = $params{$name};

    # sanity check the value
177 178 179 180 181

    # XXX - This runs the checks. Which would be good, except that
    # check_shadowdb creates the database as a sideeffect, and so the
    # checker fails the second time arround...
    if ($name ne 'shadowdb' && exists $entry->{'checker'}) {
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        my $err = $entry->{'checker'}->($value, $entry);
        die "Param $name is not valid: $err" unless $err eq '';
    }

    $param{$name} = $value;
}

sub UpdateParams {
    # --- PARAM CONVERSION CODE ---

    # Note that this isn't particuarly 'clean' in terms of separating
    # the backend code (ie this) from the actual params.
    # We don't care about that, though

    # Old bugzilla versions stored the version number in the params file
    # We don't want it, so get rid of it
    delete $param{'version'};

200 201 202 203 204 205 206 207 208 209 210 211 212
    # Change from usebrowserinfo to defaultplatform/defaultopsys combo
    if (exists $param{'usebrowserinfo'}) {
        if (!$param{'usebrowserinfo'}) {
            if (!exists $param{'defaultplatform'}) {
                $param{'defaultplatform'} = 'Other';
            }
            if (!exists $param{'defaultopsys'}) {
                $param{'defaultopsys'} = 'other';
            }
        }
        delete $param{'usebrowserinfo'};
    }

213
    # Change from a boolean for quips to multi-state
214 215
    if (exists $param{'usequip'} && !exists $param{'enablequips'}) {
        $param{'enablequips'} = $param{'usequip'} ? 'on' : 'off';
216 217 218
        delete $param{'usequip'};
    }

219 220 221 222 223 224 225 226 227 228
    # Change from old product groups to controls for group_control_map
    # 2002-10-14 bug 147275 bugreport@peshkin.net
    if (exists $param{'usebuggroups'} && !exists $param{'makeproductgroups'}) {
        $param{'makeproductgroups'} = $param{'usebuggroups'};
    }
    if (exists $param{'usebuggroupsentry'} 
       && !exists $param{'useentrygroupdefault'}) {
        $param{'useentrygroupdefault'} = $param{'usebuggroupsentry'};
    }

229 230 231 232 233
    # Modularise auth code
    if (exists $param{'useLDAP'} && !exists $param{'loginmethod'}) {
        $param{'loginmethod'} = $param{'useLDAP'} ? "LDAP" : "DB";
    }

234 235 236 237 238 239
    # set verify method to whatever loginmethod was
    if (exists $param{'loginmethod'} && !exists $param{'user_verify_class'}) {
        $param{'user_verify_class'} = $param{'loginmethod'};
        delete $param{'loginmethod'};
    }

240 241 242 243 244 245 246 247 248
    # Remove quip-display control from parameters
    # and give it to users via User Settings (Bug 41972)
    if ( exists $param{'enablequips'} 
         && !exists $param{'quip_list_entry_control'}) 
    {
        my $new_value;
        ($param{'enablequips'} eq 'on')       && do {$new_value = 'open';};
        ($param{'enablequips'} eq 'approved') && do {$new_value = 'moderated';};
        ($param{'enablequips'} eq 'frozen')   && do {$new_value = 'closed';};
249
        ($param{'enablequips'} eq 'off')      && do {$new_value = 'closed';};
250 251 252 253
        $param{'quip_list_entry_control'} = $new_value;
        delete $param{'enablequips'};
    }

254 255 256 257 258 259 260 261 262 263 264 265 266 267
    # --- DEFAULTS FOR NEW PARAMS ---

    foreach my $item (@param_list) {
        my $name = $item->{'name'};
        $param{$name} = $item->{'default'} unless exists $param{$name};
    }

    # --- REMOVE OLD PARAMS ---

    my @oldparams = ();

    # Remove any old params
    foreach my $item (keys %param) {
        if (!grep($_ eq $item, map ($_->{'name'}, @param_list))) {
268 269
            require Data::Dumper;

270 271 272 273 274 275 276 277 278 279
            local $Data::Dumper::Terse = 1;
            local $Data::Dumper::Indent = 0;
            push (@oldparams, [$item, Data::Dumper->Dump([$param{$item}])]);
            delete $param{$item};
        }
    }

    return @oldparams;
}

280 281
sub WriteParams {
    require Data::Dumper;
282

283 284 285
    # This only has an affect for Data::Dumper >= 2.12 (ie perl >= 5.8.0)
    # Its just cosmetic, though, so that doesn't matter
    local $Data::Dumper::Sortkeys = 1;
286

287
    require File::Temp;
288
    my ($fh, $tmpname) = File::Temp::tempfile('params.XXXXX',
289
                                              DIR => $datadir );
290 291 292 293 294 295

    print $fh (Data::Dumper->Dump([ \%param ], [ '*param' ]))
      || die "Can't write param file: $!";

    close $fh;

296 297
    rename $tmpname, "$datadir/params"
      || die "Can't rename $tmpname to $datadir/params: $!";
298

299
    ChmodDataFile("$datadir/params", 0666);
300 301 302 303 304 305 306 307 308 309 310
}

# Some files in the data directory must be world readable iff we don't have
# a webserver group. Call this function to do this.
# This will become a private function once all the datafile handling stuff
# moves into this package

# This sub is not perldoc'd for that reason - noone should know about it
sub ChmodDataFile {
    my ($file, $mask) = @_;
    my $perm = 0770;
311
    if ((stat($datadir))[2] & 0002) {
312 313 314 315 316 317 318 319 320 321
        $perm = 0777;
    }
    $perm = $perm & $mask;
    chmod $perm,$file;
}

sub check_multi {
    my ($value, $param) = (@_);

    if ($param->{'type'} eq "s") {
322
        unless (scalar(grep {$_ eq $value} (@{$param->{'choices'}}))) {
323
            return "Invalid choice '$value' for single-select list param '$param->{'name'}'";
324 325 326 327 328 329
        }

        return "";
    }
    elsif ($param->{'type'} eq "m") {
        foreach my $chkParam (@$value) {
330
            unless (scalar(grep {$_ eq $chkParam} (@{$param->{'choices'}}))) {
331
                return "Invalid choice '$chkParam' for multi-select list param '$param->{'name'}'";
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            }
        }

        return "";
    }
    else {
        return "Invalid param type '$param->{'type'}' for check_multi(); " .
          "contact your Bugzilla administrator";
    }
}

sub check_numeric {
    my ($value) = (@_);
    if ($value !~ /^[0-9]+$/) {
        return "must be a numeric value";
    }
    return "";
}

sub check_regexp {
    my ($value) = (@_);
    eval { qr/$value/ };
    return $@;
}

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
1;

__END__

=head1 NAME

Bugzilla::Config - Configuration parameters for Bugzilla

=head1 SYNOPSIS

  # Getting parameters
  use Bugzilla::Config;

  my $fooSetting = Param('foo');

  # Administration functions
  use Bugzilla::Config qw(:admin);

  my @valid_params = GetParamList();
  my @removed_params = UpgradeParams();
  SetParam($param, $value);
  WriteParams();

  # Localconfig variables may also be imported
  use Bugzilla::Config qw(:db);
  print "Connecting to $db_name as $db_user with $db_pass\n";

=head1 DESCRIPTION

This package contains ways to access Bugzilla configuration parameters.

=head1 FUNCTIONS

=head2 Parameters

Parameters can be set, retrieved, and updated.

=over 4

=item C<Param($name)>

Returns the Param with the specified name. Either a string, or, in the case
of multiple-choice parameters, an array reference.

=item C<GetParamList()>

Returns the list of known parameter types, from defparams.pl. Users should not
rely on this method; it is intended for editparams/doeditparams only

The format for the list is specified in defparams.pl

=item C<SetParam($name, $value)>

Sets the param named $name to $value. Values are checked using the checker
function for the given param if one exists.

=item C<UpdateParams()>

Updates the parameters, by transitioning old params to new formats, setting
defaults for new params, and removing obsolete ones.

Any removed params are returned in a list, with elements [$item, $oldvalue]
where $item is the entry in the param list.

=item C<WriteParams()>

Writes the parameters to disk.

425 426
=back

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
=head2 Parameter checking functions

All parameter checking functions are called with two parameters:

=over 4

=item *

The new value for the parameter

=item *

A reference to the entry in the param list for this parameter

=back

Functions should return error text, or the empty string if there was no error.

=over 4

=item C<check_multi>

Checks that a multi-valued parameter (ie type C<s> or type C<m>) satisfies
its contraints.

=item C<check_numeric>

Checks that the value is a valid number

=item C<check_regexp>

Checks that the value is a valid regexp

=back
461