User.pm 64 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
#                 Dennis Melentyev <dennis.melentyev@infopulse.com.ua>
31
#                 Frédéric Buclin <LpSolit@gmail.com>
32 33 34 35 36 37 38 39 40 41 42

################################################################################
# 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;

43
use Bugzilla::Error;
44
use Bugzilla::Util;
45
use Bugzilla::Constants;
46
use Bugzilla::User::Setting;
47
use Bugzilla::Product;
48
use Bugzilla::Classification;
49
use Bugzilla::Field;
50

51
use base qw(Bugzilla::Object Exporter);
52
@Bugzilla::User::EXPORT = qw(is_available_username
53
    login_to_id user_id_to_login validate_password
54 55
    USER_MATCH_MULTIPLE USER_MATCH_FAILED USER_MATCH_SUCCESS
    MATCH_SKIP_CONFIRM
56
);
57

58 59 60 61 62 63 64 65 66 67
#####################################################################
# 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;

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
use constant DEFAULT_USER => {
    'id'             => 0,
    'name'           => '',
    'login'          => '',
    'showmybugslink' => 0,
    'disabledtext'   => '',
    'disable_mail'   => 0,
};

use constant DB_TABLE => 'profiles';

# XXX Note that Bugzilla::User->name does not return the same thing
# that you passed in for "name" to new(). That's because historically
# Bugzilla::User used "name" for the realname field. This should be
# fixed one day.
use constant DB_COLUMNS => (
    'profiles.userid     AS id',
    'profiles.login_name AS login',
    'profiles.realname   AS name',
    'profiles.mybugslink AS showmybugslink',
    'profiles.disabledtext',
    'profiles.disable_mail',
);
use constant NAME_FIELD => 'login_name';
use constant ID_FIELD   => 'userid';

94 95 96 97 98 99 100 101 102 103
use constant REQUIRED_CREATE_FIELDS => qw(login_name cryptpassword);

use constant VALIDATORS => {
    cryptpassword => \&_check_password,
    disable_mail  => \&_check_disable_mail,
    disabledtext  => \&_check_disabledtext,
    login_name    => \&check_login_name_for_creation,
    realname      => \&_check_realname,
};

104 105 106 107 108 109 110
################################################################################
# Functions
################################################################################

sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
111
    my ($param) = @_;
112

113 114 115
    my $user = DEFAULT_USER;
    bless ($user, $class);
    return $user unless $param;
116

117
    return $class->SUPER::new(@_);
118 119
}

120 121 122 123
################################################################################
# Validators
################################################################################

124 125
sub _check_disable_mail { return $_[1] ? 1 : 0; }
sub _check_disabledtext { return trim($_[1]) || ''; }
126 127 128 129

# This is public since createaccount.cgi needs to use it before issuing
# a token for account creation.
sub check_login_name_for_creation {
130
    my ($self, $name) = @_;
131 132 133 134 135 136 137 138 139 140
    $name = trim($name);
    $name || ThrowUserError('user_login_required');
    validate_email_syntax($name)
        || ThrowUserError('illegal_email_address', { addr => $name });
    is_available_username($name) 
        || ThrowUserError('account_exists', { email => $name });
    return $name;
}

sub _check_password {
141
    my ($self, $pass) = @_;
142 143 144 145 146 147 148 149 150 151 152

    # If the password is '*', do not encrypt it or validate it further--we 
    # are creating a user who should not be able to log in using DB 
    # authentication.
    return $pass if $pass eq '*';

    validate_password($pass);
    my $cryptpassword = bz_crypt($pass);
    return $cryptpassword;
}

153
sub _check_realname { return trim($_[1]) || ''; }
154 155 156 157 158

################################################################################
# Methods
################################################################################

159 160
# Accessors for user attributes
sub login { $_[0]->{login}; }
161
sub email { $_[0]->{login} . Bugzilla->params->{'emailsuffix'}; }
162 163
sub disabledtext { $_[0]->{'disabledtext'}; }
sub is_disabled { $_[0]->disabledtext ? 1 : 0; }
164
sub showmybugslink { $_[0]->{showmybugslink}; }
165 166
sub email_disabled { $_[0]->{disable_mail}; }
sub email_enabled { !($_[0]->{disable_mail}); }
167

168 169 170
sub set_authorizer {
    my ($self, $authorizer) = @_;
    $self->{authorizer} = $authorizer;
171
}
172 173 174 175 176 177 178
sub authorizer {
    my ($self) = @_;
    if (!$self->{authorizer}) {
        require Bugzilla::Auth;
        $self->{authorizer} = new Bugzilla::Auth();
    }
    return $self->{authorizer};
179 180
}

181 182
# Generate a string to identify the user by name + login if the user
# has a name or by login only if she doesn't.
183 184 185
sub identity {
    my $self = shift;

186 187
    return "" unless $self->id;

188 189 190 191 192 193 194 195 196 197 198
    if (!defined $self->{identity}) {
        $self->{identity} = 
          $self->{name} ? "$self->{name} <$self->{login}>" : $self->{login};
    }

    return $self->{identity};
}

sub nick {
    my $self = shift;

199 200
    return "" unless $self->id;

201 202 203 204 205 206 207 208 209 210 211
    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};
212
    return [] unless $self->id;
213 214

    my $dbh = Bugzilla->dbh;
215
    my $used_in_whine_ref = $dbh->selectall_hashref('
216 217 218 219
                    SELECT DISTINCT query_name
                      FROM whine_events we
                INNER JOIN whine_queries wq
                        ON we.id = wq.eventid
220 221 222 223 224 225 226 227 228 229 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
                     WHERE we.owner_userid = ?',
                     'query_name', undef, $self->id);

    # If the user is in any group, there may be shared queries to be included.
    my $or_nqgm_group_id_in_usergroups = '';
    if ($self->groups_as_string) {
        $or_nqgm_group_id_in_usergroups =
            'OR MAX(nqgm.group_id) IN (' . $self->groups_as_string . ') ';
    }

    my $queries_ref = $dbh->selectall_arrayref('
                    SELECT nq.id, MAX(userid) AS userid, name, query, query_type,
                           MAX(nqgm.group_id) AS shared_with_group,
                           COUNT(nql.namedquery_id) AS link_in_footer
                      FROM namedqueries AS nq
                      LEFT JOIN namedquery_group_map nqgm
                             ON nqgm.namedquery_id = nq.id
                      LEFT JOIN namedqueries_link_in_footer AS nql
                             ON nql.namedquery_id = nq.id
                            AND nql.user_id = ? ' .
                      $dbh->sql_group_by('nq.id', 'name, query, query_type') .
                  ' HAVING MAX(nq.userid) = ? ' .
                           $or_nqgm_group_id_in_usergroups .
                ' ORDER BY UPPER(name)',
                {'Slice'=>{}}, $self->id, $self->id);

    foreach my $queries_hash (@$queries_ref) {
        # For each query, determine whether it's being used in a whine.
        if (exists($$used_in_whine_ref{$queries_hash->{'name'}})) {
            $queries_hash->{'usedinwhine'} = 1;
        }

        # For shared queries, provide the sharer's user object.
        if ($queries_hash->{'userid'} != $self->id) {
            $queries_hash->{'user'} = new Bugzilla::User($queries_hash->{'userid'});
255
        }
256
    }
257
    $self->{queries} = $queries_ref;
258 259 260 261

    return $self->{queries};
}

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
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'};
}

279 280 281 282 283 284 285 286 287 288
sub flush_queries_cache {
    my $self = shift;

    delete $self->{queries};
}

sub groups {
    my $self = shift;

    return $self->{groups} if defined $self->{groups};
289
    return {} unless $self->id;
290 291 292 293 294 295 296 297 298 299 300 301 302

    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;
303 304
    my @groupidstocheck = values(%groups);
    my %groupidschecked = ();
305 306
    my $rows = $dbh->selectall_arrayref(
                "SELECT DISTINCT groups.name, groups.id, member_id
307 308 309
                            FROM group_group_map
                      INNER JOIN groups
                              ON groups.id = grantor_id
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
                           WHERE grant_type = " . GROUP_MEMBERSHIP);
    my %group_names = ();
    my %group_membership = ();
    foreach my $row (@$rows) {
        my ($member_name, $grantor_id, $member_id) = @$row; 
        # Just save the group names
        $group_names{$grantor_id} = $member_name;
        
        # And group membership
        push (@{$group_membership{$member_id}}, $grantor_id);
    }
    
    # Let's walk the groups hierarchy tree (using FIFO)
    # On the first iteration it's pre-filled with direct groups 
    # membership. Later on, each group can add its own members into the
    # FIFO. Circular dependencies are eliminated by checking
    # $groupidschecked{$member_id} hash values.
    # As a result, %groups will have all the groups we are the member of.
    while ($#groupidstocheck >= 0) {
        # Pop the head group from FIFO
        my $member_id = shift @groupidstocheck;
        
        # Skip the group if we have already checked it
        if (!$groupidschecked{$member_id}) {
            # Mark group as checked
            $groupidschecked{$member_id} = 1;
            
            # Add all its members to the FIFO check list
            # %group_membership contains arrays of group members 
            # for all groups. Accessible by group number.
            foreach my $newgroupid (@{$group_membership{$member_id}}) {
                push @groupidstocheck, $newgroupid 
                    if (!$groupidschecked{$newgroupid});
343
            }
344 345 346 347
            # Note on if clause: we could have group in %groups from 1st
            # query and do not have it in second one
            $groups{$group_names{$member_id}} = $member_id 
                if $group_names{$member_id} && $member_id;
348 349
        }
    }
350 351 352 353 354
    $self->{groups} = \%groups;

    return $self->{groups};
}

355 356 357 358 359
sub groups_as_string {
    my $self = shift;
    return (join(',',values(%{$self->groups})) || '-1');
}

360 361 362
sub bless_groups {
    my $self = shift;

363
    return $self->{'bless_groups'} if defined $self->{'bless_groups'};
364
    return [] unless $self->id;
365 366

    my $dbh = Bugzilla->dbh;
367 368 369
    my $query;
    my $connector;
    my @bindValues;
370

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    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 = ?
388 389 390
                                 AND ggm.member_id IN(} .
                                 $self->groups_as_string . 
                               q{)))};
391 392 393
        $connector = 'AND';
        @bindValues = ($self->id, GROUP_BLESS);
    }
394

395
    # If visibilitygroups are used, restrict the set of groups.
396 397 398
    if (!$self->in_group('editusers')
        && Bugzilla->params->{'usevisibilitygroups'}) 
    {
399 400 401 402 403 404 405 406 407 408
        # 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);
409 410
}

411 412
sub in_group {
    my ($self, $group) = @_;
413 414
    return exists $self->groups->{$group} ? 1 : 0;
}
415

416 417 418 419
sub in_group_id {
    my ($self, $id) = @_;
    my %j = reverse(%{$self->groups});
    return exists $j{$id} ? 1 : 0;
420 421
}

422 423 424 425
sub can_see_user {
    my ($self, $otherUser) = @_;
    my $query;

426
    if (Bugzilla->params->{'usevisibilitygroups'}) {
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        # 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);
}

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
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));
}

465 466 467 468 469 470 471 472 473 474
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) {
475
        $sth = $dbh->prepare("SELECT 1, reporter, assigned_to, qa_contact,
476 477 478 479 480 481 482 483 484
                             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(" .
485
                               $self->groups_as_string .
486 487
                               ") WHERE bugs.bug_id = ? 
                               AND creation_ts IS NOT NULL " .
488 489 490
                             $dbh->sql_group_by('bugs.bug_id', 'reporter, ' .
                             'assigned_to, qa_contact, reporter_accessible, ' .
                             'cclist_accessible'));
491 492
    }
    $sth->execute($bugid);
493
    my ($ready, $reporter, $owner, $qacontact, $reporter_access, $cclist_access,
494
        $isoncclist, $missinggroup) = $sth->fetchrow_array();
495
    $sth->finish;
496
    $self->{sthCanSeeBug} = $sth;
497 498
    return ($ready
            && ((($reporter == $userid) && $reporter_access)
499 500
                || (Bugzilla->params->{'useqacontact'} 
                    && $qacontact && ($qacontact == $userid))
501 502 503
                || ($owner == $userid)
                || ($isoncclist && $cclist_access)
                || (!$missinggroup)));
504 505
}

506 507 508 509 510 511
sub can_see_product {
    my ($self, $product_name) = @_;

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

512
sub get_selectable_products {
513
    my $self = shift;
514
    my $classification_id = shift;
515

516 517
    if (defined $self->{selectable_products}) {
        return $self->{selectable_products};
518 519
    }

520
    my $dbh = Bugzilla->dbh;
521 522
    my @params = ();

523
    my $query = "SELECT id " .
524 525 526
                "FROM products " .
                "LEFT JOIN group_control_map " .
                "ON group_control_map.product_id = products.id ";
527
    if (Bugzilla->params->{'useentrygroupdefault'}) {
528 529 530 531 532 533
        $query .= "AND group_control_map.entry != 0 ";
    } else {
        $query .= "AND group_control_map.membercontrol = " .
                  CONTROLMAPMANDATORY . " ";
    }
    $query .= "AND group_id NOT IN(" . 
534
               $self->groups_as_string . ") " .
535 536
              "WHERE group_id IS NULL ";

537
    if (Bugzilla->params->{'useclassification'} && $classification_id) {
538 539 540 541
        $query .= "AND classification_id = ? ";
        detaint_natural($classification_id);
        push(@params, $classification_id);
    }
542

543 544 545
    $query .= "ORDER BY name";

    my $prod_ids = $dbh->selectcol_arrayref($query, undef, @params);
546
    $self->{selectable_products} = Bugzilla::Product->new_from_list($prod_ids);
547
    return $self->{selectable_products};
548 549
}

550
sub get_selectable_classifications {
551 552 553 554 555
    my ($self) = @_;

    if (defined $self->{selectable_classifications}) {
        return $self->{selectable_classifications};
    }
556 557 558 559 560

    my $products = $self->get_selectable_products;

    my $class;
    foreach my $product (@$products) {
561 562
        $class->{$product->classification_id} ||= 
            new Bugzilla::Classification($product->classification_id);
563
    }
564 565
    my @sorted_class = sort {$a->sortkey <=> $b->sortkey 
                             || lc($a->name) cmp lc($b->name)} (values %$class);
566
    $self->{selectable_classifications} = \@sorted_class;
567 568 569
    return $self->{selectable_classifications};
}

570 571 572 573 574
sub can_enter_product {
    my ($self, $product_name, $warn) = @_;
    my $dbh = Bugzilla->dbh;

    if (!defined($product_name)) {
575
        return unless $warn == THROW_ERROR;
576 577 578
        ThrowUserError('no_products');
    }
    trick_taint($product_name);
579 580
    my $can_enter =
        grep($_->name eq $product_name, @{$self->get_enterable_products});
581

582 583 584
    return 1 if $can_enter;

    return 0 unless $warn == THROW_ERROR;
585

586 587 588 589 590 591 592 593 594 595 596 597
    # Check why access was denied. These checks are slow,
    # but that's fine, because they only happen if we fail.

    my $product = new Bugzilla::Product({name => $product_name});

    # The product could not exist or you could be denied...
    if (!$product || !$product->user_has_access($self)) {
        ThrowUserError('entry_access_denied', {product => $product_name});
    }
    # It could be closed for bug entry...
    elsif ($product->disallow_new) {
        ThrowUserError('product_disabled', {product => $product->name});
598
    }
599 600 601 602 603 604 605 606 607 608
    # It could have no components...
    elsif (!@{$product->components}) {
        ThrowUserError('missing_component', {product => $product->name});
    }
    # It could have no versions...
    elsif (!@{$product->versions}) {
        ThrowUserError ('missing_version', {product => $product->name});
    }

    die "can_enter_product reached an unreachable location.";
609 610 611 612
}

sub get_enterable_products {
    my $self = shift;
613
    my $dbh = Bugzilla->dbh;
614 615 616 617 618

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

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
     # All products which the user has "Entry" access to.
     my @enterable_ids =@{$dbh->selectcol_arrayref(
           'SELECT products.id 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 group_id IS NULL
                  AND products.disallownew = 0') || []};

    if (@enterable_ids) {
        # And all of these products must have at least one component
        # and one version.
        @enterable_ids = @{$dbh->selectcol_arrayref(
               'SELECT DISTINCT products.id FROM products
            INNER JOIN components ON components.product_id = products.id
            INNER JOIN versions ON versions.product_id = products.id
                 WHERE products.id IN (' . (join(',', @enterable_ids)) .
            ')') || []};
638
    }
639 640 641

    $self->{enterable_products} =
         Bugzilla::Product->new_from_list(\@enterable_ids);
642 643 644
    return $self->{enterable_products};
}

645 646 647 648 649
# 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};
650
    return [] unless $self->id;
651
    my @visgroups = @{$self->visible_groups_direct};
652
    @visgroups = @{$self->flatten_group_membership(@visgroups)};
653 654 655 656 657 658 659 660 661 662
    $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};
663
    return [] unless $self->id;
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680

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

681 682 683 684 685
sub visible_groups_as_string {
    my $self = shift;
    return join(', ', @{$self->visible_groups_inherited()});
}

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
# This function defines the groups a user may share a query with.
# More restrictive sites may want to build this reference to a list of group IDs
# from bless_groups instead of mirroring visible_groups_inherited, perhaps.
sub queryshare_groups {
    my $self = shift;
    if ($self->in_group(Bugzilla->params->{'querysharegroup'})) {
        return $self->visible_groups_inherited();
    }
    else {
        return [];
    }
}

sub queryshare_groups_as_string {
    my $self = shift;
    return join(', ', @{$self->queryshare_groups()});
}

704 705
sub derive_regexp_groups {
    my ($self) = @_;
706 707

    my $id = $self->id;
708
    return unless $id;
709 710 711 712 713 714 715

    my $dbh = Bugzilla->dbh;

    my $sth;

    # add derived records for any matching regexps

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    $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;
737 738 739 740
        }
    }
}

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
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;
}

762 763 764
sub can_bless {
    my $self = shift;

765 766 767
    if (!scalar(@_)) {
        # If we're called without an argument, just return 
        # whether or not we can bless at all.
768
        return scalar(@{$self->bless_groups}) ? 1 : 0;
769 770
    }

771
    # Otherwise, we're checking a specific group
772 773
    my $group_id = shift;
    return (grep {$$_{'id'} eq $group_id} (@{$self->bless_groups})) ? 1 : 0;
774 775
}

776
sub flatten_group_membership {
777
    my ($self, @groups) = @_;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

    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;
            }
        }
    }
797
    return \@groups;
798 799
}

800 801
sub match {
    # Generates a list of users whose login name (email address) or real name
802
    # matches a substring or wildcard.
803 804
    # This is also called if matches are disabled (for error checking), but
    # in this case only the exact match code will end up running.
805

806
    # $str contains the string to match, while $limit contains the
807 808
    # maximum number of records to retrieve.
    my ($str, $limit, $exclude_disabled) = @_;
809 810
    my $user = Bugzilla->user;
    my $dbh = Bugzilla->dbh;
811

812
    my @users = ();
813 814
    return \@users if $str =~ /^\s*$/;

815
    # The search order is wildcards, then exact match, then substring search.
816 817 818 819 820 821 822
    # 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;

823 824 825 826
    if ($wildstr =~ s/\*/\%/g # don't do wildcards if no '*' in the string
        # or if we only want exact matches
        && Bugzilla->params->{'usermatchmode'} ne 'off') 
    {
827 828

        # Build the query.
829 830
        trick_taint($wildstr);
        my $query  = "SELECT DISTINCT login_name FROM profiles ";
831
        if (Bugzilla->params->{'usevisibilitygroups'}) {
832 833
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
834
        }
835 836 837
        $query .= "WHERE ("
            . $dbh->sql_istrcmp('login_name', '?', "LIKE") . " OR " .
              $dbh->sql_istrcmp('realname', '?', "LIKE") . ") ";
838
        if (Bugzilla->params->{'usevisibilitygroups'}) {
839
            $query .= "AND isbless = 0 " .
840
                      "AND group_id IN(" .
841
                      join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
842 843
        }
        $query    .= " AND disabledtext = '' " if $exclude_disabled;
844
        $query    .= " ORDER BY login_name ";
845
        $query    .= $dbh->sql_limit($limit) if $limit;
846 847 848

        # Execute the query, retrieve the results, and make them into
        # User objects.
849 850
        my $user_logins = $dbh->selectcol_arrayref($query, undef, ($wildstr, $wildstr));
        foreach my $login_name (@$user_logins) {
851
            push(@users, new Bugzilla::User({ name => $login_name }));
852
        }
853 854
    }
    else {    # try an exact match
855
        # Exact matches don't care if a user is disabled.
856 857 858 859
        trick_taint($str);
        my $user_id = $dbh->selectrow_array('SELECT userid FROM profiles
                                             WHERE ' . $dbh->sql_istrcmp('login_name', '?'),
                                             undef, $str);
860

861
        push(@users, new Bugzilla::User($user_id)) if $user_id;
862 863
    }

864
    # then try substring search
865
    if ((scalar(@users) == 0)
866
        && (Bugzilla->params->{'usermatchmode'} eq 'search')
867 868
        && (length($str) >= 3))
    {
869 870
        $str = lc($str);
        trick_taint($str);
871

872
        my $query   = "SELECT DISTINCT login_name FROM profiles ";
873
        if (Bugzilla->params->{'usevisibilitygroups'}) {
874 875
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
876
        }
877
        $query     .= " WHERE (" .
878 879
                $dbh->sql_position('?', 'LOWER(login_name)') . " > 0" . " OR " .
                $dbh->sql_position('?', 'LOWER(realname)') . " > 0) ";
880
        if (Bugzilla->params->{'usevisibilitygroups'}) {
881
            $query .= " AND isbless = 0" .
882
                      " AND group_id IN(" .
883
                join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
884
        }
885 886 887
        $query     .= " AND disabledtext = '' " if $exclude_disabled;
        $query    .= " ORDER BY login_name ";
        $query     .= $dbh->sql_limit($limit) if $limit;
888

889 890
        my $user_logins = $dbh->selectcol_arrayref($query, undef, ($str, $str));
        foreach my $login_name (@$user_logins) {
891
            push(@users, new Bugzilla::User({ name => $login_name }));
892 893
        }
    }
894 895 896
    return \@users;
}

897 898 899 900 901
# 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
902 903
# 2. Takes the values of those fields from the first parameter, a $cgi object 
#    and passes them to match()
904 905 906 907 908 909 910 911 912 913 914 915 916
# 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.
#
917 918 919 920 921
# 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.
#
922 923 924 925 926 927 928 929 930
# 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:
#
931
# Bugzilla::User::match_field($cgi, {
932 933 934 935 936 937 938 939 940
#   'field_name'    => { 'type' => fieldtype },
#   'field_name2'   => { 'type' => fieldtype },
#   [...]
# });
#
# fieldtype can be either 'single' or 'multi'.
#

sub match_field {
941 942
    my $cgi          = shift;   # CGI object to look up fields in
    my $fields       = shift;   # arguments as a hash
943
    my $behavior     = shift || 0; # A constant that tells us how to act
944 945 946
    my $matches      = {};      # the values sent to the template
    my $matchsuccess = 1;       # did the match fail?
    my $need_confirm = 0;       # whether to display confirmation screen
947
    my $match_multiple = 0;     # whether we ever matched more than one user
948

949 950
    my $params = Bugzilla->params;

951 952
    # prepare default form values

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

956 957 958 959 960 961 962 963 964 965 966 967
    # 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 {
968
            my @field_names = grep(/$field_pattern/, $cgi->param());
969 970 971 972
            foreach my $field_name (@field_names) {
                $expanded_fields->{$field_name} = 
                  { type => $fields->{$field_pattern}->{'type'} };
                
973 974 975
                # 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.
976
                if ($field_name =~ /^requestee-(\d+)$/) {
977 978
                    require Bugzilla::Flag;
                    my $flag = new Bugzilla::Flag($1);
979
                    $expanded_fields->{$field_name}->{'flag_type'} = 
980
                      $flag->type;
981 982
                }
                elsif ($field_name =~ /^requestee_type-(\d+)$/) {
983
                    require Bugzilla::FlagType;
984
                    $expanded_fields->{$field_name}->{'flag_type'} = 
985
                      new Bugzilla::FlagType($1);
986 987 988 989 990 991
                }
            }
        }
    }
    $fields = $expanded_fields;

992 993 994 995 996
    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
997
        # and it won't break if the CGI object does not know about them.
998 999 1000 1001
        #
        # It has the side-effect that if a bad field name is passed it will be
        # quietly ignored rather than raising a code error.

1002
        next if !defined $cgi->param($field);
1003

1004
        # Skip it if this is a --do_not_change-- field
1005
        next if $dontchange && $dontchange eq $cgi->param($field);
1006

1007
        # We need to move the query to $raw_field, where it will be split up,
1008
        # modified by the search, and put back into the CGI environment
1009 1010
        # incrementally.

1011 1012 1013
        my $raw_field = join(" ", $cgi->param($field));

        # When we add back in values later, it matters that we delete
1014
        # the field here, and not set it to '', so that we will add
1015
        # things to an empty list, and not to a list containing one
1016
        # empty string.
1017 1018
        # If the field accepts only one match (type eq "single") and
        # no match or more than one match is found for this field,
1019 1020
        # we will set it back to '' so that the field remains defined
        # outside this function (it was if we came here; else we would
1021 1022 1023
        # 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).
1024
        $cgi->delete($field);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

        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
1046 1047 1048 1049
            ThrowCodeError('bad_arg',
                           { argument => $fields->{$field}->{'type'},
                             function =>  'Bugzilla::User::match_field',
                           });
1050 1051
        }

1052
        my $limit = 0;
1053 1054
        if ($params->{'maxusermatches'}) {
            $limit = $params->{'maxusermatches'} + 1;
1055 1056
        }

1057 1058 1059
        for my $query (@queries) {

            my $users = match(
1060 1061 1062
                $query,   # match string
                $limit,   # match limit
                1         # exclude_disabled
1063 1064 1065 1066
            );

            # skip confirmation for exact matches
            if ((scalar(@{$users}) == 1)
1067
                && (lc(@{$users}[0]->{'login'}) eq lc($query)))
1068
            {
1069 1070 1071
                $cgi->append(-name=>$field,
                             -values=>[@{$users}[0]->{'login'}]);

1072 1073 1074
                next;
            }

1075 1076
            $matches->{$field}->{$query}->{'users'}  = $users;
            $matches->{$field}->{$query}->{'status'} = 'success';
1077 1078 1079

            # here is where it checks for multiple matches

1080
            if (scalar(@{$users}) == 1) { # exactly one match
1081 1082 1083 1084

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

1085
                $need_confirm = 1 if $params->{'confirmuniqueusermatch'};
1086 1087 1088

            }
            elsif ((scalar(@{$users}) > 1)
1089
                    && ($params->{'maxusermatches'} != 1)) {
1090
                $need_confirm = 1;
1091
                $match_multiple = 1;
1092

1093 1094
                if (($params->{'maxusermatches'})
                   && (scalar(@{$users}) > $params->{'maxusermatches'}))
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
                {
                    $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
            }
        }
1108
        # Above, we deleted the field before adding matches. If no match
1109 1110
        # or more than one match has been found for a field expecting only
        # one match (type eq "single"), we set it back to '' so
1111 1112
        # that the caller of this function can still check whether this
        # field was defined or not (and it was if we came here).
1113 1114 1115 1116
        if (!defined $cgi->param($field)
            && $fields->{$field}->{'type'} eq 'single') {
            $cgi->param($field, '');
        }
1117 1118
    }

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    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);
1132

1133 1134 1135
    my $template = Bugzilla->template;
    my $vars = {};

1136
    $vars->{'script'}        = Bugzilla->cgi->url(-relative => 1); # for self-referencing URLs
1137
    $vars->{'fields'}        = $fields; # fields being matched
1138 1139 1140
    $vars->{'matches'}       = $matches; # matches that were made
    $vars->{'matchsuccess'}  = $matchsuccess; # continue or fail

1141
    print Bugzilla->cgi->header();
1142

1143 1144
    $template->process("global/confirm-user-match.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
1145 1146 1147 1148 1149

    exit;

}

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
# 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,
1163
    'Attachment is patch'    => EVT_ATTACHMENT_DATA,
1164 1165
    'Depends on'             => EVT_DEPEND_BLOCK,
    'Blocks'                 => EVT_DEPEND_BLOCK);
1166 1167 1168 1169

# 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 {
1170
    my $self = shift;
1171 1172 1173 1174 1175 1176 1177
    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'};
1178
    
1179 1180 1181 1182
    # 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) {
1183
        my ($who, $whoname, $fieldName, $when, $old, $new) = @$ref;
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        # 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;
    }
1222
    
1223
    my @event_list = keys %events;
1224
    
1225 1226 1227 1228
    # XXX Temporary Compatibility Change 2 of 2:
    # See above comment.
    if (!scalar(@event_list)) {
      @event_list = (EVT_OTHER);
1229 1230
    }
    
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    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.
1248 1249 1250 1251
        my $bug_status = $dbh->selectrow_array('SELECT bug_status
                                                FROM bugs WHERE bug_id = ?',
                                                undef, $bug_id);

1252 1253
        if ($bug_status eq "UNCONFIRMED") {
            $wants_mail &= $self->wants_mail([EVT_UNCONFIRMED], $relationship);
1254 1255 1256
        }
    }
    
1257
    return $wants_mail;
1258 1259
}

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
# 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 = 
1282 1283 1284 1285 1286 1287 1288 1289
        $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));

1290
    return defined($wants_mail) ? 1 : 0;
1291
}
1292 1293 1294 1295 1296

sub is_mover {
    my $self = shift;

    if (!defined $self->{'is_mover'}) {
1297
        my @movers = map { trim($_) } split(',', Bugzilla->params->{'movers'});
1298 1299 1300 1301 1302 1303
        $self->{'is_mover'} = ($self->id
                               && lsearch(\@movers, $self->login) != -1);
    }
    return $self->{'is_mover'};
}

1304 1305 1306 1307 1308
sub get_userlist {
    my $self = shift;

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

1309
    my $dbh = Bugzilla->dbh;
1310
    my $query  = "SELECT DISTINCT login_name, realname,";
1311
    if (Bugzilla->params->{'usevisibilitygroups'}) {
1312 1313 1314 1315
        $query .= " COUNT(group_id) ";
    } else {
        $query .= " 1 ";
    }
1316
    $query     .= "FROM profiles ";
1317
    if (Bugzilla->params->{'usevisibilitygroups'}) {
1318 1319 1320
        $query .= "LEFT JOIN user_group_map " .
                  "ON user_group_map.user_id = userid AND isbless = 0 " .
                  "AND group_id IN(" .
1321
                  join(', ', (-1, @{$self->visible_groups_inherited})) . ")";
1322
    }
1323 1324
    $query    .= " WHERE disabledtext = '' ";
    $query    .= $dbh->sql_group_by('userid', 'login_name, realname');
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342

    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'};
}

1343 1344 1345
sub create {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
1346 1347
    my $dbh = Bugzilla->dbh;

1348 1349 1350
    $dbh->bz_lock_tables('profiles WRITE', 'profiles_activity WRITE',
        'user_group_map WRITE', 'email_setting WRITE', 'groups READ', 
        'tokens READ', 'fielddefs READ');
1351

1352
    my $user = $class->SUPER::create(@_);
1353

1354 1355 1356
    # Turn on all email for the new user
    foreach my $rel (RELATIONSHIPS) {
        foreach my $event (POS_EVENTS, NEG_EVENTS) {
1357 1358 1359 1360 1361 1362 1363
            # 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));

1364
            $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
1365
                      VALUES (?, ?, ?)', undef, ($user->id, $rel, $event));
1366
        }
1367 1368 1369
    }

    foreach my $event (GLOBAL_EVENTS) {
1370
        $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
1371
                  VALUES (?, ?, ?)', undef, ($user->id, REL_ANY, $event));
1372
    }
1373 1374 1375

    $user->derive_regexp_groups();

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    # Add the creation date to the profiles_activity table.
    # $who is the user who created the new user account, i.e. either an
    # admin or the new user himself.
    my $who = Bugzilla->user->id || $user->id;
    my $creation_date_fieldid = get_field_id('creation_ts');

    $dbh->do('INSERT INTO profiles_activity
                          (userid, who, profiles_when, fieldid, newvalue)
                   VALUES (?, ?, NOW(), ?, NOW())',
                   undef, ($user->id, $who, $creation_date_fieldid));

1387 1388
    $dbh->bz_unlock_tables();

1389 1390
    # Return the newly created user account.
    return $user;
1391 1392
}

1393
sub is_available_username {
1394 1395
    my ($username, $old_username) = @_;

1396
    if(login_to_id($username) != 0) {
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        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
1408
    # the new/old email addresses and sql_position() to find the delimiter (':')
1409
    # is cleaner/safer
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    my $eventdata = $dbh->selectrow_array(
        "SELECT eventdata
           FROM tokens
          WHERE (tokentype = 'emailold'
                AND SUBSTRING(eventdata, 1, (" .
                    $dbh->sql_position(q{':'}, 'eventdata') . "-  1)) = ?)
             OR (tokentype = 'emailnew'
                AND SUBSTRING(eventdata, (" .
                    $dbh->sql_position(q{':'}, 'eventdata') . "+ 1)) = ?)",
         undef, ($username, $username));

    if ($eventdata) {
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        # Allow thru owner of token
        if($old_username && ($eventdata eq "$old_username:$username")) {
            return 1;
        }
        return 0;
    }

    return 1;
}

1432
sub login_to_id {
1433
    my ($login, $throw_error) = @_;
1434
    my $dbh = Bugzilla->dbh;
1435 1436
    # $login will only be used by the following SELECT statement, so it's safe.
    trick_taint($login);
1437 1438 1439
    my $user_id = $dbh->selectrow_array("SELECT userid FROM profiles WHERE " .
                                        $dbh->sql_istrcmp('login_name', '?'),
                                        undef, $login);
1440
    if ($user_id) {
1441
        return $user_id;
1442 1443
    } elsif ($throw_error) {
        ThrowUserError('invalid_username', { name => $login });
1444 1445 1446 1447 1448
    } else {
        return 0;
    }
}

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
sub user_id_to_login {
    my $user_id = shift;
    my $dbh = Bugzilla->dbh;

    return '' unless ($user_id && detaint_natural($user_id));

    my $login = $dbh->selectrow_array('SELECT login_name FROM profiles
                                       WHERE userid = ?', undef, $user_id);
    return $login || '';
}

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
sub validate_password {
    my ($password, $matchpassword) = @_;

    if (length($password) < USER_PASSWORD_MIN_LENGTH) {
        ThrowUserError('password_too_short');
    } elsif (length($password) > USER_PASSWORD_MAX_LENGTH) {
        ThrowUserError('password_too_long');
    } elsif ((defined $matchpassword) && ($password ne $matchpassword)) {
        ThrowUserError('passwords_dont_match');
    }
    return 1;
}

1473

1474
1;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

__END__

=head1 NAME

Bugzilla::User - Object for a Bugzilla user

=head1 SYNOPSIS

  use Bugzilla::User;

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

1488 1489 1490
  my @get_selectable_classifications = 
      $user->get_selectable_classifications;

1491
  # Class Functions
1492 1493 1494 1495 1496 1497
  $user = Bugzilla::User->create({ 
      login_name    => $username, 
      realname      => $realname, 
      cryptpassword => $plaintext_password, 
      disabledtext  => $disabledtext,
      disable_mail  => 0});
1498

1499 1500 1501 1502 1503 1504 1505 1506
=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">.

1507 1508 1509 1510
C<Bugzilla::User> is an implementation of L<Bugzilla::Object>, and thus
provides all the methods of L<Bugzilla::Object> in addition to the
methods listed below.

1511 1512
=head1 CONSTANTS

1513 1514
=over

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
=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.

1535 1536
=back

1537 1538
=head1 METHODS

1539
=over
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564

=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>

1565
Returns a string for the identity of the user. This will be of the form
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
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.

1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
=item C<authorizer>

This is the L<Bugzilla::Auth> object that the User logged in with.
If the user hasn't logged in yet, a new, empty Bugzilla::Auth() object is
returned.

=item C<set_authorizer($authorizer)>

Sets the L<Bugzilla::Auth> object to be returned by C<authorizer()>.
Should only be called by C<Bugzilla::Auth::login>, for the most part.

1587 1588 1589
=item C<queries>

Returns an array of the user's named queries, sorted in a case-insensitive
1590
order by name. Each entry is a hash with five keys:
1591 1592 1593 1594 1595

=over

=item *

1596 1597 1598 1599 1600 1601 1602 1603
id - The ID of the query

=item *

userid - The query owner's user ID

=item *

1604 1605 1606 1607 1608 1609 1610 1611
name - The name of the query

=item *

query - The text for the query

=item *

1612
link_in_footer - Whether or not the query should be displayed in the footer.
1613 1614 1615

=back

1616 1617 1618 1619
=item C<disabledtext>

Returns the disable text of the user, if any.

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
=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.

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
=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
1645
obtained by C<values(%{$user-E<gt>groups})>.)
1646

1647 1648 1649 1650 1651 1652
=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.

1653 1654
=item C<in_group>

1655 1656 1657 1658 1659
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. 
1660

1661 1662
=item C<bless_groups>

1663 1664 1665 1666 1667 1668
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.
1669

1670 1671 1672 1673 1674
=item C<can_see_user(user)>

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

1675 1676 1677 1678 1679
=item C<can_edit_product(prod_id)>

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

1680 1681 1682 1683
=item C<can_see_bug(bug_id)>

Determines if the user can see the specified bug.

1684 1685 1686 1687 1688
=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.

1689
=item C<derive_regexp_groups>
1690 1691 1692 1693 1694 1695 1696

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.

1697 1698
=item C<get_selectable_products>

1699 1700 1701
 Description: Returns all products the user is allowed to access. This list
              is restricted to some given classification if $classification_id
              is given.
1702

1703 1704
 Params:      $classification_id - (optional) The ID of the classification
                                   the products belong to.
1705

1706
 Returns:     An array of product objects, sorted by the product name.
1707

1708 1709
=item C<get_selectable_classifications>

1710 1711
 Description: Returns all classifications containing at least one product
              the user is allowed to view.
1712

1713
 Params:      none
1714

1715 1716
 Returns:     An array of Bugzilla::Classification objects, sorted by
              the classification name.
1717

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
=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.

1744 1745 1746 1747 1748 1749
=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.

1750 1751 1752 1753 1754 1755 1756 1757
=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.

1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
=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.

1768 1769 1770 1771 1772
=item C<visible_groups_as_string>

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

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
=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

1799 1800
=item C<can_bless>

1801 1802 1803 1804
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:
1805
Returns C<1> if the user can bless the group with that id, returns
1806
C<0> otherwise.
1807

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
=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.

1818 1819 1820 1821 1822 1823
=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.

1824 1825
=back

1826 1827 1828 1829 1830
=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.

1831 1832
=over 4

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
=item C<create>

The same as L<Bugzilla::Object/create>.

Params: login_name - B<Required> The login name for the new user.
        realname - The full name for the new user.
        cryptpassword  - B<Required> The password for the new user.
            Even though the name says "crypt", you should just specify
            a plain-text password. If you specify '*', the user will not
            be able to log in using DB authentication.
        disabledtext - The disable-text for the new user. If given, the user 
            will be disabled, meaning he cannot log in. Defaults to an
            empty string.
        disable_mail - If 1, bug-related mail will not be  sent to this user; 
            if 0, mail will be sent depending on the user's  email preferences.
1848

1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
=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).

1862
=item C<login_to_id($login, $throw_error)>
1863 1864 1865 1866 1867

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.

1868 1869 1870
If no valid user exists with that login name, then the function returns 0.
However, if $throw_error is set, the function will throw a user error
instead of returning.
1871 1872 1873 1874 1875 1876 1877

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.

1878 1879 1880 1881 1882 1883
=item C<user_id_to_login($user_id)>

Returns the login name of the user account for the given user ID. If no
valid user ID is given or the user has no entry in the profiles table,
we return an empty string.

1884 1885 1886 1887 1888 1889 1890 1891
=item C<validate_password($passwd1, $passwd2)>

Returns true if a password is valid (i.e. meets Bugzilla's
requirements for length and content), else returns false.

If a second password is passed in, this function also verifies that
the two passwords match.

1892 1893
=back

1894 1895 1896
=head1 SEE ALSO

L<Bugzilla|Bugzilla>