User.pm 101 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7

8
package Bugzilla::User;
9

10
use 5.10.1;
11
use strict;
12
use warnings;
13

14
use Bugzilla::Error;
15
use Bugzilla::Util;
16
use Bugzilla::Constants;
17
use Bugzilla::Search::Recent;
18
use Bugzilla::User::Setting;
19
use Bugzilla::Product;
20
use Bugzilla::Classification;
21
use Bugzilla::Field;
22
use Bugzilla::Group;
23
use Bugzilla::BugUserLastVisit;
24
use Bugzilla::Hook;
25

26
use DateTime::TimeZone;
27
use List::Util qw(max);
28
use List::MoreUtils qw(any);
29
use Scalar::Util qw(blessed);
30
use Storable qw(dclone);
31 32
use URI;
use URI::QueryParam;
33

34
use parent qw(Bugzilla::Object Exporter);
35
@Bugzilla::User::EXPORT = qw(is_available_username
36 37 38
  login_to_id validate_password validate_password_check
  USER_MATCH_MULTIPLE USER_MATCH_FAILED USER_MATCH_SUCCESS
  MATCH_SKIP_CONFIRM
39
);
40

41 42 43 44 45 46 47 48
#####################################################################
# Constants
#####################################################################

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

49
use constant MATCH_SKIP_CONFIRM => 1;
50

51
use constant DEFAULT_USER => {
52 53 54 55 56 57 58
  'userid'         => 0,
  'realname'       => '',
  'login_name'     => '',
  'showmybugslink' => 0,
  'disabledtext'   => '',
  'disable_mail'   => 0,
  'is_enabled'     => 1,
59 60 61 62 63 64 65 66
};

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.
67
sub DB_COLUMNS {
68 69 70 71 72 73 74 75 76 77 78
  my $dbh = Bugzilla->dbh;
  return (
    'profiles.userid',
    'profiles.login_name',
    'profiles.realname',
    'profiles.mybugslink AS showmybugslink',
    'profiles.disabledtext',
    'profiles.disable_mail',
    'profiles.extern_id',
    'profiles.is_enabled',
    $dbh->sql_date_format('last_seen_date', '%Y-%m-%d') . ' AS last_seen_date',
79
    ),
80
    ;
81 82
}

83 84
use constant NAME_FIELD => 'login_name';
use constant ID_FIELD   => 'userid';
85
use constant LIST_ORDER => NAME_FIELD;
86

87
use constant VALIDATORS => {
88 89 90 91 92 93 94
  cryptpassword => \&_check_password,
  disable_mail  => \&_check_disable_mail,
  disabledtext  => \&_check_disabledtext,
  login_name    => \&check_login_name,
  realname      => \&_check_realname,
  extern_id     => \&_check_extern_id,
  is_enabled    => \&_check_is_enabled,
95 96
};

97
sub UPDATE_COLUMNS {
98 99 100 101 102 103 104 105 106 107 108 109
  my $self = shift;
  my @cols = qw(
    disable_mail
    disabledtext
    login_name
    realname
    extern_id
    is_enabled
  );
  push(@cols, 'cryptpassword') if exists $self->{cryptpassword};
  return @cols;
}
110

111
use constant VALIDATOR_DEPENDENCIES => {is_enabled => ['disabledtext'],};
112 113 114

use constant EXTRA_REQUIRED_FIELDS => qw(is_enabled);

115 116 117 118 119
################################################################################
# Functions
################################################################################

sub new {
120 121 122 123 124 125 126 127 128 129 130 131
  my $invocant = shift;
  my $class    = ref($invocant) || $invocant;
  my ($param)  = @_;

  my $user = {%{DEFAULT_USER()}};
  bless($user, $class);
  return $user unless $param;

  if (ref($param) eq 'HASH') {
    if (defined $param->{extern_id}) {
      $param = {condition => 'extern_id = ?', values => [$param->{extern_id}]};
      $_[0] = $param;
132
    }
133 134
  }
  return $class->SUPER::new(@_);
135 136
}

137
sub super_user {
138 139 140
  my $invocant = shift;
  my $class    = ref($invocant) || $invocant;
  my ($param)  = @_;
141

142 143 144 145 146
  my $user = {%{DEFAULT_USER()}};
  $user->{groups}       = [Bugzilla::Group->get_all];
  $user->{bless_groups} = [Bugzilla::Group->get_all];
  bless $user, $class;
  return $user;
147 148
}

149
sub _update_groups {
150 151 152 153 154 155 156 157
  my $self          = shift;
  my $group_changes = shift;
  my $changes       = shift;
  my $dbh           = Bugzilla->dbh;

  # Update group settings.
  my $sth_add_mapping = $dbh->prepare(
    qq{INSERT INTO user_group_map (
158 159 160 161
                  user_id, group_id, isbless, grant_type
                 ) VALUES (
                  ?, ?, ?, ?
                 )
162 163 164 165
          }
  );
  my $sth_remove_mapping = $dbh->prepare(
    qq{DELETE FROM user_group_map
166 167 168 169
            WHERE user_id = ?
              AND group_id = ?
              AND isbless = ?
              AND grant_type = ?
170 171
          }
  );
172

173 174
  foreach my $is_bless (keys %$group_changes) {
    my ($removed, $added) = @{$group_changes->{$is_bless}};
175

176 177 178 179 180 181
    foreach my $group (@$removed) {
      $sth_remove_mapping->execute($self->id, $group->id, $is_bless, GRANT_DIRECT);
    }
    foreach my $group (@$added) {
      $sth_add_mapping->execute($self->id, $group->id, $is_bless, GRANT_DIRECT);
    }
182

183 184
    if (!$is_bless) {
      my $query = qq{
185 186 187 188 189
                INSERT INTO profiles_activity
                    (userid, who, profiles_when, fieldid, oldvalue, newvalue)
                VALUES ( ?, ?, now(), ?, ?, ?)
            };

190 191 192 193 194 195 196 197 198 199
      $dbh->do(
        $query, undef, $self->id, Bugzilla->user->id,
        get_field_id('bug_group'),
        join(', ', map { $_->name } @$removed),
        join(', ', map { $_->name } @$added)
      );
    }
    else {
      # XXX: should create profiles_activity entries for blesser changes.
    }
200

201
    Bugzilla->memcached->clear_config({key => 'user_groups.' . $self->id});
202

203 204 205
    my $type = $is_bless ? 'bless_groups' : 'groups';
    $changes->{$type} = [[map { $_->name } @$removed], [map { $_->name } @$added],];
  }
206 207
}

208
sub update {
209 210
  my $self    = shift;
  my $options = shift;
211

212
  my $group_changes = delete $self->{_group_changes};
213

214 215 216
  my $changes = $self->SUPER::update(@_);
  my $dbh     = Bugzilla->dbh;
  $self->_update_groups($group_changes, $changes);
217

218 219 220 221 222
  if (exists $changes->{login_name}) {

    # Delete all the tokens related to the userid
    $dbh->do('DELETE FROM tokens WHERE userid = ?', undef, $self->id)
      unless $options->{keep_tokens};
223

224 225 226 227 228 229 230 231 232 233 234 235
    # And rederive regex groups
    $self->derive_regexp_groups();
  }

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

237 238 239 240
  # XXX Can update profiles_activity here as soon as it understands
  #     field names like login_name.

  return $changes;
241 242
}

243 244 245 246
################################################################################
# Validators
################################################################################

247 248
sub _check_disable_mail { return $_[1] ? 1 : 0; }
sub _check_disabledtext { return trim($_[1]) || ''; }
249

250 251
# Check whether the extern_id is unique.
sub _check_extern_id {
252 253 254 255 256 257 258 259
  my ($invocant, $extern_id) = @_;
  $extern_id = trim($extern_id);
  return undef unless defined($extern_id) && $extern_id ne "";
  if (!ref($invocant) || $invocant->extern_id ne $extern_id) {
    my $existing_login = $invocant->new({extern_id => $extern_id});
    if ($existing_login) {
      ThrowUserError('extern_id_exists',
        {extern_id => $extern_id, existing_login_name => $existing_login->login});
260
    }
261 262
  }
  return $extern_id;
263 264
}

265 266
# This is public since createaccount.cgi needs to use it before issuing
# a token for account creation.
267
sub check_login_name {
268 269 270 271
  my ($invocant, $name) = @_;
  $name = trim($name);
  $name || ThrowUserError('user_login_required');
  check_email_syntax($name);
272

273 274 275 276 277 278 279 280 281
  # Check the name if it's a new user, or if we're changing the name.
  if (!ref($invocant) || lc($invocant->login) ne lc($name)) {
    my @params = ($name);
    push(@params, $invocant->login) if ref($invocant);
    is_available_username(@params)
      || ThrowUserError('account_exists', {email => $name});
  }

  return $name;
282 283 284
}

sub _check_password {
285
  my ($self, $pass) = @_;
286

287 288 289 290
  # 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 '*';
291

292 293 294
  validate_password($pass);
  my $cryptpassword = bz_crypt($pass);
  return $cryptpassword;
295 296
}

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

299
sub _check_is_enabled {
300 301 302 303 304 305 306 307 308
  my ($invocant, $is_enabled, undef, $params) = @_;

  # is_enabled is set automatically on creation depending on whether
  # disabledtext is empty (enabled) or not empty (disabled).
  # When updating the user, is_enabled is set by calling set_disabledtext().
  # Any value passed into this validator is ignored.
  my $disabledtext
    = ref($invocant) ? $invocant->disabledtext : $params->{disabledtext};
  return $disabledtext ? 0 : 1;
309 310
}

311 312 313 314
################################################################################
# Mutators
################################################################################

315 316
sub set_disable_mail  { $_[0]->set('disable_mail', $_[1]); }
sub set_email_enabled { $_[0]->set('disable_mail', !$_[1]); }
317
sub set_extern_id     { $_[0]->set('extern_id',    $_[1]); }
318 319

sub set_login {
320 321 322 323
  my ($self, $login) = @_;
  $self->set('login_name', $login);
  delete $self->{identity};
  delete $self->{nick};
324 325 326
}

sub set_name {
327 328 329
  my ($self, $name) = @_;
  $self->set('realname', $name);
  delete $self->{identity};
330 331 332 333
}

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

334
sub set_disabledtext {
335 336
  $_[0]->set('disabledtext', $_[1]);
  $_[0]->set('is_enabled', $_[1] ? 0 : 1);
337
}
338

339
sub set_groups {
340 341
  my $self = shift;
  $self->_set_groups(GROUP_MEMBERSHIP, @_);
342 343 344
}

sub set_bless_groups {
345
  my $self = shift;
346

347 348 349 350 351 352 353 354 355 356
  # The person making the change needs to be in the editusers group
  Bugzilla->user->in_group('editusers') || ThrowUserError(
    "auth_failure",
    {
      group  => "editusers",
      reason => "cant_bless",
      action => "edit",
      object => "users"
    }
  );
357

358
  $self->_set_groups(GROUP_BLESS, @_);
359 360 361
}

sub _set_groups {
362 363 364 365
  my $self     = shift;
  my $is_bless = shift;
  my $changes  = shift;
  my $dbh      = Bugzilla->dbh;
366

367 368
  # The person making the change is $user, $self is the person being changed
  my $user = Bugzilla->user;
369

370 371
  # Input is a hash of arrays. Key is 'set', 'add' or 'remove'. The array
  # is a list of group ids and/or names.
372

373 374
  # First turn the arrays into group objects.
  $changes = $self->_set_groups_to_object($changes);
375

376 377 378
  # Get a list of the groups the user currently is a member of
  my $ids = $dbh->selectcol_arrayref(
    q{SELECT DISTINCT group_id
379
            FROM user_group_map
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
           WHERE user_id = ? AND isbless = ? AND grant_type = ?}, undef, $self->id,
    $is_bless, GRANT_DIRECT
  );

  my $current_groups = Bugzilla::Group->new_from_list($ids);
  my $new_groups     = dclone($current_groups);

  # Record the changes
  if (exists $changes->{set}) {
    $new_groups = $changes->{set};

    # We need to check the user has bless rights on the existing groups
    # If they don't, then we need to add them back to new_groups
    foreach my $group (@$current_groups) {
      if (!$user->can_bless($group->id)) {
        push @$new_groups, $group unless grep { $_->id eq $group->id } @$new_groups;
      }
397
    }
398 399 400 401
  }
  else {
    foreach my $group (@{$changes->{remove} // []}) {
      @$new_groups = grep { $_->id ne $group->id } @$new_groups;
402
    }
403 404
    foreach my $group (@{$changes->{add} // []}) {
      push @$new_groups, $group unless grep { $_->id eq $group->id } @$new_groups;
405
    }
406 407 408 409 410 411 412
  }

  # Stash the changes, so self->update can actually make them
  my @diffs = diff_arrays($current_groups, $new_groups, 'id');
  if (scalar(@{$diffs[0]}) || scalar(@{$diffs[1]})) {
    $self->{_group_changes}{$is_bless} = \@diffs;
  }
413 414 415
}

sub _set_groups_to_object {
416 417 418
  my $self    = shift;
  my $changes = shift;
  my $user    = Bugzilla->user;
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  foreach my $key (keys %$changes) {

    # Check we were given an array
    unless (ref($changes->{$key}) eq 'ARRAY') {
      ThrowCodeError('param_invalid', {param => $changes->{$key}, function => $key});
    }

    # Go through the array, and turn items into group objects
    my @groups = ();
    foreach my $value (@{$changes->{$key}}) {
      my $type = $value =~ /^\d+$/ ? 'id' : 'name';
      my $group = Bugzilla::Group->new({$type => $value});

      if (!$group || !$user->can_bless($group->id)) {
        ThrowUserError('auth_failure',
          {group => $value, reason => 'cant_bless', action => 'edit', object => 'users'});
      }
      push @groups, $group;
438
    }
439 440
    $changes->{$key} = \@groups;
  }
441

442
  return $changes;
443 444
}

445
sub update_last_seen_date {
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  my $self = shift;
  return unless $self->id;
  my $dbh  = Bugzilla->dbh;
  my $date = $dbh->selectrow_array(
    'SELECT ' . $dbh->sql_date_format('NOW()', '%Y-%m-%d'));

  if (!$self->last_seen_date or $date ne $self->last_seen_date) {
    $self->{last_seen_date} = $date;

    # We don't use the normal update() routine here as we only
    # want to update the last_seen_date column, not any other
    # pending changes
    $dbh->do("UPDATE profiles SET last_seen_date = ? WHERE userid = ?",
      undef, $date, $self->id);
    Bugzilla->memcached->clear({table => 'profiles', id => $self->id});
  }
462 463
}

464 465 466 467
################################################################################
# Methods
################################################################################

468
# Accessors for user attributes
469 470 471 472 473 474
sub name           { $_[0]->{realname}; }
sub login          { $_[0]->{login_name}; }
sub extern_id      { $_[0]->{extern_id}; }
sub email          { $_[0]->login . Bugzilla->params->{'emailsuffix'}; }
sub disabledtext   { $_[0]->{'disabledtext'}; }
sub is_enabled     { $_[0]->{'is_enabled'} ? 1 : 0; }
475
sub showmybugslink { $_[0]->{showmybugslink}; }
476
sub email_disabled { $_[0]->{disable_mail}; }
477
sub email_enabled  { !($_[0]->{disable_mail}); }
478
sub last_seen_date { $_[0]->{last_seen_date}; }
479

480
sub cryptpassword {
481 482 483 484 485 486 487 488 489
  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;
490
}
491

492
sub set_authorizer {
493 494
  my ($self, $authorizer) = @_;
  $self->{authorizer} = $authorizer;
495
}
496

497
sub authorizer {
498 499 500 501 502 503
  my ($self) = @_;
  if (!$self->{authorizer}) {
    require Bugzilla::Auth;
    $self->{authorizer} = new Bugzilla::Auth();
  }
  return $self->{authorizer};
504 505
}

506
# Generate a string to identify the user by name + login if the user
507
# has a name or by login only if they don't.
508
sub identity {
509
  my $self = shift;
510

511
  return "" unless $self->id;
512

513 514 515 516
  if (!defined $self->{identity}) {
    $self->{identity}
      = $self->name ? $self->name . " <" . $self->login . ">" : $self->login;
  }
517

518
  return $self->{identity};
519 520 521
}

sub nick {
522
  my $self = shift;
523

524
  return "" unless $self->id;
525

526 527 528
  if (!defined $self->{nick}) {
    $self->{nick} = (split(/@/, $self->login, 2))[0];
  }
529

530
  return $self->{nick};
531 532 533
}

sub queries {
534 535 536
  my $self = shift;
  return $self->{queries} if defined $self->{queries};
  return [] unless $self->id;
537

538 539 540 541 542 543
  my $dbh = Bugzilla->dbh;
  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);
544

545 546 547 548
  # 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;
549

550
  return $self->{queries};
551
}
552

553
sub queries_subscribed {
554 555 556 557 558 559 560 561 562 563 564 565 566
  my $self = shift;
  return $self->{queries_subscribed} if defined $self->{queries_subscribed};
  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';

  # 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
567 568 569 570 571
           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)
572 573 574 575 576 577
                AND " . $self->groups_in_sql, undef, $self->id
  );
  require Bugzilla::Search::Saved;
  $self->{queries_subscribed}
    = Bugzilla::Search::Saved->new_from_list($subscribed_query_ids);
  return $self->{queries_subscribed};
578
}
579

580
sub queries_available {
581 582 583
  my $self = shift;
  return $self->{queries_available} if defined $self->{queries_available};
  return [] unless $self->id;
584

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

589 590 591 592 593 594 595 596 597
  my $avail_query_ids = Bugzilla->dbh->selectcol_arrayref(
    'SELECT namedquery_id FROM namedquery_group_map
          WHERE ' . $self->groups_in_sql . "
                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};
598 599
}

600
sub tags {
601 602 603 604 605 606 607 608 609 610
  my $self = shift;
  my $dbh  = Bugzilla->dbh;

  if (!defined $self->{tags}) {

    # We must use LEFT JOIN instead of INNER JOIN as we may be
    # in the process of inserting a new tag to some bugs,
    # in which case there are no bugs with this tag yet.
    $self->{tags} = $dbh->selectall_hashref(
      'SELECT name, id, COUNT(bug_id) AS bug_count
611 612
               FROM tag
          LEFT JOIN bug_tag ON bug_tag.tag_id = tag.id
613 614 615 616 617
              WHERE user_id = ? ' . $dbh->sql_group_by('id', 'name'), 'name', undef,
      $self->id
    );
  }
  return $self->{tags};
618 619
}

620
sub bugs_ignored {
621 622 623 624 625
  my ($self) = @_;
  my $dbh = Bugzilla->dbh;
  if (!defined $self->{'bugs_ignored'}) {
    $self->{'bugs_ignored'} = $dbh->selectall_arrayref(
      'SELECT bugs.bug_id AS id,
626 627 628 629 630
                    bugs.bug_status AS status,
                    bugs.short_desc AS summary
               FROM bugs
                    INNER JOIN email_bug_ignore
                    ON bugs.bug_id = email_bug_ignore.bug_id
631 632 633 634 635 636 637 638
              WHERE user_id = ?', {Slice => {}}, $self->id
    );

    # Go ahead and load these into the visible bugs cache
    # to speed up can_see_bug checks later
    $self->visible_bugs([map { $_->{'id'} } @{$self->{'bugs_ignored'}}]);
  }
  return $self->{'bugs_ignored'};
639 640 641
}

sub is_bug_ignored {
642 643
  my ($self, $bug_id) = @_;
  return (grep { $_->{'id'} == $bug_id } @{$self->bugs_ignored}) ? 1 : 0;
644 645
}

646 647 648 649 650
##########################
# Saved Recent Bug Lists #
##########################

sub recent_searches {
651 652 653 654
  my $self = shift;
  $self->{recent_searches}
    ||= Bugzilla::Search::Recent->match({user_id => $self->id});
  return $self->{recent_searches};
655 656 657
}

sub recent_search_containing {
658 659
  my ($self, $bug_id) = @_;
  my $searches = $self->recent_searches;
660

661 662 663
  foreach my $search (@$searches) {
    return $search if grep($_ == $bug_id, @{$search->bug_list});
  }
664

665
  return undef;
666 667 668
}

sub recent_search_for {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  my ($self, $bug) = @_;
  my $params = Bugzilla->input_params;
  my $cgi    = Bugzilla->cgi;

  if ($self->id) {

    # First see if there's a list_id parameter in the query string.
    my $list_id = $params->{list_id};
    if (!$list_id) {

      # If not, check for "list_id" in the query string of the referer.
      my $referer = $cgi->referer;
      if ($referer) {
        my $uri = URI->new($referer);
        if ($uri->path =~ /buglist\.cgi$/) {
          $list_id = $uri->query_param('list_id') || $uri->query_param('regetlastlist');
685
        }
686 687
      }
    }
688

689
    if ($list_id && $list_id ne 'cookie') {
690

691 692 693 694
      # If we got a bad list_id (either some other user's or an expired
      # one) don't crash, just don't return that list.
      my $search = Bugzilla::Search::Recent->check_quietly({id => $list_id});
      return $search if $search;
695 696
    }

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    # If there's no list_id, see if the current bug's id is contained
    # in any of the user's saved lists.
    my $search = $self->recent_search_containing($bug->id);
    return $search if $search;
  }

  # Finally (or always, if we're logged out), if there's a BUGLIST cookie
  # and the selected bug is in the list, then return the cookie as a fake
  # Search::Recent object.
  if (my $list = $cgi->cookie('BUGLIST')) {

    # Also split on colons, which was used as a separator in old cookies.
    my @bug_ids = split(/[:-]/, $list);
    if (grep { $_ == $bug->id } @bug_ids) {
      my $search = Bugzilla::Search::Recent->new_from_cookie(\@bug_ids);
      return $search;
713
    }
714
  }
715

716
  return undef;
717 718 719
}

sub save_last_search {
720 721 722 723 724 725 726 727 728 729 730
  my ($self, $params) = @_;
  my ($bug_ids, $order, $vars, $list_id) = @$params{qw(bugs order vars list_id)};

  my $cgi = Bugzilla->cgi;
  if ($order) {
    $cgi->send_cookie(
      -name    => 'LASTORDER',
      -value   => $order,
      -expires => 'Fri, 01-Jan-2038 00:00:00 GMT'
    );
  }
731

732 733 734 735 736 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 762 763 764
  return if !@$bug_ids;

  my $search;
  if ($self->id) {
    on_main_db {
      if ($list_id) {
        $search = Bugzilla::Search::Recent->check_quietly({id => $list_id});
      }

      if ($search) {
        if (join(',', @{$search->bug_list}) ne join(',', @$bug_ids)) {
          $search->set_bug_list($bug_ids);
        }
        if (!$search->list_order || $order ne $search->list_order) {
          $search->set_list_order($order);
        }
        $search->update();
      }
      else {
        # If we already have an existing search with a totally
        # identical bug list, then don't create a new one. This
        # prevents people from writing over their whole
        # recent-search list by just refreshing a saved search
        # (which doesn't have list_id in the header) over and over.
        my $list_string = join(',', @$bug_ids);
        my $existing_search = Bugzilla::Search::Recent->match(
          {user_id => $self->id, bug_list => $list_string});

        if (!scalar(@$existing_search)) {
          $search
            = Bugzilla::Search::Recent->create({
            user_id => $self->id, bug_list => $bug_ids, list_order => $order
            });
765 766
        }
        else {
767
          $search = $existing_search->[0];
768
        }
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
      }
    };
    delete $self->{recent_searches};
  }

  # Logged-out users use a cookie to store a single last search. We don't
  # override that cookie with the logged-in user's latest search, because
  # if they did one search while logged out and another while logged in,
  # they may still want to navigate through the search they made while
  # logged out.
  else {
    my $bug_list = join('-', @$bug_ids);
    if (length($bug_list) < 4000) {
      $cgi->send_cookie(
        -name    => 'BUGLIST',
        -value   => $bug_list,
        -expires => 'Fri, 01-Jan-2038 00:00:00 GMT'
      );
787
    }
788 789 790 791 792 793
    else {
      $cgi->remove_cookie('BUGLIST');
      $vars->{'toolong'} = 1;
    }
  }
  return $search;
794 795
}

796
sub reports {
797 798 799
  my $self = shift;
  return $self->{reports} if defined $self->{reports};
  return [] unless $self->id;
800

801 802 803 804 805 806 807
  my $dbh = Bugzilla->dbh;
  my $report_ids
    = $dbh->selectcol_arrayref('SELECT id FROM reports WHERE user_id = ?',
    undef, $self->id);
  require Bugzilla::Report;
  $self->{reports} = Bugzilla::Report->new_from_list($report_ids);
  return $self->{reports};
808 809 810
}

sub flush_reports_cache {
811
  my $self = shift;
812

813
  delete $self->{reports};
814 815
}

816
sub settings {
817
  my ($self) = @_;
818

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

821 822 823 824 825 826 827 828 829
  # 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();
  }
830

831
  return $self->{'settings'};
832 833
}

834
sub setting {
835 836
  my ($self, $name) = @_;
  return $self->settings->{$name}->{'value'};
837 838
}

839
sub timezone {
840
  my $self = shift;
841

842 843 844 845 846 847
  if (!defined $self->{timezone}) {
    my $tz = $self->setting('timezone');
    if ($tz eq 'local') {

      # The user wants the local timezone of the server.
      $self->{timezone} = Bugzilla->local_timezone;
848
    }
849 850 851 852 853
    else {
      $self->{timezone} = DateTime::TimeZone->new(name => $tz);
    }
  }
  return $self->{timezone};
854 855
}

856
sub flush_queries_cache {
857
  my $self = shift;
858

859 860 861
  delete $self->{queries};
  delete $self->{queries_subscribed};
  delete $self->{queries_available};
862 863 864
}

sub groups {
865
  my $self = shift;
866

867 868
  return $self->{groups} if defined $self->{groups};
  return [] unless $self->id;
869

870 871
  my $user_groups_key = "user_groups." . $self->id;
  my $groups = Bugzilla->memcached->get_config({key => $user_groups_key});
872

873 874 875 876
  if (!$groups) {
    my $dbh             = Bugzilla->dbh;
    my $groups_to_check = $dbh->selectcol_arrayref(
      "SELECT DISTINCT group_id
877
               FROM user_group_map
878 879 880 881 882 883 884 885 886
              WHERE user_id = ? AND isbless = 0", undef, $self->id
    );

    my $grant_type_key = 'group_grant_type_' . GROUP_MEMBERSHIP;
    my $membership_rows
      = Bugzilla->memcached->get_config({key => $grant_type_key,});
    if (!$membership_rows) {
      $membership_rows = $dbh->selectall_arrayref(
        "SELECT DISTINCT grantor_id, member_id
887
                FROM group_group_map
888 889 890 891 892 893
                WHERE grant_type = " . GROUP_MEMBERSHIP
      );
      Bugzilla->memcached->set_config({
        key => $grant_type_key, data => $membership_rows,
      });
    }
894

895 896 897 898 899
    my %group_membership;
    foreach my $row (@$membership_rows) {
      my ($grantor_id, $member_id) = @$row;
      push(@{$group_membership{$member_id}}, $grantor_id);
    }
900

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    # 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
    # $checked_groups{$member_id} hash values.
    # As a result, %groups will have all the groups we are the member of.
    my %checked_groups;
    my %groups;
    while (scalar(@$groups_to_check) > 0) {

      # Pop the head group from FIFO
      my $member_id = shift @$groups_to_check;

      # Skip the group if we have already checked it
      if (!$checked_groups{$member_id}) {

        # Mark group as checked
        $checked_groups{$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.
        my $members = $group_membership{$member_id};
        my @new_to_check = grep(!$checked_groups{$_}, @$members);
        push(@$groups_to_check, @new_to_check);
926

927 928
        $groups{$member_id} = 1;
      }
929
    }
930
    $groups = [keys %groups];
931

932 933 934 935 936
    Bugzilla->memcached->set_config({key => $user_groups_key, data => $groups,});
  }

  $self->{groups} = Bugzilla::Group->new_from_list($groups);
  return $self->{groups};
937 938
}

939
sub last_visited {
940
  my ($self, $ids) = @_;
941

942 943 944
  return Bugzilla::BugUserLastVisit->match({
    user_id => $self->id, $ids ? (bug_id => $ids) : ()
  });
945 946 947
}

sub is_involved_in_bug {
948 949 950
  my ($self, $bug) = @_;
  my $user_id    = $self->id;
  my $user_login = $self->login;
951

952 953 954
  return unless $user_id;
  return 1 if $user_id == $bug->assigned_to->id;
  return 1 if $user_id == $bug->reporter->id;
955

956 957 958
  if (Bugzilla->params->{'useqacontact'} and $bug->qa_contact) {
    return 1 if $user_id == $bug->qa_contact->id;
  }
959

960
  return any { $user_login eq $_ } @{$bug->cc};
961 962
}

963 964 965 966 967
# It turns out that calling ->id on objects a few hundred thousand
# times is pretty slow. (It showed up as a significant time contributor
# when profiling xt/search.t.) So we cache the group ids separately from
# groups for functions that need the group ids.
sub _group_ids {
968 969 970
  my ($self) = @_;
  $self->{group_ids} ||= [map { $_->id } @{$self->groups}];
  return $self->{group_ids};
971 972
}

973
sub groups_as_string {
974 975 976
  my $self = shift;
  my $ids  = $self->_group_ids;
  return scalar(@$ids) ? join(',', @$ids) : '-1';
977 978
}

979
sub groups_in_sql {
980 981 982 983 984
  my ($self, $field) = @_;
  $field ||= 'group_id';
  my $ids = $self->_group_ids;
  $ids = [-1] if !scalar @$ids;
  return Bugzilla->dbh->sql_in($field, $ids);
985 986
}

987
sub bless_groups {
988
  my $self = shift;
989

990 991
  return $self->{'bless_groups'} if defined $self->{'bless_groups'};
  return [] unless $self->id;
992

993
  if ($self->in_group('editusers')) {
994

995 996 997 998 999 1000 1001 1002 1003 1004
    # Users having editusers permissions may bless all groups.
    $self->{'bless_groups'} = [Bugzilla::Group->get_all];
    return $self->{'bless_groups'};
  }

  if (Bugzilla->params->{usevisibilitygroups}
    && !@{$self->visible_groups_inherited})
  {
    return [];
  }
1005

1006
  my $dbh = Bugzilla->dbh;
1007

1008 1009
  # Get all groups for the user where they have direct bless privileges.
  my $query = "
1010 1011 1012 1013
        SELECT DISTINCT group_id
          FROM user_group_map
         WHERE user_id = ?
               AND isbless = 1";
1014 1015 1016 1017 1018 1019 1020 1021 1022
  if (Bugzilla->params->{usevisibilitygroups}) {
    $query .= " AND " . $dbh->sql_in('group_id', $self->visible_groups_inherited);
  }

  # Get all groups for the user where they are a member of a group that
  # inherits bless privs.
  my @group_ids = map { $_->id } @{$self->groups};
  if (@group_ids) {
    $query .= "
1023 1024 1025 1026 1027
            UNION
            SELECT DISTINCT grantor_id
            FROM group_group_map
            WHERE grant_type = " . GROUP_BLESS . "
                AND " . $dbh->sql_in('member_id', \@group_ids);
1028 1029
    if (Bugzilla->params->{usevisibilitygroups}) {
      $query .= " AND " . $dbh->sql_in('grantor_id', $self->visible_groups_inherited);
1030
    }
1031
  }
1032

1033 1034
  my $ids = $dbh->selectcol_arrayref($query, undef, $self->id);
  return $self->{bless_groups} = Bugzilla::Group->new_from_list($ids);
1035 1036
}

1037
sub in_group {
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  my ($self, $group, $product_id) = @_;
  $group = $group->name if blessed $group;
  if (scalar grep($_->name eq $group, @{$self->groups})) {
    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
1054 1055 1056
                              FROM group_control_map
                             WHERE product_id = ?
                                   AND $group != 0
1057 1058 1059
                                   AND "
          . $self->groups_in_sql . ' ' . $dbh->sql_limit(1), undef, $product_id
      );
1060

1061
      $self->{"product_$product_id"}->{$group} = $in_group ? 1 : 0;
1062
    }
1063 1064 1065 1066 1067
    return $self->{"product_$product_id"}->{$group};
  }

  # If we come here, then the user is not in the requested group.
  return 0;
1068
}
1069

1070
sub in_group_id {
1071 1072
  my ($self, $id) = @_;
  return grep($_->id == $id, @{$self->groups}) ? 1 : 0;
1073 1074
}

1075 1076 1077
# This is a helper to get all groups which have an icon to be displayed
# besides the name of the commenter.
sub groups_with_icon {
1078
  my $self = shift;
1079

1080
  return $self->{groups_with_icon} //= [grep { $_->icon_url } @{$self->groups}];
1081 1082
}

1083
sub get_products_by_permission {
1084 1085 1086 1087
  my ($self, $group) = @_;

  # Make sure $group exists on a per-product basis.
  return [] unless (grep { $_ eq $group } PER_PRODUCT_PRIVILEGES);
1088

1089 1090
  my $product_ids = Bugzilla->dbh->selectcol_arrayref(
    "SELECT DISTINCT product_id
1091 1092
                             FROM group_control_map
                            WHERE $group != 0
1093 1094
                              AND " . $self->groups_in_sql
  );
1095

1096 1097 1098
  # No need to go further if the user has no "special" privs.
  return [] unless scalar(@$product_ids);
  my %product_map = map { $_ => 1 } @$product_ids;
1099

1100 1101 1102 1103
  # We will restrict the list to products the user can see.
  my $selectable_products = $self->get_selectable_products;
  my @products = grep { $product_map{$_->id} } @$selectable_products;
  return \@products;
1104 1105
}

1106
sub can_see_user {
1107 1108
  my ($self, $otherUser) = @_;
  my $query;
1109

1110 1111 1112 1113 1114
  if (Bugzilla->params->{'usevisibilitygroups'}) {

    # If the user can see no groups, then no users are visible either.
    my $visibleGroups = $self->visible_groups_as_string() || return 0;
    $query = qq{SELECT COUNT(DISTINCT userid)
1115 1116 1117 1118 1119 1120
                    FROM profiles, user_group_map
                    WHERE userid = ?
                    AND user_id = userid
                    AND isbless = 0
                    AND group_id IN ($visibleGroups)
                   };
1121 1122 1123
  }
  else {
    $query = qq{SELECT COUNT(userid)
1124 1125 1126
                    FROM profiles
                    WHERE userid = ?
                   };
1127 1128
  }
  return Bugzilla->dbh->selectrow_array($query, undef, $otherUser->id);
1129 1130
}

1131
sub can_edit_product {
1132 1133
  my ($self, $prod_id) = @_;
  my $dbh = Bugzilla->dbh;
1134

1135 1136 1137 1138 1139 1140 1141 1142
  if (Bugzilla->params->{'or_groups'}) {
    my $groups = $self->groups_as_string;

    # For or-groups, we check if there are any can_edit groups for the
    # product, and if the user is in any of them. If there are none or
    # the user is in at least one of them, they can edit the product
    my ($cnt_can_edit, $cnt_group_member) = $dbh->selectrow_array(
      "SELECT SUM(p.cnt_can_edit),
1143 1144 1145 1146
                   SUM(p.cnt_group_member)
              FROM (SELECT CASE WHEN canedit = 1 THEN 1 ELSE 0 END AS cnt_can_edit,
                           CASE WHEN canedit = 1 AND group_id IN ($groups) THEN 1 ELSE 0 END AS cnt_group_member
                    FROM group_control_map
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
                    WHERE product_id = $prod_id) AS p"
    );
    return (!$cnt_can_edit or $cnt_group_member);
  }
  else {
    # For and-groups, a user needs to be in all canedit groups. Therefore
    # if the user is not in a can_edit group for the product, they cannot
    # edit the product.
    my $has_external_groups = $dbh->selectrow_array(
      'SELECT 1
1157 1158 1159
                                   FROM group_control_map
                                  WHERE product_id = ?
                                    AND canedit != 0
1160 1161 1162
                                    AND group_id NOT IN('
        . $self->groups_as_string . ')', undef, $prod_id
    );
1163

1164 1165
    return !$has_external_groups;
  }
1166 1167
}

1168
sub can_see_bug {
1169 1170
  my ($self, $bug_id) = @_;
  return @{$self->visible_bugs([$bug_id])} ? 1 : 0;
1171 1172 1173
}

sub visible_bugs {
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  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.
  # Bugzilla::Bug->update automatically removes updated bugs
  # from the cache to force them to be checked again.
  my $visible_cache = $self->{_visible_bugs_cache} ||= {};
  my @check_ids = grep(!exists $visible_cache->{$_}, @bug_ids);
1185

1186 1187 1188 1189 1190 1191
  if (@check_ids) {
    foreach my $id (@check_ids) {
      my $orig_id = $id;
      detaint_natural($id)
        || ThrowCodeError('param_must_be_numeric',
        {param => $orig_id, function => 'Bugzilla::User->visible_bugs'});
1192
    }
1193

1194 1195 1196 1197 1198 1199
    Bugzilla->params->{'or_groups'}
      ? $self->_visible_bugs_check_or(\@check_ids)
      : $self->_visible_bugs_check_and(\@check_ids);
  }

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

1202
sub _visible_bugs_check_or {
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
  my ($self, $check_ids) = @_;
  my $visible_cache = $self->{_visible_bugs_cache};
  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};
  }
  my $query = qq{
1215 1216 1217 1218 1219
        SELECT DISTINCT bugs.bug_id
        FROM bugs
            LEFT JOIN bug_group_map AS security_map ON bugs.bug_id = security_map.bug_id
            LEFT JOIN cc AS security_cc ON bugs.bug_id = security_cc.bug_id AND security_cc.who = $user_id
        WHERE bugs.bug_id IN (} . join(',', ('?') x @$check_ids) . qq{)
1220 1221
          AND ((security_map.group_id IS NULL OR security_map.group_id IN (}
    . $self->groups_as_string . qq{))
1222 1223 1224 1225 1226
            OR (bugs.reporter_accessible = 1 AND bugs.reporter = $user_id)
            OR (bugs.cclist_accessible = 1 AND security_cc.who IS NOT NULL)
            OR bugs.assigned_to = $user_id
    };

1227 1228 1229 1230
  if (Bugzilla->params->{'useqacontact'}) {
    $query .= " OR bugs.qa_contact = $user_id";
  }
  $query .= ')';
1231

1232 1233 1234 1235
  $sth ||= $dbh->prepare($query);
  if (scalar(@$check_ids) == 1) {
    $self->{_sth_one_visible_bug} = $sth;
  }
1236

1237 1238 1239 1240
  # Set all bugs as non visible
  foreach my $bug_id (@$check_ids) {
    $visible_cache->{$bug_id} = 0;
  }
1241

1242 1243 1244 1245 1246
  # Now get the bugs the user can see
  my $visible_bug_ids = $dbh->selectcol_arrayref($sth, undef, @$check_ids);
  foreach my $bug_id (@$visible_bug_ids) {
    $visible_cache->{$bug_id} = 1;
  }
1247 1248 1249
}

sub _visible_bugs_check_and {
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
  my ($self, $check_ids) = @_;
  my $visible_cache = $self->{_visible_bugs_cache};
  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,
1273 1274 1275 1276 1277 1278 1279 1280 1281
                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 ("
1282
      . $self->groups_as_string . ')
1283
          WHERE bugs.bug_id IN (' . join(',', ('?') x @$check_ids) . ')
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
                AND creation_ts IS NOT NULL '
  );
  if (scalar(@$check_ids) == 1) {
    $self->{_sth_one_visible_bug} = $sth;
  }

  $sth->execute(@$check_ids);
  my $use_qa_contact = Bugzilla->params->{'useqacontact'};
  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)
        || ($use_qa_contact && $qacontact && ($qacontact == $user_id))
        || ($owner == $user_id)
        || ($isoncclist && $cclist_access)
        || !$missinggroup) ? 1 : 0;
  }
1303 1304 1305

}

1306
sub clear_product_cache {
1307 1308 1309 1310
  my $self = shift;
  delete $self->{enterable_products};
  delete $self->{selectable_products};
  delete $self->{selectable_classifications};
1311 1312
}

1313
sub can_see_product {
1314
  my ($self, $product_name) = @_;
1315

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

1320
sub get_selectable_products {
1321 1322 1323
  my $self             = shift;
  my $class_id         = shift;
  my $class_restricted = Bugzilla->params->{'useclassification'} && $class_id;
1324

1325 1326
  if (!defined $self->{selectable_products}) {
    my $query = "SELECT id
1327 1328 1329
                     FROM products
                         LEFT JOIN group_control_map
                             ON group_control_map.product_id = products.id
1330 1331 1332 1333 1334 1335 1336 1337
                             AND group_control_map.membercontrol = "
      . CONTROLMAPMANDATORY;

    if (Bugzilla->params->{'or_groups'}) {

      # Either the user is in at least one of the MANDATORY groups, or
      # there are no such groups for the product.
      $query .= " WHERE group_id IN (" . $self->groups_as_string . ")
1338
                        OR group_id IS NULL";
1339 1340 1341 1342
    }
    else {
      # There must be no MANDATORY groups that the user is not in.
      $query .= " AND group_id NOT IN (" . $self->groups_as_string . ")
1343
                        WHERE group_id IS NULL";
1344 1345
    }

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    my $prod_ids = Bugzilla->dbh->selectcol_arrayref($query);
    $self->{selectable_products} = Bugzilla::Product->new_from_list($prod_ids);
  }

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

  # If we come here, then we want all selectable products.
  return $self->{selectable_products};
1358 1359
}

1360
sub get_selectable_classifications {
1361
  my ($self) = @_;
1362

1363 1364 1365
  if (!defined $self->{selectable_classifications}) {
    my $products = $self->get_selectable_products;
    my %class_ids = map { $_->classification_id => 1 } @$products;
1366

1367 1368 1369 1370
    $self->{selectable_classifications}
      = Bugzilla::Classification->new_from_list([keys %class_ids]);
  }
  return $self->{selectable_classifications};
1371 1372
}

1373
sub can_enter_product {
1374 1375 1376
  my ($self, $input, $warn) = @_;
  my $dbh = Bugzilla->dbh;
  $warn ||= 0;
1377

1378 1379 1380 1381 1382
  $input = trim($input) if !ref $input;
  if (!defined $input or $input eq '') {
    return unless $warn == THROW_ERROR;
    ThrowUserError('object_not_specified', {class => 'Bugzilla::Product'});
  }
1383

1384 1385 1386 1387
  if (!scalar @{$self->get_enterable_products}) {
    return unless $warn == THROW_ERROR;
    ThrowUserError('no_products');
  }
1388

1389 1390 1391 1392
  my $product
    = blessed($input) ? $input : new Bugzilla::Product({name => $input});
  my $can_enter = $product
    && grep($_->name eq $product->name, @{$self->get_enterable_products});
1393

1394
  return $product if $can_enter;
1395

1396
  return 0 unless $warn == THROW_ERROR;
1397

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

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  # 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;

  # The product could not exist or you could be denied...
  if (!$product || !$product->user_has_access($self)) {
    ThrowUserError('entry_access_denied', {product => $name});
  }

  # It could be closed for bug entry...
  elsif (!$product->is_active) {
    ThrowUserError('product_disabled', {product => $product});
  }
1415

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
  # It could have no components...
  elsif (!@{$product->components}
    || !grep { $_->is_active } @{$product->components})
  {
    ThrowUserError('missing_component', {product => $product});
  }

  # It could have no versions...
  elsif (!@{$product->versions} || !grep { $_->is_active } @{$product->versions})
  {
    ThrowUserError('missing_version', {product => $product});
  }

  die "can_enter_product reached an unreachable location.";
1430 1431 1432
}

sub get_enterable_products {
1433 1434
  my $self = shift;
  my $dbh  = Bugzilla->dbh;
1435

1436 1437 1438
  if (defined $self->{enterable_products}) {
    return $self->{enterable_products};
  }
1439

1440 1441
  # All products which the user has "Entry" access to.
  my $query = 'SELECT products.id FROM products
1442 1443 1444 1445
            LEFT JOIN group_control_map
                ON group_control_map.product_id = products.id
                    AND group_control_map.entry != 0';

1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
  if (Bugzilla->params->{'or_groups'}) {
    $query
      .= " WHERE (group_id IN ("
      . $self->groups_as_string . ")"
      . "    OR group_id IS NULL)";
  }
  else {
    $query
      .= " AND group_id NOT IN ("
      . $self->groups_as_string . ")"
      . " WHERE group_id IS NULL";
  }
  $query .= " AND products.isactive = 1";
  my $enterable_ids = $dbh->selectcol_arrayref($query);

  if (scalar @$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
              WHERE '
        . $dbh->sql_in('products.id', $enterable_ids)
        . ' AND products.id IN (SELECT DISTINCT components.product_id
1470 1471 1472 1473
                                      FROM components
                                     WHERE components.isactive = 1)
                AND products.id IN (SELECT DISTINCT versions.product_id
                                      FROM versions
1474 1475 1476
                                     WHERE versions.isactive = 1)'
    );
  }
1477

1478 1479
  $self->{enterable_products} = Bugzilla::Product->new_from_list($enterable_ids);
  return $self->{enterable_products};
1480 1481
}

1482
sub can_access_product {
1483 1484 1485 1486
  my ($self, $product) = @_;
  my $product_name = blessed($product) ? $product->name : $product;
  return
    scalar(grep { $_->name eq $product_name } @{$self->get_accessible_products});
1487 1488
}

1489
sub get_accessible_products {
1490 1491 1492 1493 1494 1495 1496
  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 [sort { $a->name cmp $b->name } values %products];
1497 1498
}

1499
sub can_administer {
1500 1501 1502 1503
  my $self = shift;

  if (not defined $self->{can_administer}) {
    my $can_administer = 0;
1504

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    $can_administer = 1
      if $self->in_group('admin')
      || $self->in_group('tweakparams')
      || $self->in_group('editusers')
      || $self->can_bless
      || (Bugzilla->params->{'useclassification'}
      && $self->in_group('editclassifications'))
      || $self->in_group('editcomponents')
      || scalar(@{$self->get_products_by_permission('editcomponents')})
      || $self->in_group('creategroups')
      || $self->in_group('editkeywords')
      || $self->in_group('bz_canusewhines');

    Bugzilla::Hook::process('user_can_administer',
      {can_administer => \$can_administer});
    $self->{can_administer} = $can_administer;
  }

  return $self->{can_administer};
1524 1525
}

1526
sub check_can_admin_product {
1527
  my ($self, $product_name) = @_;
1528

1529 1530
  # First make sure the product name is valid.
  my $product = Bugzilla::Product->check($product_name);
1531

1532 1533 1534
  (      $self->in_group('editcomponents', $product->id)
      && $self->can_see_product($product->name))
    || ThrowUserError('product_admin_denied', {product => $product->name});
1535

1536 1537
  # Return the validated product object.
  return $product;
1538 1539
}

1540
sub check_can_admin_flagtype {
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
  my ($self, $flagtype_id) = @_;

  my $flagtype = Bugzilla::FlagType->check({id => $flagtype_id});
  my $can_fully_edit = 1;

  if (!$self->in_group('editcomponents')) {
    my $products = $self->get_products_by_permission('editcomponents');

    # You need editcomponents privs for at least one product to have
    # a chance to edit the flagtype.
    scalar(@$products)
      || ThrowUserError('auth_failure',
      {group => 'editcomponents', action => 'edit', object => 'flagtypes'});
    my $can_admin = 0;
    my $i         = $flagtype->inclusions_as_hash;
    my $e         = $flagtype->exclusions_as_hash;

    # If there is at least one product for which the user doesn't have
    # editcomponents privs, then don't allow them to do everything with
    # this flagtype, independently of whether this product is in the
    # exclusion list or not.
    my %product_ids;
    map { $product_ids{$_->id} = 1 } @$products;
    $can_fully_edit = 0 if grep { !$product_ids{$_} } keys %$i;

    unless ($e->{0}->{0}) {
      foreach my $product (@$products) {
        my $id = $product->id;
        next if $e->{$id}->{0};

        # If we are here, the product has not been explicitly excluded.
        # Check whether it's explicitly included, or at least one of
        # its components.
        $can_admin
          = (  $i->{0}->{0}
            || $i->{$id}->{0}
            || scalar(grep { !$e->{$id}->{$_} } keys %{$i->{$id}}));
        last if $can_admin;
      }
    }
    $can_admin || ThrowUserError('flag_type_not_editable', {flagtype => $flagtype});
  }
  return wantarray ? ($flagtype, $can_fully_edit) : $flagtype;
1584 1585
}

1586
sub can_request_flag {
1587
  my ($self, $flag_type) = @_;
1588

1589 1590 1591
  return ($self->can_set_flag($flag_type)
      || !$flag_type->request_group_id
      || $self->in_group_id($flag_type->request_group_id)) ? 1 : 0;
1592 1593 1594
}

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

1597 1598
  return (!$flag_type->grant_group_id
      || $self->in_group_id($flag_type->grant_group_id)) ? 1 : 0;
1599 1600
}

1601 1602 1603
# visible_groups_inherited returns a reference to a list of all the groups
# whose members are visible to this user.
sub visible_groups_inherited {
1604 1605 1606 1607 1608 1609 1610 1611
  my $self = shift;
  return $self->{visible_groups_inherited}
    if defined $self->{visible_groups_inherited};
  return [] unless $self->id;
  my @visgroups = @{$self->visible_groups_direct};
  @visgroups = @{Bugzilla::Group->flatten_group_membership(@visgroups)};
  $self->{visible_groups_inherited} = \@visgroups;
  return $self->{visible_groups_inherited};
1612 1613 1614 1615 1616
}

# visible_groups_direct returns a reference to a list of all the groups that
# are visible to this user.
sub visible_groups_direct {
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  my $self      = shift;
  my @visgroups = ();
  return $self->{visible_groups_direct} if defined $self->{visible_groups_direct};
  return [] unless $self->id;

  my $dbh = Bugzilla->dbh;
  my $sth;

  if (Bugzilla->params->{'usevisibilitygroups'}) {
    $sth = $dbh->prepare(
      "SELECT DISTINCT grantor_id
1628
                                 FROM group_group_map
1629
                                WHERE " . $self->groups_in_sql('member_id') . "
1630 1631 1632 1633 1634 1635 1636 1637
                                  AND grant_type=" . GROUP_VISIBLE
    );
  }
  else {
    # All groups are visible if usevisibilitygroups is off.
    $sth = $dbh->prepare('SELECT id FROM groups');
  }
  $sth->execute();
1638

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

1644
  return $self->{visible_groups_direct};
1645 1646
}

1647
sub visible_groups_as_string {
1648 1649
  my $self = shift;
  return join(', ', @{$self->visible_groups_inherited()});
1650 1651
}

1652 1653 1654 1655
# 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 {
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
  my $self = shift;
  my @queryshare_groups;

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

  if ($self->in_group(Bugzilla->params->{'querysharegroup'})) {

    # 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, $_);
      }
1671
    }
1672 1673 1674 1675
    else {
      @queryshare_groups = @{$self->_group_ids};
    }
  }
1676

1677
  return $self->{queryshare_groups} = \@queryshare_groups;
1678 1679 1680
}

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

1685
sub derive_regexp_groups {
1686
  my ($self) = @_;
1687

1688 1689
  my $id = $self->id;
  return unless $id;
1690

1691
  my $dbh = Bugzilla->dbh;
1692

1693
  my $sth;
1694

1695
  # add derived records for any matching regexps
1696

1697 1698
  $sth = $dbh->prepare(
    "SELECT id, userregexp, user_group_map.group_id
1699 1700 1701 1702
                            FROM groups
                       LEFT JOIN user_group_map
                              ON groups.id = user_group_map.group_id
                             AND user_group_map.user_id = ?
1703 1704 1705
                             AND user_group_map.grant_type = ?"
  );
  $sth->execute($id, GRANT_REGEXP);
1706

1707 1708
  my $group_insert = $dbh->prepare(
    q{INSERT INTO user_group_map
1709
                                       (user_id, group_id, isbless, grant_type)
1710 1711 1712 1713
                                       VALUES (?, ?, 0, ?)}
  );
  my $group_delete = $dbh->prepare(
    q{DELETE FROM user_group_map
1714 1715 1716
                                       WHERE user_id = ?
                                         AND group_id = ?
                                         AND isbless = 0
1717 1718 1719 1720 1721
                                         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;
1722
    }
1723 1724 1725 1726
    else {
      $group_delete->execute($id, $group, GRANT_REGEXP) if $present;
    }
  }
1727

1728
  Bugzilla->memcached->clear_config({key => "user_groups.$id"});
1729 1730
}

1731
sub product_responsibilities {
1732 1733
  my $self = shift;
  my $dbh  = Bugzilla->dbh;
1734

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

1738 1739
  my $list = $dbh->selectall_arrayref(
    'SELECT components.product_id, components.id
1740
                                           FROM components
1741 1742 1743 1744 1745
                                           LEFT JOIN component_cc
                                           ON components.id = component_cc.component_id
                                          WHERE components.initialowner = ?
                                             OR components.initialqacontact = ?
                                             OR component_cc.user_id = ?',
1746 1747
    {Slice => {}}, ($self->id, $self->id, $self->id)
  );
1748

1749 1750
  unless ($list) {
    $self->{'product_resp'} = [];
1751
    return $self->{'product_resp'};
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
  }

  my @prod_ids = map { $_->{'product_id'} } @$list;
  my $products = Bugzilla::Product->new_from_list(\@prod_ids);

  # We cannot |use| it, because Component.pm already |use|s User.pm.
  require Bugzilla::Component;
  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;
  return $self->{'product_resp'};
1779 1780
}

1781
sub can_bless {
1782
  my $self = shift;
1783

1784 1785 1786 1787 1788 1789
  if (!scalar(@_)) {

    # If we're called without an argument, just return
    # whether or not we can bless at all.
    return scalar(@{$self->bless_groups}) ? 1 : 0;
  }
1790

1791 1792 1793
  # Otherwise, we're checking a specific group
  my $group_id = shift;
  return grep($_->id == $group_id, @{$self->bless_groups}) ? 1 : 0;
1794 1795
}

1796
sub match {
1797

1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
  # Generates a list of users whose login name (email address) or real name
  # matches a substring or wildcard.
  # This is also called if matches are disabled (for error checking), but
  # in this case only the exact match code will end up running.

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

  $str = trim($str);

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

  # The search order is wildcards, then exact match, then substring search.
  # 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;

  # Do not do wildcards if there is no '*' in the string.
  if ($wildstr =~ s/\*/\%/g && $user->id) {

    # Build the query.
    trick_taint($wildstr);
    my $query = "SELECT DISTINCT userid FROM profiles ";
    if (Bugzilla->params->{'usevisibilitygroups'}) {
      $query .= "INNER JOIN user_group_map
                               ON user_group_map.user_id = profiles.userid ";
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 1860
    $query
      .= "WHERE ("
      . $dbh->sql_istrcmp('login_name', '?', "LIKE") . " OR "
      . $dbh->sql_istrcmp('realname',   '?', "LIKE") . ") ";
    if (Bugzilla->params->{'usevisibilitygroups'}) {
      $query
        .= "AND isbless = 0 "
        . "AND group_id IN("
        . join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
    }
    $query .= " AND is_enabled = 1 "  if $exclude_disabled;
    $query .= $dbh->sql_limit($limit) if $limit;

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

    push(@users, new Bugzilla::User($user_id)) if $user_id;
  }
1861

1862 1863 1864
  # then try substring search
  if (!scalar(@users) && length($str) >= 3 && $user->id) {
    trick_taint($str);
1865

1866 1867 1868
    my $query = "SELECT DISTINCT userid FROM profiles ";
    if (Bugzilla->params->{'usevisibilitygroups'}) {
      $query .= "INNER JOIN user_group_map
1869 1870
                               ON user_group_map.user_id = profiles.userid ";
    }
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    $query
      .= " WHERE ("
      . $dbh->sql_iposition('?', 'login_name') . " > 0" . " OR "
      . $dbh->sql_iposition('?', 'realname')
      . " > 0) ";
    if (Bugzilla->params->{'usevisibilitygroups'}) {
      $query
        .= " AND isbless = 0"
        . " AND group_id IN("
        . join(', ', (-1, @{$user->visible_groups_inherited})) . ") ";
    }
    $query .= " AND is_enabled = 1 "  if $exclude_disabled;
    $query .= $dbh->sql_limit($limit) if $limit;
    my $user_ids = $dbh->selectcol_arrayref($query, undef, ($str, $str));
    @users = @{Bugzilla::User->new_from_list($user_ids)};
  }
  return \@users;
1888 1889
}

1890
sub match_field {
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
  my $fields = shift;                            # arguments as a hash
  my $data = shift || Bugzilla->input_params;    # hash to look up fields in
  my $behavior       = shift || 0;    # A constant that tells us how to act
  my $matches        = {};            # the values sent to the template
  my $matchsuccess   = 1;             # did the match fail?
  my $need_confirm   = 0;             # whether to display confirmation screen
  my $match_multiple = 0;             # whether we ever matched more than one user
  my @non_conclusive_fields;          # fields which don't have a unique user.

  my $params = Bugzilla->params;

  # prepare default form values

  # 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 {
      my @field_names = grep(/$field_pattern/, keys %$data);

      foreach my $field_name (@field_names) {
        $expanded_fields->{$field_name} = {type => $fields->{$field_pattern}->{'type'}};

        # 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.
        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};
            delete $data->{$field_name};
          }
1945
        }
1946
      }
1947
    }
1948 1949
  }
  $fields = $expanded_fields;
1950

1951 1952
  foreach my $field (keys %{$fields}) {
    next unless defined $data->{$field};
1953

1954 1955 1956 1957 1958 1959 1960 1961 1962
    #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 || '');
1963

1964 1965 1966 1967 1968 1969
    # 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.
    my @queries;
    if ($fields->{$field}->{'type'} eq 'single') {
      @queries = ($raw_field);
1970

1971 1972 1973 1974 1975 1976
      # 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} = '';
    }
    elsif ($fields->{$field}->{'type'} eq 'multi') {
      @queries = split(/[,;]+/, $raw_field);
1977

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
      # We will repopulate it later if a match is found, else it must
      # be undefined.
      delete $data->{$field};
    }
    else {
      # bad argument
      ThrowCodeError(
        'bad_arg',
        {
          argument => $fields->{$field}->{'type'},
          function => 'Bugzilla::User::match_field',
1989
        }
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
      );
    }

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

    my $limit = 0;
    if ($params->{'maxusermatches'}) {
      $limit = $params->{'maxusermatches'} + 1;
    }

    my @logins;
    for my $query (@queries) {
      $query = trim($query);
      next if $query eq '';

      my $users = match(
        $query,    # match string
        $limit,    # match limit
        1          # exclude_disabled
      );

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

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

2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
        $matches->{$field}->{$query}->{'status'} = 'success';
        $need_confirm = 1 if $params->{'confirmuniqueusermatch'};

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

        if ( ($params->{'maxusermatches'})
          && (scalar(@{$users}) > $params->{'maxusermatches'}))
        {
          $matches->{$field}->{$query}->{'status'} = 'trunc';
          pop @{$users};    # take the last one out
2034
        }
2035 2036
        else {
          $matches->{$field}->{$query}->{'status'} = 'success';
2037
        }
2038

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
      }
      else {
        # everything else fails
        $matchsuccess = 0;    # fail
        push(@non_conclusive_fields, $field);
        $matches->{$field}->{$query}->{'status'} = 'fail';
        $need_confirm = 1;    # confirmation screen shows failures
      }

      $matches->{$field}->{$query}->{'users'} = $users;
2049
    }
2050 2051 2052 2053 2054 2055 2056

    # 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
    # field was defined or not (and it was if we came here).
    if ($fields->{$field}->{'type'} eq 'single') {
      $data->{$field} = $logins[0] || '';
2057
    }
2058 2059
    elsif (scalar @logins) {
      $data->{$field} = \@logins;
2060
    }
2061
  }
2062

2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
  my $retval;
  if (!$matchsuccess) {
    $retval = USER_MATCH_FAILED;
  }
  elsif ($match_multiple) {
    $retval = USER_MATCH_MULTIPLE;
  }
  else {
    $retval = USER_MATCH_SUCCESS;
  }
2073

2074 2075 2076 2077
  # Skip confirmation if we were told to, or if we don't need to confirm.
  if ($behavior == MATCH_SKIP_CONFIRM || !$need_confirm) {
    return wantarray ? ($retval, \@non_conclusive_fields) : $retval;
  }
2078

2079 2080 2081
  my $template = Bugzilla->template;
  my $cgi      = Bugzilla->cgi;
  my $vars     = {};
2082

2083 2084 2085 2086 2087
  $vars->{'script'}       = $cgi->url(-relative => 1); # for self-referencing URLs
  $vars->{'fields'}       = $fields;                   # fields being matched
  $vars->{'matches'}      = $matches;                  # matches that were made
  $vars->{'matchsuccess'} = $matchsuccess;             # continue or fail
  $vars->{'matchmultiple'} = $match_multiple;
2088

2089 2090 2091 2092 2093
  print $cgi->header();

  $template->process("global/confirm-user-match.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
  exit;
2094 2095 2096

}

2097 2098
# Changes in some fields automatically trigger events. The field names are
# from the fielddefs table.
2099
our %names_to_events = (
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
  'resolution'              => EVT_OPENED_CLOSED,
  'keywords'                => EVT_KEYWORD,
  'cc'                      => EVT_CC,
  'bug_severity'            => EVT_PROJ_MANAGEMENT,
  'priority'                => EVT_PROJ_MANAGEMENT,
  'bug_status'              => EVT_PROJ_MANAGEMENT,
  'target_milestone'        => EVT_PROJ_MANAGEMENT,
  'attachments.description' => EVT_ATTACHMENT_DATA,
  'attachments.mimetype'    => EVT_ATTACHMENT_DATA,
  'attachments.ispatch'     => EVT_ATTACHMENT_DATA,
  'dependson'               => EVT_DEPEND_BLOCK,
  'blocked'                 => EVT_DEPEND_BLOCK,
  'product'                 => EVT_COMPONENT,
  'component'               => EVT_COMPONENT
);
2115 2116 2117 2118

# 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 {
2119 2120
  my $self = shift;
  my ($bug, $relationship, $fieldDiffs, $comments, $dep_mail, $changer) = @_;
2121

2122 2123 2124 2125 2126
  # 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 $change (@$fieldDiffs) {
    my $fieldName = $change->{field_name};
2127

2128 2129 2130
    # A change to any of the above fields sets the corresponding event
    if (defined($names_to_events{$fieldName})) {
      $events{$names_to_events{$fieldName}} = 1;
2131
    }
2132 2133 2134
    else {
      # Catch-all for any change not caught by a more specific event
      $events{+EVT_OTHER} = 1;
2135
    }
2136 2137 2138 2139 2140 2141 2142

    # If the user is in a particular role and the value of that role
    # changed, we need the ADDED_REMOVED event.
    if ( ($fieldName eq "assigned_to" && $relationship == REL_ASSIGNEE)
      || ($fieldName eq "qa_contact" && $relationship == REL_QA))
    {
      $events{+EVT_ADDED_REMOVED} = 1;
2143
    }
2144 2145 2146 2147 2148 2149 2150 2151

    if ($fieldName eq "cc") {
      my $login = $self->login;
      my $inold = ($change->{old} =~ /^(.*,\s*)?\Q$login\E(,.*)?$/);
      my $innew = ($change->{new} =~ /^(.*,\s*)?\Q$login\E(,.*)?$/);
      if ($inold != $innew) {
        $events{+EVT_ADDED_REMOVED} = 1;
      }
2152
    }
2153 2154 2155 2156 2157 2158
  }

  if (!$bug->lastdiffed) {

    # Notify about new bugs.
    $events{+EVT_BUG_CREATED} = 1;
2159

2160 2161 2162 2163 2164 2165 2166
    # 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
      || $relationship == REL_QA
      || $relationship == REL_CC)
    {
      $events{+EVT_ADDED_REMOVED} = 1;
2167
    }
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
  }

  if (grep { $_->type == CMT_ATTACHMENT_CREATED } @$comments) {
    $events{+EVT_ATTACHMENT} = 1;
  }
  elsif (defined($$comments[0])) {
    $events{+EVT_COMMENT} = 1;
  }

  # Dependent changed bugmails must have an event to ensure the bugmail is
  # emailed.
  if ($dep_mail) {
    $events{+EVT_DEPEND_BLOCK} = 1;
  }

  my @event_list = keys %events;

  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->id == $changer->id)) {
    $wants_mail &= $self->wants_mail([EVT_CHANGED_BY_ME], $relationship);
  }

  if ($wants_mail && $bug->bug_status eq 'UNCONFIRMED') {
    $wants_mail &= $self->wants_mail([EVT_UNCONFIRMED], $relationship);
  }

  return $wants_mail;
2201 2202
}

2203 2204
# Returns true if the user wants mail for a given set of events.
sub wants_mail {
2205 2206 2207 2208 2209 2210 2211 2212
  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'};
2213

2214 2215
  # No mail if there are no events
  return 0 if !scalar(@$events);
2216

2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
  # If a relationship isn't given, default to REL_ANY.
  if (!defined($relationship)) {
    $relationship = REL_ANY;
  }

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

  my $wants_mail = grep { $self->mail_settings->{$relationship}{$_} } @$events;
  return $wants_mail ? 1 : 0;
2227 2228 2229
}

sub mail_settings {
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
  my $self = shift;
  my $dbh  = Bugzilla->dbh;

  if (!defined $self->{'mail_settings'}) {
    my $data = $dbh->selectall_arrayref(
      'SELECT relationship, event FROM email_setting
                                    WHERE user_id = ?', undef, $self->id
    );
    my %mail;

    # The hash is of the form $mail{$relationship}{$event} = 1.
    $mail{$_->[0]}{$_->[1]} = 1 foreach @$data;

    $self->{'mail_settings'} = \%mail;
  }
  return $self->{'mail_settings'};
2246
}
2247

2248
sub has_audit_entries {
2249 2250
  my $self = shift;
  my $dbh  = Bugzilla->dbh;
2251

2252 2253 2254 2255 2256 2257 2258
  if (!exists $self->{'has_audit_entries'}) {
    $self->{'has_audit_entries'}
      = $dbh->selectrow_array(
      'SELECT 1 FROM audit_log WHERE user_id = ? ' . $dbh->sql_limit(1),
      undef, $self->id);
  }
  return $self->{'has_audit_entries'};
2259 2260
}

2261
sub is_insider {
2262
  my $self = shift;
2263

2264 2265 2266 2267 2268 2269
  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'};
2270 2271
}

2272
sub is_global_watcher {
2273
  my $self = shift;
2274

2275 2276 2277 2278 2279 2280
  if (!defined $self->{'is_global_watcher'}) {
    my @watchers = split(/[,;]+/, Bugzilla->params->{'globalwatchers'});
    $self->{'is_global_watcher'}
      = scalar(grep { $_ eq $self->login } @watchers) ? 1 : 0;
  }
  return $self->{'is_global_watcher'};
2281 2282
}

2283
sub is_timetracker {
2284
  my $self = shift;
2285

2286 2287 2288 2289 2290
  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'};
2291 2292
}

2293
sub can_tag_comments {
2294
  my $self = shift;
2295

2296 2297 2298 2299 2300
  if (!defined $self->{'can_tag_comments'}) {
    my $group = Bugzilla->params->{'comment_taggers_group'};
    $self->{'can_tag_comments'} = ($group && $self->in_group($group)) ? 1 : 0;
  }
  return $self->{'can_tag_comments'};
2301 2302
}

2303
sub get_userlist {
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
  my $self = shift;

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

  my $dbh   = Bugzilla->dbh;
  my $query = "SELECT DISTINCT login_name, realname,";
  if (Bugzilla->params->{'usevisibilitygroups'}) {
    $query .= " COUNT(group_id) ";
  }
  else {
    $query .= " 1 ";
  }
  $query .= "FROM profiles ";
  if (Bugzilla->params->{'usevisibilitygroups'}) {
    $query
      .= "LEFT JOIN user_group_map "
      . "ON user_group_map.user_id = userid AND isbless = 0 "
      . "AND group_id IN("
      . join(', ', (-1, @{$self->visible_groups_inherited})) . ")";
  }
  $query .= " WHERE is_enabled = 1 ";
  $query .= $dbh->sql_group_by('userid', 'login_name, realname');

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

2345
sub create {
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
  my $invocant = shift;
  my $class    = ref($invocant) || $invocant;
  my $dbh      = Bugzilla->dbh;

  $dbh->bz_start_transaction();

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

  # Turn on all email for the new user
  require Bugzilla::BugMail;
  my %relationships = Bugzilla::BugMail::relationships();
  foreach my $rel (keys %relationships) {
    foreach my $event (POS_EVENTS, NEG_EVENTS) {

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

      $dbh->do(
        'INSERT INTO email_setting (user_id, relationship, event)
                      VALUES (?, ?, ?)', undef, ($user->id, $rel, $event)
      );
    }
  }

  foreach my $event (GLOBAL_EVENTS) {
    $dbh->do(
      'INSERT INTO email_setting (user_id, relationship, event)
                  VALUES (?, ?, ?)', undef, ($user->id, REL_ANY, $event)
    );
  }
2380

2381
  $user->derive_regexp_groups();
2382

2383 2384 2385 2386 2387
  # 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');
2388

2389 2390
  $dbh->do(
    'INSERT INTO profiles_activity
2391
                          (userid, who, profiles_when, fieldid, newvalue)
2392 2393 2394
                   VALUES (?, ?, NOW(), ?, NOW())', undef,
    ($user->id, $who, $creation_date_fieldid)
  );
2395

2396
  $dbh->bz_commit_transaction();
2397

2398 2399
  # Return the newly created user account.
  return $user;
2400 2401
}

2402 2403 2404 2405 2406
###########################
# Account Lockout Methods #
###########################

sub account_is_locked_out {
2407 2408 2409
  my $self           = shift;
  my $login_failures = scalar @{$self->account_ip_login_failures};
  return $login_failures >= MAX_LOGIN_ATTEMPTS ? 1 : 0;
2410 2411 2412
}

sub note_login_failure {
2413 2414 2415 2416 2417 2418 2419 2420
  my $self    = shift;
  my $ip_addr = remote_ip();
  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};
2421 2422 2423
}

sub clear_login_failures {
2424 2425 2426 2427 2428 2429
  my $self    = shift;
  my $ip_addr = remote_ip();
  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};
2430 2431 2432
}

sub account_ip_login_failures {
2433 2434 2435 2436 2437 2438 2439 2440
  my $self = shift;
  my $dbh  = Bugzilla->dbh;
  my $time = $dbh->sql_date_math('LOCALTIMESTAMP(0)', '-', LOGIN_LOCKOUT_INTERVAL,
    'MINUTE');
  my $ip_addr = remote_ip();
  trick_taint($ip_addr);
  $self->{account_ip_login_failures} ||= Bugzilla->dbh->selectall_arrayref(
    "SELECT login_time, ip_addr, user_id FROM login_failure
2441
          WHERE user_id = ? AND login_time > $time
2442
                AND ip_addr = ?
2443 2444 2445
       ORDER BY login_time", {Slice => {}}, $self->id, $ip_addr
  );
  return $self->{account_ip_login_failures};
2446 2447 2448 2449 2450 2451
}

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

2452
sub is_available_username {
2453
  my ($username, $old_username) = @_;
2454

2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
  if (login_to_id($username) != 0) {
    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
  # the new/old email addresses and sql_position() to find the delimiter (':')
  # is cleaner/safer
  my ($tokentype, $eventdata) = $dbh->selectrow_array(
    "SELECT tokentype, eventdata
2473 2474
           FROM tokens
          WHERE (tokentype = 'emailold'
2475 2476
                AND SUBSTRING(eventdata, 1, ("
      . $dbh->sql_position(q{':'}, 'eventdata') . "-  1)) = ?)
2477
             OR (tokentype = 'emailnew'
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
                AND SUBSTRING(eventdata, ("
      . $dbh->sql_position(q{':'}, 'eventdata')
      . "+ 1), LENGTH(eventdata)) = ?)",
    undef, ($username, $username)
  );

  if ($eventdata) {

    # Allow thru owner of token
    if (
      $old_username
      && ( ($tokentype eq 'emailnew' && $eventdata eq "$old_username:$username")
        || ($tokentype eq 'emailold' && $eventdata eq "$username:$old_username"))
      )
    {
      return 1;
2494
    }
2495 2496
    return 0;
  }
2497

2498
  return 1;
2499 2500
}

2501
sub check_account_creation_enabled {
2502
  my $self = shift;
2503

2504 2505 2506
  # If we're using e.g. LDAP for login, then we can't create a new account.
  $self->authorizer->user_can_create_account
    || ThrowUserError('auth_cant_create_account');
2507

2508 2509
  Bugzilla->params->{'createemailregexp'}
    || ThrowUserError('account_creation_disabled');
2510 2511 2512
}

sub check_and_send_account_creation_confirmation {
2513 2514
  my ($self, $login) = @_;
  my $dbh = Bugzilla->dbh;
2515

2516
  $dbh->bz_start_transaction;
2517

2518 2519
  $login = $self->check_login_name($login);
  my $creation_regexp = Bugzilla->params->{'createemailregexp'};
2520

2521 2522 2523
  if ($login !~ /$creation_regexp/i) {
    ThrowUserError('account_creation_restricted');
  }
2524

2525 2526
  # Allow extensions to do extra checks.
  Bugzilla::Hook::process('user_check_account_creation', {login => $login});
2527

2528 2529 2530
  # Create and send a token for this new account.
  require Bugzilla::Token;
  Bugzilla::Token::issue_new_user_account_token($login);
2531

2532
  $dbh->bz_commit_transaction;
2533 2534
}

2535 2536
# This is used in a few performance-critical areas where we don't want to
# do check() and pull all the user data from the database.
2537
sub login_to_id {
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
  my ($login, $throw_error) = @_;
  my $dbh = Bugzilla->dbh;
  my $cache = Bugzilla->request_cache->{user_login_to_id} ||= {};

  # We cache lookups because this function showed up as taking up a
  # significant amount of time in profiles of xt/search.t. However,
  # for users that don't exist, we re-do the check every time, because
  # otherwise we break is_available_username.
  my $user_id;
  if (defined $cache->{$login}) {
    $user_id = $cache->{$login};
  }
  else {
    # No need to validate $login -- it will be used by the following SELECT
    # statement only, so it's safe to simply trick_taint.
    trick_taint($login);
    $user_id = $dbh->selectrow_array(
      "SELECT userid FROM profiles 
              WHERE " . $dbh->sql_istrcmp('login_name', '?'), undef, $login
    );
    $cache->{$login} = $user_id;
  }

  if ($user_id) {
    return $user_id;
  }
  elsif ($throw_error) {
    ThrowUserError('invalid_username', {name => $login});
  }
  else {
    return 0;
  }
2570 2571
}

2572
sub validate_password {
2573 2574 2575
  my $check = validate_password_check(@_);
  ThrowUserError($check) if $check;
  return 1;
2576 2577 2578
}

sub validate_password_check {
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
  my ($password, $matchpassword) = @_;

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

  my $complexity_level = Bugzilla->params->{password_complexity};
  if ($complexity_level eq 'letters_numbers_specialchars') {
    return 'password_not_complex'
      if ($password !~ /[[:alpha:]]/
      || $password !~ /\d/
      || $password !~ /[[:punct:]]/);
  }
  elsif ($complexity_level eq 'letters_numbers') {
    return 'password_not_complex'
      if ($password !~ /[[:lower:]]/
      || $password !~ /[[:upper:]]/
      || $password !~ /\d/);
  }
  elsif ($complexity_level eq 'mixed_letters') {
    return 'password_not_complex'
      if ($password !~ /[[:lower:]]/ || $password !~ /[[:upper:]]/);
  }

  # Having done these checks makes us consider the password untainted.
  trick_taint($_[0]);
  return;
2609 2610
}

2611

2612
1;
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625

__END__

=head1 NAME

Bugzilla::User - Object for a Bugzilla user

=head1 SYNOPSIS

  use Bugzilla::User;

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

2626 2627 2628
  my @get_selectable_classifications = 
      $user->get_selectable_classifications;

2629
  # Class Functions
2630 2631 2632 2633 2634 2635
  $user = Bugzilla::User->create({ 
      login_name    => $username, 
      realname      => $realname, 
      cryptpassword => $plaintext_password, 
      disabledtext  => $disabledtext,
      disable_mail  => 0});
2636

2637 2638 2639 2640 2641 2642 2643 2644
=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">.

2645 2646 2647 2648
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.

2649 2650
=head1 CONSTANTS

2651 2652
=over

2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
=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.

2673 2674
=back

2675 2676
=head1 METHODS

2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
=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

2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
=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.

2721 2722 2723 2724 2725
=item C<tags>

Returns a hashref with tag IDs as key, and a hashref with tag 'id',
'name' and 'bug_count' as value.

2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
=item C<bugs_ignored>

Returns an array of hashrefs containing information about bugs currently
being ignored by the user.

Each hashref contains the following information:

=over

=item C<id>

C<int> The id of the bug.

=item C<status>

C<string> The current status of the bug.

=item C<summary>

C<string> The current summary of the bug.

=back

=item C<is_bug_ignored>

Returns true if the user does not want email notifications for the
specified bug ID, else returns false.

2754 2755
=back

2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
=head2 Saved Recent Bug Lists

=over

=item C<recent_searches>

Returns an arrayref of L<Bugzilla::Search::Recent> objects
containing the user's recent searches.

=item C<recent_search_containing(bug_id)>

Returns a L<Bugzilla::Search::Recent> object that contains the most recent
search by the user for the specified bug id. Retuns undef if no match is found.

=item C<recent_search_for(bug)>

Returns a L<Bugzilla::Search::Recent> object that contains a search by the
user. Uses the list_id of the current loaded page, or the referrer page, and
the bug id if that fails. Finally it will check the BUGLIST cookie, and create
an object based on that, or undef if it does not exist.

=item C<save_last_search>

Saves the users most recent search in the database if logged in, or in the
2780
BUGLIST cookie if not logged in. Parameters are bug_ids, order, vars and
2781 2782 2783 2784
list_id.

=back

2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
=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>.

2806 2807 2808 2809
=item C<set_email_enabled>

C<bool> - Sets C<disable_mail> to the inverse of the boolean provided.

2810 2811
=back

2812 2813
=head2 Other Methods

2814
=over
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834

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

2835
Returns C<1> if the user has set their preference to show the 'My Bugs' link in
2836 2837 2838 2839
the page footer, and C<0> otherwise.

=item C<identity>

2840
Returns a string for the identity of the user. This will be of the form
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
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.

2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
=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.

2862 2863 2864 2865
=item C<disabledtext>

Returns the disable text of the user, if any.

2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
=item C<reports>

Returns an arrayref of the user's own saved reports. The array contains 
L<Bugzilla::Reports> objects.

=item C<flush_reports_cache>

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

2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
=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.

2891 2892 2893 2894
=item C<setting(name)>

Returns the value for the specified setting.

2895 2896 2897 2898 2899
=item C<timezone>

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

2900 2901
=item C<groups>

2902 2903
Returns an arrayref of L<Bugzilla::Group> objects representing
groups that this user is a member of.
2904

2905 2906
=item C<groups_as_string>

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

2911 2912 2913 2914 2915 2916 2917
=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.

2918
=item C<in_group($group_name, $product_id)>
2919

2920 2921 2922
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.
2923 2924 2925 2926

=item C<in_group_id>

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

2928 2929
=item C<bless_groups>

2930 2931
Returns an arrayref of L<Bugzilla::Group> objects.

2932 2933
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
2934
that you need to be able to see a group in order to bless it.
2935

2936 2937 2938
=item C<get_products_by_permission($group)>

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

2942 2943 2944 2945 2946
=item C<can_see_user(user)>

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

2947 2948 2949 2950 2951
=item C<can_edit_product(prod_id)>

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

2952 2953 2954 2955 2956 2957
=item C<visible_bugs($bugs)>

Description: Determines if a list of bugs are visible to the user.
Params:      C<$bugs> - An arrayref of Bugzilla::Bug objects or bug ids
Returns:     An arrayref of the bug ids that the user can see

2958 2959 2960 2961
=item C<can_see_bug(bug_id)>

Determines if the user can see the specified bug.

2962 2963 2964 2965 2966
=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.

2967
=item C<derive_regexp_groups>
2968 2969 2970 2971 2972 2973 2974

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.

2975 2976 2977 2978 2979 2980
=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>.

2981 2982
=item C<get_selectable_products>

2983 2984 2985
 Description: Returns all products the user is allowed to access. This list
              is restricted to some given classification if $classification_id
              is given.
2986

2987 2988
 Params:      $classification_id - (optional) The ID of the classification
                                   the products belong to.
2989

2990
 Returns:     An array of product objects, sorted by the product name.
2991

2992 2993
=item C<get_selectable_classifications>

2994 2995
 Description: Returns all classifications containing at least one product
              the user is allowed to view.
2996

2997
 Params:      none
2998

2999 3000
 Returns:     An array of Bugzilla::Classification objects, sorted by
              the classification name.
3001

3002 3003
=item C<can_enter_product($product_name, $warn)>

3004 3005
 Description: Returns a product object if the user can enter bugs into the
              specified product.
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
              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.

3016
 Returns:     A product object if the user can enter bugs into the product,
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
              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.

3029
=item C<can_access_product($product)>
3030

3031 3032 3033
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.
3034 3035 3036 3037 3038 3039 3040 3041 3042 3043

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

3044 3045 3046 3047
=item C<can_administer>

Returns 1 if the user can see the admin menu. Otherwise, returns 0

3048 3049 3050 3051 3052 3053 3054 3055
=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.

3056 3057 3058 3059 3060
=item C<check_can_admin_flagtype($flagtype_id)>

 Description: Checks whether the user is allowed to edit properties of the flag type.
              If the flag type is also used by some products for which the user
              hasn't editcomponents privs, then the user is only allowed to edit
3061
              the inclusion and exclusion lists for products they can administrate.
3062 3063 3064 3065 3066 3067 3068 3069 3070

 Params:      $flagtype_id - a flag type ID.

 Returns:     On success, a flag type object. On failure, an error is thrown.
              In list context, a boolean indicating whether the user can edit
              all properties of the flag type is also returned. The boolean
              is false if the user can only edit the inclusion and exclusions
              lists.

3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
=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.

3089 3090 3091 3092 3093 3094
=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.

3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
=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.

3105 3106
=item C<visible_groups_as_string>

3107
Returns the result of C<visible_groups_inherited> as a string (a comma-separated
3108 3109
list).

3110 3111
=item C<product_responsibilities>

3112 3113
Retrieve user's product responsibilities as a list of component objects.
Each object is a component the user has a responsibility for.
3114

3115 3116
=item C<can_bless>

3117 3118 3119 3120
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:
3121
Returns C<1> if the user can bless the group with that id, returns
3122
C<0> otherwise.
3123

3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
=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.

3134 3135 3136 3137 3138
=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.

3139 3140 3141 3142 3143
=item C<is_global_watcher>

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

3144 3145 3146 3147 3148 3149
=item C<can_tag_comments>

Returns true if the user can attach tags to comments.
i.e. if the 'comment_taggers_group' parameter is set and the user belongs to
this group.

3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
=item C<last_visited>

Returns an arrayref L<Bugzilla::BugUserLastVisit> objects.

=item C<is_involved_in_bug($bug)>

Returns true if any of the following conditions are met, false otherwise.

=over

=item *

User is the assignee of the bug

=item *

User is the reporter of the bug

=item *

User is the QA contact of the bug (if Bugzilla is configured to use a QA
contact)

=item *

User is in the cc list for the bug.

=back

3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209
=item C<set_groups>

C<hash> These specify the groups that this user is directly a member of.
To set these, you should pass a hash as the value. The hash may contain
the following fields:

=over

=item C<add> An array of C<int>s or C<string>s. The group ids or group names
that the user should be added to.

=item C<remove> An array of C<int>s or C<string>s. The group ids or group names
that the user should be removed from.

=item C<set> An array of C<int>s or C<string>s. An exact set of group ids
and group names that the user should be a member of. NOTE: This does not
remove groups from the user where the person making the change does not
have the bless privilege for.

If you specify C<set>, then C<add> and C<remove> will be ignored. A group in
both the C<add> and C<remove> list will be added. Specifying a group that the
user making the change does not have bless rights will generate an error.

=back

=item C<set_bless_groups>

C<hash> - This is the same as set_groups, but affects what groups a user
has direct membership to bless that group. It takes the same inputs as
set_groups.

3210 3211
=back

3212 3213 3214 3215 3216
=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.

3217 3218
=over 4

3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
=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 
3230
            will be disabled, meaning they cannot log in. Defaults to an
3231 3232 3233
            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.
3234

3235 3236 3237 3238 3239
=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.

3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
=item C<check_account_creation_enabled>

Checks that users can create new user accounts, and throws an error
if user creation is disabled.

=item C<check_and_send_account_creation_confirmation($login)>

If the user request for a new account passes validation checks, an email
is sent to this user for confirmation. Otherwise an error is thrown
indicating why the request has been rejected.

3251 3252 3253 3254 3255 3256 3257 3258 3259
=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,
3260 3261
            here. Then, as long as it's the right user for that token, they
            can change their username to $username. (That is, this function
3262 3263
            will return a boolean true value).

3264
=item C<login_to_id($login, $throw_error)>
3265 3266 3267 3268 3269

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.

3270 3271 3272
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.
3273 3274 3275 3276 3277 3278 3279

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.

3280 3281 3282
=item C<validate_password($passwd1, $passwd2)>

Returns true if a password is valid (i.e. meets Bugzilla's
3283
requirements for length and content), else throws an error.
3284
Untaints C<$passwd1> if successful.
3285 3286

If a second password is passed in, this function also verifies that
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
the two passwords match.

=item C<validate_password_check($passwd1, $passwd2)>

This sub routine is similair to C<validate_password>, except that it allows
the calling code to handle its own errors.

Returns undef and untaints C<$passwd1> if a password is valid (i.e. meets
Bugzilla's requirements for length and content), else returns the error.

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

3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
=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

3343 3344
=back

3345 3346 3347
=head1 SEE ALSO

L<Bugzilla|Bugzilla>
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399

=head1 B<Methods in need of POD>

=over

=item email_enabled

=item cryptpassword

=item clear_login_failures

=item set_disable_mail

=item has_audit_entries

=item groups_with_icon

=item check_login_name

=item set_extern_id

=item mail_settings

=item email_disabled

=item update

=item is_timetracker

=item is_enabled

=item queryshare_groups_as_string

=item set_login

=item set_password

=item last_seen_date

=item set_disabledtext

=item update_last_seen_date

=item set_name

=item DB_COLUMNS

=item extern_id

=item UPDATE_COLUMNS

=back