User.pm 76.8 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
#                 Mads Bondo Dydensborg <mbd@dbc.dk>
33 34 35 36 37 38 39 40 41 42 43

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

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

53
use DateTime::TimeZone;
54 55
use Scalar::Util qw(blessed);
use Storable qw(dclone);
56

57
use base qw(Bugzilla::Object Exporter);
58
@Bugzilla::User::EXPORT = qw(is_available_username
59
    login_to_id user_id_to_login validate_password
60 61
    USER_MATCH_MULTIPLE USER_MATCH_FAILED USER_MATCH_SUCCESS
    MATCH_SKIP_CONFIRM
62
);
63

64 65 66 67 68 69 70 71 72 73
#####################################################################
# 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;

74
use constant DEFAULT_USER => {
75
    'userid'         => 0,
76 77
    'realname'       => '',
    'login_name'     => '',
78 79 80 81 82 83 84 85 86 87 88 89
    '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 => (
90
    'profiles.userid',
91 92
    'profiles.login_name',
    'profiles.realname',
93 94 95 96 97 98
    'profiles.mybugslink AS showmybugslink',
    'profiles.disabledtext',
    'profiles.disable_mail',
);
use constant NAME_FIELD => 'login_name';
use constant ID_FIELD   => 'userid';
99
use constant LIST_ORDER => NAME_FIELD;
100

101 102 103 104 105 106 107 108 109 110
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,
};

111 112 113 114 115 116 117 118 119 120 121 122
sub UPDATE_COLUMNS {
    my $self = shift;
    my @cols = qw(
        disable_mail
        disabledtext
        login_name
        realname
    );
    push(@cols, 'cryptpassword') if exists $self->{cryptpassword};
    return @cols;
};

123 124 125 126 127 128 129
################################################################################
# Functions
################################################################################

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

132 133 134
    my $user = DEFAULT_USER;
    bless ($user, $class);
    return $user unless $param;
135

136
    return $class->SUPER::new(@_);
137 138
}

139 140 141 142 143 144 145 146 147 148 149 150
sub super_user {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my ($param) = @_;

    my $user = dclone(DEFAULT_USER);
    $user->{groups} = [Bugzilla::Group->get_all];
    $user->{bless_groups} = [Bugzilla::Group->get_all];
    bless $user, $class;
    return $user;
}

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
sub update {
    my $self = shift;
    my $changes = $self->SUPER::update(@_);
    my $dbh = Bugzilla->dbh;

    if (exists $changes->{login_name}) {
        # If we changed the login, silently delete any tokens.
        $dbh->do('DELETE FROM tokens WHERE userid = ?', undef, $self->id);
        # And rederive regex groups
        $self->derive_regexp_groups();
    }

    # Logout the user if necessary.
    Bugzilla->logout_user($self) 
        if (exists $changes->{login_name} || exists $changes->{disabledtext}
            || exists $changes->{cryptpassword});

    # XXX Can update profiles_activity here as soon as it understands
    #     field names like login_name.

    return $changes;
}

174 175 176 177
################################################################################
# Validators
################################################################################

178 179
sub _check_disable_mail { return $_[1] ? 1 : 0; }
sub _check_disabledtext { return trim($_[1]) || ''; }
180 181 182 183

# This is public since createaccount.cgi needs to use it before issuing
# a token for account creation.
sub check_login_name_for_creation {
184
    my ($invocant, $name) = @_;
185 186 187 188
    $name = trim($name);
    $name || ThrowUserError('user_login_required');
    validate_email_syntax($name)
        || ThrowUserError('illegal_email_address', { addr => $name });
189 190 191 192 193 194 195

    # Check the name if it's a new user, or if we're changing the name.
    if (!ref($invocant) || $invocant->login ne $name) {
        is_available_username($name) 
            || ThrowUserError('account_exists', { email => $name });
    }

196 197 198 199
    return $name;
}

sub _check_password {
200
    my ($self, $pass) = @_;
201 202 203 204 205 206 207 208 209 210 211

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

212
sub _check_realname { return trim($_[1]) || ''; }
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
################################################################################
# Mutators
################################################################################

sub set_disabledtext { $_[0]->set('disabledtext', $_[1]); }
sub set_disable_mail { $_[0]->set('disable_mail', $_[1]); }

sub set_login {
    my ($self, $login) = @_;
    $self->set('login_name', $login);
    delete $self->{identity};
    delete $self->{nick};
}

sub set_name {
    my ($self, $name) = @_;
    $self->set('realname', $name);
    delete $self->{identity};
}

sub set_password { $_[0]->set('cryptpassword', $_[1]); }


237 238 239 240
################################################################################
# Methods
################################################################################

241
# Accessors for user attributes
242 243 244
sub name  { $_[0]->{realname};   }
sub login { $_[0]->{login_name}; }
sub email { $_[0]->login . Bugzilla->params->{'emailsuffix'}; }
245 246
sub disabledtext { $_[0]->{'disabledtext'}; }
sub is_disabled { $_[0]->disabledtext ? 1 : 0; }
247
sub showmybugslink { $_[0]->{showmybugslink}; }
248 249
sub email_disabled { $_[0]->{disable_mail}; }
sub email_enabled { !($_[0]->{disable_mail}); }
250 251 252 253 254 255 256 257 258
sub cryptpassword {
    my $self = shift;
    # We don't store it because we never want it in the object (we
    # don't want to accidentally dump even the hash somewhere).
    my ($pw) = Bugzilla->dbh->selectrow_array(
        'SELECT cryptpassword FROM profiles WHERE userid = ?',
        undef, $self->id);
    return $pw;
}
259

260 261 262
sub set_authorizer {
    my ($self, $authorizer) = @_;
    $self->{authorizer} = $authorizer;
263
}
264 265 266 267 268 269 270
sub authorizer {
    my ($self) = @_;
    if (!$self->{authorizer}) {
        require Bugzilla::Auth;
        $self->{authorizer} = new Bugzilla::Auth();
    }
    return $self->{authorizer};
271 272
}

273 274
# Generate a string to identify the user by name + login if the user
# has a name or by login only if she doesn't.
275 276 277
sub identity {
    my $self = shift;

278 279
    return "" unless $self->id;

280 281
    if (!defined $self->{identity}) {
        $self->{identity} = 
282
          $self->name ? $self->name . " <" . $self->login. ">" : $self->login;
283 284 285 286 287 288 289 290
    }

    return $self->{identity};
}

sub nick {
    my $self = shift;

291 292
    return "" unless $self->id;

293
    if (!defined $self->{nick}) {
294
        $self->{nick} = (split(/@/, $self->login, 2))[0];
295 296 297 298 299 300 301 302
    }

    return $self->{nick};
}

sub queries {
    my $self = shift;
    return $self->{queries} if defined $self->{queries};
303
    return [] unless $self->id;
304 305

    my $dbh = Bugzilla->dbh;
306 307 308 309
    my $query_ids = $dbh->selectcol_arrayref(
        'SELECT id FROM namedqueries WHERE userid = ?', undef, $self->id);
    require Bugzilla::Search::Saved;
    $self->{queries} = Bugzilla::Search::Saved->new_from_list($query_ids);
310 311 312 313 314

    # We preload link_in_footer from here as this information is always requested.
    # This only works if the user object represents the current logged in user.
    Bugzilla::Search::Saved::preload($self->{queries}) if $self->id == Bugzilla->user->id;

315 316
    return $self->{queries};
}
317

318 319 320 321
sub queries_subscribed {
    my $self = shift;
    return $self->{queries_subscribed} if defined $self->{queries_subscribed};
    return [] unless $self->id;
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336
    # Exclude the user's own queries.
    my @my_query_ids = map($_->id, @{$self->queries});
    my $query_id_string = join(',', @my_query_ids) || '-1';

    # Only show subscriptions that we can still actually see. If a
    # user changes the shared group of a query, our subscription
    # will remain but we won't have access to the query anymore.
    my $subscribed_query_ids = Bugzilla->dbh->selectcol_arrayref(
        "SELECT lif.namedquery_id
           FROM namedqueries_link_in_footer lif
                INNER JOIN namedquery_group_map ngm
                ON ngm.namedquery_id = lif.namedquery_id
          WHERE lif.user_id = ? 
                AND lif.namedquery_id NOT IN ($query_id_string)
337
                AND " . $self->groups_in_sql,
338 339 340 341 342 343
          undef, $self->id);
    require Bugzilla::Search::Saved;
    $self->{queries_subscribed} =
        Bugzilla::Search::Saved->new_from_list($subscribed_query_ids);
    return $self->{queries_subscribed};
}
344

345 346 347 348 349 350 351 352 353 354 355
sub queries_available {
    my $self = shift;
    return $self->{queries_available} if defined $self->{queries_available};
    return [] unless $self->id;

    # Exclude the user's own queries.
    my @my_query_ids = map($_->id, @{$self->queries});
    my $query_id_string = join(',', @my_query_ids) || '-1';

    my $avail_query_ids = Bugzilla->dbh->selectcol_arrayref(
        'SELECT namedquery_id FROM namedquery_group_map
356
          WHERE '  . $self->groups_in_sql . "
357 358 359 360 361
                AND namedquery_id NOT IN ($query_id_string)");
    require Bugzilla::Search::Saved;
    $self->{queries_available} =
        Bugzilla::Search::Saved->new_from_list($avail_query_ids);
    return $self->{queries_available};
362 363
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
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'};
}

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
sub timezone {
    my $self = shift;

    if (!defined $self->{timezone}) {
        my $tz = $self->settings->{timezone}->{value};
        if ($tz eq 'local') {
            # The user wants the local timezone of the server.
            $self->{timezone} = Bugzilla->local_timezone;
        }
        else {
            $self->{timezone} = DateTime::TimeZone->new(name => $tz);
        }
    }
    return $self->{timezone};
}

397 398 399 400
sub flush_queries_cache {
    my $self = shift;

    delete $self->{queries};
401 402
    delete $self->{queries_subscribed};
    delete $self->{queries_available};
403 404 405 406 407 408
}

sub groups {
    my $self = shift;

    return $self->{groups} if defined $self->{groups};
409
    return [] unless $self->id;
410 411

    my $dbh = Bugzilla->dbh;
412 413 414 415 416
    my $groups_to_check = $dbh->selectcol_arrayref(
        q{SELECT DISTINCT group_id
            FROM user_group_map
           WHERE user_id = ? AND isbless = 0}, undef, $self->id);

417
    my $rows = $dbh->selectall_arrayref(
418 419 420 421 422
        "SELECT DISTINCT grantor_id, member_id
           FROM group_group_map
          WHERE grant_type = " . GROUP_MEMBERSHIP);

    my %group_membership;
423
    foreach my $row (@$rows) {
424 425
        my ($grantor_id, $member_id) = @$row; 
        push (@{ $group_membership{$member_id} }, $grantor_id);
426 427 428 429 430 431
    }
    
    # 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
432
    # $checked_groups{$member_id} hash values.
433
    # As a result, %groups will have all the groups we are the member of.
434 435 436
    my %checked_groups;
    my %groups;
    while (scalar(@$groups_to_check) > 0) {
437
        # Pop the head group from FIFO
438
        my $member_id = shift @$groups_to_check;
439 440
        
        # Skip the group if we have already checked it
441
        if (!$checked_groups{$member_id}) {
442
            # Mark group as checked
443
            $checked_groups{$member_id} = 1;
444 445 446 447
            
            # Add all its members to the FIFO check list
            # %group_membership contains arrays of group members 
            # for all groups. Accessible by group number.
448 449 450 451 452
            my $members = $group_membership{$member_id};
            my @new_to_check = grep(!$checked_groups{$_}, @$members);
            push(@$groups_to_check, @new_to_check);

            $groups{$member_id} = 1;
453 454
        }
    }
455 456

    $self->{groups} = Bugzilla::Group->new_from_list([keys %groups]);
457 458 459 460

    return $self->{groups};
}

461 462
sub groups_as_string {
    my $self = shift;
463 464
    my @ids = map { $_->id } @{ $self->groups };
    return scalar(@ids) ? join(',', @ids) : '-1';
465 466
}

467 468 469 470 471 472 473 474
sub groups_in_sql {
    my ($self, $field) = @_;
    $field ||= 'group_id';
    my @ids = map { $_->id } @{ $self->groups };
    @ids = (-1) if !scalar @ids;
    return Bugzilla->dbh->sql_in($field, \@ids);
}

475 476 477
sub bless_groups {
    my $self = shift;

478
    return $self->{'bless_groups'} if defined $self->{'bless_groups'};
479
    return [] unless $self->id;
480

481 482
    if ($self->in_group('editusers')) {
        # Users having editusers permissions may bless all groups.
483 484
        $self->{'bless_groups'} = [Bugzilla::Group->get_all];
        return $self->{'bless_groups'};
485
    }
486

487 488 489 490 491
    my $dbh = Bugzilla->dbh;

    # Get all groups for the user where:
    #    + They have direct bless privileges
    #    + They are a member of a group that inherits bless privs.
492 493
    my @group_ids = map {$_->id} @{ $self->groups };
    @group_ids = (-1) if !@group_ids;
494 495 496 497 498 499 500 501
    my $query =
        'SELECT DISTINCT groups.id
           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 = ' . GROUP_BLESS . '
502
                         AND ' . $dbh->sql_in('ggm.member_id', \@group_ids)
503 504
                     . ') )';

505
    # If visibilitygroups are used, restrict the set of groups.
506 507
    if (Bugzilla->params->{'usevisibilitygroups'}) {
        return [] if !$self->visible_groups_as_string;
508
        # Users need to see a group in order to bless it.
509 510
        $query .= " AND "
            . $dbh->sql_in('groups.id', $self->visible_groups_inherited);
511 512
    }

513 514
    my $ids = $dbh->selectcol_arrayref($query, undef, $self->id);
    return $self->{'bless_groups'} = Bugzilla::Group->new_from_list($ids);
515 516
}

517
sub in_group {
518
    my ($self, $group, $product_id) = @_;
519
    $group = $group->name if blessed $group;
520
    if (scalar grep($_->name eq $group, @{ $self->groups })) {
521 522 523 524 525 526 527 528 529 530 531 532 533 534
        return 1;
    }
    elsif ($product_id && detaint_natural($product_id)) {
        # Make sure $group exists on a per-product basis.
        return 0 unless (grep {$_ eq $group} PER_PRODUCT_PRIVILEGES);

        $self->{"product_$product_id"} = {} unless exists $self->{"product_$product_id"};
        if (!defined $self->{"product_$product_id"}->{$group}) {
            my $dbh = Bugzilla->dbh;
            my $in_group = $dbh->selectrow_array(
                           "SELECT 1
                              FROM group_control_map
                             WHERE product_id = ?
                                   AND $group != 0
535
                                   AND " . $self->groups_in_sql . ' ' .
536 537 538 539 540 541 542 543 544
                              $dbh->sql_limit(1),
                             undef, $product_id);

            $self->{"product_$product_id"}->{$group} = $in_group ? 1 : 0;
        }
        return $self->{"product_$product_id"}->{$group};
    }
    # If we come here, then the user is not in the requested group.
    return 0;
545
}
546

547 548
sub in_group_id {
    my ($self, $id) = @_;
549
    return grep($_->id == $id, @{ $self->groups }) ? 1 : 0;
550 551
}

552 553 554 555 556 557 558 559 560
sub get_products_by_permission {
    my ($self, $group) = @_;
    # Make sure $group exists on a per-product basis.
    return [] unless (grep {$_ eq $group} PER_PRODUCT_PRIVILEGES);

    my $product_ids = Bugzilla->dbh->selectcol_arrayref(
                          "SELECT DISTINCT product_id
                             FROM group_control_map
                            WHERE $group != 0
561
                              AND " . $self->groups_in_sql);
562 563 564 565 566 567 568 569 570 571

    # No need to go further if the user has no "special" privs.
    return [] unless scalar(@$product_ids);

    # We will restrict the list to products the user can see.
    my $selectable_products = $self->get_selectable_products;
    my @products = grep {lsearch($product_ids, $_->id) > -1} @$selectable_products;
    return \@products;
}

572 573 574 575
sub can_see_user {
    my ($self, $otherUser) = @_;
    my $query;

576
    if (Bugzilla->params->{'usevisibilitygroups'}) {
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        # 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);
}

595 596 597
sub can_edit_product {
    my ($self, $prod_id) = @_;
    my $dbh = Bugzilla->dbh;
598 599 600 601 602 603 604 605 606 607

    my $has_external_groups =
      $dbh->selectrow_array('SELECT 1
                               FROM group_control_map
                              WHERE product_id = ?
                                AND canedit != 0
                                AND group_id NOT IN(' . $self->groups_as_string . ')',
                             undef, $prod_id);

    return !$has_external_groups;
608 609
}

610
sub can_see_bug {
611 612 613 614 615 616 617 618 619 620 621
    my ($self, $bug_id) = @_;
    return @{ $self->visible_bugs([$bug_id]) } ? 1 : 0;
}

sub visible_bugs {
    my ($self, $bugs) = @_;
    # Allow users to pass in Bug objects and bug ids both.
    my @bug_ids = map { blessed $_ ? $_->id : $_ } @$bugs;

    # We only check the visibility of bugs that we haven't
    # checked yet.
622 623
    # Bugzilla::Bug->update automatically removes updated bugs
    # from the cache to force them to be checked again.
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    my $visible_cache = $self->{_visible_bugs_cache} ||= {};
    my @check_ids = grep(!exists $visible_cache->{$_}, @bug_ids);

    if (@check_ids) {
        my $dbh = Bugzilla->dbh;
        my $user_id = $self->id;
        my $sth;
        # Speed up the can_see_bug case.
        if (scalar(@check_ids) == 1) {
            $sth = $self->{_sth_one_visible_bug};
        }
        $sth ||= $dbh->prepare(
            # This checks for groups that the bug is in that the user
            # *isn't* in. Then, in the Perl code below, we check if
            # the user can otherwise access the bug (for example, by being
            # the assignee or QA Contact).
            #
            # The DISTINCT exists because the bug could be in *several*
            # groups that the user isn't in, but they will all return the
            # same result for bug_group_map.bug_id (so DISTINCT filters
            # out duplicate rows).
            "SELECT DISTINCT bugs.bug_id, reporter, assigned_to, qa_contact,
                    reporter_accessible, cclist_accessible, cc.who,
                    bug_group_map.bug_id
               FROM bugs
                    LEFT JOIN cc
                              ON cc.bug_id = bugs.bug_id
                                 AND cc.who = $user_id
                    LEFT JOIN bug_group_map 
                              ON bugs.bug_id = bug_group_map.bug_id
                                 AND bug_group_map.group_id NOT IN ("
                                     . $self->groups_as_string . ')
              WHERE bugs.bug_id IN (' . join(',', ('?') x @check_ids) . ')
                    AND creation_ts IS NOT NULL ');
        if (scalar(@check_ids) == 1) {
            $self->{_sth_one_visible_bug} = $sth;
        }

        $sth->execute(@check_ids);
663
        my $use_qa_contact = Bugzilla->params->{'useqacontact'};
664 665 666 667 668
        while (my $row = $sth->fetchrow_arrayref) {
            my ($bug_id, $reporter, $owner, $qacontact, $reporter_access, 
                $cclist_access, $isoncclist, $missinggroup) = @$row;
            $visible_cache->{$bug_id} ||= 
                ((($reporter == $user_id) && $reporter_access)
669
                 || ($use_qa_contact
670 671 672 673 674
                     && $qacontact && ($qacontact == $user_id))
                 || ($owner == $user_id)
                 || ($isoncclist && $cclist_access)
                 || !$missinggroup) ? 1 : 0;
        }
675
    }
676 677

    return [grep { $visible_cache->{blessed $_ ? $_->id : $_} } @$bugs];
678 679
}

680 681 682 683 684 685 686
sub clear_product_cache {
    my $self = shift;
    delete $self->{enterable_products};
    delete $self->{selectable_products};
    delete $self->{selectable_classifications};
}

687 688 689 690 691 692
sub can_see_product {
    my ($self, $product_name) = @_;

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

693
sub get_selectable_products {
694
    my $self = shift;
695 696 697 698 699 700 701
    my $class_id = shift;
    my $class_restricted = Bugzilla->params->{'useclassification'} && $class_id;

    if (!defined $self->{selectable_products}) {
        my $query = "SELECT id " .
                    "  FROM products " .
                 "LEFT JOIN group_control_map " .
702 703 704
                        "ON group_control_map.product_id = products.id " .
                      " AND group_control_map.membercontrol = " . CONTROLMAPMANDATORY .
                      " AND group_id NOT IN(" . $self->groups_as_string . ") " .
705 706
                  "   WHERE group_id IS NULL " .
                  "ORDER BY name";
707

708 709
        my $prod_ids = Bugzilla->dbh->selectcol_arrayref($query);
        $self->{selectable_products} = Bugzilla::Product->new_from_list($prod_ids);
710 711
    }

712 713 714
    # Restrict the list of products to those being in the classification, if any.
    if ($class_restricted) {
        return [grep {$_->classification_id == $class_id} @{$self->{selectable_products}}];
715
    }
716
    # If we come here, then we want all selectable products.
717
    return $self->{selectable_products};
718 719
}

720
sub get_selectable_classifications {
721 722
    my ($self) = @_;

723 724 725
    if (!defined $self->{selectable_classifications}) {
        my $products = $self->get_selectable_products;
        my %class_ids = map { $_->classification_id => 1 } @$products;
726

727
        $self->{selectable_classifications} = Bugzilla::Classification->new_from_list([keys %class_ids]);
728 729 730 731
    }
    return $self->{selectable_classifications};
}

732
sub can_enter_product {
733
    my ($self, $input, $warn) = @_;
734
    my $dbh = Bugzilla->dbh;
735
    $warn ||= 0;
736

737 738 739 740 741 742 743 744
    $input = trim($input) if !ref $input;
    if (!defined $input or $input eq '') {
        return unless $warn == THROW_ERROR;
        ThrowUserError('object_not_specified',
                       { class => 'Bugzilla::Product' });
    }

    if (!scalar @{ $self->get_enterable_products }) {
745
        return unless $warn == THROW_ERROR;
746 747
        ThrowUserError('no_products');
    }
748

749 750
    my $product = blessed($input) ? $input 
                                  : new Bugzilla::Product({ name => $input });
751
    my $can_enter =
752 753
      $product && grep($_->name eq $product->name,
                       @{ $self->get_enterable_products });
754

755 756 757
    return 1 if $can_enter;

    return 0 unless $warn == THROW_ERROR;
758

759 760 761
    # Check why access was denied. These checks are slow,
    # but that's fine, because they only happen if we fail.

762 763 764 765 766
    # We don't just use $product->name for error messages, because if it
    # changes case from $input, then that's a clue that the product does
    # exist but is hidden.
    my $name = blessed($input) ? $input->name : $input;

767 768
    # The product could not exist or you could be denied...
    if (!$product || !$product->user_has_access($self)) {
769
        ThrowUserError('entry_access_denied', { product => $name });
770 771
    }
    # It could be closed for bug entry...
772
    elsif (!$product->is_active) {
773
        ThrowUserError('product_disabled', { product => $product });
774
    }
775 776
    # It could have no components...
    elsif (!@{$product->components}) {
777
        ThrowUserError('missing_component', { product => $product });
778 779 780
    }
    # It could have no versions...
    elsif (!@{$product->versions}) {
781
        ThrowUserError ('missing_version', { product => $product });
782 783 784
    }

    die "can_enter_product reached an unreachable location.";
785 786 787 788
}

sub get_enterable_products {
    my $self = shift;
789
    my $dbh = Bugzilla->dbh;
790 791 792 793 794

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

795 796 797 798 799 800 801 802
     # 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
803
                  AND products.isactive = 1') || []};
804 805 806 807 808 809 810 811 812 813

    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)) .
            ')') || []};
814
    }
815 816 817

    $self->{enterable_products} =
         Bugzilla::Product->new_from_list(\@enterable_ids);
818 819 820
    return $self->{enterable_products};
}

821
sub can_access_product {
822 823
    my ($self, $product) = @_;
    my $product_name = blessed($product) ? $product->name : $product;
824 825 826
    return scalar(grep {$_->name eq $product_name} @{$self->get_accessible_products});
}

827 828 829 830 831 832 833 834 835 836 837
sub get_accessible_products {
    my $self = shift;
    
    # Map the objects into a hash using the ids as keys
    my %products = map { $_->id => $_ }
                       @{$self->get_selectable_products},
                       @{$self->get_enterable_products};
    
    return [ values %products ];
}

838 839 840 841 842 843 844 845
sub check_can_admin_product {
    my ($self, $product_name) = @_;

    # First make sure the product name is valid.
    my $product = Bugzilla::Product::check_product($product_name);

    ($self->in_group('editcomponents', $product->id)
       && $self->can_see_product($product->name))
846
         || ThrowUserError('product_admin_denied', {product => $product->name});
847 848 849 850 851

    # Return the validated product object.
    return $product;
}

852 853 854 855
sub can_request_flag {
    my ($self, $flag_type) = @_;

    return ($self->can_set_flag($flag_type)
856 857
            || !$flag_type->request_group_id
            || $self->in_group_id($flag_type->request_group_id)) ? 1 : 0;
858 859 860 861 862
}

sub can_set_flag {
    my ($self, $flag_type) = @_;

863 864
    return (!$flag_type->grant_group_id
            || $self->in_group_id($flag_type->grant_group_id)) ? 1 : 0;
865 866
}

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
sub direct_group_membership {
    my $self = shift;
    my $dbh = Bugzilla->dbh;

    if (!$self->{'direct_group_membership'}) {
        my $gid = $dbh->selectcol_arrayref('SELECT id
                                              FROM groups
                                        INNER JOIN user_group_map
                                                ON groups.id = user_group_map.group_id
                                             WHERE user_id = ?
                                               AND isbless = 0',
                                             undef, $self->id);
        $self->{'direct_group_membership'} = Bugzilla::Group->new_from_list($gid);
    }
    return $self->{'direct_group_membership'};
}


885 886 887 888 889
# 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};
890
    return [] unless $self->id;
891
    my @visgroups = @{$self->visible_groups_direct};
892
    @visgroups = @{Bugzilla::Group->flatten_group_membership(@visgroups)};
893 894 895 896 897 898 899 900 901 902
    $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};
903
    return [] unless $self->id;
904 905

    my $dbh = Bugzilla->dbh;
906 907 908 909 910
    my $sth;
   
    if (Bugzilla->params->{'usevisibilitygroups'}) {
        $sth = $dbh->prepare("SELECT DISTINCT grantor_id
                                 FROM group_group_map
911
                                WHERE " . $self->groups_in_sql('member_id') . "
912 913 914 915 916 917
                                  AND grant_type=" . GROUP_VISIBLE);
    }
    else {
        # All groups are visible if usevisibilitygroups is off.
        $sth = $dbh->prepare('SELECT id FROM groups');
    }
918 919 920 921 922 923 924 925 926 927
    $sth->execute();

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

    return $self->{visible_groups_direct};
}

928 929 930 931 932
sub visible_groups_as_string {
    my $self = shift;
    return join(', ', @{$self->visible_groups_inherited()});
}

933 934 935 936 937
# 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;
938 939 940 941
    my @queryshare_groups;

    return $self->{queryshare_groups} if defined $self->{queryshare_groups};

942
    if ($self->in_group(Bugzilla->params->{'querysharegroup'})) {
943 944 945 946 947 948 949 950 951 952
        # We want to be allowed to share with groups we're in only.
        # If usevisibilitygroups is on, then we need to restrict this to groups
        # we may see.
        if (Bugzilla->params->{'usevisibilitygroups'}) {
            foreach(@{$self->visible_groups_inherited()}) {
                next unless $self->in_group_id($_);
                push(@queryshare_groups, $_);
            }
        }
        else {
953
            @queryshare_groups = map { $_->id } @{ $self->groups };
954
        }
955
    }
956 957

    return $self->{queryshare_groups} = \@queryshare_groups;
958 959 960 961 962 963 964
}

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

965 966
sub derive_regexp_groups {
    my ($self) = @_;
967 968

    my $id = $self->id;
969
    return unless $id;
970 971 972 973 974 975 976

    my $dbh = Bugzilla->dbh;

    my $sth;

    # add derived records for any matching regexps

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    $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()) {
994
        if (($regexp ne '') && ($self->login =~ m/$regexp/i)) {
995 996 997
            $group_insert->execute($id, $group, GRANT_REGEXP) unless $present;
        } else {
            $group_delete->execute($id, $group, GRANT_REGEXP) if $present;
998 999 1000 1001
        }
    }
}

1002 1003
sub product_responsibilities {
    my $self = shift;
1004
    my $dbh = Bugzilla->dbh;
1005 1006 1007 1008

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

1009 1010 1011 1012 1013
    my $list = $dbh->selectall_arrayref('SELECT product_id, id
                                           FROM components
                                          WHERE initialowner = ?
                                             OR initialqacontact = ?',
                                  {Slice => {}}, ($self->id, $self->id));
1014

1015 1016 1017 1018 1019 1020 1021
    unless ($list) {
        $self->{'product_resp'} = [];
        return $self->{'product_resp'};
    }

    my @prod_ids = map {$_->{'product_id'}} @$list;
    my $products = Bugzilla::Product->new_from_list(\@prod_ids);
1022 1023
    # We cannot |use| it, because Component.pm already |use|s User.pm.
    require Bugzilla::Component;
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    my @comp_ids = map {$_->{'id'}} @$list;
    my $components = Bugzilla::Component->new_from_list(\@comp_ids);

    my @prod_list;
    # @$products is already sorted alphabetically.
    foreach my $prod (@$products) {
        # We use @components instead of $prod->components because we only want
        # components where the user is either the default assignee or QA contact.
        push(@prod_list, {product    => $prod,
                          components => [grep {$_->product_id == $prod->id} @$components]});
    }
    $self->{'product_resp'} = \@prod_list;
1036
    return $self->{'product_resp'};
1037 1038
}

1039 1040 1041
sub can_bless {
    my $self = shift;

1042 1043 1044
    if (!scalar(@_)) {
        # If we're called without an argument, just return 
        # whether or not we can bless at all.
1045
        return scalar(@{ $self->bless_groups }) ? 1 : 0;
1046 1047
    }

1048
    # Otherwise, we're checking a specific group
1049
    my $group_id = shift;
1050
    return grep($_->id == $group_id, @{ $self->bless_groups }) ? 1 : 0;
1051 1052
}

1053 1054
sub match {
    # Generates a list of users whose login name (email address) or real name
1055
    # matches a substring or wildcard.
1056 1057
    # This is also called if matches are disabled (for error checking), but
    # in this case only the exact match code will end up running.
1058

1059
    # $str contains the string to match, while $limit contains the
1060 1061
    # maximum number of records to retrieve.
    my ($str, $limit, $exclude_disabled) = @_;
1062 1063
    my $user = Bugzilla->user;
    my $dbh = Bugzilla->dbh;
1064

1065
    my @users = ();
1066 1067
    return \@users if $str =~ /^\s*$/;

1068
    # The search order is wildcards, then exact match, then substring search.
1069 1070 1071 1072 1073 1074 1075
    # 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;

1076 1077
    # Do not do wildcards if there is no '*' in the string.
    if ($wildstr =~ s/\*/\%/g && $user->id) {
1078
        # Build the query.
1079
        trick_taint($wildstr);
1080
        my $query  = "SELECT DISTINCT userid FROM profiles ";
1081
        if (Bugzilla->params->{'usevisibilitygroups'}) {
1082 1083
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
1084
        }
1085 1086 1087
        $query .= "WHERE ("
            . $dbh->sql_istrcmp('login_name', '?', "LIKE") . " OR " .
              $dbh->sql_istrcmp('realname', '?', "LIKE") . ") ";
1088
        if (Bugzilla->params->{'usevisibilitygroups'}) {
1089
            $query .= "AND isbless = 0 " .
1090
                      "AND group_id IN(" .
1091
                      join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
1092 1093
        }
        $query    .= " AND disabledtext = '' " if $exclude_disabled;
1094
        $query    .= $dbh->sql_limit($limit) if $limit;
1095 1096 1097

        # Execute the query, retrieve the results, and make them into
        # User objects.
1098 1099
        my $user_ids = $dbh->selectcol_arrayref($query, undef, ($wildstr, $wildstr));
        @users = @{Bugzilla::User->new_from_list($user_ids)};
1100 1101
    }
    else {    # try an exact match
1102
        # Exact matches don't care if a user is disabled.
1103 1104 1105 1106
        trick_taint($str);
        my $user_id = $dbh->selectrow_array('SELECT userid FROM profiles
                                             WHERE ' . $dbh->sql_istrcmp('login_name', '?'),
                                             undef, $str);
1107

1108
        push(@users, new Bugzilla::User($user_id)) if $user_id;
1109 1110
    }

1111
    # then try substring search
1112
    if (!scalar(@users) && length($str) >= 3 && $user->id) {
1113
        trick_taint($str);
1114

1115
        my $query   = "SELECT DISTINCT userid FROM profiles ";
1116
        if (Bugzilla->params->{'usevisibilitygroups'}) {
1117 1118
            $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
1119
        }
1120
        $query     .= " WHERE (" .
1121 1122
                $dbh->sql_iposition('?', 'login_name') . " > 0" . " OR " .
                $dbh->sql_iposition('?', 'realname') . " > 0) ";
1123
        if (Bugzilla->params->{'usevisibilitygroups'}) {
1124
            $query .= " AND isbless = 0" .
1125
                      " AND group_id IN(" .
1126
                join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
1127
        }
1128 1129
        $query     .= " AND disabledtext = '' " if $exclude_disabled;
        $query     .= $dbh->sql_limit($limit) if $limit;
1130 1131
        my $user_ids = $dbh->selectcol_arrayref($query, undef, ($str, $str));
        @users = @{Bugzilla::User->new_from_list($user_ids)};
1132
    }
1133 1134 1135
    return \@users;
}

1136
sub match_field {
1137
    my $fields       = shift;   # arguments as a hash
1138
    my $data         = shift || Bugzilla->input_params; # hash to look up fields in
1139
    my $behavior     = shift || 0; # A constant that tells us how to act
1140 1141 1142
    my $matches      = {};      # the values sent to the template
    my $matchsuccess = 1;       # did the match fail?
    my $need_confirm = 0;       # whether to display confirmation screen
1143
    my $match_multiple = 0;     # whether we ever matched more than one user
1144
    my @non_conclusive_fields;  # fields which don't have a unique user.
1145

1146 1147
    my $params = Bugzilla->params;

1148 1149
    # prepare default form values

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    # 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 {
1162 1163
            my @field_names = grep(/$field_pattern/, keys %$data);

1164 1165 1166 1167
            foreach my $field_name (@field_names) {
                $expanded_fields->{$field_name} = 
                  { type => $fields->{$field_pattern}->{'type'} };
                
1168 1169 1170
                # 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.
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
                if ($field_name =~ /^requestee(_type)?-(\d+)$/) {
                    my $flag_type;
                    if ($1) {
                        require Bugzilla::FlagType;
                        $flag_type = new Bugzilla::FlagType($2);
                    }
                    else {
                        require Bugzilla::Flag;
                        my $flag = new Bugzilla::Flag($2);
                        $flag_type = $flag->type if $flag;
                    }
                    if ($flag_type) {
                        $expanded_fields->{$field_name}->{'flag_type'} = $flag_type;
                    }
                    else {
                        # No need to look for a valid requestee if the flag(type)
                        # has been deleted (may occur in race conditions).
                        delete $expanded_fields->{$field_name};
1189
                        delete $data->{$field_name};
1190
                    }
1191 1192 1193 1194 1195 1196
                }
            }
        }
    }
    $fields = $expanded_fields;

1197 1198 1199
    foreach my $field (keys %{$fields}) {
        next unless defined $data->{$field};

1200 1201 1202 1203 1204 1205 1206 1207 1208
        #Concatenate login names, so that we have a common way to handle them.
        my $raw_field;
        if (ref $data->{$field}) {
            $raw_field = join(" ", @{$data->{$field}});
        }
        else {
            $raw_field = $data->{$field};
        }
        $raw_field = clean_text($raw_field || '');
1209 1210 1211 1212

        # 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.
1213
        my @queries;
1214
        if ($fields->{$field}->{'type'} eq 'single') {
1215
            @queries = ($raw_field);
1216 1217 1218
            # We will repopulate it later if a match is found, else it must
            # be set to an empty string so that the field remains defined.
            $data->{$field} = '';
1219 1220
        }
        elsif ($fields->{$field}->{'type'} eq 'multi') {
1221
            @queries =  split(/[\s,;]+/, $raw_field);
1222 1223 1224
            # We will repopulate it later if a match is found, else it must
            # be undefined.
            delete $data->{$field};
1225 1226 1227
        }
        else {
            # bad argument
1228 1229 1230 1231
            ThrowCodeError('bad_arg',
                           { argument => $fields->{$field}->{'type'},
                             function =>  'Bugzilla::User::match_field',
                           });
1232 1233
        }

1234 1235 1236 1237
        # Tolerate fields that do not exist (in case you specify
        # e.g. the QA contact, and it's currently not in use).
        next unless (defined $raw_field && $raw_field ne '');

1238
        my $limit = 0;
1239 1240
        if ($params->{'maxusermatches'}) {
            $limit = $params->{'maxusermatches'} + 1;
1241 1242
        }

1243
        my @logins;
1244 1245
        for my $query (@queries) {
            my $users = match(
1246 1247 1248
                $query,   # match string
                $limit,   # match limit
                1         # exclude_disabled
1249 1250 1251
            );

            # here is where it checks for multiple matches
1252
            if (scalar(@{$users}) == 1) { # exactly one match
1253
                push(@logins, @{$users}[0]->login);
1254

1255 1256
                # skip confirmation for exact matches
                next if (lc(@{$users}[0]->login) eq lc($query));
1257

1258
                $matches->{$field}->{$query}->{'status'} = 'success';
1259
                $need_confirm = 1 if $params->{'confirmuniqueusermatch'};
1260 1261 1262

            }
            elsif ((scalar(@{$users}) > 1)
1263
                    && ($params->{'maxusermatches'} != 1)) {
1264
                $need_confirm = 1;
1265
                $match_multiple = 1;
1266
                push(@non_conclusive_fields, $field);
1267

1268 1269
                if (($params->{'maxusermatches'})
                   && (scalar(@{$users}) > $params->{'maxusermatches'}))
1270 1271 1272 1273
                {
                    $matches->{$field}->{$query}->{'status'} = 'trunc';
                    pop @{$users};  # take the last one out
                }
1274 1275 1276
                else {
                    $matches->{$field}->{$query}->{'status'} = 'success';
                }
1277 1278 1279 1280 1281

            }
            else {
                # everything else fails
                $matchsuccess = 0; # fail
1282
                push(@non_conclusive_fields, $field);
1283 1284 1285
                $matches->{$field}->{$query}->{'status'} = 'fail';
                $need_confirm = 1;  # confirmation screen shows failures
            }
1286 1287

            $matches->{$field}->{$query}->{'users'}  = $users;
1288
        }
1289 1290 1291 1292

        # If no match or more than one match has been found for a field
        # expecting only one match (type eq "single"), we set it back to ''
        # so that the caller of this function can still check whether this
1293
        # field was defined or not (and it was if we came here).
1294 1295 1296
        if ($fields->{$field}->{'type'} eq 'single') {
            $data->{$field} = $logins[0] || '';
        }
1297
        elsif (scalar @logins) {
1298
            $data->{$field} = \@logins;
1299
        }
1300 1301
    }

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    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.
1314 1315 1316
    if ($behavior == MATCH_SKIP_CONFIRM || !$need_confirm) {
        return wantarray ? ($retval, \@non_conclusive_fields) : $retval;
    }
1317

1318
    my $template = Bugzilla->template;
1319
    my $cgi = Bugzilla->cgi;
1320 1321
    my $vars = {};

1322
    $vars->{'script'}        = $cgi->url(-relative => 1); # for self-referencing URLs
1323
    $vars->{'fields'}        = $fields; # fields being matched
1324 1325
    $vars->{'matches'}       = $matches; # matches that were made
    $vars->{'matchsuccess'}  = $matchsuccess; # continue or fail
1326
    $vars->{'matchmultiple'} = $match_multiple;
1327

1328
    print $cgi->header();
1329

1330 1331
    $template->process("global/confirm-user-match.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
1332 1333 1334 1335
    exit;

}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
# 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,
1349
    'Attachment is patch'    => EVT_ATTACHMENT_DATA,
1350 1351
    'Depends on'             => EVT_DEPEND_BLOCK,
    'Blocks'                 => EVT_DEPEND_BLOCK);
1352 1353 1354 1355

# 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 {
1356
    my $self = shift;
1357
    my ($bug_id, $relationship, $fieldDiffs, $comments, $dependencyText,
1358
        $changer, $bug_is_new) = @_;
1359 1360 1361 1362 1363

    # 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) {
1364
        my ($who, $whoname, $fieldName, $when, $old, $new) = @$ref;
1365 1366 1367 1368 1369 1370
        # 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
1371
            $events{+EVT_OTHER} = 1;            
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
        }

        # 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;
1384 1385
            my $inold = ($old =~ /^(.*,\s*)?\Q$login\E(,.*)?$/);
            my $innew = ($new =~ /^(.*,\s*)?\Q$login\E(,.*)?$/);
1386 1387 1388 1389 1390 1391 1392
            if ($inold != $innew)
            {
                $events{+EVT_ADDED_REMOVED} = 1;
            }
        }
    }

1393 1394 1395 1396 1397 1398 1399
    if ($bug_is_new) {
        # Notify about new bugs.
        $events{+EVT_BUG_CREATED} = 1;

        # You role is new if the bug itself is.
        # Only makes sense for the assignee, QA contact and the CC list.
        if ($relationship == REL_ASSIGNEE
1400
            || $relationship == REL_QA
1401 1402 1403 1404
            || $relationship == REL_CC)
        {
            $events{+EVT_ADDED_REMOVED} = 1;
        }
1405 1406
    }

1407
    if (grep { $_->type == CMT_ATTACHMENT_CREATED } @$comments) {
1408 1409
        $events{+EVT_ATTACHMENT} = 1;
    }
1410
    elsif (defined($$comments[0])) {
1411 1412
        $events{+EVT_COMMENT} = 1;
    }
1413
    
1414 1415 1416 1417 1418 1419
    # Dependent changed bugmails must have an event to ensure the bugmail is
    # emailed.
    if ($dependencyText ne '') {
        $events{+EVT_DEPEND_BLOCK} = 1;
    }

1420
    my @event_list = keys %events;
1421
    
1422 1423 1424 1425 1426 1427 1428
    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.
1429
    if ($wants_mail && $changer && ($self->login eq $changer)) {
1430 1431 1432 1433 1434 1435 1436 1437 1438
        $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.
1439 1440 1441 1442
        my $bug_status = $dbh->selectrow_array('SELECT bug_status
                                                FROM bugs WHERE bug_id = ?',
                                                undef, $bug_id);

1443 1444
        if ($bug_status eq "UNCONFIRMED") {
            $wants_mail &= $self->wants_mail([EVT_UNCONFIRMED], $relationship);
1445 1446 1447
        }
    }
    
1448
    return $wants_mail;
1449 1450
}

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
# 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);
1464

1465 1466 1467 1468
    # If a relationship isn't given, default to REL_ANY.
    if (!defined($relationship)) {
        $relationship = REL_ANY;
    }
1469 1470 1471 1472 1473 1474

    # Skip DB query if relationship is explicit
    return 1 if $relationship == REL_GLOBAL_WATCHER;

    my $dbh = Bugzilla->dbh;

1475
    my $wants_mail = 
1476 1477 1478 1479 1480 1481
        $dbh->selectrow_array('SELECT 1
                                 FROM email_setting
                                WHERE user_id = ?
                                  AND relationship = ?
                                  AND event IN (' . join(',', @$events) . ') ' .
                                      $dbh->sql_limit(1),
1482
                              undef, ($self->id, $relationship));
1483

1484
    return defined($wants_mail) ? 1 : 0;
1485
}
1486 1487 1488 1489 1490

sub is_mover {
    my $self = shift;

    if (!defined $self->{'is_mover'}) {
1491
        my @movers = map { trim($_) } split(',', Bugzilla->params->{'movers'});
1492 1493 1494 1495 1496 1497
        $self->{'is_mover'} = ($self->id
                               && lsearch(\@movers, $self->login) != -1);
    }
    return $self->{'is_mover'};
}

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
sub is_insider {
    my $self = shift;

    if (!defined $self->{'is_insider'}) {
        my $insider_group = Bugzilla->params->{'insidergroup'};
        $self->{'is_insider'} =
            ($insider_group && $self->in_group($insider_group)) ? 1 : 0;
    }
    return $self->{'is_insider'};
}

1509 1510 1511 1512 1513
sub is_global_watcher {
    my $self = shift;

    if (!defined $self->{'is_global_watcher'}) {
        my @watchers = split(/[,\s]+/, Bugzilla->params->{'globalwatchers'});
1514
        $self->{'is_global_watcher'} = scalar(grep { $_ eq $self->login } @watchers) ? 1 : 0;
1515 1516 1517 1518
    }
    return  $self->{'is_global_watcher'};
}

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
sub is_timetracker {
    my $self = shift;

    if (!defined $self->{'is_timetracker'}) {
        my $tt_group = Bugzilla->params->{'timetrackinggroup'};
        $self->{'is_timetracker'} =
            ($tt_group && $self->in_group($tt_group)) ? 1 : 0;
    }
    return $self->{'is_timetracker'};
}

1530 1531 1532 1533 1534
sub get_userlist {
    my $self = shift;

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

1535
    my $dbh = Bugzilla->dbh;
1536
    my $query  = "SELECT DISTINCT login_name, realname,";
1537
    if (Bugzilla->params->{'usevisibilitygroups'}) {
1538 1539 1540 1541
        $query .= " COUNT(group_id) ";
    } else {
        $query .= " 1 ";
    }
1542
    $query     .= "FROM profiles ";
1543
    if (Bugzilla->params->{'usevisibilitygroups'}) {
1544 1545 1546
        $query .= "LEFT JOIN user_group_map " .
                  "ON user_group_map.user_id = userid AND isbless = 0 " .
                  "AND group_id IN(" .
1547
                  join(', ', (-1, @{$self->visible_groups_inherited})) . ")";
1548
    }
1549 1550
    $query    .= " WHERE disabledtext = '' ";
    $query    .= $dbh->sql_group_by('userid', 'login_name, realname');
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568

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

1569 1570 1571
sub create {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
1572 1573
    my $dbh = Bugzilla->dbh;

1574
    $dbh->bz_start_transaction();
1575

1576
    my $user = $class->SUPER::create(@_);
1577

1578
    # Turn on all email for the new user
1579 1580 1581
    require Bugzilla::BugMail;
    my %relationships = Bugzilla::BugMail::relationships();
    foreach my $rel (keys %relationships) {
1582
        foreach my $event (POS_EVENTS, NEG_EVENTS) {
1583 1584 1585 1586 1587 1588 1589
            # 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));

1590
            $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
1591
                      VALUES (?, ?, ?)', undef, ($user->id, $rel, $event));
1592
        }
1593 1594 1595
    }

    foreach my $event (GLOBAL_EVENTS) {
1596
        $dbh->do('INSERT INTO email_setting (user_id, relationship, event)
1597
                  VALUES (?, ?, ?)', undef, ($user->id, REL_ANY, $event));
1598
    }
1599 1600 1601

    $user->derive_regexp_groups();

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
    # 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));

1613
    $dbh->bz_commit_transaction();
1614

1615 1616
    # Return the newly created user account.
    return $user;
1617 1618
}

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
###########################
# Account Lockout Methods #
###########################

sub account_is_locked_out {
    my $self = shift;
    my $login_failures = scalar @{ $self->account_ip_login_failures };
    return $login_failures >= MAX_LOGIN_ATTEMPTS ? 1 : 0;
}

sub note_login_failure {
    my $self = shift;
1631
    my $ip_addr = remote_ip();
1632 1633 1634 1635 1636 1637 1638 1639 1640
    trick_taint($ip_addr);
    Bugzilla->dbh->do("INSERT INTO login_failure (user_id, ip_addr, login_time)
                       VALUES (?, ?, LOCALTIMESTAMP(0))",
                      undef, $self->id, $ip_addr);
    delete $self->{account_ip_login_failures};
}

sub clear_login_failures {
    my $self = shift;
1641
    my $ip_addr = remote_ip();
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
    trick_taint($ip_addr);
    Bugzilla->dbh->do(
        'DELETE FROM login_failure WHERE user_id = ? AND ip_addr = ?',
        undef, $self->id, $ip_addr);
    delete $self->{account_ip_login_failures};
}

sub account_ip_login_failures {
    my $self = shift;
    my $dbh = Bugzilla->dbh;
    my $time = $dbh->sql_interval(LOGIN_LOCKOUT_INTERVAL, 'MINUTE');
1653
    my $ip_addr = remote_ip();
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    trick_taint($ip_addr);
    $self->{account_ip_login_failures} ||= Bugzilla->dbh->selectall_arrayref(
        "SELECT login_time, ip_addr, user_id FROM login_failure
          WHERE user_id = ? AND login_time > LOCALTIMESTAMP(0) - $time
                AND ip_addr = ?
       ORDER BY login_time", {Slice => {}}, $self->id, $ip_addr);
    return $self->{account_ip_login_failures};
}

###############
# Subroutines #
###############

1667
sub is_available_username {
1668 1669
    my ($username, $old_username) = @_;

1670
    if(login_to_id($username) != 0) {
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
        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
1682
    # the new/old email addresses and sql_position() to find the delimiter (':')
1683
    # is cleaner/safer
1684 1685 1686 1687 1688 1689 1690 1691
    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, (" .
1692
                    $dbh->sql_position(q{':'}, 'eventdata') . "+ 1), LENGTH(eventdata)) = ?)",
1693 1694 1695
         undef, ($username, $username));

    if ($eventdata) {
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        # Allow thru owner of token
        if($old_username && ($eventdata eq "$old_username:$username")) {
            return 1;
        }
        return 0;
    }

    return 1;
}

1706
sub login_to_id {
1707
    my ($login, $throw_error) = @_;
1708
    my $dbh = Bugzilla->dbh;
1709 1710
    # No need to validate $login -- it will be used by the following SELECT
    # statement only, so it's safe to simply trick_taint.
1711
    trick_taint($login);
1712 1713 1714
    my $user_id = $dbh->selectrow_array("SELECT userid FROM profiles WHERE " .
                                        $dbh->sql_istrcmp('login_name', '?'),
                                        undef, $login);
1715
    if ($user_id) {
1716
        return $user_id;
1717 1718
    } elsif ($throw_error) {
        ThrowUserError('invalid_username', { name => $login });
1719 1720 1721 1722 1723
    } else {
        return 0;
    }
}

1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
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 || '';
}

1735 1736 1737 1738 1739 1740 1741 1742
sub validate_password {
    my ($password, $matchpassword) = @_;

    if (length($password) < USER_PASSWORD_MIN_LENGTH) {
        ThrowUserError('password_too_short');
    } elsif ((defined $matchpassword) && ($password ne $matchpassword)) {
        ThrowUserError('passwords_dont_match');
    }
1743 1744
    # Having done these checks makes us consider the password untainted.
    trick_taint($_[0]);
1745 1746 1747
    return 1;
}

1748

1749
1;
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

__END__

=head1 NAME

Bugzilla::User - Object for a Bugzilla user

=head1 SYNOPSIS

  use Bugzilla::User;

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

1763 1764 1765
  my @get_selectable_classifications = 
      $user->get_selectable_classifications;

1766
  # Class Functions
1767 1768 1769 1770 1771 1772
  $user = Bugzilla::User->create({ 
      login_name    => $username, 
      realname      => $realname, 
      cryptpassword => $plaintext_password, 
      disabledtext  => $disabledtext,
      disable_mail  => 0});
1773

1774 1775 1776 1777 1778 1779 1780 1781
=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">.

1782 1783 1784 1785
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.

1786 1787
=head1 CONSTANTS

1788 1789
=over

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
=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.

1810 1811
=back

1812 1813
=head1 METHODS

1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
=head2 Constructors

=over

=item C<super_user>

Returns a user who is in all groups, but who does not really exist in the
database. Used for non-web scripts like L<checksetup> that need to make 
database changes and so on.

=back

1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
=head2 Saved and Shared Queries

=over

=item C<queries>

Returns an arrayref of the user's own saved queries, sorted by name. The 
array contains L<Bugzilla::Search::Saved> objects.

=item C<queries_subscribed>

Returns an arrayref of shared queries that the user has subscribed to.
That is, these are shared queries that the user sees in their footer.
This array contains L<Bugzilla::Search::Saved> objects.

=item C<queries_available>

Returns an arrayref of all queries to which the user could possibly
subscribe. This includes the contents of L</queries_subscribed>.
An array of L<Bugzilla::Search::Saved> objects.

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

An arrayref of group ids. The user can share their own queries with these
groups.

=back

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
=head2 Account Lockout

=over

=item C<account_is_locked_out>

Returns C<1> if the account has failed to log in too many times recently,
and thus is locked out for a period of time. Returns C<0> otherwise.

=item C<account_ip_login_failures>

Returns an arrayref of hashrefs, that contains information about the recent
times that this account has failed to log in from the current remote IP.
The hashes contain C<ip_addr>, C<login_time>, and C<user_id>.

=item C<note_login_failure>

This notes that this account has failed to log in, and stores the fact
in the database. The storing happens immediately, it does not wait for
you to call C<update>.

=back

1883 1884
=head2 Other Methods

1885
=over
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910

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

1911
Returns a string for the identity of the user. This will be of the form
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
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.

1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
=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.

1933 1934 1935 1936
=item C<disabledtext>

Returns the disable text of the user, if any.

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
=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.

1951 1952 1953 1954 1955
=item C<timezone>

Returns the timezone used to display dates and times to the user,
as a DateTime::TimeZone object.

1956 1957
=item C<groups>

1958 1959
Returns an arrayref of L<Bugzilla::Group> objects representing
groups that this user is a member of.
1960

1961 1962
=item C<groups_as_string>

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

1967 1968 1969 1970 1971 1972 1973
=item C<groups_in_sql>

This returns an C<IN> clause for SQL, containing either all of the groups
the user is in, or C<-1> if the user is in no groups. This takes one
argument--the name of the SQL field that should be on the left-hand-side
of the C<IN> statement, which defaults to C<group_id> if not specified.

1974
=item C<in_group($group_name, $product_id)>
1975

1976 1977 1978
Determines whether or not a user is in the given group by name.
If $product_id is given, it also checks for local privileges for
this product.
1979 1980 1981 1982

=item C<in_group_id>

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

1984 1985
=item C<bless_groups>

1986 1987
Returns an arrayref of L<Bugzilla::Group> objects.

1988 1989
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
1990
that you need to be able to see a group in order to bless it.
1991

1992 1993 1994 1995 1996 1997
=item C<get_products_by_permission($group)>

Returns a list of product objects for which the user has $group privileges
and which he can access.
$group must be one of the groups defined in PER_PRODUCT_PRIVILEGES.

1998 1999 2000 2001 2002
=item C<can_see_user(user)>

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

2003 2004 2005 2006 2007
=item C<can_edit_product(prod_id)>

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

2008 2009 2010 2011
=item C<can_see_bug(bug_id)>

Determines if the user can see the specified bug.

2012 2013 2014 2015 2016
=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.

2017
=item C<derive_regexp_groups>
2018 2019 2020 2021 2022 2023 2024

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.

2025 2026 2027 2028 2029 2030
=item C<clear_product_cache>

Clears the stored values for L</get_selectable_products>, 
L</get_enterable_products>, etc. so that their data will be read from
the database again. Used mostly by L<Bugzilla::Product>.

2031 2032
=item C<get_selectable_products>

2033 2034 2035
 Description: Returns all products the user is allowed to access. This list
              is restricted to some given classification if $classification_id
              is given.
2036

2037 2038
 Params:      $classification_id - (optional) The ID of the classification
                                   the products belong to.
2039

2040
 Returns:     An array of product objects, sorted by the product name.
2041

2042 2043
=item C<get_selectable_classifications>

2044 2045
 Description: Returns all classifications containing at least one product
              the user is allowed to view.
2046

2047
 Params:      none
2048

2049 2050
 Returns:     An array of Bugzilla::Classification objects, sorted by
              the classification name.
2051

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
=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.

2078
=item C<can_access_product($product)>
2079

2080 2081 2082
Returns 1 if the user can search or enter bugs into the specified product
(either a L<Bugzilla::Product> or a product name), and 0 if the user should
not be aware of the existence of the product.
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092

=item C<get_accessible_products>

 Description: Returns an array of product objects the user can search
              or enter bugs against.

 Params:      none

 Returns:     an array of product objects.

2093 2094 2095 2096 2097 2098 2099 2100
=item C<check_can_admin_product($product_name)>

 Description: Checks whether the user is allowed to administrate the product.

 Params:      $product_name - a product name.

 Returns:     On success, a product object. On failure, an error is thrown.

2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
=item C<can_request_flag($flag_type)>

 Description: Checks whether the user can request flags of the given type.

 Params:      $flag_type - a Bugzilla::FlagType object.

 Returns:     1 if the user can request flags of the given type,
              0 otherwise.

=item C<can_set_flag($flag_type)>

 Description: Checks whether the user can set flags of the given type.

 Params:      $flag_type - a Bugzilla::FlagType object.

 Returns:     1 if the user can set flags of the given type,
              0 otherwise.

2119 2120 2121 2122 2123 2124
=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.

2125 2126 2127 2128 2129
=item C<direct_group_membership>

Returns a reference to an array of group objects. Groups the user belong to
by group inheritance are excluded from the list.

2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
=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.

2140 2141
=item C<visible_groups_as_string>

2142
Returns the result of C<visible_groups_inherited> as a string (a comma-separated
2143 2144
list).

2145 2146
=item C<product_responsibilities>

2147 2148
Retrieve user's product responsibilities as a list of component objects.
Each object is a component the user has a responsibility for.
2149

2150 2151
=item C<can_bless>

2152 2153 2154 2155
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:
2156
Returns C<1> if the user can bless the group with that id, returns
2157
C<0> otherwise.
2158

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
=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.

2169 2170 2171 2172 2173 2174
=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.

2175 2176 2177 2178 2179
=item C<is_insider>

Returns true if the user can access private comments and attachments,
i.e. if the 'insidergroup' parameter is set and the user belongs to this group.

2180 2181 2182 2183 2184
=item C<is_global_watcher>

Returns true if the user is a global watcher,
i.e. if the 'globalwatchers' parameter contains the user.

2185 2186
=back

2187 2188 2189 2190 2191
=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.

2192 2193
=over 4

2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
=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.
2209

2210 2211 2212 2213 2214
=item C<check>

Takes a username as its only argument. Throws an error if there is no
user with that username. Returns a C<Bugzilla::User> object.

2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
=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).

2228
=item C<login_to_id($login, $throw_error)>
2229 2230 2231 2232 2233

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.

2234 2235 2236
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.
2237 2238 2239 2240 2241 2242 2243

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.

2244 2245 2246 2247 2248 2249
=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.

2250 2251 2252 2253
=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.
2254
Untaints C<$passwd1> if successful.
2255 2256 2257 2258

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

2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
=item C<match_field($data, $fields, $behavior)>

=over

=item B<Description>

Wrapper for the C<match()> function.

=item B<Params>

=over

=item C<$fields> - A hashref with field names as keys and a hash as values.
Each hash is of the form { 'type' => 'single|multi' }, which specifies
whether the field can take a single login name only or several.

=item C<$data> (optional) - A hashref with field names as keys and field values
as values. If undefined, C<Bugzilla-E<gt>input_params> is used.

=item C<$behavior> (optional) - If set to C<MATCH_SKIP_CONFIRM>, no confirmation
screen is displayed. In that case, the fields which don't match a unique user
are left undefined. If not set, a confirmation screen is displayed if at
least one field doesn't match any login name or match more than one.

=back

=item B<Returns>

If the third parameter is set to C<MATCH_SKIP_CONFIRM>, the function returns
either C<USER_MATCH_SUCCESS> if all fields can be set unambiguously,
C<USER_MATCH_FAILED> if at least one field doesn't match any user account,
or C<USER_MATCH_MULTIPLE> if some fields match more than one user account.

If the third parameter is not set, then if all fields could be set
unambiguously, nothing is returned, else a confirmation page is displayed.

=item B<Note>

This function must be called early in a script, before anything external
is done with the data.

=back

2302 2303
=back

2304 2305 2306
=head1 SEE ALSO

L<Bugzilla|Bugzilla>