userprefs.cgi 20 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# -*- 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): Terry Weissman <terry@mozilla.org>
17
#                 Dan Mosedale <dmose@mozilla.org>
18
#                 Alan Raetz <al_raetz@yahoo.com>
19
#                 David Miller <justdave@syndicomm.com>
20
#                 Christopher Aillon <christopher@aillon.com>
21
#                 Gervase Markham <gerv@gerv.net>
22
#                 Vlad Dascalu <jocuri@softhome.net>
23
#                 Shane H. W. Travis <travis@sedsystems.ca>
24 25 26

use strict;

27
use lib qw(. lib);
28

29
use Bugzilla;
30
use Bugzilla::Constants;
31
use Bugzilla::Search;
32
use Bugzilla::Util;
33
use Bugzilla::Error;
34
use Bugzilla::User;
35
use Bugzilla::Token;
36

37
my $template = Bugzilla->template;
38
local our $vars = {};
39

40 41 42
###############################################################################
# Each panel has two functions - panel Foo has a DoFoo, to get the data 
# necessary for displaying the panel, and a SaveFoo, to save the panel's 
43
# contents from the form data (if appropriate). 
44 45 46
# SaveFoo may be called before DoFoo.    
###############################################################################
sub DoAccount {
47
    my $dbh = Bugzilla->dbh;
48 49
    my $user = Bugzilla->user;

50
    ($vars->{'realname'}) = $dbh->selectrow_array(
51
        "SELECT realname FROM profiles WHERE userid = ?", undef, $user->id);
52

53
    if(Bugzilla->params->{'allowemailchange'} 
54
       && Bugzilla->user->authorizer->can_change_email) {
55 56 57
       # First delete old tokens.
       Bugzilla::Token::CleanTokenTable();

58 59
        my @token = $dbh->selectrow_array(
            "SELECT tokentype, issuedate + " .
60
                    $dbh->sql_interval(MAX_TOKEN_AGE, 'DAY') . ", eventdata
61 62 63
               FROM tokens
              WHERE userid = ?
                AND tokentype LIKE 'email%'
64
           ORDER BY tokentype ASC " . $dbh->sql_limit(1), undef, $user->id);
65 66
        if (scalar(@token) > 0) {
            my ($tokentype, $change_date, $eventdata) = @token;
67 68 69 70 71 72 73 74
            $vars->{'login_change_date'} = $change_date;

            if($tokentype eq 'emailnew') {
                my ($oldemail,$newemail) = split(/:/,$eventdata);
                $vars->{'new_login_name'} = $newemail;
            }
        }
    }
75 76 77
}

sub SaveAccount {
78
    my $cgi = Bugzilla->cgi;
79
    my $dbh = Bugzilla->dbh;
80
    my $user = Bugzilla->user;
81

82 83 84
    my $pwd1 = $cgi->param('new_password1');
    my $pwd2 = $cgi->param('new_password2');

85 86
    if ($user->authorizer->can_change_password
        && ($cgi->param('Bugzilla_password') ne "" || $pwd1 ne "" || $pwd2 ne ""))
87
    {
88 89
        my ($oldcryptedpwd) = $dbh->selectrow_array(
                        q{SELECT cryptpassword FROM profiles WHERE userid = ?},
90
                        undef, $user->id);
91 92
        $oldcryptedpwd || ThrowCodeError("unable_to_retrieve_password");

93
        if (crypt(scalar($cgi->param('Bugzilla_password')), $oldcryptedpwd) ne 
94 95
                  $oldcryptedpwd) 
        {
96
            ThrowUserError("old_password_incorrect");
97
        }
98 99 100

        if ($pwd1 ne "" || $pwd2 ne "")
        {
101 102
            $cgi->param('new_password1')
              || ThrowUserError("new_password_missing");
103
            validate_password($pwd1, $pwd2);
104 105 106 107 108 109 110 111 112 113 114

            if ($cgi->param('Bugzilla_password') ne $pwd1) {
                my $cryptedpassword = bz_crypt($pwd1);
                $dbh->do(q{UPDATE profiles
                              SET cryptpassword = ?
                            WHERE userid = ?},
                         undef, ($cryptedpassword, $user->id));

                # Invalidate all logins except for the current one
                Bugzilla->logout(LOGOUT_KEEP_CURRENT);
            }
115
        }
116 117
    }

118 119 120 121
    if ($user->authorizer->can_change_email
        && Bugzilla->params->{"allowemailchange"}
        && $cgi->param('new_login_name'))
    {
122 123
        my $old_login_name = $cgi->param('Bugzilla_login');
        my $new_login_name = trim($cgi->param('new_login_name'));
124 125

        if($old_login_name ne $new_login_name) {
126
            $cgi->param('Bugzilla_password') 
127
              || ThrowUserError("old_password_required");
128

129
            use Bugzilla::Token;
130
            # Block multiple email changes for the same user.
131
            if (Bugzilla::Token::HasEmailChangeToken($user->id)) {
132
                ThrowUserError("email_change_in_progress");
133 134 135
            }

            # Before changing an email address, confirm one does not exist.
136 137
            validate_email_syntax($new_login_name)
              || ThrowUserError('illegal_email_address', {addr => $new_login_name});
138
            is_available_username($new_login_name)
139
              || ThrowUserError("account_exists", {email => $new_login_name});
140

141
            Bugzilla::Token::IssueEmailChangeToken($user, $old_login_name,
142
                                                   $new_login_name);
143

144
            $vars->{'email_changes_saved'} = 1;
145 146
        }
    }
147

148 149 150
    my $realname = trim($cgi->param('realname'));
    trick_taint($realname); # Only used in a placeholder
    $dbh->do("UPDATE profiles SET realname = ? WHERE userid = ?",
151
             undef, ($realname, $user->id));
152 153 154
}


155
sub DoSettings {
156 157 158
    my $user = Bugzilla->user;

    my $settings = $user->settings;
159
    $vars->{'settings'} = $settings;
160

161
    my @setting_list = keys %$settings;
162
    $vars->{'setting_names'} = \@setting_list;
163 164 165 166 167 168 169 170 171 172

    $vars->{'has_settings_enabled'} = 0;
    # Is there at least one user setting enabled?
    foreach my $setting_name (@setting_list) {
        if ($settings->{"$setting_name"}->{'is_enabled'}) {
            $vars->{'has_settings_enabled'} = 1;
            last;
        }
    }
    $vars->{'dont_show_button'} = !$vars->{'has_settings_enabled'};
173 174 175 176
}

sub SaveSettings {
    my $cgi = Bugzilla->cgi;
177
    my $user = Bugzilla->user;
178

179 180
    my $settings = $user->settings;
    my @setting_list = keys %$settings;
181 182 183 184

    foreach my $name (@setting_list) {
        next if ! ($settings->{$name}->{'is_enabled'});
        my $value = $cgi->param($name);
185
        my $setting = new Bugzilla::User::Setting($name);
186 187 188

        if ($value eq "${name}-isdefault" ) {
            if (! $settings->{$name}->{'is_default'}) {
189
                $settings->{$name}->reset_to_default;
190 191 192
            }
        }
        else {
193 194
            $setting->validate_value($value);
            $settings->{$name}->set($value);
195 196
        }
    }
197
    $vars->{'settings'} = $user->settings(1);
198 199
}

200
sub DoEmail {
201
    my $dbh = Bugzilla->dbh;
202
    my $user = Bugzilla->user;
203 204 205 206
    
    ###########################################################################
    # User watching
    ###########################################################################
207
    if (Bugzilla->params->{"supportwatchers"}) {
208
        my $watched_ref = $dbh->selectcol_arrayref(
209 210
            "SELECT profiles.login_name FROM watch INNER JOIN profiles" .
            " ON watch.watched = profiles.userid" .
211 212
            " WHERE watcher = ?" .
            " ORDER BY profiles.login_name",
213
            undef, $user->id);
214
        $vars->{'watchedusers'} = $watched_ref;
215 216 217

        my $watcher_ids = $dbh->selectcol_arrayref(
            "SELECT watcher FROM watch WHERE watched = ?",
218
            undef, $user->id);
219 220 221 222 223 224 225 226 227

        my @watchers;
        foreach my $watcher_id (@$watcher_ids) {
            my $watcher = new Bugzilla::User($watcher_id);
            push (@watchers, Bugzilla::User::identity($watcher));
        }

        @watchers = sort { lc($a) cmp lc($b) } @watchers;
        $vars->{'watchers'} = \@watchers;
228
    }
229

230 231 232
    ###########################################################################
    # Role-based preferences
    ###########################################################################
233 234 235 236
    my $sth = $dbh->prepare("SELECT relationship, event " . 
                            "FROM email_setting " . 
                            "WHERE user_id = ?");
    $sth->execute($user->id);
237 238 239 240 241

    my %mail;
    while (my ($relationship, $event) = $sth->fetchrow_array()) {
        $mail{$relationship}{$event} = 1;
    }
242

243 244
    $vars->{'mail'} = \%mail;      
}
245

246 247 248
sub SaveEmail {
    my $dbh = Bugzilla->dbh;
    my $cgi = Bugzilla->cgi;
249
    my $user = Bugzilla->user;
250 251 252 253 254

    if (Bugzilla->params->{"supportwatchers"}) {
        Bugzilla::User::match_field($cgi, { 'new_watchedusers' => {'type' => 'multi'} });
    }

255 256 257
    ###########################################################################
    # Role-based preferences
    ###########################################################################
258
    $dbh->bz_start_transaction();
259 260

    # Delete all the user's current preferences
261
    $dbh->do("DELETE FROM email_setting WHERE user_id = ?", undef, $user->id);
262 263 264 265 266 267 268 269

    # Repopulate the table - first, with normal events in the 
    # relationship/event matrix.
    # Note: the database holds only "off" email preferences, as can be implied 
    # from the name of the table - profiles_nomail.
    foreach my $rel (RELATIONSHIPS) {
        # Positive events: a ticked box means "send me mail."
        foreach my $event (POS_EVENTS) {
270 271 272
            if (defined($cgi->param("email-$rel-$event"))
                && $cgi->param("email-$rel-$event") == 1)
            {
273 274
                $dbh->do("INSERT INTO email_setting " . 
                         "(user_id, relationship, event) " . 
275 276
                         "VALUES (?, ?, ?)",
                         undef, ($user->id, $rel, $event));
277
            }
278 279 280 281 282 283 284 285 286
        }
        
        # Negative events: a ticked box means "don't send me mail."
        foreach my $event (NEG_EVENTS) {
            if (!defined($cgi->param("neg-email-$rel-$event")) ||
                $cgi->param("neg-email-$rel-$event") != 1) 
            {
                $dbh->do("INSERT INTO email_setting " . 
                         "(user_id, relationship, event) " . 
287 288
                         "VALUES (?, ?, ?)",
                         undef, ($user->id, $rel, $event));
289
            }
290
        }
291
    }
292

293 294
    # Global positive events: a ticked box means "send me mail."
    foreach my $event (GLOBAL_EVENTS) {
295 296 297
        if (defined($cgi->param("email-" . REL_ANY . "-$event"))
            && $cgi->param("email-" . REL_ANY . "-$event") == 1)
        {
298 299
            $dbh->do("INSERT INTO email_setting " . 
                     "(user_id, relationship, event) " . 
300 301
                     "VALUES (?, ?, ?)",
                     undef, ($user->id, REL_ANY, $event));
302
        }
303
    }
304

305
    $dbh->bz_commit_transaction();
306 307 308 309

    ###########################################################################
    # User watching
    ###########################################################################
310
    if (Bugzilla->params->{"supportwatchers"} 
311 312
        && (defined $cgi->param('new_watchedusers')
            || defined $cgi->param('remove_watched_users'))) 
313
    {
314
        $dbh->bz_start_transaction();
315

316
        # Use this to protect error messages on duplicate submissions
317 318
        my $old_watch_ids =
            $dbh->selectcol_arrayref("SELECT watched FROM watch"
319
                                   . " WHERE watcher = ?", undef, $user->id);
320 321

        # The new information given to us by the user.
322 323
        my $new_watched_users = join(',', $cgi->param('new_watchedusers')) || '';
        my @new_watch_names = split(/[,\s]+/, $new_watched_users);
324
        my %new_watch_ids;
325

326
        foreach my $username (@new_watch_names) {
327
            my $watched_userid = login_to_id(trim($username), THROW_ERROR);
328
            $new_watch_ids{$watched_userid} = 1;
329 330 331 332 333
        }

        # Add people who were added.
        my $insert_sth = $dbh->prepare('INSERT INTO watch (watched, watcher)'
                                     . ' VALUES (?, ?)');
334 335
        foreach my $add_me (keys(%new_watch_ids)) {
            next if grep($_ == $add_me, @$old_watch_ids);
336
            $insert_sth->execute($add_me, $user->id);
337
        }
338

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        if (defined $cgi->param('remove_watched_users')) {
            my @removed = $cgi->param('watched_by_you');
            # Remove people who were removed.
            my $delete_sth = $dbh->prepare('DELETE FROM watch WHERE watched = ?'
                                         . ' AND watcher = ?');
            
            my %remove_watch_ids;
            foreach my $username (@removed) {
                my $watched_userid = login_to_id(trim($username), THROW_ERROR);
                $remove_watch_ids{$watched_userid} = 1;
            }
            foreach my $remove_me (keys(%remove_watch_ids)) {
                $delete_sth->execute($remove_me, $user->id);
            }
        }

355
        $dbh->bz_commit_transaction();
356
    }
357 358 359
}


360
sub DoPermissions {
361
    my $dbh = Bugzilla->dbh;
362
    my $user = Bugzilla->user;
363 364
    my (@has_bits, @set_bits);
    
365 366
    my $groups = $dbh->selectall_arrayref(
               "SELECT DISTINCT name, description FROM groups WHERE id IN (" . 
367
               $user->groups_as_string . ") ORDER BY name");
368 369
    foreach my $group (@$groups) {
        my ($nam, $desc) = @$group;
370
        push(@has_bits, {"desc" => $desc, "name" => $nam});
371
    }
372 373 374
    $groups = $dbh->selectall_arrayref('SELECT DISTINCT id, name, description
                                          FROM groups
                                         ORDER BY name');
375
    foreach my $group (@$groups) {
376 377
        my ($group_id, $nam, $desc) = @$group;
        if ($user->can_bless($group_id)) {
378
            push(@set_bits, {"desc" => $desc, "name" => $nam});
379 380
        }
    }
381 382 383 384 385 386 387

    # If the user has product specific privileges, inform him about that.
    foreach my $privs (PER_PRODUCT_PRIVILEGES) {
        next if $user->in_group($privs);
        $vars->{"local_$privs"} = $user->get_products_by_permission($privs);
    }

388 389
    $vars->{'has_bits'} = \@has_bits;
    $vars->{'set_bits'} = \@set_bits;    
390
}
391

392
# No SavePermissions() because this panel has no changeable fields.
393

394

395
sub DoSavedSearches {
396
    my $dbh = Bugzilla->dbh;
397 398
    my $user = Bugzilla->user;

399
    if ($user->queryshare_groups_as_string) {
400 401
        $vars->{'queryshare_groups'} =
            Bugzilla::Group->new_from_list($user->queryshare_groups);
402
    }
403
    $vars->{'bless_group_ids'} = [map { $_->id } @{$user->bless_groups}];
404 405
}

406
sub SaveSavedSearches {
407 408
    my $cgi = Bugzilla->cgi;
    my $dbh = Bugzilla->dbh;
409 410
    my $user = Bugzilla->user;

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    # We'll need this in a loop, so do the call once.
    my $user_id = $user->id;

    my $sth_insert_nl = $dbh->prepare('INSERT INTO namedqueries_link_in_footer
                                       (namedquery_id, user_id)
                                       VALUES (?, ?)');
    my $sth_delete_nl = $dbh->prepare('DELETE FROM namedqueries_link_in_footer
                                             WHERE namedquery_id = ?
                                               AND user_id = ?');
    my $sth_insert_ngm = $dbh->prepare('INSERT INTO namedquery_group_map
                                        (namedquery_id, group_id)
                                        VALUES (?, ?)');
    my $sth_update_ngm = $dbh->prepare('UPDATE namedquery_group_map
                                           SET group_id = ?
                                         WHERE namedquery_id = ?');
    my $sth_delete_ngm = $dbh->prepare('DELETE FROM namedquery_group_map
                                              WHERE namedquery_id = ?');
428 429 430 431 432

    # Update namedqueries_link_in_footer for this user.
    foreach my $q (@{$user->queries}, @{$user->queries_available}) {
        if (defined $cgi->param("link_in_footer_" . $q->id)) {
            $sth_insert_nl->execute($q->id, $user_id) if !$q->link_in_footer;
433 434
        }
        else {
435
            $sth_delete_nl->execute($q->id, $user_id) if $q->link_in_footer;
436
        }
437
    }
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    # For user's own queries, update namedquery_group_map.
    foreach my $q (@{$user->queries}) {
        my $group_id;

        if ($user->in_group(Bugzilla->params->{'querysharegroup'})) {
            $group_id = $cgi->param("share_" . $q->id) || '';
        }

        if ($group_id) {
            # Don't allow the user to share queries with groups he's not
            # allowed to.
            next unless grep($_ eq $group_id, @{$user->queryshare_groups});

            # $group_id is now definitely a valid ID of a group the
            # user can share queries with, so we can trick_taint.
            detaint_natural($group_id);
            if ($q->shared_with_group) {
                $sth_update_ngm->execute($group_id, $q->id);
457 458
            }
            else {
459 460
                $sth_insert_ngm->execute($q->id, $group_id);
            }
461

462
            # If we're sharing our query with a group we can bless, we 
463 464 465
            # have the ability to add link to our search to the footer of
            # direct group members automatically.
            if ($user->can_bless($group_id) && $cgi->param('force_' . $q->id)) {
466 467 468 469 470 471 472
                my $group = new Bugzilla::Group($group_id);
                my $members = $group->members_non_inherited;
                foreach my $member (@$members) {
                    next if $member->id == $user->id;
                    $sth_insert_nl->execute($q->id, $member->id)
                        if !$q->link_in_footer($member);
                }
473 474
            }
        }
475 476 477 478 479 480 481 482 483 484 485
        else {
            # They have unshared that query.
            if ($q->shared_with_group) {
                $sth_delete_ngm->execute($q->id);
            }

            # Don't remove namedqueries_link_in_footer entries for users
            # subscribing to the shared query. The idea is that they will
            # probably want to be subscribers again should the sharing
            # user choose to share the query again.
        }
486 487
    }

488
    $user->flush_queries_cache;
489
    
490
    # Update profiles.mybugslink.
491
    my $showmybugslink = defined($cgi->param("showmybugslink")) ? 1 : 0;
492 493 494
    $dbh->do("UPDATE profiles SET mybugslink = ? WHERE userid = ?",
             undef, ($showmybugslink, $user->id));    
    $user->{'showmybugslink'} = $showmybugslink;
495
}
496 497


498 499 500
###############################################################################
# Live code (not subroutine definitions) starts here
###############################################################################
501

502 503 504
my $cgi = Bugzilla->cgi;

# This script needs direct access to the username and password CGI variables,
505
# so we save them before their removal in Bugzilla->login, and delete them 
506
# before login in case we might be in a sudo session.
507 508
my $bugzilla_login    = $cgi->param('Bugzilla_login');
my $bugzilla_password = $cgi->param('Bugzilla_password');
509
$cgi->delete('Bugzilla_login', 'Bugzilla_password') if ($cgi->cookie('sudo'));
510

511
Bugzilla->login(LOGIN_REQUIRED);
512 513
$cgi->param('Bugzilla_login', $bugzilla_login);
$cgi->param('Bugzilla_password', $bugzilla_password);
514

515
$vars->{'changes_saved'} = $cgi->param('dosave');
516

517
my $current_tab_name = $cgi->param('tab') || "settings";
518

519 520 521
# The SWITCH below makes sure that this is valid
trick_taint($current_tab_name);

522
$vars->{'current_tab_name'} = $current_tab_name;
523

524 525 526
# Do any saving, and then display the current tab.
SWITCH: for ($current_tab_name) {
    /^account$/ && do {
527
        SaveAccount() if $cgi->param('dosave');
528 529 530
        DoAccount();
        last SWITCH;
    };
531 532 533 534 535
    /^settings$/ && do {
        SaveSettings() if $cgi->param('dosave');
        DoSettings();
        last SWITCH;
    };
536
    /^email$/ && do {
537
        SaveEmail() if $cgi->param('dosave');
538 539 540 541 542 543 544
        DoEmail();
        last SWITCH;
    };
    /^permissions$/ && do {
        DoPermissions();
        last SWITCH;
    };
545
    /^saved-searches$/ && do {
546
        SaveSavedSearches() if $cgi->param('dosave');
547 548 549
        DoSavedSearches();
        last SWITCH;
    };
550 551
    ThrowUserError("unknown_tab",
                   { current_tab_name => $current_tab_name });
552 553
}

554
# Generate and return the UI (HTML page) from the appropriate template.
555
print $cgi->header();
556 557
$template->process("account/prefs/prefs.html.tmpl", $vars)
  || ThrowTemplateError($template->error());