userprefs.cgi 11.6 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 23 24

use strict;

25 26
use lib qw(.);

27 28
use Bugzilla;

29 30
require "CGI.pl";

31 32
use RelationSet;

33
# Use global template variables.
34
use vars qw($template $vars $userid);
35

36 37
# The default email flags leave all email on.
my $defaultflagstring = "ExcludeSelf~on~";
38

39 40
my @roles = ("Owner", "Reporter", "QAcontact", "CClist", "Voter");
my @reasons = ("Removeme", "Comments", "Attachments", "Status", "Resolved", 
41
               "Keywords", "CC", "Other", "Unconfirmed");
42 43 44

foreach my $role (@roles) {
    foreach my $reason (@reasons) {
45 46
        $defaultflagstring .= "email$role$reason~on~";
    }
47 48
}

49 50
# Remove final "~".
chop $defaultflagstring;
51

52 53 54 55 56 57 58
###############################################################################
# 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 {
59
    SendSQL("SELECT realname FROM profiles WHERE userid = $userid");
60
    $vars->{'realname'} = FetchSQLData();
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

    if(Param('allowemailchange')) {
        SendSQL("SELECT tokentype, issuedate + INTERVAL 3 DAY, eventdata 
                    FROM tokens
                    WHERE userid = $userid
                    AND tokentype LIKE 'email%' 
                    ORDER BY tokentype ASC LIMIT 1");
        if(MoreSQLData()) {
            my ($tokentype, $change_date, $eventdata) = &::FetchSQLData();
            $vars->{'login_change_date'} = $change_date;

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

sub SaveAccount {
81 82 83
    my $pwd1 = $::FORM{'new_password1'};
    my $pwd2 = $::FORM{'new_password2'};

84
    if ($::FORM{'Bugzilla_password'} ne "" || 
85
        $pwd1 ne "" || $pwd2 ne "") 
86
    {
87
        my $old = SqlQuote($::FORM{'Bugzilla_password'});
88 89
        SendSQL("SELECT cryptpassword FROM profiles WHERE userid = $userid");
        my $oldcryptedpwd = FetchOneColumn();
90 91
        $oldcryptedpwd || ThrowCodeError("unable_to_retrieve_password");

92 93 94
        if (crypt($::FORM{'Bugzilla_password'}, $oldcryptedpwd) ne 
                  $oldcryptedpwd) 
        {
95
            ThrowUserError("old_password_incorrect");
96
        }
97 98 99

        if ($pwd1 ne "" || $pwd2 ne "")
        {
100
            $::FORM{'new_password1'} || ThrowUserError("new_password_missing");
101
            ValidatePassword($pwd1, $pwd2);
102 103 104 105 106 107 108
        
            my $cryptedpassword = SqlQuote(Crypt($pwd1));
            SendSQL("UPDATE profiles 
                     SET    cryptpassword = $cryptedpassword 
                     WHERE  userid = $userid");
            # Invalidate all logins except for the current one
            InvalidateLogins($userid, $::COOKIE{"Bugzilla_logincookie"});
109
        }
110 111 112 113 114 115 116
    }

    if(Param("allowemailchange") && $::FORM{'new_login_name'}) {
        my $old_login_name = $::FORM{'Bugzilla_login'};
        my $new_login_name = trim($::FORM{'new_login_name'});

        if($old_login_name ne $new_login_name) {
117 118
            $::FORM{'Bugzilla_password'} 
              || ThrowCodeError("old_password_required");
119 120 121 122

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

            # Before changing an email address, confirm one does not exist.
            CheckEmailSyntax($new_login_name);
            trick_taint($new_login_name);
129 130
            ValidateNewUser($new_login_name)
              || ThrowUserError("account_exists", {email => $new_login_name});
131 132 133 134

            Token::IssueEmailChangeToken($userid,$old_login_name,
                                                 $new_login_name);

135
            $vars->{'email_changes_saved'} = 1;
136 137
        }
    }
138

139
    SendSQL("UPDATE profiles SET " .
140
            "realname = " . SqlQuote(trim($::FORM{'realname'})) .
141 142 143 144
            " WHERE userid = $userid");
}


145
sub DoEmail {
146 147 148
    if (Param("supportwatchers")) {
        my $watcheduserSet = new RelationSet;
        $watcheduserSet->mergeFromDB("SELECT watched FROM watch WHERE" .
149
                                    " watcher=$userid");
150
        $vars->{'watchedusers'} = $watcheduserSet->toString();
151
    }
152

153
    SendSQL("SELECT emailflags FROM profiles WHERE userid = $userid");
154

155
    my ($flagstring) = FetchSQLData();
156

157 158 159
    # If the emailflags haven't been set before, that means that this user 
    # hasn't been to the email pane of userprefs.cgi since the change to 
    # use emailflags. Create a default flagset for them, based on
160
    # static defaults. 
161 162 163 164
    if (!$flagstring) {
        $flagstring = $defaultflagstring;
        SendSQL("UPDATE profiles SET emailflags = " .
                SqlQuote($flagstring) . " WHERE userid = $userid");
165
    }
166

167 168 169 170
    # The 255 param is here, because without a third param, split will
    # trim any trailing null fields, which causes Perl to eject lots of
    # warnings. Any suitably large number would do.
    my %emailflags = split(/~/, $flagstring, 255);
171

172 173 174 175
    # Determine the value of the "excludeself" global email preference.
    # Note that the value of "excludeself" is assumed to be off if the
    # preference does not exist in the user's list, unlike other 
    # preferences whose value is assumed to be on if they do not exist.
176 177
    if (exists($emailflags{'ExcludeSelf'}) 
        && $emailflags{'ExcludeSelf'} eq 'on')
178 179 180 181 182 183 184
    {
        $vars->{'excludeself'} = 1;
    }
    else {
        $vars->{'excludeself'} = 0;
    }
    
185
    foreach my $flag (qw(FlagRequestee FlagRequester)) {
186 187 188 189
        $vars->{$flag} = 
          !exists($emailflags{$flag}) || $emailflags{$flag} eq 'on';
    }
    
190
    # Parse the info into a hash of hashes; the first hash keyed by role,
191 192 193 194 195 196 197 198 199 200 201 202
    # the second by reason, and the value being 1 or 0 for (on or off).
    # Preferences not existing in the user's list are assumed to be on.
    foreach my $role (@roles) {
        $vars->{$role} = {};
        foreach my $reason (@reasons) {
            my $key = "email$role$reason";
            if (!exists($emailflags{$key}) || $emailflags{$key} eq 'on') {
                $vars->{$role}{$reason} = 1;
            }
            else {
                $vars->{$role}{$reason} = 0;
            }
203
        }
204
    }
205 206
}

207 208 209 210 211
# Note: we no longer store "off" values in the database.
sub SaveEmail {
    my $updateString = "";
    
    if (defined $::FORM{'ExcludeSelf'}) {
212
        $updateString .= 'ExcludeSelf~on';
213
    } else {
214 215
        $updateString .= 'ExcludeSelf~';
    }
216
    
217
    foreach my $flag (qw(FlagRequestee FlagRequester)) {
218 219 220
        $updateString .= "~$flag~" . (defined($::FORM{$flag}) ? "on" : "");
    }
    
221 222 223 224 225 226 227 228 229
    foreach my $role (@roles) {
        foreach my $reason (@reasons) {
            # Add this preference to the list without giving it a value,
            # which is the equivalent of setting the value to "off."
            $updateString .= "~email$role$reason~";
            
            # If the form field for this preference is defined, then we
            # know the checkbox was checked, so set the value to "on".
            $updateString .= "on" if defined $::FORM{"email$role$reason"};
230
        }
231
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
            
    SendSQL("UPDATE profiles SET emailflags = " . SqlQuote($updateString) . 
            " WHERE userid = $userid");

    if (Param("supportwatchers") && exists $::FORM{'watchedusers'}) {
        # 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.
        SendSQL("LOCK TABLES watch WRITE, profiles READ");

        # what the db looks like now
        my $origWatchedUsers = new RelationSet;
        $origWatchedUsers->mergeFromDB("SELECT watched FROM watch WHERE" .
                                       " watcher=$userid");

        # Update the database to look like the form
        my $newWatchedUsers = new RelationSet($::FORM{'watchedusers'});
        my @CCDELTAS = $origWatchedUsers->generateSqlDeltas(
                                                         $newWatchedUsers, 
                                                         "watch", 
                                                         "watcher", 
                                                         $userid,
                                                         "watched");
        ($CCDELTAS[0] eq "") || SendSQL($CCDELTAS[0]);
        ($CCDELTAS[1] eq "") || SendSQL($CCDELTAS[1]);

        SendSQL("UNLOCK TABLES");       
260
    }
261 262 263
}


264 265 266
sub DoPermissions {
    my (@has_bits, @set_bits);
    
267 268 269 270 271
    SendSQL("SELECT DISTINCT name, description FROM groups, user_group_map " .
            "WHERE user_group_map.group_id = groups.id " .
            "AND user_id = $::userid " .
            "AND isbless = 0 " .
            "ORDER BY name");
272
    while (MoreSQLData()) {
273 274
        my ($nam, $desc) = FetchSQLData();
        push(@has_bits, {"desc" => $desc, "name" => $nam});
275
    }
276 277 278 279 280 281 282
    my @set_ids = ();
    SendSQL("SELECT DISTINCT name, description FROM groups " .
            "ORDER BY name");
    while (MoreSQLData()) {
        my ($nam, $desc) = FetchSQLData();
        if (UserCanBlessGroup($nam)) {
            push(@set_bits, {"desc" => $desc, "name" => $nam});
283 284
        }
    }
285 286 287
    
    $vars->{'has_bits'} = \@has_bits;
    $vars->{'set_bits'} = \@set_bits;    
288
}
289

290
# No SavePermissions() because this panel has no changeable fields.
291

292 293 294
###############################################################################
# Live code (not subroutine definitions) starts here
###############################################################################
295 296

ConnectToDatabase();
297 298 299 300
confirm_login();

GetVersionTable();

301 302
my $cgi = Bugzilla->cgi;

303 304
$vars->{'login'} = $::COOKIE{'Bugzilla_login'};
$vars->{'changes_saved'} = $::FORM{'dosave'};
305

306
my $current_tab_name = $::FORM{'tab'} || "account";
307

308 309 310
# The SWITCH below makes sure that this is valid
trick_taint($current_tab_name);

311
$vars->{'current_tab_name'} = $current_tab_name;
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
# Do any saving, and then display the current tab.
SWITCH: for ($current_tab_name) {
    /^account$/ && do {
        SaveAccount() if $::FORM{'dosave'};
        DoAccount();
        last SWITCH;
    };
    /^email$/ && do {
        SaveEmail() if $::FORM{'dosave'};
        DoEmail();
        last SWITCH;
    };
    /^permissions$/ && do {
        DoPermissions();
        last SWITCH;
    };
329 330
    ThrowUserError("unknown_tab",
                   { current_tab_name => $current_tab_name });
331 332
}

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