Setting.pm 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# -*- 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.
#
# Contributor(s): Shane H. W. Travis <travis@sedsystems.ca>
16
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
17
#                 Marc Schumann <wurblzap@gmail.com>
18 19 20 21 22 23 24 25
#


package Bugzilla::User::Setting;

use strict;
use base qw(Exporter);

26

27 28 29 30 31
# Module stuff
@Bugzilla::User::Setting::EXPORT = qw(get_all_settings get_defaults
     add_setting);

use Bugzilla::Error;
32
use Bugzilla::Util qw(trick_taint get_text);
33 34 35 36 37 38 39 40 41 42 43

###############################
###  Module Initialization  ###
###############################

sub new {
    my $invocant = shift;
    my $setting_name = shift;
    my $user_id = shift;

    my $class = ref($invocant) || $invocant;
44
    my $subclass = '';
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

    # Create a ref to an empty hash and bless it
    my $self = {};

    my $dbh = Bugzilla->dbh;

    # Confirm that the $setting_name is properly formed;
    # if not, throw a code error. 
    # 
    # NOTE: due to the way that setting names are used in templates,
    # they must conform to to the limitations set for HTML NAMEs and IDs.
    #
    if ( !($setting_name =~ /^[a-zA-Z][-.:\w]*$/) ) {
      ThrowCodeError("setting_name_invalid", { name => $setting_name });
    }

    # If there were only two parameters passed in, then we need
    # to retrieve the information for this setting ourselves.
    if (scalar @_ == 0) {

65 66
        my ($default, $is_enabled, $value);
        ($default, $is_enabled, $value, $subclass) = 
67
          $dbh->selectrow_array(
68
             q{SELECT default_value, is_enabled, setting_value, subclass
69 70 71 72
                 FROM setting
            LEFT JOIN profile_setting
                   ON setting.name = profile_setting.setting_name
                WHERE name = ?
73
                  AND profile_setting.user_id = ?},
74 75 76
             undef, 
             $setting_name, $user_id);

77 78
        # if not defined, then grab the default value
        if (! defined $value) {
79
            ($default, $is_enabled, $subclass) =
80
              $dbh->selectrow_array(
81
                 q{SELECT default_value, is_enabled, subclass
82 83 84 85 86 87
                   FROM setting
                   WHERE name = ?},
              undef,
              $setting_name);
        }

88 89 90 91 92 93 94 95 96 97 98 99 100 101
        $self->{'is_enabled'} = $is_enabled;
        $self->{'default_value'} = $default;

        # IF the setting is enabled, AND the user has chosen a setting
        # THEN return that value
        # ELSE return the site default, and note that it is the default.
        if ( ($is_enabled) && (defined $value) ) {
            $self->{'value'} = $value;
        } else {
            $self->{'value'} = $default;
            $self->{'isdefault'} = 1;
        }
    }
    else {
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        ($subclass) = $dbh->selectrow_array(
            q{SELECT subclass FROM setting WHERE name = ?},
            undef,
            $setting_name);
        # If the values were passed in, simply assign them and return.
        $self->{'is_enabled'}    = shift;
        $self->{'default_value'} = shift;
        $self->{'value'}         = shift;
        $self->{'is_default'}    = shift;
    }
    if ($subclass) {
        eval('require ' . $class . '::' . $subclass);
        $@ && ThrowCodeError('setting_subclass_invalid',
                             {'subclass' => $subclass});
        $class = $class . '::' . $subclass;
117
    }
118
    bless($self, $class);
119 120 121 122 123 124 125 126 127 128 129 130

    $self->{'_setting_name'} = $setting_name;
    $self->{'_user_id'}      = $user_id;

    return $self;
}

###############################
###  Subroutine Definitions ###
###############################

sub add_setting {
131
    my ($name, $values, $default_value, $subclass) = @_;
132 133 134 135
    my $dbh = Bugzilla->dbh;

    return if _setting_exists($name);

136
    ($name && $default_value)
137 138
      ||  ThrowCodeError("setting_info_invalid");

139
    print get_text('install_setting_new', { name => $name }) . "\n";
140 141 142
    $dbh->do(q{INSERT INTO setting (name, default_value, is_enabled, subclass)
                    VALUES (?, ?, 1, ?)},
             undef, ($name, $default_value, $subclass));
143 144 145 146

    my $sth = $dbh->prepare(q{INSERT INTO setting_value (name, value, sortindex)
                                    VALUES (?, ?, ?)});

147 148 149 150
    my $sortindex = 5;
    foreach my $key (@$values){
        $sth->execute($name, $key, $sortindex);
        $sortindex += 5;
151 152 153 154 155
    }
}

sub get_all_settings {
    my ($user_id) = @_;
156
    my $settings = get_defaults($user_id); # first get the defaults
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    my $dbh = Bugzilla->dbh;

    my $sth = $dbh->prepare(
           q{SELECT name, default_value, is_enabled, setting_value
               FROM setting
          LEFT JOIN profile_setting
                 ON setting.name = profile_setting.setting_name
              WHERE profile_setting.user_id = ?
           ORDER BY name});

    $sth->execute($user_id);
    while (my ($name, $default_value, $is_enabled, $value) 
               = $sth->fetchrow_array()) {

        my $is_default;

        if ( ($is_enabled) && (defined $value) ) {
            $is_default = 0;
        } else {
            $value = $default_value;
            $is_default = 1;
        }

        $settings->{$name} = new Bugzilla::User::Setting(
           $name, $user_id, $is_enabled, 
           $default_value, $value, $is_default);
    }

    return $settings;
}

sub get_defaults {
189
    my ($user_id) = @_;
190
    my $dbh = Bugzilla->dbh;
191
    my $default_settings = {};
192

193 194
    $user_id ||= 0;

195 196 197 198 199 200 201
    my $sth = $dbh->prepare(q{SELECT name, default_value, is_enabled
                                FROM setting
                            ORDER BY name});
    $sth->execute();
    while (my ($name, $default_value, $is_enabled) = $sth->fetchrow_array()) {

        $default_settings->{$name} = new Bugzilla::User::Setting(
202
            $name, $user_id, $is_enabled, $default_value, $default_value, 1);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    }

    return $default_settings;
}

sub set_default {
    my ($setting_name, $default_value, $is_enabled) = @_;
    my $dbh = Bugzilla->dbh;

    my $sth = $dbh->prepare(q{UPDATE setting
                                 SET default_value = ?, is_enabled = ?
                               WHERE name = ?});
    $sth->execute($default_value, $is_enabled, $setting_name);
}

sub _setting_exists {
    my ($setting_name) = @_;
    my $dbh = Bugzilla->dbh;
    my $sth = $dbh->prepare("SELECT name FROM setting WHERE name = ?");
    $sth->execute($setting_name);
    return ($sth->rows) ? 1 : 0;
}


sub legal_values {
    my ($self) = @_;

    return $self->{'legal_values'} if defined $self->{'legal_values'};

    my $dbh = Bugzilla->dbh;
    $self->{'legal_values'} = $dbh->selectcol_arrayref(
              q{SELECT value
                  FROM setting_value
                 WHERE name = ?
              ORDER BY sortindex},
        undef, $self->{'_setting_name'});

    return $self->{'legal_values'};
}

243 244 245 246 247 248 249 250 251 252 253 254 255
sub validate_value {
    my $self = shift;

    if (grep(/^$_[0]$/, @{$self->legal_values()})) {
        trick_taint($_[0]);
    }
    else {
        ThrowCodeError('setting_value_invalid',
                       {'name'  => $self->{'_setting_name'},
                        'value' => $_[0]});
    }
}

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
sub reset_to_default {
    my ($self) = @_;

    my $dbh = Bugzilla->dbh;
    my $sth = $dbh->do(q{ DELETE
                            FROM profile_setting
                           WHERE setting_name = ?
                             AND user_id = ?},
                       undef, $self->{'_setting_name'}, $self->{'_user_id'});
      $self->{'value'}       = $self->{'default_value'};
      $self->{'is_default'}  = 1;
}

sub set {
    my ($self, $value) = @_;
    my $dbh = Bugzilla->dbh;
    my $query;

    if ($self->{'is_default'}) {
        $query = q{INSERT INTO profile_setting
                   (setting_value, setting_name, user_id)
                   VALUES (?,?,?)};
    } else {
        $query = q{UPDATE profile_setting
                      SET setting_value = ?
                    WHERE setting_name = ?
                      AND user_id = ?};
    }
    $dbh->do($query, undef, $value, $self->{'_setting_name'}, $self->{'_user_id'});

    $self->{'value'}       = $value;
    $self->{'is_default'}  = 0;
}



1;

__END__

=head1 NAME
297

298 299 300
Bugzilla::User::Setting - Object for a user preference setting

=head1 SYNOPSIS
301

302 303 304 305 306 307
Setting.pm creates a setting object, which is a hash containing the user
preference information for a single preference for a single user. These 
are usually accessed through the "settings" object of a user, and not 
directly.

=head1 DESCRIPTION
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
use Bugzilla::User::Setting;
my $settings;

$settings->{$setting_name} = new Bugzilla::User::Setting(
   $setting_name, $user_id);

OR

$settings->{$setting_name} = new Bugzilla::User::Setting(
   $setting_name, $user_id, $is_enabled,
   $default_value, $value, $is_default);

=head1 CLASS FUNCTIONS

=over 4

325
=item C<add_setting($name, \@values, $default_value)>
326 327 328

Description: Checks for the existence of a setting, and adds it 
             to the database if it does not yet exist.
329

330
Params:      C<$name> - string - the name of the new setting
331 332
             C<$values> - arrayref - contains the new choices
               for the new Setting.
333
             C<$default_value> - string - the site default
334

335
Returns:     a pointer to a hash of settings
336 337


338 339 340 341 342 343 344 345
=item C<get_all_settings($user_id)>

Description: Provides the user's choices for each setting in the 
             system; if the user has made no choice, uses the site
             default instead.
Params:      C<$user_id> - integer - the user id.
Returns:     a pointer to a hash of settings

346
=item C<get_defaults($user_id)>
347 348 349

Description: When a user is not logged in, they must use the site
             defaults for every settings; this subroutine provides them.
350 351 352 353
Params:      C<$user_id> (optional) - integer - the user id.  Note that
             this optional parameter is mainly for internal use only.
Returns:     A pointer to a hash of settings.  If $user_id was passed, set
             the user_id value for each setting.
354 355 356 357 358 359 360 361 362 363 364 365

=item C<set_default($setting_name, $default_value, $is_enabled)>

Description: Sets the global default for a given setting. Also sets
             whether users are allowed to choose their own value for
             this setting, or if they must use the global default.
Params:      C<$setting_name> - string - the name of the setting
             C<$default_value> - string - the new default value for this setting
             C<$is_enabled> - boolean - if false, all users must use the global default
Returns:     nothing

=begin private
366

367 368 369 370 371 372
=item C<_setting_exists>

Description: Determines if a given setting exists in the database.
Params:      C<$setting_name> - string - the setting name
Returns:     boolean - true if the setting already exists in the DB.

373 374
=back

375
=end private
376

377 378 379 380 381 382 383 384 385 386
=head1 METHODS

=over 4

=item C<legal_values($setting_name)>

Description: Returns all legal values for this setting
Params:      none
Returns:     A reference to an array containing all legal values

387 388 389 390 391 392 393 394 395
=item C<validate_value>

Description: Determines whether a value is valid for the setting
             by checking against the list of legal values.
             Untaints the parameter if the value is indeed valid,
             and throws a setting_value_invalid code error if not.
Params:      An lvalue containing a candidate for a setting value
Returns:     nothing

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
=item C<reset_to_default>

Description: If a user chooses to use the global default for a given 
             setting, their saved entry is removed from the database via 
             this subroutine.
Params:      none
Returns:     nothing

=item C<set($value)>

Description: If a user chooses to use their own value rather than the 
             global value for a given setting, OR changes their value for
             a given setting, this subroutine is called to insert or 
             update the database as appropriate.
Params:      C<$value> - string - the new value for this setting for this user.
Returns:     nothing

413
=back