userprefs.cgi 22 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 28
use lib qw(.);

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

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

39 40 41 42 43 44 45
###############################################################################
# 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 
# contents from the form data (if appropriate.) 
# SaveFoo may be called before DoFoo.    
###############################################################################
sub DoAccount {
46
    my $dbh = Bugzilla->dbh;
47 48
    my $user = Bugzilla->user;

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

52
    if(Bugzilla->params->{'allowemailchange'} 
53
       && Bugzilla->user->authorizer->can_change_email) {
54 55
        my @token = $dbh->selectrow_array(
            "SELECT tokentype, issuedate + " .
56
                    $dbh->sql_interval(MAX_TOKEN_AGE, 'DAY') . ", eventdata
57 58 59
               FROM tokens
              WHERE userid = ?
                AND tokentype LIKE 'email%'
60
           ORDER BY tokentype ASC " . $dbh->sql_limit(1), undef, $user->id);
61 62
        if (scalar(@token) > 0) {
            my ($tokentype, $change_date, $eventdata) = @token;
63 64 65 66 67 68 69 70
            $vars->{'login_change_date'} = $change_date;

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

sub SaveAccount {
74
    my $cgi = Bugzilla->cgi;
75
    my $dbh = Bugzilla->dbh;
76
    my $user = Bugzilla->user;
77

78 79 80 81
    my $pwd1 = $cgi->param('new_password1');
    my $pwd2 = $cgi->param('new_password2');

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

89
        if (crypt(scalar($cgi->param('Bugzilla_password')), $oldcryptedpwd) ne 
90 91
                  $oldcryptedpwd) 
        {
92
            ThrowUserError("old_password_incorrect");
93
        }
94 95 96

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

            if ($cgi->param('Bugzilla_password') ne $pwd1) {
                my $cryptedpassword = bz_crypt($pwd1);
                trick_taint($cryptedpassword); # Only used in a placeholder
                $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);
            }
112
        }
113 114
    }

115
    if(Bugzilla->params->{"allowemailchange"} && $cgi->param('new_login_name')) {
116 117
        my $old_login_name = $cgi->param('Bugzilla_login');
        my $new_login_name = trim($cgi->param('new_login_name'));
118 119

        if($old_login_name ne $new_login_name) {
120
            $cgi->param('Bugzilla_password') 
121
              || ThrowUserError("old_password_required");
122

123
            use Bugzilla::Token;
124
            # Block multiple email changes for the same user.
125
            if (Bugzilla::Token::HasEmailChangeToken($user->id)) {
126
                ThrowUserError("email_change_in_progress");
127 128 129
            }

            # Before changing an email address, confirm one does not exist.
130 131
            validate_email_syntax($new_login_name)
              || ThrowUserError('illegal_email_address', {addr => $new_login_name});
132
            trick_taint($new_login_name);
133
            is_available_username($new_login_name)
134
              || ThrowUserError("account_exists", {email => $new_login_name});
135

136 137
            Bugzilla::Token::IssueEmailChangeToken($user->id, $old_login_name,
                                                   $new_login_name);
138

139
            $vars->{'email_changes_saved'} = 1;
140 141
        }
    }
142

143 144 145
    my $realname = trim($cgi->param('realname'));
    trick_taint($realname); # Only used in a placeholder
    $dbh->do("UPDATE profiles SET realname = ? WHERE userid = ?",
146
             undef, ($realname, $user->id));
147 148 149
}


150
sub DoSettings {
151 152 153
    my $user = Bugzilla->user;

    my $settings = $user->settings;
154
    $vars->{'settings'} = $settings;
155

156
    my @setting_list = keys %$settings;
157
    $vars->{'setting_names'} = \@setting_list;
158 159 160 161 162 163 164 165 166 167

    $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'};
168 169 170 171
}

sub SaveSettings {
    my $cgi = Bugzilla->cgi;
172
    my $user = Bugzilla->user;
173

174 175
    my $settings = $user->settings;
    my @setting_list = keys %$settings;
176 177 178 179

    foreach my $name (@setting_list) {
        next if ! ($settings->{$name}->{'is_enabled'});
        my $value = $cgi->param($name);
180
        my $setting = new Bugzilla::User::Setting($name);
181 182 183

        if ($value eq "${name}-isdefault" ) {
            if (! $settings->{$name}->{'is_default'}) {
184
                $settings->{$name}->reset_to_default;
185 186 187
            }
        }
        else {
188 189
            $setting->validate_value($value);
            $settings->{$name}->set($value);
190 191
        }
    }
192
    $vars->{'settings'} = $user->settings(1);
193 194
}

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

        my $watcher_ids = $dbh->selectcol_arrayref(
            "SELECT watcher FROM watch WHERE watched = ?",
212
            undef, $user->id);
213 214 215 216 217 218 219 220 221

        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;
222
    }
223

224 225 226
    ###########################################################################
    # Role-based preferences
    ###########################################################################
227 228 229 230
    my $sth = $dbh->prepare("SELECT relationship, event " . 
                            "FROM email_setting " . 
                            "WHERE user_id = ?");
    $sth->execute($user->id);
231 232 233 234 235

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

237 238
    $vars->{'mail'} = \%mail;      
}
239

240 241 242
sub SaveEmail {
    my $dbh = Bugzilla->dbh;
    my $cgi = Bugzilla->cgi;
243
    my $user = Bugzilla->user;
244
    
245 246 247 248 249 250
    ###########################################################################
    # Role-based preferences
    ###########################################################################
    $dbh->bz_lock_tables("email_setting WRITE");

    # Delete all the user's current preferences
251
    $dbh->do("DELETE FROM email_setting WHERE user_id = ?", undef, $user->id);
252 253 254 255 256 257 258 259

    # 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) {
260 261 262
            if (defined($cgi->param("email-$rel-$event"))
                && $cgi->param("email-$rel-$event") == 1)
            {
263 264
                $dbh->do("INSERT INTO email_setting " . 
                         "(user_id, relationship, event) " . 
265 266
                         "VALUES (?, ?, ?)",
                         undef, ($user->id, $rel, $event));
267
            }
268 269 270 271 272 273 274 275 276
        }
        
        # 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) " . 
277 278
                         "VALUES (?, ?, ?)",
                         undef, ($user->id, $rel, $event));
279
            }
280
        }
281
    }
282

283 284
    # Global positive events: a ticked box means "send me mail."
    foreach my $event (GLOBAL_EVENTS) {
285 286 287
        if (defined($cgi->param("email-" . REL_ANY . "-$event"))
            && $cgi->param("email-" . REL_ANY . "-$event") == 1)
        {
288 289
            $dbh->do("INSERT INTO email_setting " . 
                     "(user_id, relationship, event) " . 
290 291
                     "VALUES (?, ?, ?)",
                     undef, ($user->id, REL_ANY, $event));
292
        }
293
    }
294

295 296 297 298 299
    $dbh->bz_unlock_tables();

    ###########################################################################
    # User watching
    ###########################################################################
300
    if (Bugzilla->params->{"supportwatchers"} 
301 302
        && (defined $cgi->param('new_watchedusers')
            || defined $cgi->param('remove_watched_users'))) 
303
    {
304 305 306 307
        # Just in case.  Note that this much locking is actually overkill:
        # we don't really care if anyone reads the watch table.  So 
        # some small amount of contention could be gotten rid of by
        # using user-defined locks rather than table locking.
308
        $dbh->bz_lock_tables('watch WRITE', 'profiles READ');
309

310
        # Use this to protect error messages on duplicate submissions
311 312
        my $old_watch_ids =
            $dbh->selectcol_arrayref("SELECT watched FROM watch"
313
                                   . " WHERE watcher = ?", undef, $user->id);
314 315 316

        # The new information given to us by the user.
        my @new_watch_names = split(/[,\s]+/, $cgi->param('new_watchedusers'));
317
        my %new_watch_ids;
318

319
        foreach my $username (@new_watch_names) {
320
            my $watched_userid = login_to_id(trim($username), THROW_ERROR);
321
            $new_watch_ids{$watched_userid} = 1;
322 323 324 325 326
        }

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

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
        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);
            }
        }

348
        $dbh->bz_unlock_tables();
349
    }
350 351 352
}


353
sub DoPermissions {
354
    my $dbh = Bugzilla->dbh;
355
    my $user = Bugzilla->user;
356 357
    my (@has_bits, @set_bits);
    
358 359
    my $groups = $dbh->selectall_arrayref(
               "SELECT DISTINCT name, description FROM groups WHERE id IN (" . 
360
               $user->groups_as_string . ") ORDER BY name");
361 362
    foreach my $group (@$groups) {
        my ($nam, $desc) = @$group;
363
        push(@has_bits, {"desc" => $desc, "name" => $nam});
364
    }
365 366 367
    $groups = $dbh->selectall_arrayref('SELECT DISTINCT id, name, description
                                          FROM groups
                                         ORDER BY name');
368
    foreach my $group (@$groups) {
369 370
        my ($group_id, $nam, $desc) = @$group;
        if ($user->can_bless($group_id)) {
371
            push(@set_bits, {"desc" => $desc, "name" => $nam});
372 373
        }
    }
374 375 376
    
    $vars->{'has_bits'} = \@has_bits;
    $vars->{'set_bits'} = \@set_bits;    
377
}
378

379
# No SavePermissions() because this panel has no changeable fields.
380

381

382
sub DoSavedSearches {
383 384
    # 2004-12-13 - colin.ogilvie@gmail.com, bug 274397
    # Need to work around the possibly missing query_format=advanced
385
    my $dbh = Bugzilla->dbh;
386 387 388
    my $user = Bugzilla->user;

    my @queries = @{$user->queries};
389 390
    my @newqueries;
    foreach my $q (@queries) {
391 392 393 394 395 396 397 398 399
        if ($q->{'query'} =~ /query_format=([^&]*)/) {
            my $format = $1;
            if (!IsValidQueryType($format)) {
                if ($format eq "") {
                    $q->{'query'} =~ s/query_format=/query_format=advanced/;
                }
                else {
                    $q->{'query'} .= '&query_format=advanced';
                }
400
            }
401 402
        } else {
            $q->{'query'} .= '&query_format=advanced';
403 404 405 406
        }
        push @newqueries, $q;
    }
    $vars->{'queries'} = \@newqueries;
407
    if ($user->queryshare_groups_as_string) {
408 409
        $vars->{'queryshare_groups'} =
            Bugzilla::Group->new_from_list($user->queryshare_groups);
410
    }
411 412
}

413
sub SaveSavedSearches {
414 415
    my $cgi = Bugzilla->cgi;
    my $dbh = Bugzilla->dbh;
416 417
    my $user = Bugzilla->user;

418 419 420
    # We'll need this in a loop, so do the call once.
    my $user_id = $user->id;

421
    my @queries = @{$user->queries};
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    my $sth_check_nl = $dbh->prepare('SELECT COUNT(*)
                                        FROM namedqueries_link_in_footer
                                       WHERE namedquery_id = ?
                                         AND 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_check_ngm = $dbh->prepare('SELECT COUNT(*)
                                         FROM namedquery_group_map
                                        WHERE namedquery_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 = ?');
    my $sth_direct_group_members =
        $dbh->prepare('SELECT user_id
                         FROM user_group_map
                        WHERE group_id = ?
                          AND isbless = ' . GROUP_MEMBERSHIP . '
                          AND grant_type = ' . GRANT_DIRECT);
449
    foreach my $q (@queries) {
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        # Update namedqueries_link_in_footer.
        $sth_check_nl->execute($q->{'id'}, $user_id);
        my ($link_in_footer_entries) = $sth_check_nl->fetchrow_array();
        if (defined($cgi->param("link_in_footer_$q->{'id'}"))) {
            if ($link_in_footer_entries == 0) {
                $sth_insert_nl->execute($q->{'id'}, $user_id);
            }
        }
        else {
            if ($link_in_footer_entries > 0) {
                $sth_delete_nl->execute($q->{'id'}, $user_id);
            }
        }

        # For user's own queries, update namedquery_group_map.
        if ($q->{'userid'} == $user_id) {
            my ($group_id, $group_map_entries);
            if ($user->in_group(Bugzilla->params->{'querysharegroup'})) {
                $sth_check_ngm->execute($q->{'id'});
                ($group_map_entries) = $sth_check_ngm->fetchrow_array();
                $group_id = $cgi->param("share_$q->{'id'}") || '';
            }
            if ($group_id) {
                if (grep(/^\Q$group_id\E$/, @{$user->queryshare_groups()})) {
                    # $group_id is now definitely a valid ID of a group the
                    # user can see, so we can trick_taint.
                    trick_taint($group_id);
                    if ($group_map_entries == 0) {
                        $sth_insert_ngm->execute($q->{'id'}, $group_id);
                    }
                    else {
                        $sth_update_ngm->execute($group_id, $q->{'id'});
                    }

                    # If we're sharing our query with a group we can bless,
                    # we're subscribing direct group members to our search
                    # automatically. Otherwise, the group members need to
                    # opt in. This behaviour is deemed most likely to fit
                    # users' needs.
                    if ($user->can_bless($group_id)) {
                        $sth_direct_group_members->execute($group_id);
                        my $user_id;
                        while ($user_id =
                               $sth_direct_group_members->fetchrow_array()) {
                            next if $user_id == $user->id;

                            $sth_check_nl->execute($q->{'id'}, $user_id);
                            my ($already_shown_in_footer) =
                                $sth_check_nl->fetchrow_array();
                            if (! $already_shown_in_footer) {
                                $sth_insert_nl->execute($q->{'id'}, $user_id);
                            }
                        }
                    }
                }
                else {
                    # In the unlikely case somebody removed visibility to the
                    # group in the meantime, don't modify sharing.
                }
            }
            else {
                if ($group_map_entries > 0) {
                    $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.
            }
        }
521 522
    }

523
    $user->flush_queries_cache;
524
    
525
    # Update profiles.mybugslink.
526
    my $showmybugslink = defined($cgi->param("showmybugslink")) ? 1 : 0;
527 528 529
    $dbh->do("UPDATE profiles SET mybugslink = ? WHERE userid = ?",
             undef, ($showmybugslink, $user->id));    
    $user->{'showmybugslink'} = $showmybugslink;
530
}
531 532


533 534 535
###############################################################################
# Live code (not subroutine definitions) starts here
###############################################################################
536

537 538 539
my $cgi = Bugzilla->cgi;

# This script needs direct access to the username and password CGI variables,
540 541
# so we save them before their removal in Bugzilla->login, and delete them 
# prior to login if we might possibly be in an sudo session.
542 543
my $bugzilla_login    = $cgi->param('Bugzilla_login');
my $bugzilla_password = $cgi->param('Bugzilla_password');
544
$cgi->delete('Bugzilla_login', 'Bugzilla_password') if ($cgi->cookie('sudo'));
545

546
Bugzilla->login(LOGIN_REQUIRED);
547 548
$cgi->param('Bugzilla_login', $bugzilla_login);
$cgi->param('Bugzilla_password', $bugzilla_password);
549

550
$vars->{'changes_saved'} = $cgi->param('dosave');
551

552
my $current_tab_name = $cgi->param('tab') || "account";
553

554 555 556
# The SWITCH below makes sure that this is valid
trick_taint($current_tab_name);

557
$vars->{'current_tab_name'} = $current_tab_name;
558

559 560 561
# Do any saving, and then display the current tab.
SWITCH: for ($current_tab_name) {
    /^account$/ && do {
562
        SaveAccount() if $cgi->param('dosave');
563 564 565
        DoAccount();
        last SWITCH;
    };
566 567 568 569 570
    /^settings$/ && do {
        SaveSettings() if $cgi->param('dosave');
        DoSettings();
        last SWITCH;
    };
571
    /^email$/ && do {
572
        SaveEmail() if $cgi->param('dosave');
573 574 575 576 577 578 579
        DoEmail();
        last SWITCH;
    };
    /^permissions$/ && do {
        DoPermissions();
        last SWITCH;
    };
580
    /^saved-searches$/ && do {
581
        SaveSavedSearches() if $cgi->param('dosave');
582 583 584
        DoSavedSearches();
        last SWITCH;
    };
585 586
    ThrowUserError("unknown_tab",
                   { current_tab_name => $current_tab_name });
587 588
}

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