User.pm 60.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# -*- 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.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Myk Melez <myk@mozilla.org>
21
#                 Erik Stambaugh <erik@dasbistro.com>
22 23
#                 Bradley Baetz <bbaetz@acm.org>
#                 Joel Peshkin <bugreport@peshkin.net> 
24
#                 Byron Jones <bugzilla@glob.com.au>
25
#                 Shane H. W. Travis <travis@sedsystems.ca>
26
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
27
#                 Gervase Markham <gerv@gerv.net>
28
#                 Lance Larsh <lance.larsh@oracle.com>
29
#                 Justin C. De Vries <judevries@novell.com>
30 31 32 33 34 35 36 37 38 39 40

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

# Make it harder for us to do dangerous things in Perl.
use strict;

# This module implements utilities for dealing with Bugzilla users.
package Bugzilla::User;

41
use Bugzilla::Config;
42
use Bugzilla::Error;
43
use Bugzilla::Util;
44
use Bugzilla::Constants;
45
use Bugzilla::User::Setting;
46
use Bugzilla::Product;
47
use Bugzilla::Classification;
48

49
use base qw(Exporter);
50 51
@Bugzilla::User::EXPORT = qw(insert_new_user is_available_username
    login_to_id
52
    UserInGroup
53 54
    USER_MATCH_MULTIPLE USER_MATCH_FAILED USER_MATCH_SUCCESS
    MATCH_SKIP_CONFIRM
55
);
56

57 58 59 60 61 62 63 64 65 66
#####################################################################
# Constants
#####################################################################

use constant USER_MATCH_MULTIPLE => -1;
use constant USER_MATCH_FAILED   => 0;
use constant USER_MATCH_SUCCESS  => 1;

use constant MATCH_SKIP_CONFIRM  => 1;

67 68 69 70 71
################################################################################
# Functions
################################################################################

sub new {
72
    my $invocant = shift;
73 74 75 76 77 78 79 80 81 82 83 84
    my $user_id = shift;

    if ($user_id) {
        my $uid = $user_id;
        detaint_natural($user_id)
          || ThrowCodeError('invalid_numeric_argument',
                            {argument => 'userID',
                             value    => $uid,
                             function => 'Bugzilla::User::new'});
        return $invocant->_create("userid=?", $user_id);
    }
    else {
85 86
        return $invocant->_create;
    }
87
}
88

89 90 91 92 93 94 95
# This routine is sort of evil. Nothing except the login stuff should
# be dealing with addresses as an input, and they can get the id as a
# side effect of the other sql they have to do anyway.
# Bugzilla::BugMail still does this, probably as a left over from the
# pre-id days. Provide this as a helper, but don't document it, and hope
# that it can go away.
# The request flag stuff also does this, but it really should be passing
96
# in the id it already had to validate (or the User.pm object, of course)
97 98
sub new_from_login {
    my $invocant = shift;
99 100
    my $login = shift;

101
    my $dbh = Bugzilla->dbh;
102
    return $invocant->_create($dbh->sql_istrcmp('login_name', '?'), $login);
103 104 105 106 107 108
}

# Internal helper for the above |new| methods
# $cond is a string (including a placeholder ?) for the search
# requirement for the profiles table
sub _create {
109 110
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
111 112 113 114

    my $cond = shift;
    my $val = shift;

115 116 117 118 119 120
    # Allow invocation with no parameters to create a blank object
    my $self = {
        'id'             => 0,
        'name'           => '',
        'login'          => '',
        'showmybugslink' => 0,
121
        'disabledtext'   => '',
122
        'flags'          => {},
123 124
    };
    bless ($self, $class);
125
    return $self unless $cond && $val;
126

127 128 129 130 131
    # We're checking for validity here, so any value is OK
    trick_taint($val);

    my $dbh = Bugzilla->dbh;

132 133 134 135 136
    my ($id, $login, $name, $disabledtext, $mybugslink) =
        $dbh->selectrow_array(qq{SELECT userid, login_name, realname,
                                        disabledtext, mybugslink
                                 FROM profiles WHERE $cond},
                                 undef, $val);
137 138 139

    return undef unless defined $id;

140 141 142
    $self->{'id'}             = $id;
    $self->{'name'}           = $name;
    $self->{'login'}          = $login;
143
    $self->{'disabledtext'}   = $disabledtext;
144
    $self->{'showmybugslink'} = $mybugslink;
145

146 147 148
    return $self;
}

149 150 151
# Accessors for user attributes
sub id { $_[0]->{id}; }
sub login { $_[0]->{login}; }
152
sub email { $_[0]->{login} . Param('emailsuffix'); }
153
sub name { $_[0]->{name}; }
154 155
sub disabledtext { $_[0]->{'disabledtext'}; }
sub is_disabled { $_[0]->disabledtext ? 1 : 0; }
156 157
sub showmybugslink { $_[0]->{showmybugslink}; }

158 159 160 161 162 163 164 165 166 167 168 169 170
sub set_flags {
    my $self = shift;
    while (my $key = shift) {
        $self->{'flags'}->{$key} = shift;
    }
}

sub get_flag {
    my $self = shift;
    my $key = shift;
    return $self->{'flags'}->{$key};
}

171 172
# Generate a string to identify the user by name + login if the user
# has a name or by login only if she doesn't.
173 174 175
sub identity {
    my $self = shift;

176 177
    return "" unless $self->id;

178 179 180 181 182 183 184 185 186 187 188
    if (!defined $self->{identity}) {
        $self->{identity} = 
          $self->{name} ? "$self->{name} <$self->{login}>" : $self->{login};
    }

    return $self->{identity};
}

sub nick {
    my $self = shift;

189 190
    return "" unless $self->id;

191 192 193 194 195 196 197 198 199 200 201
    if (!defined $self->{nick}) {
        $self->{nick} = (split(/@/, $self->{login}, 2))[0];
    }

    return $self->{nick};
}

sub queries {
    my $self = shift;

    return $self->{queries} if defined $self->{queries};
202
    return [] unless $self->id;
203 204

    my $dbh = Bugzilla->dbh;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    my $used_in_whine_ref = $dbh->selectcol_arrayref(q{
                    SELECT DISTINCT query_name
                      FROM whine_events we
                INNER JOIN whine_queries wq
                        ON we.id = wq.eventid
                     WHERE we.owner_userid = ?}, undef, $self->{id});

    my $queries_ref = $dbh->selectall_arrayref(q{
                    SELECT name, query, linkinfooter, query_type
                      FROM namedqueries 
                     WHERE userid = ?
                  ORDER BY UPPER(name)},{'Slice'=>{}}, $self->{id});

    foreach my $name (@$used_in_whine_ref) { 
        foreach my $queries_hash (@$queries_ref) {
            if ($queries_hash->{name} eq $name) {
                $queries_hash->{usedinwhine} = 1;
                last;
            }
        }
225
    }
226
    $self->{queries} = $queries_ref;
227 228 229 230

    return $self->{queries};
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
sub settings {
    my ($self) = @_;

    return $self->{'settings'} if (defined $self->{'settings'});

    # IF the user is logged in
    # THEN get the user's settings
    # ELSE get default settings
    if ($self->id) {
        $self->{'settings'} = get_all_settings($self->id);
    } else {
        $self->{'settings'} = get_defaults();
    }

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

248 249 250 251 252 253 254 255 256 257
sub flush_queries_cache {
    my $self = shift;

    delete $self->{queries};
}

sub groups {
    my $self = shift;

    return $self->{groups} if defined $self->{groups};
258
    return {} unless $self->id;
259 260 261 262 263 264 265 266 267 268 269 270 271

    my $dbh = Bugzilla->dbh;
    my $groups = $dbh->selectcol_arrayref(q{SELECT DISTINCT groups.name, group_id
                                              FROM groups, user_group_map
                                             WHERE groups.id=user_group_map.group_id
                                               AND user_id=?
                                               AND isbless=0},
                                          { Columns=>[1,2] },
                                          $self->{id});

    # The above gives us an arrayref [name, id, name, id, ...]
    # Convert that into a hashref
    my %groups = @$groups;
272 273 274
    my $sth;
    my @groupidstocheck = values(%groups);
    my %groupidschecked = ();
275
    $sth = $dbh->prepare("SELECT groups.name, groups.id
276 277 278
                            FROM group_group_map
                      INNER JOIN groups
                              ON groups.id = grantor_id
279 280 281 282 283 284 285 286 287 288
                           WHERE member_id = ? 
                             AND grant_type = " . GROUP_MEMBERSHIP);
    while (my $node = shift @groupidstocheck) {
        $sth->execute($node);
        my ($member_name, $member_id);
        while (($member_name, $member_id) = $sth->fetchrow_array) {
            if (!$groupidschecked{$member_id}) {
                $groupidschecked{$member_id} = 1;
                push @groupidstocheck, $member_id;
                $groups{$member_name} = $member_id;
289 290 291
            }
        }
    }
292 293 294 295 296
    $self->{groups} = \%groups;

    return $self->{groups};
}

297 298 299 300 301
sub groups_as_string {
    my $self = shift;
    return (join(',',values(%{$self->groups})) || '-1');
}

302 303 304
sub bless_groups {
    my $self = shift;

305
    return $self->{'bless_groups'} if defined $self->{'bless_groups'};
306
    return [] unless $self->id;
307 308

    my $dbh = Bugzilla->dbh;
309 310 311
    my $query;
    my $connector;
    my @bindValues;
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    if ($self->in_group('editusers')) {
        # Users having editusers permissions may bless all groups.
        $query = 'SELECT DISTINCT id, name, description FROM groups';
        $connector = 'WHERE';
    }
    else {
        # Get all groups for the user where:
        #    + They have direct bless privileges
        #    + They are a member of a group that inherits bless privs.
        $query = q{
            SELECT DISTINCT groups.id, groups.name, groups.description
                       FROM groups, user_group_map, group_group_map AS ggm
                      WHERE user_group_map.user_id = ?
                        AND ((user_group_map.isbless = 1
                              AND groups.id=user_group_map.group_id)
                             OR (groups.id = ggm.grantor_id
                                 AND ggm.grant_type = ?
330 331 332
                                 AND ggm.member_id IN(} .
                                 $self->groups_as_string . 
                               q{)))};
333 334 335
        $connector = 'AND';
        @bindValues = ($self->id, GROUP_BLESS);
    }
336

337
    # If visibilitygroups are used, restrict the set of groups.
338
    if ((!$self->in_group('editusers')) && Param('usevisibilitygroups')) {
339 340 341 342 343 344 345 346 347 348
        # Users need to see a group in order to bless it.
        my $visibleGroups = join(', ', @{$self->visible_groups_direct()})
            || return $self->{'bless_groups'} = [];
        $query .= " $connector id in ($visibleGroups)";
    }

    $query .= ' ORDER BY name';

    return $self->{'bless_groups'} =
        $dbh->selectall_arrayref($query, {'Slice' => {}}, @bindValues);
349 350
}

351 352
sub in_group {
    my ($self, $group) = @_;
353 354
    return exists $self->groups->{$group} ? 1 : 0;
}
355

356 357 358 359
sub in_group_id {
    my ($self, $id) = @_;
    my %j = reverse(%{$self->groups});
    return exists $j{$id} ? 1 : 0;
360 361
}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
sub can_see_user {
    my ($self, $otherUser) = @_;
    my $query;

    if (Param('usevisibilitygroups')) {
        # If the user can see no groups, then no users are visible either.
        my $visibleGroups = $self->visible_groups_as_string() || return 0;
        $query = qq{SELECT COUNT(DISTINCT userid)
                    FROM profiles, user_group_map
                    WHERE userid = ?
                    AND user_id = userid
                    AND isbless = 0
                    AND group_id IN ($visibleGroups)
                   };
    } else {
        $query = qq{SELECT COUNT(userid)
                    FROM profiles
                    WHERE userid = ?
                   };
    }
    return Bugzilla->dbh->selectrow_array($query, undef, $otherUser->id);
}

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
sub can_edit_product {
    my ($self, $prod_id) = @_;
    my $dbh = Bugzilla->dbh;
    my $sth = $self->{sthCanEditProductId};
    my $userid = $self->{id};
    my $query = q{SELECT group_id FROM group_control_map 
                   WHERE product_id =? 
                     AND canedit != 0 };
    if (%{$self->groups}) {
        my $groups = join(',', values(%{$self->groups}));
        $query .= qq{AND group_id NOT IN($groups)};
    }
    unless ($sth) { $sth = $dbh->prepare($query); }
    $sth->execute($prod_id);
    $self->{sthCanEditProductId} = $sth;
    my $result = $sth->fetchrow_array();
    
    return (!defined($result));
}

405 406 407 408 409 410 411 412 413 414
sub can_see_bug {
    my ($self, $bugid) = @_;
    my $dbh = Bugzilla->dbh;
    my $sth  = $self->{sthCanSeeBug};
    my $userid  = $self->{id};
    # Get fields from bug, presence of user on cclist, and determine if
    # the user is missing any groups required by the bug. The prepared query
    # is cached because this may be called for every row in buglists or
    # every bug in a dependency list.
    unless ($sth) {
415
        $sth = $dbh->prepare("SELECT 1, reporter, assigned_to, qa_contact,
416 417 418 419 420 421 422 423 424
                             reporter_accessible, cclist_accessible,
                             COUNT(cc.who), COUNT(bug_group_map.bug_id)
                             FROM bugs
                             LEFT JOIN cc 
                               ON cc.bug_id = bugs.bug_id
                               AND cc.who = $userid
                             LEFT JOIN bug_group_map 
                               ON bugs.bug_id = bug_group_map.bug_id
                               AND bug_group_map.group_ID NOT IN(" .
425
                               $self->groups_as_string .
426 427
                               ") WHERE bugs.bug_id = ? 
                               AND creation_ts IS NOT NULL " .
428 429 430
                             $dbh->sql_group_by('bugs.bug_id', 'reporter, ' .
                             'assigned_to, qa_contact, reporter_accessible, ' .
                             'cclist_accessible'));
431 432
    }
    $sth->execute($bugid);
433
    my ($ready, $reporter, $owner, $qacontact, $reporter_access, $cclist_access,
434
        $isoncclist, $missinggroup) = $sth->fetchrow_array();
435
    $sth->finish;
436
    $self->{sthCanSeeBug} = $sth;
437 438 439 440 441 442
    return ($ready
            && ((($reporter == $userid) && $reporter_access)
                || (Param('useqacontact') && $qacontact && ($qacontact == $userid))
                || ($owner == $userid)
                || ($isoncclist && $cclist_access)
                || (!$missinggroup)));
443 444
}

445 446 447 448 449 450
sub can_see_product {
    my ($self, $product_name) = @_;

    return scalar(grep {$_->name eq $product_name} @{$self->get_selectable_products});
}

451
sub get_selectable_products {
452
    my $self = shift;
453
    my $classification_id = shift;
454

455 456
    if (defined $self->{selectable_products}) {
        return $self->{selectable_products};
457 458
    }

459
    my $dbh = Bugzilla->dbh;
460 461
    my @params = ();

462
    my $query = "SELECT id " .
463 464 465 466 467 468 469 470 471 472
                "FROM products " .
                "LEFT JOIN group_control_map " .
                "ON group_control_map.product_id = products.id ";
    if (Param('useentrygroupdefault')) {
        $query .= "AND group_control_map.entry != 0 ";
    } else {
        $query .= "AND group_control_map.membercontrol = " .
                  CONTROLMAPMANDATORY . " ";
    }
    $query .= "AND group_id NOT IN(" . 
473
               $self->groups_as_string . ") " .
474 475 476 477 478 479 480
              "WHERE group_id IS NULL ";

    if (Param('useclassification') && $classification_id) {
        $query .= "AND classification_id = ? ";
        detaint_natural($classification_id);
        push(@params, $classification_id);
    }
481

482 483 484
    $query .= "ORDER BY name";

    my $prod_ids = $dbh->selectcol_arrayref($query, undef, @params);
485 486 487
    my @products;
    foreach my $prod_id (@$prod_ids) {
        push(@products, new Bugzilla::Product($prod_id));
488
    }
489 490
    $self->{selectable_products} = \@products;
    return $self->{selectable_products};
491 492
}

493
sub get_selectable_classifications {
494 495 496 497 498
    my ($self) = @_;

    if (defined $self->{selectable_classifications}) {
        return $self->{selectable_classifications};
    }
499 500 501 502 503

    my $products = $self->get_selectable_products;

    my $class;
    foreach my $product (@$products) {
504 505
        $class->{$product->classification_id} ||= 
            new Bugzilla::Classification($product->classification_id);
506
    }
507 508
    my @sorted_class = sort {lc($a->name) cmp lc($b->name)} (values %$class);
    $self->{selectable_classifications} = \@sorted_class;
509 510 511
    return $self->{selectable_classifications};
}

512 513 514 515 516 517 518 519 520 521 522
sub can_enter_product {
    my ($self, $product_name, $warn) = @_;
    my $dbh = Bugzilla->dbh;

    if (!defined($product_name)) {
        return unless $warn;
        ThrowUserError('no_products');
    }
    trick_taint($product_name);

    # Checks whether the user has access to the product.
523 524
    my $has_access = $dbh->selectrow_array('SELECT CASE WHEN group_id IS NULL
                                                        THEN 1 ELSE 0 END
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
                                              FROM products
                                         LEFT JOIN group_control_map
                                                ON group_control_map.product_id = products.id
                                               AND group_control_map.entry != 0
                                               AND group_id NOT IN (' . $self->groups_as_string . ')
                                             WHERE products.name = ? ' .
                                             $dbh->sql_limit(1),
                                            undef, $product_name);

    if (!$has_access) {
        return unless $warn;
        ThrowUserError('entry_access_denied', { product => $product_name });
    }

    # Checks whether the product is open for new bugs and
    # has at least one component and one version.
    my ($is_open, $has_version) = 
542 543 544 545
        $dbh->selectrow_array('SELECT CASE WHEN disallownew = 0
                                           THEN 1 ELSE 0 END,
                                      CASE WHEN versions.value IS NOT NULL
                                           THEN 1 ELSE 0 END
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
                                 FROM products
                           INNER JOIN components
                                   ON components.product_id = products.id
                            LEFT JOIN versions
                                   ON versions.product_id = products.id
                                WHERE products.name = ? ' .
                               $dbh->sql_limit(1), undef, $product_name);

    # Returns undef if the product has no components
    # Returns 0 if the product has no versions, or is closed for bug entry
    # Returns 1 if the user can enter bugs into the product
    return ($is_open && $has_version) unless $warn;

    # (undef, undef): the product has no components,
    # (0,     ?)    : the product is closed for new bug entry,
    # (?,     0)    : the product has no versions,
    # (1,     1)    : the user can enter bugs into the product,
    if (!defined $is_open) {
        ThrowUserError('missing_component', { product => $product_name });
    } elsif (!$is_open) {
        ThrowUserError('product_disabled', { product => $product_name });
    } elsif (!$has_version) {
        ThrowUserError('missing_version', { product => $product_name });
    }
    return 1;
}

sub get_enterable_products {
    my $self = shift;

    if (defined $self->{enterable_products}) {
        return $self->{enterable_products};
    }

    my @products;
    foreach my $product (Bugzilla::Product::get_all_products()) {
        if ($self->can_enter_product($product->name)) {
            push(@products, $product);
        }
    }
    $self->{enterable_products} = \@products;
    return $self->{enterable_products};
}

590 591 592 593 594
# visible_groups_inherited returns a reference to a list of all the groups
# whose members are visible to this user.
sub visible_groups_inherited {
    my $self = shift;
    return $self->{visible_groups_inherited} if defined $self->{visible_groups_inherited};
595
    return [] unless $self->id;
596
    my @visgroups = @{$self->visible_groups_direct};
597
    @visgroups = @{$self->flatten_group_membership(@visgroups)};
598 599 600 601 602 603 604 605 606 607
    $self->{visible_groups_inherited} = \@visgroups;
    return $self->{visible_groups_inherited};
}

# visible_groups_direct returns a reference to a list of all the groups that
# are visible to this user.
sub visible_groups_direct {
    my $self = shift;
    my @visgroups = ();
    return $self->{visible_groups_direct} if defined $self->{visible_groups_direct};
608
    return [] unless $self->id;
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

    my $dbh = Bugzilla->dbh;
    my $glist = join(',',(-1,values(%{$self->groups})));
    my $sth = $dbh->prepare("SELECT DISTINCT grantor_id
                                FROM group_group_map
                               WHERE member_id IN($glist)
                                 AND grant_type=" . GROUP_VISIBLE);
    $sth->execute();

    while (my ($row) = $sth->fetchrow_array) {
        push @visgroups,$row;
    }
    $self->{visible_groups_direct} = \@visgroups;

    return $self->{visible_groups_direct};
}

626 627 628 629 630
sub visible_groups_as_string {
    my $self = shift;
    return join(', ', @{$self->visible_groups_inherited()});
}

631 632
sub derive_regexp_groups {
    my ($self) = @_;
633 634

    my $id = $self->id;
635
    return unless $id;
636 637 638 639 640 641 642 643 644 645

    my $dbh = Bugzilla->dbh;

    my $sth;

    # avoid races, we are only up to date as of the BEGINNING of this process
    my $time = $dbh->selectrow_array("SELECT NOW()");

    # add derived records for any matching regexps

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    $sth = $dbh->prepare("SELECT id, userregexp, user_group_map.group_id
                            FROM groups
                       LEFT JOIN user_group_map
                              ON groups.id = user_group_map.group_id
                             AND user_group_map.user_id = ?
                             AND user_group_map.grant_type = ?");
    $sth->execute($id, GRANT_REGEXP);

    my $group_insert = $dbh->prepare(q{INSERT INTO user_group_map
                                       (user_id, group_id, isbless, grant_type)
                                       VALUES (?, ?, 0, ?)});
    my $group_delete = $dbh->prepare(q{DELETE FROM user_group_map
                                       WHERE user_id = ?
                                         AND group_id = ?
                                         AND isbless = 0
                                         AND grant_type = ?});
    while (my ($group, $regexp, $present) = $sth->fetchrow_array()) {
        if (($regexp ne '') && ($self->{login} =~ m/$regexp/i)) {
            $group_insert->execute($id, $group, GRANT_REGEXP) unless $present;
        } else {
            $group_delete->execute($id, $group, GRANT_REGEXP) if $present;
667 668 669
        }
    }

670 671
    $dbh->do(q{UPDATE profiles SET refreshed_when = ? WHERE userid = ?},
             undef, ($time, $id));
672 673
}

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
sub product_responsibilities {
    my $self = shift;

    return $self->{'product_resp'} if defined $self->{'product_resp'};
    return [] unless $self->id;

    my $h = Bugzilla->dbh->selectall_arrayref(
        qq{SELECT products.name AS productname,
                  components.name AS componentname,
                  initialowner,
                  initialqacontact
           FROM products, components
           WHERE products.id = components.product_id
             AND ? IN (initialowner, initialqacontact)
          },
        {'Slice' => {}}, $self->id);
    $self->{'product_resp'} = $h;

    return $h;
}

695 696 697
sub can_bless {
    my $self = shift;

698 699 700
    if (!scalar(@_)) {
        # If we're called without an argument, just return 
        # whether or not we can bless at all.
701
        return scalar(@{$self->bless_groups}) ? 1 : 0;
702 703
    }

704 705
    # Otherwise, we're checking a specific group
    my $group_name = shift;
706
    return (grep {$$_{'name'} eq $group_name} (@{$self->bless_groups})) ? 1 : 0;
707 708
}

709
sub flatten_group_membership {
710
    my ($self, @groups) = @_;
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

    my $dbh = Bugzilla->dbh;
    my $sth;
    my @groupidstocheck = @groups;
    my %groupidschecked = ();
    $sth = $dbh->prepare("SELECT member_id FROM group_group_map
                             WHERE grantor_id = ? 
                               AND grant_type = " . GROUP_MEMBERSHIP);
    while (my $node = shift @groupidstocheck) {
        $sth->execute($node);
        my $member;
        while (($member) = $sth->fetchrow_array) {
            if (!$groupidschecked{$member}) {
                $groupidschecked{$member} = 1;
                push @groupidstocheck, $member;
                push @groups, $member unless grep $_ == $member, @groups;
            }
        }
    }
730
    return \@groups;
731 732
}

733 734
sub match {
    # Generates a list of users whose login name (email address) or real name
735
    # matches a substring or wildcard.
736 737
    # This is also called if matches are disabled (for error checking), but
    # in this case only the exact match code will end up running.
738

739
    # $str contains the string to match, while $limit contains the
740 741
    # maximum number of records to retrieve.
    my ($str, $limit, $exclude_disabled) = @_;
742 743
    my $user = Bugzilla->user;
    my $dbh = Bugzilla->dbh;
744

745
    my @users = ();
746 747
    return \@users if $str =~ /^\s*$/;

748
    # The search order is wildcards, then exact match, then substring search.
749 750 751 752 753 754 755
    # Wildcard matching is skipped if there is no '*', and exact matches will
    # not (?) have a '*' in them.  If any search comes up with something, the
    # ones following it will not execute.

    # first try wildcards
    my $wildstr = $str;

756 757
    if ($wildstr =~ s/\*/\%/g && # don't do wildcards if no '*' in the string
        Param('usermatchmode') ne 'off') { # or if we only want exact matches
758 759

        # Build the query.
760 761 762 763 764
        trick_taint($wildstr);
        my $query  = "SELECT DISTINCT login_name FROM profiles ";
        if (Param('usevisibilitygroups')) {
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
765
        }
766 767 768 769 770
        $query .= "WHERE ("
            . $dbh->sql_istrcmp('login_name', '?', "LIKE") . " OR " .
              $dbh->sql_istrcmp('realname', '?', "LIKE") . ") ";
        if (Param('usevisibilitygroups')) {
            $query .= "AND isbless = 0 " .
771
                      "AND group_id IN(" .
772
                      join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
773 774
        }
        $query    .= " AND disabledtext = '' " if $exclude_disabled;
775
        $query    .= " ORDER BY login_name ";
776
        $query    .= $dbh->sql_limit($limit) if $limit;
777 778 779

        # Execute the query, retrieve the results, and make them into
        # User objects.
780 781 782 783
        my $user_logins = $dbh->selectcol_arrayref($query, undef, ($wildstr, $wildstr));
        foreach my $login_name (@$user_logins) {
            push(@users, Bugzilla::User->new_from_login($login_name));
        }
784 785
    }
    else {    # try an exact match
786
        # Exact matches don't care if a user is disabled.
787 788 789 790
        trick_taint($str);
        my $user_id = $dbh->selectrow_array('SELECT userid FROM profiles
                                             WHERE ' . $dbh->sql_istrcmp('login_name', '?'),
                                             undef, $str);
791

792
        push(@users, new Bugzilla::User($user_id)) if $user_id;
793 794
    }

795
    # then try substring search
796
    if ((scalar(@users) == 0)
797
        && (Param('usermatchmode') eq 'search')
798 799
        && (length($str) >= 3))
    {
800 801
        $str = lc($str);
        trick_taint($str);
802

803 804 805 806
        my $query   = "SELECT DISTINCT login_name FROM profiles ";
        if (Param('usevisibilitygroups')) {
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
807
        }
808
        $query     .= " WHERE (" .
809 810 811 812
                $dbh->sql_position('?', 'LOWER(login_name)') . " > 0" . " OR " .
                $dbh->sql_position('?', 'LOWER(realname)') . " > 0) ";
        if (Param('usevisibilitygroups')) {
            $query .= " AND isbless = 0" .
813
                      " AND group_id IN(" .
814
                join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
815
        }
816 817 818
        $query     .= " AND disabledtext = '' " if $exclude_disabled;
        $query    .= " ORDER BY login_name ";
        $query     .= $dbh->sql_limit($limit) if $limit;
819

820 821 822 823 824
        my $user_logins = $dbh->selectcol_arrayref($query, undef, ($str, $str));
        foreach my $login_name (@$user_logins) {
            push(@users, Bugzilla::User->new_from_login($login_name));
        }
    }
825 826 827
    return \@users;
}

828 829 830 831 832
# match_field() is a CGI wrapper for the match() function.
#
# Here's what it does:
#
# 1. Accepts a list of fields along with whether they may take multiple values
833 834
# 2. Takes the values of those fields from the first parameter, a $cgi object 
#    and passes them to match()
835 836 837 838 839 840 841 842 843 844 845 846 847
# 3. Checks the results of the match and displays confirmation or failure
#    messages as appropriate.
#
# The confirmation screen functions the same way as verify-new-product and
# confirm-duplicate, by rolling all of the state information into a
# form which is passed back, but in this case the searched fields are
# replaced with the search results.
#
# The act of displaying the confirmation or failure messages means it must
# throw a template and terminate.  When confirmation is sent, all of the
# searchable fields have been replaced by exact fields and the calling script
# is executed as normal.
#
848 849 850 851 852
# You also have the choice of *never* displaying the confirmation screen.
# In this case, match_field will return one of the three USER_MATCH 
# constants described in the POD docs. To make match_field behave this
# way, pass in MATCH_SKIP_CONFIRM as the third argument.
#
853 854 855 856 857 858 859 860 861
# match_field must be called early in a script, before anything external is
# done with the form data.
#
# In order to do a simple match without dealing with templates, confirmation,
# or globals, simply calling Bugzilla::User::match instead will be
# sufficient.

# How to call it:
#
862
# Bugzilla::User::match_field($cgi, {
863 864 865 866 867 868 869 870 871
#   'field_name'    => { 'type' => fieldtype },
#   'field_name2'   => { 'type' => fieldtype },
#   [...]
# });
#
# fieldtype can be either 'single' or 'multi'.
#

sub match_field {
872 873
    my $cgi          = shift;   # CGI object to look up fields in
    my $fields       = shift;   # arguments as a hash
874
    my $behavior     = shift || 0; # A constant that tells us how to act
875 876 877
    my $matches      = {};      # the values sent to the template
    my $matchsuccess = 1;       # did the match fail?
    my $need_confirm = 0;       # whether to display confirmation screen
878
    my $match_multiple = 0;     # whether we ever matched more than one user
879 880 881

    # prepare default form values

882
    # What does a "--do_not_change--" field look like (if any)?
883
    my $dontchange = $cgi->param('dontchange');
884

885 886 887 888 889 890 891 892 893 894 895 896
    # Fields can be regular expressions matching multiple form fields
    # (f.e. "requestee-(\d+)"), so expand each non-literal field
    # into the list of form fields it matches.
    my $expanded_fields = {};
    foreach my $field_pattern (keys %{$fields}) {
        # Check if the field has any non-word characters.  Only those fields
        # can be regular expressions, so don't expand the field if it doesn't
        # have any of those characters.
        if ($field_pattern =~ /^\w+$/) {
            $expanded_fields->{$field_pattern} = $fields->{$field_pattern};
        }
        else {
897
            my @field_names = grep(/$field_pattern/, $cgi->param());
898 899 900 901
            foreach my $field_name (@field_names) {
                $expanded_fields->{$field_name} = 
                  { type => $fields->{$field_pattern}->{'type'} };
                
902 903 904
                # The field is a requestee field; in order for its name 
                # to show up correctly on the confirmation page, we need 
                # to find out the name of its flag type.
905
                if ($field_name =~ /^requestee-(\d+)$/) {
906 907 908 909 910
                    my $flag = Bugzilla::Flag::get($1);
                    $expanded_fields->{$field_name}->{'flag_type'} = 
                      $flag->{'type'};
                }
                elsif ($field_name =~ /^requestee_type-(\d+)$/) {
911 912 913 914 915 916 917 918
                    $expanded_fields->{$field_name}->{'flag_type'} = 
                      Bugzilla::FlagType::get($1);
                }
            }
        }
    }
    $fields = $expanded_fields;

919 920 921 922 923
    for my $field (keys %{$fields}) {

        # Tolerate fields that do not exist.
        #
        # This is so that fields like qa_contact can be specified in the code
924
        # and it won't break if the CGI object does not know about them.
925 926 927 928
        #
        # It has the side-effect that if a bad field name is passed it will be
        # quietly ignored rather than raising a code error.

929
        next if !defined $cgi->param($field);
930

931
        # Skip it if this is a --do_not_change-- field
932
        next if $dontchange && $dontchange eq $cgi->param($field);
933

934
        # We need to move the query to $raw_field, where it will be split up,
935
        # modified by the search, and put back into the CGI environment
936 937
        # incrementally.

938 939 940
        my $raw_field = join(" ", $cgi->param($field));

        # When we add back in values later, it matters that we delete
941
        # the field here, and not set it to '', so that we will add
942
        # things to an empty list, and not to a list containing one
943
        # empty string.
944 945
        # If the field accepts only one match (type eq "single") and
        # no match or more than one match is found for this field,
946 947
        # we will set it back to '' so that the field remains defined
        # outside this function (it was if we came here; else we would
948 949 950
        # have returned earlier above).
        # If the field accepts several matches (type eq "multi") and no match
        # is found, we leave this field undefined (= empty array).
951
        $cgi->delete($field);
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

        my @queries = ();

        # Now we either split $raw_field by spaces/commas and put the list
        # into @queries, or in the case of fields which only accept single
        # entries, we simply use the verbatim text.

        $raw_field =~ s/^\s+|\s+$//sg;  # trim leading/trailing space

        # single field
        if ($fields->{$field}->{'type'} eq 'single') {
            @queries = ($raw_field) unless $raw_field =~ /^\s*$/;

        # multi-field
        }
        elsif ($fields->{$field}->{'type'} eq 'multi') {
            @queries =  split(/[\s,]+/, $raw_field);

        }
        else {
            # bad argument
973 974 975 976
            ThrowCodeError('bad_arg',
                           { argument => $fields->{$field}->{'type'},
                             function =>  'Bugzilla::User::match_field',
                           });
977 978
        }

979 980 981 982 983
        my $limit = 0;
        if (&::Param('maxusermatches')) {
            $limit = &::Param('maxusermatches') + 1;
        }

984 985 986
        for my $query (@queries) {

            my $users = match(
987 988 989
                $query,   # match string
                $limit,   # match limit
                1         # exclude_disabled
990 991 992 993
            );

            # skip confirmation for exact matches
            if ((scalar(@{$users}) == 1)
994
                && (@{$users}[0]->{'login'} eq $query))
995
            {
996 997 998
                $cgi->append(-name=>$field,
                             -values=>[@{$users}[0]->{'login'}]);

999 1000 1001
                next;
            }

1002 1003
            $matches->{$field}->{$query}->{'users'}  = $users;
            $matches->{$field}->{$query}->{'status'} = 'success';
1004 1005 1006

            # here is where it checks for multiple matches

1007
            if (scalar(@{$users}) == 1) { # exactly one match
1008 1009 1010 1011

                $cgi->append(-name=>$field,
                             -values=>[@{$users}[0]->{'login'}]);

1012 1013 1014 1015 1016 1017
                $need_confirm = 1 if &::Param('confirmuniqueusermatch');

            }
            elsif ((scalar(@{$users}) > 1)
                    && (&::Param('maxusermatches') != 1)) {
                $need_confirm = 1;
1018
                $match_multiple = 1;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

                if ((&::Param('maxusermatches'))
                   && (scalar(@{$users}) > &::Param('maxusermatches')))
                {
                    $matches->{$field}->{$query}->{'status'} = 'trunc';
                    pop @{$users};  # take the last one out
                }

            }
            else {
                # everything else fails
                $matchsuccess = 0; # fail
                $matches->{$field}->{$query}->{'status'} = 'fail';
                $need_confirm = 1;  # confirmation screen shows failures
            }
        }
1035
        # Above, we deleted the field before adding matches. If no match
1036 1037
        # or more than one match has been found for a field expecting only
        # one match (type eq "single"), we set it back to '' so
1038 1039
        # that the caller of this function can still check whether this
        # field was defined or not (and it was if we came here).
1040 1041 1042 1043
        if (!defined $cgi->param($field)
            && $fields->{$field}->{'type'} eq 'single') {
            $cgi->param($field, '');
        }
1044 1045
    }

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    my $retval;
    if (!$matchsuccess) {
        $retval = USER_MATCH_FAILED;
    }
    elsif ($match_multiple) {
        $retval = USER_MATCH_MULTIPLE;
    }
    else {
        $retval = USER_MATCH_SUCCESS;
    }

    # Skip confirmation if we were told to, or if we don't need to confirm.
    return $retval if ($behavior == MATCH_SKIP_CONFIRM || !$need_confirm);
1059

1060 1061 1062
    my $template = Bugzilla->template;
    my $vars = {};

1063
    $vars->{'script'}        = Bugzilla->cgi->url(-relative => 1); # for self-referencing URLs
1064
    $vars->{'fields'}        = $fields; # fields being matched
1065 1066 1067
    $vars->{'matches'}       = $matches; # matches that were made
    $vars->{'matchsuccess'}  = $matchsuccess; # continue or fail

1068
    print Bugzilla->cgi->header();
1069

1070 1071
    $template->process("global/confirm-user-match.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
1072 1073 1074 1075 1076

    exit;

}

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
# Changes in some fields automatically trigger events. The 'field names' are
# from the fielddefs table. We really should be using proper field names 
# throughout.
our %names_to_events = (
    'Resolution'             => EVT_OPENED_CLOSED,
    'Keywords'               => EVT_KEYWORD,
    'CC'                     => EVT_CC,
    'Severity'               => EVT_PROJ_MANAGEMENT,
    'Priority'               => EVT_PROJ_MANAGEMENT,
    'Status'                 => EVT_PROJ_MANAGEMENT,
    'Target Milestone'       => EVT_PROJ_MANAGEMENT,
    'Attachment description' => EVT_ATTACHMENT_DATA,
    'Attachment mime type'   => EVT_ATTACHMENT_DATA,
1090 1091 1092
    'Attachment is patch'    => EVT_ATTACHMENT_DATA,
    'BugsThisDependsOn'      => EVT_DEPEND_BLOCK,
    'OtherBugsDependingOnThis' => EVT_DEPEND_BLOCK);
1093 1094 1095 1096

# Returns true if the user wants mail for a given bug change.
# Note: the "+" signs before the constants suppress bareword quoting.
sub wants_bug_mail {
1097
    my $self = shift;
1098 1099 1100 1101 1102 1103 1104
    my ($bug_id, $relationship, $fieldDiffs, $commentField, $changer) = @_;

    # Don't send any mail, ever, if account is disabled 
    # XXX Temporary Compatibility Change 1 of 2:
    # This code is disabled for the moment to make the behaviour like the old
    # system, which sent bugmail to disabled accounts.
    # return 0 if $self->{'disabledtext'};
1105
    
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    # Make a list of the events which have happened during this bug change,
    # from the point of view of this user.    
    my %events;    
    foreach my $ref (@$fieldDiffs) {
        my ($who, $fieldName, $when, $old, $new) = @$ref;
        # A change to any of the above fields sets the corresponding event
        if (defined($names_to_events{$fieldName})) {
            $events{$names_to_events{$fieldName}} = 1;
        }
        else {
            # Catch-all for any change not caught by a more specific event
            # XXX: Temporary Compatibility Change 2 of 2:
            # This code is disabled, and replaced with the code a few lines
            # below, in order to make the behaviour more like the original, 
            # which only added this event if _all_ changes were of "other" type.
            # $events{+EVT_OTHER} = 1;            
        }

        # If the user is in a particular role and the value of that role
        # changed, we need the ADDED_REMOVED event.
        if (($fieldName eq "AssignedTo" && $relationship == REL_ASSIGNEE) ||
            ($fieldName eq "QAContact" && $relationship == REL_QA)) 
        {
            $events{+EVT_ADDED_REMOVED} = 1;
        }
        
        if ($fieldName eq "CC") {
            my $login = $self->login;
            my $inold = ($old =~ /^(.*,)?\Q$login\E(,.*)?$/);
            my $innew = ($new =~ /^(.*,)?\Q$login\E(,.*)?$/);
            if ($inold != $innew)
            {
                $events{+EVT_ADDED_REMOVED} = 1;
            }
        }
    }

    if ($commentField =~ /Created an attachment \(/) {
        $events{+EVT_ATTACHMENT} = 1;
    }
    elsif ($commentField ne '') {
        $events{+EVT_COMMENT} = 1;
    }
1149
    
1150
    my @event_list = keys %events;
1151
    
1152 1153 1154 1155
    # XXX Temporary Compatibility Change 2 of 2:
    # See above comment.
    if (!scalar(@event_list)) {
      @event_list = (EVT_OTHER);
1156 1157
    }
    
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    my $wants_mail = $self->wants_mail(\@event_list, $relationship);

    # The negative events are handled separately - they can't be incorporated
    # into the first wants_mail call, because they are of the opposite sense.
    # 
    # We do them separately because if _any_ of them are set, we don't want
    # the mail.
    if ($wants_mail && $changer && ($self->{'login'} eq $changer)) {
        $wants_mail &= $self->wants_mail([EVT_CHANGED_BY_ME], $relationship);
    }    
    
    if ($wants_mail) {
        my $dbh = Bugzilla->dbh;
        # We don't create a Bug object from the bug_id here because we only
        # need one piece of information, and doing so (as of 2004-11-23) slows
        # down bugmail sending by a factor of 2. If Bug creation was more
        # lazy, this might not be so bad.
1175 1176 1177 1178
        my $bug_status = $dbh->selectrow_array('SELECT bug_status
                                                FROM bugs WHERE bug_id = ?',
                                                undef, $bug_id);

1179 1180
        if ($bug_status eq "UNCONFIRMED") {
            $wants_mail &= $self->wants_mail([EVT_UNCONFIRMED], $relationship);
1181 1182 1183
        }
    }
    
1184
    return $wants_mail;
1185 1186
}

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
# Returns true if the user wants mail for a given set of events.
sub wants_mail {
    my $self = shift;
    my ($events, $relationship) = @_;
    
    # Don't send any mail, ever, if account is disabled 
    # XXX Temporary Compatibility Change 1 of 2:
    # This code is disabled for the moment to make the behaviour like the old
    # system, which sent bugmail to disabled accounts.
    # return 0 if $self->{'disabledtext'};
    
    # No mail if there are no events
    return 0 if !scalar(@$events);
    
    my $dbh = Bugzilla->dbh;
    
    # If a relationship isn't given, default to REL_ANY.
    if (!defined($relationship)) {
        $relationship = REL_ANY;
    }
    
    my $wants_mail = 
1209 1210 1211 1212 1213 1214 1215 1216
        $dbh->selectrow_array('SELECT 1
                                 FROM email_setting
                                WHERE user_id = ?
                                  AND relationship = ?
                                  AND event IN (' . join(',', @$events) . ') ' .
                                      $dbh->sql_limit(1),
                              undef, ($self->{'id'}, $relationship));

1217
    return defined($wants_mail) ? 1 : 0;
1218
}
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

sub is_mover {
    my $self = shift;

    if (!defined $self->{'is_mover'}) {
        my @movers = map { trim($_) } split(',', Param('movers'));
        $self->{'is_mover'} = ($self->id
                               && lsearch(\@movers, $self->login) != -1);
    }
    return $self->{'is_mover'};
}

1231 1232 1233 1234 1235
sub get_userlist {
    my $self = shift;

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

1236
    my $dbh = Bugzilla->dbh;
1237 1238 1239 1240 1241 1242
    my $query  = "SELECT DISTINCT login_name, realname,";
    if (&::Param('usevisibilitygroups')) {
        $query .= " COUNT(group_id) ";
    } else {
        $query .= " 1 ";
    }
1243
    $query     .= "FROM profiles ";
1244
    if (Param('usevisibilitygroups')) {
1245 1246 1247
        $query .= "LEFT JOIN user_group_map " .
                  "ON user_group_map.user_id = userid AND isbless = 0 " .
                  "AND group_id IN(" .
1248
                  join(', ', (-1, @{$self->visible_groups_inherited})) . ")";
1249
    }
1250 1251
    $query    .= " WHERE disabledtext = '' ";
    $query    .= $dbh->sql_group_by('userid', 'login_name, realname');
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269

    my $sth = $dbh->prepare($query);
    $sth->execute;

    my @userlist;
    while (my($login, $name, $visible) = $sth->fetchrow_array) {
        push @userlist, {
            login => $login,
            identity => $name ? "$name <$login>" : $login,
            visible => $visible,
        };
    }
    @userlist = sort { lc $$a{'identity'} cmp lc $$b{'identity'} } @userlist;

    $self->{'userlist'} = \@userlist;
    return $self->{'userlist'};
}

1270
sub insert_new_user {
1271
    my ($username, $realname, $password, $disabledtext) = (@_);
1272 1273
    my $dbh = Bugzilla->dbh;

1274 1275 1276
    $disabledtext ||= '';

    # If not specified, generate a new random password for the user.
1277 1278
    # If the password is '*', do not encrypt it; we are creating a user
    # based on the ENV auth method.
1279
    $password ||= generate_random_password();
1280
    my $cryptpassword = ($password ne '*') ? bz_crypt($password) : $password;
1281

1282
    # XXX - These should be moved into is_available_username or validate_email_syntax
1283 1284 1285 1286 1287 1288
    #       At the least, they shouldn't be here. They're safe for now, though.
    trick_taint($username);
    trick_taint($realname);

    # Insert the new user record into the database.
    $dbh->do("INSERT INTO profiles 
1289 1290 1291
                          (login_name, realname, cryptpassword, disabledtext,
                           refreshed_when) 
                   VALUES (?, ?, ?, ?, '1901-01-01 00:00:00')",
1292
             undef, 
1293
             ($username, $realname, $cryptpassword, $disabledtext));
1294

1295 1296 1297 1298 1299
    # Turn on all email for the new user
    my $userid = $dbh->bz_last_key('profiles', 'userid');

    foreach my $rel (RELATIONSHIPS) {
        foreach my $event (POS_EVENTS, NEG_EVENTS) {
1300 1301 1302 1303 1304 1305 1306
            # These "exceptions" define the default email preferences.
            # 
            # We enable mail unless the change was made by the user, or it's
            # just a CC list addition and the user is not the reporter.
            next if ($event == EVT_CHANGED_BY_ME);
            next if (($event == EVT_CC) && ($rel != REL_REPORTER));

1307 1308 1309
            $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
                      VALUES (?, ?, ?)', undef, ($userid, $rel, $event));
        }
1310 1311 1312
    }

    foreach my $event (GLOBAL_EVENTS) {
1313 1314
        $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
                  VALUES (?, ?, ?)', undef, ($userid, REL_ANY, $event));
1315
    }
1316 1317 1318 1319

    my $user = new Bugzilla::User($userid);
    $user->derive_regexp_groups();

1320
    
1321 1322 1323 1324 1325
    # Return the password to the calling code so it can be included
    # in an email sent to the user.
    return $password;
}

1326
sub is_available_username {
1327 1328
    my ($username, $old_username) = @_;

1329
    if(login_to_id($username) != 0) {
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
        return 0;
    }

    my $dbh = Bugzilla->dbh;
    # $username is safe because it is only used in SELECT placeholders.
    trick_taint($username);
    # Reject if the new login is part of an email change which is
    # still in progress
    #
    # substring/locate stuff: bug 165221; this used to use regexes, but that
    # was unsafe and required weird escaping; using substring to pull out
1341
    # the new/old email addresses and sql_position() to find the delimiter (':')
1342 1343 1344
    # is cleaner/safer
    my $sth = $dbh->prepare(
        "SELECT eventdata FROM tokens WHERE tokentype = 'emailold'
1345 1346 1347 1348
        AND SUBSTRING(eventdata, 1, (" 
        . $dbh->sql_position(q{':'}, 'eventdata') . "-  1)) = ?
        OR SUBSTRING(eventdata, (" 
        . $dbh->sql_position(q{':'}, 'eventdata') . "+ 1)) = ?");
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    $sth->execute($username, $username);

    if (my ($eventdata) = $sth->fetchrow_array()) {
        # Allow thru owner of token
        if($old_username && ($eventdata eq "$old_username:$username")) {
            return 1;
        }
        return 0;
    }

    return 1;
}

1362
sub login_to_id {
1363 1364
    my ($login) = (@_);
    my $dbh = Bugzilla->dbh;
1365 1366
    # $login will only be used by the following SELECT statement, so it's safe.
    trick_taint($login);
1367 1368 1369
    my $user_id = $dbh->selectrow_array("SELECT userid FROM profiles WHERE " .
                                        $dbh->sql_istrcmp('login_name', '?'),
                                        undef, $login);
1370
    if ($user_id) {
1371 1372 1373 1374 1375 1376
        return $user_id;
    } else {
        return 0;
    }
}

1377
sub UserInGroup {
1378
    return exists Bugzilla->user->groups->{$_[0]} ? 1 : 0;
1379 1380
}

1381
1;
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394

__END__

=head1 NAME

Bugzilla::User - Object for a Bugzilla user

=head1 SYNOPSIS

  use Bugzilla::User;

  my $user = new Bugzilla::User($id);

1395 1396 1397
  my @get_selectable_classifications = 
      $user->get_selectable_classifications;

1398
  # Class Functions
1399
  $password = insert_new_user($username, $realname, $password, $disabledtext);
1400

1401 1402 1403 1404 1405 1406 1407 1408
=head1 DESCRIPTION

This package handles Bugzilla users. Data obtained from here is read-only;
there is currently no way to modify a user from this package.

Note that the currently logged in user (if any) is available via
L<Bugzilla-E<gt>user|Bugzilla/"user">.

1409 1410
=head1 CONSTANTS

1411 1412
=over

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
=item C<USER_MATCH_MULTIPLE>

Returned by C<match_field()> when at least one field matched more than 
one user, but no matches failed.

=item C<USER_MATCH_FAILED>

Returned by C<match_field()> when at least one field failed to match 
anything.

=item C<USER_MATCH_SUCCESS>

Returned by C<match_field()> when all fields successfully matched only one
user.

=item C<MATCH_SKIP_CONFIRM>

Passed in to match_field to tell match_field to never display a 
confirmation screen.

1433 1434
=back

1435 1436 1437 1438 1439 1440
=head1 METHODS

=over 4

=item C<new($userid)>

timeless%mozdev.org's avatar
timeless%mozdev.org committed
1441
Creates a new C<Bugzilla::User> object for the given user id.  If no user
1442 1443 1444
id was given, a blank object is created with no user attributes.

If an id was given but there was no matching user found, undef is returned.
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

=begin undocumented

=item C<new_from_login($login)>

Creates a new C<Bugzilla::User> object given the provided login. Returns
C<undef> if no matching user is found.

This routine should not be required in general; most scripts should be using
userids instead.

=end undocumented

=item C<id>

Returns the userid for this user.

=item C<login>

Returns the login name for this user.

=item C<email>

Returns the user's email address. Currently this is the same value as the
login.

=item C<name>

Returns the 'real' name for this user, if any.

=item C<showmybugslink>

Returns C<1> if the user has set his preference to show the 'My Bugs' link in
the page footer, and C<0> otherwise.

=item C<identity>

1482
Returns a string for the identity of the user. This will be of the form
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
C<name E<lt>emailE<gt>> if the user has specified a name, and C<email>
otherwise.

=item C<nick>

Returns a user "nickname" -- i.e. a shorter, not-necessarily-unique name by
which to identify the user. Currently the part of the user's email address
before the at sign (@), but that could change, especially if we implement
usernames not dependent on email address.

=item C<queries>

Returns an array of the user's named queries, sorted in a case-insensitive
order by name. Each entry is a hash with three keys:

=over

=item *

name - The name of the query

=item *

query - The text for the query

=item *

linkinfooter - Whether or not the query should be displayed in the footer.

=back

1514 1515 1516 1517
=item C<disabledtext>

Returns the disable text of the user, if any.

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
=item C<settings>

Returns a hash of hashes which holds the user's settings. The first key is
the name of the setting, as found in setting.name. The second key is one of:
is_enabled     - true if the user is allowed to set the preference themselves;
                 false to force the site defaults
                 for themselves or must accept the global site default value
default_value  - the global site default for this setting
value          - the value of this setting for this user. Will be the same
                 as the default_value if the user is not logged in, or if 
                 is_default is true.
is_default     - a boolean to indicate whether the user has chosen to make
                 a preference for themself or use the site default.

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
=item C<flush_queries_cache>

Some code modifies the set of stored queries. Because C<Bugzilla::User> does
not handle these modifications, but does cache the result of calling C<queries>
internally, such code must call this method to flush the cached result.

=item C<groups>

Returns a hashref of group names for groups the user is a member of. The keys
are the names of the groups, whilst the values are the respective group ids.
(This is so that a set of all groupids for groups the user is in can be
1543
obtained by C<values(%{$user-E<gt>groups})>.)
1544

1545 1546 1547 1548 1549 1550
=item C<groups_as_string>

Returns a string containing a comma-seperated list of numeric group ids.  If
the user is not a member of any groups, returns "-1". This is most often used
within an SQL IN() function.

1551 1552
=item C<in_group>

1553 1554 1555 1556 1557
Determines whether or not a user is in the given group by name. 

=item C<in_group_id>

Determines whether or not a user is in the given group by id. 
1558

1559 1560
=item C<bless_groups>

1561 1562 1563 1564 1565 1566
Returns an arrayref of hashes of C<groups> entries, where the keys of each hash
are the names of C<id>, C<name> and C<description> columns of the C<groups>
table.
The arrayref consists of the groups the user can bless, taking into account
that having editusers permissions means that you can bless all groups, and
that you need to be aware of a group in order to bless a group.
1567

1568 1569 1570 1571 1572
=item C<can_see_user(user)>

Returns 1 if the specified user account exists and is visible to the user,
0 otherwise.

1573 1574 1575 1576 1577
=item C<can_edit_product(prod_id)>

Determines if, given a product id, the user can edit bugs in this product
at all.

1578 1579 1580 1581
=item C<can_see_bug(bug_id)>

Determines if the user can see the specified bug.

1582 1583 1584 1585 1586
=item C<can_see_product(product_name)>

Returns 1 if the user can access the specified product, and 0 if the user
should not be aware of the existence of the product.

1587
=item C<derive_regexp_groups>
1588 1589 1590 1591 1592 1593 1594

Bugzilla allows for group inheritance. When data about the user (or any of the
groups) changes, the database must be updated. Handling updated groups is taken
care of by the constructor. However, when updating the email address, the
user may be placed into different groups, based on a new email regexp. This
method should be called in such a case to force reresolution of these groups.

1595 1596
=item C<get_selectable_products>

1597 1598 1599
 Description: Returns all products the user is allowed to access. This list
              is restricted to some given classification if $classification_id
              is given.
1600

1601 1602
 Params:      $classification_id - (optional) The ID of the classification
                                   the products belong to.
1603

1604
 Returns:     An array of product objects, sorted by the product name.
1605

1606 1607
=item C<get_selectable_classifications>

1608 1609
 Description: Returns all classifications containing at least one product
              the user is allowed to view.
1610

1611
 Params:      none
1612

1613 1614
 Returns:     An array of Bugzilla::Classification objects, sorted by
              the classification name.
1615

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
=item C<can_enter_product($product_name, $warn)>

 Description: Returns 1 if the user can enter bugs into the specified product.
              If the user cannot enter bugs into the product, the behavior of
              this method depends on the value of $warn:
              - if $warn is false (or not given), a 'false' value is returned;
              - if $warn is true, an error is thrown.

 Params:      $product_name - a product name.
              $warn         - optional parameter, indicating whether an error
                              must be thrown if the user cannot enter bugs
                              into the specified product.

 Returns:     1 if the user can enter bugs into the product,
              0 if the user cannot enter bugs into the product and if $warn
              is false (an error is thrown if $warn is true).

=item C<get_enterable_products>

 Description: Returns an array of product objects into which the user is
              allowed to enter bugs.

 Params:      none

 Returns:     an array of product objects.

1642 1643 1644 1645 1646 1647
=item C<get_userlist>

Returns a reference to an array of users.  The array is populated with hashrefs
containing the login, identity and visibility.  Users that are not visible to this
user will have 'visible' set to zero.

1648 1649 1650 1651 1652 1653 1654 1655
=item C<flatten_group_membership>

Accepts a list of groups and returns a list of all the groups whose members 
inherit membership in any group on the list.  So, we can determine if a user
is in any of the groups input to flatten_group_membership by querying the
user_group_map for any user with DIRECT or REGEXP membership IN() the list
of groups returned.

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
=item C<visible_groups_inherited>

Returns a list of all groups whose members should be visible to this user.
Since this list is flattened already, there is no need for all users to
be have derived groups up-to-date to select the users meeting this criteria.

=item C<visible_groups_direct>

Returns a list of groups that the user is aware of.

1666 1667 1668 1669 1670
=item C<visible_groups_as_string>

Returns the result of C<visible_groups_direct> as a string (a comma-separated
list).

1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
=item C<product_responsibilities>

Retrieve user's product responsibilities as a list of hashes.
One hash per Bugzilla component the user has a responsibility for.
These are the hash keys:

=over

=item productname

Name of the product.

=item componentname

Name of the component.

=item initialowner

User ID of default assignee.

=item initialqacontact

User ID of default QA contact.

=back

1697 1698
=item C<can_bless>

1699 1700 1701 1702 1703 1704
When called with no arguments:
Returns C<1> if the user can bless at least one group, returns C<0> otherwise.

When called with one argument:
Returns C<1> if the user can bless the group with that name, returns
C<0> otherwise.
1705

1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
=item C<set_flags>
=item C<get_flag>

User flags are template-accessible user status information, stored in the form
of a hash.  For an example of use, when the current user is authenticated in
such a way that they are allowed to log out, the 'can_logout' flag is set to
true (1).  The template then checks this flag before displaying the "Log Out"
link.

C<set_flags> is called with any number of key,value pairs.  Flags for each key
will be set to the specified value.

C<get_flag> is called with a single key name, which returns the associated
value.

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
=item C<wants_bug_mail>

Returns true if the user wants mail for a given bug change.

=item C<wants_mail>

Returns true if the user wants mail for a given set of events. This method is
more general than C<wants_bug_mail>, allowing you to check e.g. permissions
for flag mail.

1731 1732 1733 1734 1735 1736
=item C<is_mover>

Returns true if the user is in the list of users allowed to move bugs
to another database. Note that this method doesn't check whether bug
moving is enabled.

1737 1738
=back

1739 1740 1741 1742 1743
=head1 CLASS FUNCTIONS

These are functions that are not called on a User object, but instead are
called "statically," just like a normal procedural function.

1744 1745
=over 4

1746 1747
=item C<insert_new_user>

1748
Creates a new user in the database.
1749 1750 1751

Params: $username (scalar, string) - The login name for the new user.
        $realname (scalar, string) - The full name for the new user.
1752 1753 1754 1755 1756
        $password (scalar, string) - Optional. The password for the new user;
                                     if not given, a random password will be
                                     generated.
        $disabledtext (scalar, string) - Optional. The disable text for the new
                                         user; if not given, it will be empty.
1757 1758 1759
                                         If given, the user will be disabled,
                                         meaning the account will be
                                         unavailable for login.
1760 1761 1762

Returns: The password for this user, in plain text, so it can be included
         in an e-mail sent to the user.
1763

1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
=item C<is_available_username>

Returns a boolean indicating whether or not the supplied username is
already taken in Bugzilla.

Params: $username (scalar, string) - The full login name of the username 
            that you are checking.
        $old_username (scalar, string) - If you are checking an email-change
            token, insert the "old" username that the user is changing from,
            here. Then, as long as it's the right user for that token, he 
            can change his username to $username. (That is, this function
            will return a boolean true value).

1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
=item C<login_to_id($login)>

Takes a login name of a Bugzilla user and changes that into a numeric
ID for that user. This ID can then be passed to Bugzilla::User::new to
create a new user.

If no valid user exists with that login name, then the function will return 0.

This function can also be used when you want to just find out the userid
of a user, but you don't want the full weight of Bugzilla::User.

However, consider using a Bugzilla::User object instead of this function
if you need more information about the user than just their ID.

1791 1792 1793 1794 1795 1796
=item C<UserInGroup($groupname)>

Takes a name of a group, and returns 1 if a user is in the group, 0 otherwise.

=back

1797 1798 1799
=head1 SEE ALSO

L<Bugzilla|Bugzilla>