Config.pm 12.9 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
#                 Frédéric Buclin <LpSolit@gmail.com>
30 31 32 33 34 35

package Bugzilla::Config;

use strict;

use base qw(Exporter);
36
use Bugzilla::Constants;
37
use Bugzilla::Hook;
38 39
use Data::Dumper;
use File::Temp;
40

41 42 43 44 45
# 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
%Bugzilla::Config::EXPORT_TAGS =
  (
46
   admin => [qw(update_params SetParam write_params)],
47
  );
48
Exporter::export_ok_tags('admin');
49 50

use vars qw(@param_list);
51

52
# INITIALISATION CODE
53
# Perl throws a warning if we use bz_locations() directly after do.
54
our %params;
55
# Load in the param definitions
56
sub _load_params {
57
    my $panels = param_panels();
58
    my %hook_panels;
59 60 61
    foreach my $panel (keys %$panels) {
        my $module = $panels->{$panel};
        eval("require $module") || die $@;
62 63
        my @new_param_list = $module->get_param_list();
        $hook_panels{lc($panel)} = { params => \@new_param_list };
64 65 66 67
        foreach my $item (@new_param_list) {
            $params{$item->{'name'}} = $item;
        }
        push(@param_list, @new_param_list);
68
    }
69 70 71 72
    # This hook is also called in editparams.cgi. This call here is required
    # to make SetParam work.
    Bugzilla::Hook::process('config-modify_panels', 
                            { panels => \%hook_panels });
73 74 75 76 77
}
# END INIT CODE

# Subroutines go here

78
sub param_panels {
79
    my $param_panels = {};
80 81 82 83
    my $libpath = bz_locations()->{'libpath'};
    foreach my $item ((glob "$libpath/Bugzilla/Config/*.pm")) {
        $item =~ m#/([^/]+)\.pm$#;
        my $module = $1;
84
        $param_panels->{$module} = "Bugzilla::Config::$module" unless $module eq 'Common';
85
    }
86
    # Now check for any hooked params
87 88
    Bugzilla::Hook::process('config-add_panels', 
                            { panel_modules => $param_panels });
89
    return $param_panels;
90 91
}

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

95
    _load_params unless %params;
96 97 98 99 100
    die "Unknown param $name" unless (exists $params{$name});

    my $entry = $params{$name};

    # sanity check the value
101 102

    # XXX - This runs the checks. Which would be good, except that
103 104
    # check_shadowdb creates the database as a side effect, and so the
    # checker fails the second time around...
105
    if ($name ne 'shadowdb' && exists $entry->{'checker'}) {
106 107 108 109
        my $err = $entry->{'checker'}->($value, $entry);
        die "Param $name is not valid: $err" unless $err eq '';
    }

110
    Bugzilla->params->{$name} = $value;
111 112
}

113 114
sub update_params {
    my ($params) = @_;
115
    my $answer = Bugzilla->installation_answers;
116 117 118 119 120

    my $param = read_param_file();

    # If we didn't return any param values, then this is a new installation.
    my $new_install = !(keys %$param);
121

122
    # --- UPDATE OLD PARAMS ---
123

124
    # Old Bugzilla versions stored the version number in the params file
125
    # We don't want it, so get rid of it
126
    delete $param->{'version'};
127

128
    # Change from usebrowserinfo to defaultplatform/defaultopsys combo
129 130 131 132
    if (exists $param->{'usebrowserinfo'}) {
        if (!$param->{'usebrowserinfo'}) {
            if (!exists $param->{'defaultplatform'}) {
                $param->{'defaultplatform'} = 'Other';
133
            }
134 135
            if (!exists $param->{'defaultopsys'}) {
                $param->{'defaultopsys'} = 'Other';
136 137
            }
        }
138
        delete $param->{'usebrowserinfo'};
139 140
    }

141
    # Change from a boolean for quips to multi-state
142 143 144
    if (exists $param->{'usequip'} && !exists $param->{'enablequips'}) {
        $param->{'enablequips'} = $param->{'usequip'} ? 'on' : 'off';
        delete $param->{'usequip'};
145 146
    }

147 148
    # Change from old product groups to controls for group_control_map
    # 2002-10-14 bug 147275 bugreport@peshkin.net
149 150 151
    if (exists $param->{'usebuggroups'} && 
        !exists $param->{'makeproductgroups'}) 
    {
152
        $param->{'makeproductgroups'} = $param->{'usebuggroups'};
153
    }
154 155 156
    if (exists $param->{'usebuggroupsentry'} 
       && !exists $param->{'useentrygroupdefault'}) {
        $param->{'useentrygroupdefault'} = $param->{'usebuggroupsentry'};
157 158
    }

159
    # Modularise auth code
160 161
    if (exists $param->{'useLDAP'} && !exists $param->{'loginmethod'}) {
        $param->{'loginmethod'} = $param->{'useLDAP'} ? "LDAP" : "DB";
162 163
    }

164
    # set verify method to whatever loginmethod was
165 166 167
    if (exists $param->{'loginmethod'} 
        && !exists $param->{'user_verify_class'}) 
    {
168 169
        $param->{'user_verify_class'} = $param->{'loginmethod'};
        delete $param->{'loginmethod'};
170 171
    }

172 173
    # Remove quip-display control from parameters
    # and give it to users via User Settings (Bug 41972)
174 175
    if ( exists $param->{'enablequips'} 
         && !exists $param->{'quip_list_entry_control'}) 
176 177
    {
        my $new_value;
178 179 180 181 182 183
        ($param->{'enablequips'} eq 'on')       && do {$new_value = 'open';};
        ($param->{'enablequips'} eq 'approved') && do {$new_value = 'moderated';};
        ($param->{'enablequips'} eq 'frozen')   && do {$new_value = 'closed';};
        ($param->{'enablequips'} eq 'off')      && do {$new_value = 'closed';};
        $param->{'quip_list_entry_control'} = $new_value;
        delete $param->{'enablequips'};
184 185
    }

186 187 188 189 190 191 192 193 194 195 196 197 198
    # Old mail_delivery_method choices contained no uppercase characters
    if (exists $param->{'mail_delivery_method'}
        && $param->{'mail_delivery_method'} !~ /[A-Z]/) {
        my $method = $param->{'mail_delivery_method'};
        my %translation = (
            'sendmail' => 'Sendmail',
            'smtp'     => 'SMTP',
            'qmail'    => 'Qmail',
            'testfile' => 'Test',
            'none'     => 'None');
        $param->{'mail_delivery_method'} = $translation{$method};
    }

199 200
    # --- DEFAULTS FOR NEW PARAMS ---

201
    _load_params unless %params;
202 203
    foreach my $item (@param_list) {
        my $name = $item->{'name'};
204 205 206 207
        unless (exists $param->{$name}) {
            print "New parameter: $name\n" unless $new_install;
            $param->{$name} = $answer->{$name} || $item->{'default'};
        }
208 209
    }

210
    $param->{'utf8'} = 1 if $new_install;
211

212
    # --- REMOVE OLD PARAMS ---
213

214
    my %oldparams;
215
    # Remove any old params, put them in old-params.txt
216
    foreach my $item (keys %$param) {
217
        if (!grep($_ eq $item, map ($_->{'name'}, @param_list))) {
218
            $oldparams{$item} = $param->{$item};
219
            delete $param->{$item};
220 221 222
        }
    }

223
    if (scalar(keys %oldparams)) {
224 225 226 227 228 229 230
        my $op_file = new IO::File('old-params.txt', '>>', 0600)
          || die "old-params.txt: $!";

        print "The following parameters are no longer used in Bugzilla,",
              " and so have been\nmoved from your parameters file into",
              " old-params.txt:\n";

231 232 233 234 235 236 237 238
        local $Data::Dumper::Terse  = 1;
        local $Data::Dumper::Indent = 0;

        my $comma = "";
        foreach my $item (keys %oldparams) {
            print $op_file "\n\n$item:\n" . Data::Dumper->Dump([$oldparams{$item}]) . "\n";
            print "${comma}$item";
            $comma = ", ";
239 240 241 242 243 244
        }
        print "\n";
        $op_file->close;
    }

    if (ON_WINDOWS && !-e SENDMAIL_EXE
245
        && $param->{'mail_delivery_method'} eq 'Sendmail')
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    {
        my $smtp = $answer->{'SMTP_SERVER'};
        if (!$smtp) {
            print "\nBugzilla requires an SMTP server to function on",
                  " Windows.\nPlease enter your SMTP server's hostname: ";
            $smtp = <STDIN>;
            chomp $smtp;
            if ($smtp) {
                $param->{'smtpserver'} = $smtp;
             }
             else {
                print "\nWarning: No SMTP Server provided, defaulting to",
                      " localhost\n";
            }
        }

262
        $param->{'mail_delivery_method'} = 'SMTP';
263 264 265
    }

    write_params($param);
266 267 268 269

    # Return deleted params and values so that checksetup.pl has a chance
    # to convert old params to new data.
    return %oldparams;
270 271
}

272 273 274 275 276 277
sub write_params {
    my ($param_data) = @_;
    $param_data ||= Bugzilla->params;

    my $datadir    = bz_locations()->{'datadir'};
    my $param_file = "$datadir/params";
278

279
    local $Data::Dumper::Sortkeys = 1;
280 281

    my ($fh, $tmpname) = File::Temp::tempfile('params.XXXXX',
282
                                              DIR => $datadir );
283

284
    print $fh (Data::Dumper->Dump([$param_data], ['*param']))
285 286 287 288
      || die "Can't write param file: $!";

    close $fh;

289 290 291 292
    rename $tmpname, $param_file
      || die "Can't rename $tmpname to $param_file: $!";

    ChmodDataFile($param_file, 0666);
293

294 295 296
    # And now we have to reset the params cache so that Bugzilla will re-read
    # them.
    delete Bugzilla->request_cache->{params};
297 298
}

299 300
# Some files in the data directory must be world readable if and only if
# we don't have a webserver group. Call this function to do this.
301 302 303 304 305 306 307
# 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;
308
    if ((stat(bz_locations()->{'datadir'}))[2] & 0002) {
309 310 311 312 313 314
        $perm = 0777;
    }
    $perm = $perm & $mask;
    chmod $perm,$file;
}

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
sub read_param_file {
    my %params;
    my $datadir = bz_locations()->{'datadir'};
    if (-e "$datadir/params") {
        # Note that checksetup.pl sets file permissions on '$datadir/params'

        # 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;

        $s->rdo("$datadir/params");
        die "Error reading $datadir/params: $!" if $!;
        die "Error evaluating $datadir/params: $@" if $@;

        # Now read the param back out from the sandbox
        %params = %{$s->varglob('param')};
    }
333 334 335 336 337 338 339 340 341 342 343
    elsif ($ENV{'SERVER_SOFTWARE'}) {
       # We're in a CGI, but the params file doesn't exist. We can't
       # Template Toolkit, or even install_string, since checksetup
       # might not have thrown an error. Bugzilla::CGI->new
       # hasn't even been called yet, so we manually use CGI::Carp here
       # so that the user sees the error.
       require CGI::Carp;
       CGI::Carp->import('fatalsToBrowser');
       die "The $datadir/params file does not exist."
           . ' You probably need to run checksetup.pl.',
    }
344 345 346
    return \%params;
}

347 348 349 350 351 352 353 354 355 356 357 358 359
1;

__END__

=head1 NAME

Bugzilla::Config - Configuration parameters for Bugzilla

=head1 SYNOPSIS

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

360
  update_params();
361
  SetParam($param, $value);
362
  write_params();
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

=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<SetParam($name, $value)>

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

381
=item C<update_params()>
382 383

Updates the parameters, by transitioning old params to new formats, setting
384 385
defaults for new params, and removing obsolete ones. Used by F<checksetup.pl>
in the process of an installation or upgrade.
386

387
Prints out information about what it's doing, if it makes any changes.
388

389 390
May prompt the user for input, if certain required parameters are not
specified.
391

392
=item C<write_params($params)>
393

394
Description: Writes the parameters to disk.
395

396 397 398
Params:      C<$params> (optional) - A hashref to write to the disk
               instead of C<Bugzilla->params>. Used only by
               C<update_params>.
399

400
Returns:     nothing
401

402
=item C<read_param_file()>
403

404 405 406
Description: Most callers should never need this. This is used
             by C<Bugzilla->params> to directly read C<$datadir/params>
             and load it into memory. Use C<Bugzilla->params> instead.
407

408
Params:      none
409

410
Returns:     A hashref containing the current params in C<$datadir/params>.
411 412

=back