User.pm 46.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Myk Melez <myk@mozilla.org>
21
#                 Erik Stambaugh <erik@dasbistro.com>
22 23
#                 Bradley Baetz <bbaetz@acm.org>
#                 Joel Peshkin <bugreport@peshkin.net> 
24
#                 Byron Jones <bugzilla@glob.com.au>
25
#                 Shane H. W. Travis <travis@sedsystems.ca>
26
#                 Max Kanat-Alexander <mkanat@kerio.com>
27 28 29 30 31 32 33 34 35 36 37

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

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

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

38
use Bugzilla::Config;
39
use Bugzilla::Error;
40
use Bugzilla::Util;
41
use Bugzilla::Constants;
42
use Bugzilla::User::Setting;
43 44
use Bugzilla::Auth;

45
use base qw(Exporter);
46 47
@Bugzilla::User::EXPORT = qw(insert_new_user is_available_username
    login_to_id
48
    UserInGroup
49
);
50

51 52 53 54 55
################################################################################
# Functions
################################################################################

sub new {
56
    my $invocant = shift;
57 58 59
    if (scalar @_ == 0) {
        return $invocant->_create;
    }
60 61
    return $invocant->_create("userid=?", @_);
}
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
# This routine is sort of evil. Nothing except the login stuff should
# be dealing with addresses as an input, and they can get the id as a
# side effect of the other sql they have to do anyway.
# Bugzilla::BugMail still does this, probably as a left over from the
# pre-id days. Provide this as a helper, but don't document it, and hope
# that it can go away.
# The request flag stuff also does this, but it really should be passing
# in the id its already had to validate (or the User.pm object, of course)
sub new_from_login {
    my $invocant = shift;
    return $invocant->_create("login_name=?", @_);
}

# Internal helper for the above |new| methods
# $cond is a string (including a placeholder ?) for the search
# requirement for the profiles table
sub _create {
80 81
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
82 83 84 85

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

86 87 88 89 90 91
    # Allow invocation with no parameters to create a blank object
    my $self = {
        'id'             => 0,
        'name'           => '',
        'login'          => '',
        'showmybugslink' => 0,
92
        'disabledtext'   => '',
93
        'flags'          => {},
94 95
    };
    bless ($self, $class);
96
    return $self unless $cond && $val;
97

98 99 100 101 102 103 104 105 106 107
    # We're checking for validity here, so any value is OK
    trick_taint($val);

    my $tables_locked_for_derive_groups = shift;

    my $dbh = Bugzilla->dbh;

    my ($id,
        $login,
        $name,
108
        $disabledtext,
109 110 111
        $mybugslink) = $dbh->selectrow_array(qq{SELECT userid,
                                                       login_name,
                                                       realname,
112
                                                       disabledtext,
113 114 115 116 117 118 119 120
                                                       mybugslink
                                                  FROM profiles
                                                 WHERE $cond},
                                             undef,
                                             $val);

    return undef unless defined $id;

121 122 123
    $self->{'id'}             = $id;
    $self->{'name'}           = $name;
    $self->{'login'}          = $login;
124
    $self->{'disabledtext'}   = $disabledtext;
125
    $self->{'showmybugslink'} = $mybugslink;
126 127 128 129 130 131 132 133 134 135 136

    # Now update any old group information if needed
    my $result = $dbh->selectrow_array(q{SELECT 1
                                           FROM profiles, groups
                                          WHERE userid=?
                                            AND profiles.refreshed_when <=
                                                  groups.last_changed},
                                       undef,
                                       $id);

    if ($result) {
137 138 139 140
        my $is_main_db;
        unless ($is_main_db = Bugzilla->dbwritesallowed()) {
            Bugzilla->switch_to_main_db();
        }
141
        $self->derive_groups($tables_locked_for_derive_groups);
142 143 144
        unless ($is_main_db) {
            Bugzilla->switch_to_shadow_db();
        }
145
    }
146

147 148 149
    return $self;
}

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

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

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

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

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

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

    return $self->{identity};
}

sub nick {
    my $self = shift;

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

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

    return $self->{nick};
}

sub queries {
    my $self = shift;

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

    my $dbh = Bugzilla->dbh;
206 207
    my $sth = $dbh->prepare(q{ SELECT
                             DISTINCT name, query, linkinfooter,
208 209 210
                                      CASE WHEN whine_queries.id 
                                      IS NOT NULL THEN 1 ELSE 0 END,
                                      UPPER(name) AS uppername 
211 212 213 214
                                 FROM namedqueries
                            LEFT JOIN whine_queries
                                   ON whine_queries.query_name = name
                                WHERE userid=?
215
                             ORDER BY uppername});
216 217 218 219 220 221 222 223
    $sth->execute($self->{id});

    my @queries;
    while (my $row = $sth->fetch) {
        push (@queries, {
                          name         => $row->[0],
                          query        => $row->[1],
                          linkinfooter => $row->[2],
224
                          usedinwhine  => $row->[3],
225 226 227 228 229 230 231
                        });
    }
    $self->{queries} = \@queries;

    return $self->{queries};
}

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

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

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

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

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

    delete $self->{queries};
}

sub groups {
    my $self = shift;

    return $self->{groups} if defined $self->{groups};
259
    return {} unless $self->id;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

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

    # The above gives us an arrayref [name, id, name, id, ...]
    # Convert that into a hashref
    my %groups = @$groups;
    $self->{groups} = \%groups;

    return $self->{groups};
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
sub bless_groups {
    my $self = shift;

    return $self->{bless_groups} if defined $self->{bless_groups};
    return {} unless $self->id;

    my $dbh = Bugzilla->dbh;
    # Get all groups for the user where:
    #    + They have direct bless privileges
    #    + They are a member of a group that inherits bless privs.
    # Because of the second requirement, derive_groups must be up-to-date
    # for this to function properly in all circumstances.
    my $bless_groups = $dbh->selectcol_arrayref(
        q{SELECT DISTINCT groups.name, groups.id
            FROM groups, user_group_map, group_group_map AS ggm
           WHERE user_group_map.user_id = ?
             AND ((user_group_map.isbless = 1
                   AND groups.id=user_group_map.group_id)
                  OR (groups.id = ggm.grantor_id
                      AND ggm.grant_type = } . GROUP_BLESS .
                   q{ AND user_group_map.group_id = ggm.member_id
                      AND user_group_map.isbless = 0))},
         { Columns=>[1,2] }, $self->{id});

    # The above gives us an arrayref [name, id, name, id, ...]
    # Convert that into a hashref
    my %bless_groups_hashref = @$bless_groups;
    $self->{bless_groups} = \%bless_groups_hashref;

    return $self->{bless_groups};
}

310 311 312 313 314
sub in_group {
    my ($self, $group) = @_;

    # If we already have the info, just return it.
    return defined($self->{groups}->{$group}) if defined $self->{groups};
315
    return 0 unless $self->id;
316 317 318 319 320

    # Otherwise, go check for it

    my $dbh = Bugzilla->dbh;

321
    my ($res) = $dbh->selectrow_array(q{SELECT 1
322 323 324 325 326 327 328 329 330 331 332 333
                                  FROM groups, user_group_map
                                 WHERE groups.id=user_group_map.group_id
                                   AND user_group_map.user_id=?
                                   AND isbless=0
                                   AND groups.name=?},
                              undef,
                              $self->id,
                              $group);

    return defined($res);
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
sub can_see_bug {
    my ($self, $bugid) = @_;
    my $dbh = Bugzilla->dbh;
    my $sth  = $self->{sthCanSeeBug};
    my $userid  = $self->{id};
    # Get fields from bug, presence of user on cclist, and determine if
    # the user is missing any groups required by the bug. The prepared query
    # is cached because this may be called for every row in buglists or
    # every bug in a dependency list.
    unless ($sth) {
        $sth = $dbh->prepare("SELECT reporter, assigned_to, qa_contact,
                             reporter_accessible, cclist_accessible,
                             COUNT(cc.who), COUNT(bug_group_map.bug_id)
                             FROM bugs
                             LEFT JOIN cc 
                               ON cc.bug_id = bugs.bug_id
                               AND cc.who = $userid
                             LEFT JOIN bug_group_map 
                               ON bugs.bug_id = bug_group_map.bug_id
                               AND bug_group_map.group_ID NOT IN(" .
                               join(',',(-1, values(%{$self->groups}))) .
                               ") WHERE bugs.bug_id = ? GROUP BY bugs.bug_id");
    }
    $sth->execute($bugid);
    my ($reporter, $owner, $qacontact, $reporter_access, $cclist_access,
        $isoncclist, $missinggroup) = $sth->fetchrow_array();
360
    $sth->finish;
361 362
    $self->{sthCanSeeBug} = $sth;
    return ( (($reporter == $userid) && $reporter_access)
363 364
           || (Param('useqacontact') && $qacontact && 
              ($qacontact == $userid))
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
           || ($owner == $userid)
           || ($isoncclist && $cclist_access)
           || (!$missinggroup) );
}

sub get_selectable_products {
    my ($self, $by_id) = @_;

    if (defined $self->{SelectableProducts}) {
        my %list = @{$self->{SelectableProducts}};
        return \%list if $by_id;
        return values(%list);
    }

    my $query = "SELECT id, name " .
                "FROM products " .
                "LEFT JOIN group_control_map " .
                "ON group_control_map.product_id = products.id ";
    if (Param('useentrygroupdefault')) {
        $query .= "AND group_control_map.entry != 0 ";
    } else {
        $query .= "AND group_control_map.membercontrol = " .
                  CONTROLMAPMANDATORY . " ";
    }
    $query .= "AND group_id NOT IN(" . 
               join(',', (-1,values(%{Bugzilla->user->groups}))) . ") " .
              "WHERE group_id IS NULL ORDER BY name";
    my $dbh = Bugzilla->dbh;
    my $sth = $dbh->prepare($query);
    $sth->execute();
    my @products = ();
    while (my @row = $sth->fetchrow_array) {
        push(@products, @row);
    }
    $self->{SelectableProducts} = \@products;
    my %list = @products;
    return \%list if $by_id;
    return values(%list);
}

405 406 407 408 409
# visible_groups_inherited returns a reference to a list of all the groups
# whose members are visible to this user.
sub visible_groups_inherited {
    my $self = shift;
    return $self->{visible_groups_inherited} if defined $self->{visible_groups_inherited};
410
    return [] unless $self->id;
411
    my @visgroups = @{$self->visible_groups_direct};
412
    @visgroups = @{$self->flatten_group_membership(@visgroups)};
413 414 415 416 417 418 419 420 421 422
    $self->{visible_groups_inherited} = \@visgroups;
    return $self->{visible_groups_inherited};
}

# visible_groups_direct returns a reference to a list of all the groups that
# are visible to this user.
sub visible_groups_direct {
    my $self = shift;
    my @visgroups = ();
    return $self->{visible_groups_direct} if defined $self->{visible_groups_direct};
423
    return [] unless $self->id;
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

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

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

    return $self->{visible_groups_direct};
}

441 442 443 444
sub derive_groups {
    my ($self, $already_locked) = @_;

    my $id = $self->id;
445
    return unless $id;
446 447 448 449 450

    my $dbh = Bugzilla->dbh;

    my $sth;

451 452 453
    $dbh->bz_lock_tables('profiles WRITE', 'user_group_map WRITE',
                         'group_group_map READ',
                         'groups READ') unless $already_locked;
454 455 456 457 458 459 460

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

    # first remove any old derived stuff for this user
    $dbh->do(q{DELETE FROM user_group_map
                      WHERE user_id = ?
461
                        AND grant_type != ?},
462
             undef,
463 464
             $id,
             GRANT_DIRECT);
465 466 467 468 469 470 471 472 473 474 475

    my %groupidsadded = ();
    # add derived records for any matching regexps

    $sth = $dbh->prepare("SELECT id, userregexp FROM groups WHERE userregexp != ''");
    $sth->execute;

    my $group_insert;
    while (my $row = $sth->fetch) {
        if ($self->{login} =~ m/$row->[1]/i) {
            $group_insert ||= $dbh->prepare(q{INSERT INTO user_group_map
476 477
                                              (user_id, group_id, isbless, grant_type)
                                              VALUES (?, ?, 0, ?)});
478
            $groupidsadded{$row->[0]} = 1;
479
            $group_insert->execute($id, $row->[0], GRANT_REGEXP);
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        }
    }

    # Get a list of the groups of which the user is a member.
    my %groupidschecked = ();

    my @groupidstocheck = @{$dbh->selectcol_arrayref(q{SELECT group_id
                                                         FROM user_group_map
                                                        WHERE user_id=?},
                                                     undef,
                                                     $id)};

    # Each group needs to be checked for inherited memberships once.
    my $group_sth;
    while (@groupidstocheck) {
        my $group = shift @groupidstocheck;
        if (!defined($groupidschecked{"$group"})) {
            $groupidschecked{"$group"} = 1;
            $group_sth ||= $dbh->prepare(q{SELECT grantor_id
                                             FROM group_group_map
                                            WHERE member_id=?
501 502
                                              AND grant_type = } .
                                                  GROUP_MEMBERSHIP);
503
            $group_sth->execute($group);
504
            while (my ($groupid) = $group_sth->fetchrow_array) {
505 506 507 508 509 510
                if (!defined($groupidschecked{"$groupid"})) {
                    push(@groupidstocheck,$groupid);
                }
                if (!$groupidsadded{$groupid}) {
                    $groupidsadded{$groupid} = 1;
                    $group_insert ||= $dbh->prepare(q{INSERT INTO user_group_map
511 512 513
                                                      (user_id, group_id, isbless, grant_type)
                                                      VALUES (?, ?, 0, ?)});
                    $group_insert->execute($id, $groupid, GRANT_DERIVED);
514 515 516 517 518 519 520 521 522 523 524
                }
            }
        }
    }

    $dbh->do(q{UPDATE profiles
                  SET refreshed_when = ?
                WHERE userid=?},
             undef,
             $time,
             $id);
525
    $dbh->bz_unlock_tables() unless $already_locked;
526 527 528 529 530
}

sub can_bless {
    my $self = shift;

531 532 533 534
    if (!scalar(@_)) {
        # If we're called without an argument, just return 
        # whether or not we can bless at all.
        return scalar(keys %{$self->bless_groups}) ? 1 : 0;
535 536
    }

537 538 539
    # Otherwise, we're checking a specific group
    my $group_name = shift;
    return exists($self->bless_groups->{$group_name});
540 541
}

542
sub flatten_group_membership {
543
    my ($self, @groups) = @_;
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

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

566 567
sub match {
    # Generates a list of users whose login name (email address) or real name
568
    # matches a substring or wildcard.
569 570
    # This is also called if matches are disabled (for error checking), but
    # in this case only the exact match code will end up running.
571

572
    # $str contains the string to match, while $limit contains the
573 574 575
    # maximum number of records to retrieve.
    my ($str, $limit, $exclude_disabled) = @_;
    
576 577 578 579
    my @users = ();

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

580
    # The search order is wildcards, then exact match, then substring search.
581 582 583 584 585 586 587
    # 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;
588
    my $user = Bugzilla->user;
589
    my $dbh = Bugzilla->dbh;
590

591 592
    if ($wildstr =~ s/\*/\%/g && # don't do wildcards if no '*' in the string
        Param('usermatchmode') ne 'off') { # or if we only want exact matches
593 594 595

        # Build the query.
        my $sqlstr = &::SqlQuote($wildstr);
596 597 598 599 600 601
        my $query  = "SELECT DISTINCT userid, realname, login_name " .
                     "FROM profiles ";
        if (&::Param('usevisibilitygroups')) {
            $query .= ", user_group_map ";
        }
        $query    .= "WHERE (login_name LIKE $sqlstr " .
602
                     "OR realname LIKE $sqlstr) ";
603 604 605 606 607 608 609 610
        if (&::Param('usevisibilitygroups')) {
            $query .= "AND user_group_map.user_id = userid " .
                      "AND isbless = 0 " .
                      "AND group_id IN(" .
                      join(', ', (-1, @{$user->visible_groups_inherited})) . ") " .
                      "AND grant_type <> " . GRANT_DERIVED;
        }
        $query    .= " AND disabledtext = '' " if $exclude_disabled;
611
        $query    .= "ORDER BY length(login_name) ";
612
        $query    .= $dbh->sql_limit($limit) if $limit;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

        # Execute the query, retrieve the results, and make them into
        # User objects.

        &::PushGlobalSQLState();
        &::SendSQL($query);
        push(@users, new Bugzilla::User(&::FetchSQLData())) while &::MoreSQLData();
        &::PopGlobalSQLState();

    }
    else {    # try an exact match

        my $sqlstr = &::SqlQuote($str);
        my $query  = "SELECT userid, realname, login_name " .
                     "FROM profiles " .
                     "WHERE login_name = $sqlstr ";
629
        # Exact matches don't care if a user is disabled.
630 631 632 633 634 635 636

        &::PushGlobalSQLState();
        &::SendSQL($query);
        push(@users, new Bugzilla::User(&::FetchSQLData())) if &::MoreSQLData();
        &::PopGlobalSQLState();
    }

637
    # then try substring search
638 639 640 641 642 643

    if ((scalar(@users) == 0)
        && (&::Param('usermatchmode') eq 'search')
        && (length($str) >= 3))
    {

644
        my $sqlstr = &::SqlQuote(uc($str));
645

646 647
        my $query   = "SELECT DISTINCT userid, realname, login_name " .
                      "FROM  profiles";
648
        if (&::Param('usevisibilitygroups')) {
649
            $query .= ", user_group_map";
650
        }
651 652 653 654
        $query     .= " WHERE " . $dbh->sql_position($sqlstr,
                                                     "UPPER(login_name)") .
                      " OR " . $dbh->sql_position($sqlstr,
                                                  "UPPER(realname)");
655
        if (&::Param('usevisibilitygroups')) {
656 657 658 659 660
            $query .= " AND user_group_map.user_id = userid" .
                      " AND isbless = 0" .
                      " AND group_id IN(" .
                join(', ', (-1, @{$user->visible_groups_inherited})) . ")" .
                      " AND grant_type <> " . GRANT_DERIVED;
661
        }
662 663 664
        $query     .= " AND disabledtext = ''" if $exclude_disabled;
        $query     .= " ORDER BY length(login_name)";
        $query     .= " " . $dbh->sql_limit($limit) if $limit;
665 666 667 668 669 670 671 672
        &::PushGlobalSQLState();
        &::SendSQL($query);
        push(@users, new Bugzilla::User(&::FetchSQLData())) while &::MoreSQLData();
        &::PopGlobalSQLState();
    }

    # order @users by alpha

673
    @users = sort { uc($a->login) cmp uc($b->login) } @users;
674 675 676 677

    return \@users;
}

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
# match_field() is a CGI wrapper for the match() function.
#
# Here's what it does:
#
# 1. Accepts a list of fields along with whether they may take multiple values
# 2. Takes the values of those fields from $::FORM and passes them to match()
# 3. Checks the results of the match and displays confirmation or failure
#    messages as appropriate.
#
# The confirmation screen functions the same way as verify-new-product and
# confirm-duplicate, by rolling all of the state information into a
# form which is passed back, but in this case the searched fields are
# replaced with the search results.
#
# The act of displaying the confirmation or failure messages means it must
# throw a template and terminate.  When confirmation is sent, all of the
# searchable fields have been replaced by exact fields and the calling script
# is executed as normal.
#
# match_field must be called early in a script, before anything external is
# done with the form data.
#
# In order to do a simple match without dealing with templates, confirmation,
# or globals, simply calling Bugzilla::User::match instead will be
# sufficient.

# How to call it:
#
# Bugzilla::User::match_field ({
#   'field_name'    => { 'type' => fieldtype },
#   'field_name2'   => { 'type' => fieldtype },
#   [...]
# });
#
# fieldtype can be either 'single' or 'multi'.
#

sub match_field {

    my $fields         = shift;   # arguments as a hash
    my $matches      = {};      # the values sent to the template
    my $matchsuccess = 1;       # did the match fail?
    my $need_confirm = 0;       # whether to display confirmation screen

    # prepare default form values

    my $vars = $::vars;
    $vars->{'form'}  = \%::FORM;
    $vars->{'mform'} = \%::MFORM;

728 729 730
    # What does a "--do_not_change--" field look like (if any)?
    my $dontchange = $vars->{'form'}->{'dontchange'};

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    # 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 %{$vars->{'form'}});
            foreach my $field_name (@field_names) {
                $expanded_fields->{$field_name} = 
                  { type => $fields->{$field_pattern}->{'type'} };
                
748 749 750
                # 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.
751
                if ($field_name =~ /^requestee-(\d+)$/) {
752 753 754 755 756
                    my $flag = Bugzilla::Flag::get($1);
                    $expanded_fields->{$field_name}->{'flag_type'} = 
                      $flag->{'type'};
                }
                elsif ($field_name =~ /^requestee_type-(\d+)$/) {
757 758 759 760 761 762 763 764
                    $expanded_fields->{$field_name}->{'flag_type'} = 
                      Bugzilla::FlagType::get($1);
                }
            }
        }
    }
    $fields = $expanded_fields;

765 766 767 768 769 770 771 772 773 774 775 776
    for my $field (keys %{$fields}) {

        # Tolerate fields that do not exist.
        #
        # This is so that fields like qa_contact can be specified in the code
        # and it won't break if $::MFORM does not define them.
        #
        # It has the side-effect that if a bad field name is passed it will be
        # quietly ignored rather than raising a code error.

        next if !defined($vars->{'mform'}->{$field});

777
        # Skip it if this is a --do_not_change-- field
778
        next if $dontchange && $dontchange eq $vars->{'form'}->{$field};
779

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        # We need to move the query to $raw_field, where it will be split up,
        # modified by the search, and put back into $::FORM and $::MFORM
        # incrementally.

        my $raw_field = join(" ", @{$vars->{'mform'}->{$field}});
        $vars->{'form'}->{$field}  = '';
        $vars->{'mform'}->{$field} = [];

        my @queries = ();

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

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

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

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

        }
        else {
            # bad argument
808 809 810 811
            ThrowCodeError('bad_arg',
                           { argument => $fields->{$field}->{'type'},
                             function =>  'Bugzilla::User::match_field',
                           });
812 813
        }

814 815 816 817 818
        my $limit = 0;
        if (&::Param('maxusermatches')) {
            $limit = &::Param('maxusermatches') + 1;
        }

819 820 821
        for my $query (@queries) {

            my $users = match(
822 823 824
                $query,   # match string
                $limit,   # match limit
                1         # exclude_disabled
825 826 827 828
            );

            # skip confirmation for exact matches
            if ((scalar(@{$users}) == 1)
829
                && (@{$users}[0]->{'login'} eq $query))
830
            {
831 832 833 834
                # delimit with spaces if necessary
                if ($vars->{'form'}->{$field}) {
                    $vars->{'form'}->{$field} .= " ";
                }
835 836
                $vars->{'form'}->{$field} .= @{$users}[0]->{'login'};
                push @{$vars->{'mform'}->{$field}}, @{$users}[0]->{'login'};
837 838 839
                next;
            }

840 841
            $matches->{$field}->{$query}->{'users'}  = $users;
            $matches->{$field}->{$query}->{'status'} = 'success';
842 843 844

            # here is where it checks for multiple matches

845 846 847 848 849
            if (scalar(@{$users}) == 1) { # exactly one match
                # delimit with spaces if necessary
                if ($vars->{'form'}->{$field}) {
                    $vars->{'form'}->{$field} .= " ";
                }
850 851
                $vars->{'form'}->{$field} .= @{$users}[0]->{'login'};
                push @{$vars->{'mform'}->{$field}}, @{$users}[0]->{'login'};
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
                $need_confirm = 1 if &::Param('confirmuniqueusermatch');

            }
            elsif ((scalar(@{$users}) > 1)
                    && (&::Param('maxusermatches') != 1)) {
                $need_confirm = 1;

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

            }
            else {
                # everything else fails
                $matchsuccess = 0; # fail
                $matches->{$field}->{$query}->{'status'} = 'fail';
                $need_confirm = 1;  # confirmation screen shows failures
            }
        }
    }

    return 1 unless $need_confirm; # skip confirmation if not needed.

    $vars->{'script'}        = $ENV{'SCRIPT_NAME'}; # for self-referencing URLs
879
    $vars->{'fields'}        = $fields; # fields being matched
880 881 882
    $vars->{'matches'}       = $matches; # matches that were made
    $vars->{'matchsuccess'}  = $matchsuccess; # continue or fail

883
    print Bugzilla->cgi->header();
884 885

    $::template->process("global/confirm-user-match.html.tmpl", $vars)
886
      || ThrowTemplateError($::template->error());
887 888 889 890 891

    exit;

}

892 893 894 895
sub email_prefs {
    # Get or set (not implemented) the user's email notification preferences.
    
    my $self = shift;
896
    return {} unless $self->id;
897 898 899 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 926 927
    
    # If the calling code is setting the email preferences, update the object
    # but don't do anything else.  This needs to write email preferences back
    # to the database.
    if (@_) { $self->{email_prefs} = shift; return; }
    
    # If we already got them from the database, return the existing values.
    return $self->{email_prefs} if $self->{email_prefs};
    
    # Retrieve the values from the database.
    &::SendSQL("SELECT emailflags FROM profiles WHERE userid = $self->{id}");
    my ($flags) = &::FetchSQLData();

    my @roles = qw(Owner Reporter QAcontact CClist Voter);
    my @reasons = qw(Removeme Comments Attachments Status Resolved Keywords 
                     CC Other Unconfirmed);

    # Convert the prefs from the flags string from the database into
    # a Perl record.  The 255 param is here because split will trim 
    # any trailing null fields without a third param, which causes Perl 
    # to eject lots of warnings. Any suitably large number would do.
    my $prefs = { split(/~/, $flags, 255) };
    
    # Determine the value of the "excludeself" global email preference.
    # Note that the value of "excludeself" is assumed to be off if the
    # preference does not exist in the user's list, unlike other 
    # preferences whose value is assumed to be on if they do not exist.
    $prefs->{ExcludeSelf} = 
      exists($prefs->{ExcludeSelf}) && $prefs->{ExcludeSelf} eq "on";
    
    # Determine the value of the global request preferences.
myk%mozilla.org's avatar
myk%mozilla.org committed
928
    foreach my $pref (qw(FlagRequestee FlagRequester)) {
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
        $prefs->{$pref} = !exists($prefs->{$pref}) || $prefs->{$pref} eq "on";
    }
    
    # Determine the value of the rest of the preferences by looping over
    # all roles and reasons and converting their values to Perl booleans.
    foreach my $role (@roles) {
        foreach my $reason (@reasons) {
            my $key = "email$role$reason";
            $prefs->{$key} = !exists($prefs->{$key}) || $prefs->{$key} eq "on";
        }
    }

    $self->{email_prefs} = $prefs;
    
    return $self->{email_prefs};
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
sub get_userlist {
    my $self = shift;

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

    my $query  = "SELECT DISTINCT login_name, realname,";
    if (&::Param('usevisibilitygroups')) {
        $query .= " COUNT(group_id) ";
    } else {
        $query .= " 1 ";
    }
        $query .= "FROM profiles ";
    if (&::Param('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})) . ") " .
                  "AND grant_type <> " . GRANT_DERIVED;
    }
    $query    .= " WHERE disabledtext = '' GROUP BY userid";

    my $dbh = Bugzilla->dbh;
    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'};
}

985 986
sub insert_new_user ($$;$$) {
    my ($username, $realname, $password, $disabledtext) = (@_);
987 988
    my $dbh = Bugzilla->dbh;

989 990 991 992
    $disabledtext ||= '';

    # If not specified, generate a new random password for the user.
    $password ||= &::GenerateRandomPassword();
993 994 995 996 997 998 999 1000 1001
    my $cryptpassword = bz_crypt($password);

    # XXX - These should be moved into ValidateNewUser or CheckEmailSyntax
    #       At the least, they shouldn't be here. They're safe for now, though.
    trick_taint($username);
    trick_taint($realname);

    # Insert the new user record into the database.
    $dbh->do("INSERT INTO profiles 
1002 1003 1004
                          (login_name, realname, cryptpassword, emailflags,
                           disabledtext) 
                   VALUES (?, ?, ?, ?, ?)",
1005
             undef, 
1006 1007
             ($username, $realname, $cryptpassword, DEFAULT_EMAIL_SETTINGS,
              $disabledtext));
1008 1009 1010 1011 1012 1013

    # Return the password to the calling code so it can be included
    # in an email sent to the user.
    return $password;
}

1014 1015 1016
sub is_available_username ($;$) {
    my ($username, $old_username) = @_;

1017
    if(login_to_id($username) != 0) {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        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 locate() to find the delimeter (':')
    # is cleaner/safer
    my $sth = $dbh->prepare(
        "SELECT eventdata FROM tokens WHERE tokentype = 'emailold'
        AND SUBSTRING(eventdata, 1, (LOCATE(':', eventdata) - 1)) = ?
        OR SUBSTRING(eventdata, (LOCATE(':', eventdata) + 1)) = ?");
    $sth->execute($username, $username);

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

    return 1;
}

1048 1049 1050
sub login_to_id ($) {
    my ($login) = (@_);
    my $dbh = Bugzilla->dbh;
1051 1052
    # $login will only be used by the following SELECT statement, so it's safe.
    trick_taint($login);
1053 1054
    my $user_id = $dbh->selectrow_array(
        "SELECT userid FROM profiles WHERE login_name = ?", undef, $login);
1055
    if ($user_id) {
1056 1057 1058 1059 1060 1061
        return $user_id;
    } else {
        return 0;
    }
}

1062 1063 1064 1065
sub UserInGroup ($) {
    return defined Bugzilla->user->groups->{$_[0]} ? 1 : 0;
}

1066
1;
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

__END__

=head1 NAME

Bugzilla::User - Object for a Bugzilla user

=head1 SYNOPSIS

  use Bugzilla::User;

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

1080
  # Class Functions
1081
  $password = insert_new_user($username, $realname, $password, $disabledtext);
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
=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">.

=head1 METHODS

=over 4

=item C<new($userid)>

1097 1098 1099 1100
Creates a new C{Bugzilla::User> object for the given user id.  If no user
id was given, a blank object is created with no user attributes.

If an id was given but there was no matching user found, undef is returned.
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

=begin undocumented

=item C<new_from_login($login)>

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

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

This routine and C<new> both take an extra optional argument, which is
passed as the argument to C<derive_groups> to avoid locking. See that
routine's documentation for details.

=end undocumented

=item C<id>

Returns the userid for this user.

=item C<login>

Returns the login name for this user.

=item C<email>

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

=item C<name>

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

=item C<showmybugslink>

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

=item C<identity>

Retruns a string for the identity of the user. This will be of the form
C<name E<lt>emailE<gt>> if the user has specified a name, and C<email>
otherwise.

=item C<nick>

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

=item C<queries>

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

=over

=item *

name - The name of the query

=item *

query - The text for the query

=item *

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

=back

1174 1175 1176 1177
=item C<disabledtext>

Returns the disable text of the user, if any.

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
=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.

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
=item C<flush_queries_cache>

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

=item C<groups>

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

=item C<in_group>

Determines whether or not a user is in the given group. This method is mainly
intended for cases where we are not looking at the currently logged in user,
and only need to make a quick check for the group, where calling C<groups>
and getting all of the groups would be overkill.

1212 1213 1214 1215 1216
=item C<bless_groups>

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

1219 1220 1221 1222
=item C<can_see_bug(bug_id)>

Determines if the user can see the specified bug.

1223 1224 1225 1226 1227 1228 1229 1230
=item C<derive_groups>

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.

1231 1232 1233 1234 1235 1236 1237
=item C<get_selectable_products(by_id)>

Returns an alphabetical list of product names from which
the user can select bugs.  If the $by_id parameter is true, it returns
a hash where the keys are the product ids and the values are the
product names.

1238 1239 1240 1241 1242 1243
=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.

1244 1245 1246 1247 1248 1249 1250 1251
=item C<flatten_group_membership>

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

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
=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.

1262 1263 1264
=begin undocumented

This routine takes an optional argument. If true, then this routine will not
1265
lock the tables, but will rely on the caller to have done so itsself.
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

This is required because mysql will only execute a query if all of the tables
are locked, or if none of them are, not a mixture. If the caller has already
done some locking, then this routine would fail. Thus the caller needs to lock
all the tables required by this method, and then C<derive_groups> won't do
any locking.

This is a really ugly solution, and when Bugzilla supports transactions
instead of using the explicit table locking we were forced to do when thats
all MySQL supported, this will go away.

=end undocumented

=item C<can_bless>

1281 1282 1283 1284 1285 1286
When called with no arguments:
Returns C<1> if the user can bless at least one group, returns C<0> otherwise.

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

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
=item C<set_flags>
=item C<get_flag>

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

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

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

1303 1304
=back

1305 1306 1307 1308 1309 1310 1311 1312 1313
=head1 CLASS FUNCTIONS

=over4

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

=item C<insert_new_user>

1314
Creates a new user in the database.
1315 1316 1317

Params: $username (scalar, string) - The login name for the new user.
        $realname (scalar, string) - The full name for the new user.
1318 1319 1320 1321 1322
        $password (scalar, string) - Optional. The password for the new user;
                                     if not given, a random password will be
                                     generated.
        $disabledtext (scalar, string) - Optional. The disable text for the new
                                         user; if not given, it will be empty.
1323 1324 1325
                                         If given, the user will be disabled,
                                         meaning the account will be
                                         unavailable for login.
1326 1327 1328

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

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
=item C<is_available_username>

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

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

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
=item C<login_to_id($login)>

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

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

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

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

1357 1358 1359 1360 1361 1362
=item C<UserInGroup($groupname)>

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

=back

1363 1364 1365
=head1 SEE ALSO

L<Bugzilla|Bugzilla>