userprefs.cgi 13.7 KB
Newer Older
1
#!/usr/bonsaitools/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 25

use diagnostics;
use strict;

26 27
use lib qw(.);

28 29
require "CGI.pl";

30 31
use RelationSet;

32
# Shut up misguided -w warnings about "used only once". "use vars" just
33 34 35 36
# doesn't work for me.
sub sillyness {
    my $zz;
    $zz = $::defaultqueryname;
37
    $zz = $::usergroupset;
38
}
39

40
# Use global template variables.
41
use vars qw($template $vars $userid);
42

43 44
# The default email flags leave all email on.
my $defaultflagstring = "ExcludeSelf~on~";
45

46 47
my @roles = ("Owner", "Reporter", "QAcontact", "CClist", "Voter");
my @reasons = ("Removeme", "Comments", "Attachments", "Status", "Resolved", 
48
               "Keywords", "CC", "Other", "Unconfirmed");
49 50 51

foreach my $role (@roles) {
    foreach my $reason (@reasons) {
52 53
        $defaultflagstring .= "email$role$reason~on~";
    }
54 55
}

56 57
# Remove final "~".
chop $defaultflagstring;
58

59 60 61 62 63 64 65
###############################################################################
# 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 {
66
    SendSQL("SELECT realname FROM profiles WHERE userid = $userid");
67
    $vars->{'realname'} = FetchSQLData();
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    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;
            }
        }
    }
85 86 87
}

sub SaveAccount {
88 89 90
    my $pwd1 = $::FORM{'new_password1'};
    my $pwd2 = $::FORM{'new_password2'};

91
    if ($::FORM{'Bugzilla_password'} ne "" || 
92
        $pwd1 ne "" || $pwd2 ne "") 
93
    {
94
        my $old = SqlQuote($::FORM{'Bugzilla_password'});
95 96
        SendSQL("SELECT cryptpassword FROM profiles WHERE userid = $userid");
        my $oldcryptedpwd = FetchOneColumn();
97 98 99
        if (!$oldcryptedpwd) {
            DisplayError("I was unable to retrieve your old password from the database.");
            exit;
100
        }
101 102 103 104 105
        if (crypt($::FORM{'Bugzilla_password'}, $oldcryptedpwd) ne 
                  $oldcryptedpwd) 
        {
            DisplayError("You did not enter your old password correctly.");
            exit;
106
        }
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

        if ($pwd1 ne "" || $pwd2 ne "")
        {
            if ($pwd1 ne $pwd2) {
                DisplayError("The two passwords you entered did not match.");
                exit;
            }
            if ($::FORM{'new_password1'} eq '') {
                DisplayError("You must enter a new password.");
                exit;
            }
            my $passworderror = ValidatePassword($pwd1);
            (DisplayError($passworderror) && exit) if $passworderror;
        
            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"});
127
        }
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    }

    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) {
            if( $::FORM{'Bugzilla_password'} eq "") {
                DisplayError("You must enter your old password to 
                                             change email address.");
                exit;
            }

            use Token;
            # Block multiple email changes for the same user.
            if (Token::HasEmailChangeToken($userid)) {
                DisplayError("Email change already in progress; 
                                          please check your email.");
                exit;
            }

            # Before changing an email address, confirm one does not exist.
            CheckEmailSyntax($new_login_name);
            trick_taint($new_login_name);
            if (!ValidateNewUser($new_login_name)) {
                DisplayError("Account $new_login_name already exists");
                exit;
            }

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

            $vars->{'changes_saved'} = 
                "An email has been sent to both old and new email 
                 addresses to confirm the change of email address.";
163 164
        }
    }
165

166
    SendSQL("UPDATE profiles SET " .
167
            "realname = " . SqlQuote(trim($::FORM{'realname'})) .
168 169 170 171
            " WHERE userid = $userid");
}


172
sub DoEmail {
173 174 175
    if (Param("supportwatchers")) {
        my $watcheduserSet = new RelationSet;
        $watcheduserSet->mergeFromDB("SELECT watched FROM watch WHERE" .
176
                                    " watcher=$userid");
177
        $vars->{'watchedusers'} = $watcheduserSet->toString();
178
    }
179

180
    SendSQL("SELECT emailflags FROM profiles WHERE userid = $userid");
181

182
    my ($flagstring) = FetchSQLData();
183

184 185 186
    # 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
187
    # static defaults. 
188 189 190 191
    if (!$flagstring) {
        $flagstring = $defaultflagstring;
        SendSQL("UPDATE profiles SET emailflags = " .
                SqlQuote($flagstring) . " WHERE userid = $userid");
192
    }
193

194 195 196 197
    # 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);
198

199 200 201 202
    # 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.
203 204
    if (exists($emailflags{'ExcludeSelf'}) 
        && $emailflags{'ExcludeSelf'} eq 'on')
205 206 207 208 209 210 211
    {
        $vars->{'excludeself'} = 1;
    }
    else {
        $vars->{'excludeself'} = 0;
    }
    
212
    # Parse the info into a hash of hashes; the first hash keyed by role,
213 214 215 216 217 218 219 220 221 222 223 224
    # 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;
            }
225
        }
226
    }
227 228
}

229 230 231 232 233
# Note: we no longer store "off" values in the database.
sub SaveEmail {
    my $updateString = "";
    
    if (defined $::FORM{'ExcludeSelf'}) {
234
        $updateString .= 'ExcludeSelf~on';
235
    } else {
236 237
        $updateString .= 'ExcludeSelf~';
    }
238
    
239 240 241 242 243 244 245 246 247
    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"};
248
        }
249
    }
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
            
    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");       
278
    }
279 280 281
}


282
sub DoFooter {
283 284
    SendSQL("SELECT mybugslink FROM profiles " .
            "WHERE userid = $userid");
285 286
    $vars->{'mybugslink'} = FetchSQLData();
    
287 288
    SendSQL("SELECT name, linkinfooter FROM namedqueries " .
            "WHERE userid = $userid");
289 290
    
    my @queries;        
291
    while (MoreSQLData()) {
292 293 294 295
        my ($name, $footer) = (FetchSQLData());
        next if ($name eq $::defaultqueryname);
        
        push (@queries, { name => $name, footer => $footer });        
296
    }
297 298
    
    $vars->{'queries'} = \@queries;
299 300 301 302 303 304 305
}
              
sub SaveFooter {
    my %old;
    SendSQL("SELECT name, linkinfooter FROM namedqueries " .
            "WHERE userid = $userid");
    while (MoreSQLData()) {
306 307
        my ($name, $footer) = (FetchSQLData());
        $old{$name} = $footer;
308
    }
309
    
310
    for (my $c = 0; $c < $::FORM{'numqueries'}; $c++) {
311 312 313
        my $name = $::FORM{"name-$c"};
        if (exists $old{$name}) {
            my $new = $::FORM{"query-$c"};
314
            if ($new ne $old{$name}) {
315
                detaint_natural($new);
316 317 318 319
                SendSQL("UPDATE namedqueries SET linkinfooter = $new " .
                        "WHERE userid = $userid " .
                        "AND name = " . SqlQuote($name));
            }
320
        } else {
321
            DisplayError("Hmm, the $name query seems to have gone away.");
322 323
        }
    }
324 325
    SendSQL("UPDATE profiles SET mybugslink = " . 
            SqlQuote($::FORM{'mybugslink'}) . " WHERE userid = $userid");
326 327 328

    # Regenerate cached info about queries in footer.            
    $vars->{'user'} = GetUserInfo($::userid);
329 330
}
    
331 332 333 334
    
sub DoPermissions {
    my (@has_bits, @set_bits);
    
335 336 337 338
    SendSQL("SELECT description FROM groups " .
            "WHERE bit & $::usergroupset != 0 " .
            "ORDER BY bit");
    while (MoreSQLData()) {
339
        push(@has_bits, FetchSQLData());
340
    }
341
    
342 343 344 345 346 347 348
    SendSQL("SELECT blessgroupset FROM profiles WHERE userid = $userid");
    my $blessgroupset = FetchOneColumn();
    if ($blessgroupset) {
        SendSQL("SELECT description FROM groups " .
                "WHERE bit & $blessgroupset != 0 " .
                "ORDER BY bit");
        while (MoreSQLData()) {
349
            push(@set_bits, FetchSQLData());
350 351
        }
    }
352 353 354
    
    $vars->{'has_bits'} = \@has_bits;
    $vars->{'set_bits'} = \@set_bits;    
355
}
356

357
# No SavePermissions() because this panel has no changeable fields.
358

359 360 361
###############################################################################
# Live code (not subroutine definitions) starts here
###############################################################################
362 363

ConnectToDatabase();
364 365 366 367
confirm_login();

GetVersionTable();

368 369
$vars->{'login'} = $::COOKIE{'Bugzilla_login'};
$vars->{'changes_saved'} = $::FORM{'dosave'};
370

371
my $current_tab_name = $::FORM{'tab'} || "account";
372

373
$vars->{'current_tab_name'} = $current_tab_name;
374

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
# 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;
    };
    /^footer$/ && do {
        SaveFooter() if $::FORM{'dosave'};
        DoFooter();
        last SWITCH;
    };
    /^permissions$/ && do {
        DoPermissions();
        last SWITCH;
    };
396 397
}

398 399
# Generate and return the UI (HTML page) from the appropriate template.
print "Content-type: text/html\n\n";
400 401
$template->process("account/prefs/prefs.html.tmpl", $vars)
  || ThrowTemplateError($template->error());
402