FlagType.pm 18.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- 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>

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
=head1 NAME

Bugzilla::FlagType - A module to deal with Bugzilla flag types.

=head1 SYNOPSIS

FlagType.pm provides an interface to flag types as stored in Bugzilla.
See below for more information.

=head1 NOTES

=over

=item *

Prior to calling routines in this module, it's assumed that you have
38
already done a C<require globals.pl>.
39 40 41 42 43 44 45 46 47 48 49 50 51

=item *

Use of private functions/variables outside this module may lead to
unexpected results after an upgrade.  Please avoid using private
functions in other files/modules.  Private functions are functions
whose names start with _ or are specifically noted as being private.

=back

=cut

######################################################################
52
# Module Initialization
53
######################################################################
54 55 56 57 58 59 60 61 62 63

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

# This module implements flag types for the flag tracker.
package Bugzilla::FlagType;

# Use Bugzilla's User module which contains utilities for handling users.
use Bugzilla::User;

64 65
use Bugzilla::Error;
use Bugzilla::Util;
66
use Bugzilla::Config;
67

68
######################################################################
69
# Global Variables
70
######################################################################
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85
=begin private

=head1 PRIVATE VARIABLES/CONSTANTS

=over

=item C<@base_columns>

basic sets of columns and tables for getting flag types from the
database.  B<Used by get, match, sqlify_criteria and perlify_record>

=back

=cut
86 87 88 89 90

my @base_columns = 
  ("1", "flagtypes.id", "flagtypes.name", "flagtypes.description", 
   "flagtypes.cc_list", "flagtypes.target_type", "flagtypes.sortkey", 
   "flagtypes.is_active", "flagtypes.is_requestable", 
91 92
   "flagtypes.is_requesteeble", "flagtypes.is_multiplicable", 
   "flagtypes.grant_group_id", "flagtypes.request_group_id");
93

94 95 96 97 98 99 100 101 102
=pod

=over

=item C<@base_tables>

Which database(s) is the data coming from?

Note: when adding tables to @base_tables, make sure to include the separator 
103 104 105
(i.e. words like "LEFT OUTER JOIN") before the table name, since tables take
multiple separators based on the join type, and therefore it is not possible
to join them later using a single known separator.
106 107 108 109 110 111 112
B<Used by get, match, sqlify_criteria and perlify_record>

=back

=end private

=cut
113 114 115

my @base_tables = ("flagtypes");

116
######################################################################
117
# Public Functions
118
######################################################################
119

120
=head1 PUBLIC FUNCTIONS/METHODS
121

122 123 124 125 126 127 128
=over

=item C<get($id)>

Returns a hash of information about a flag type.

=back
129

130 131 132
=cut

sub get {
133 134 135 136 137 138 139 140 141 142 143 144 145 146
    my ($id) = @_;

    my $select_clause = "SELECT " . join(", ", @base_columns);
    my $from_clause = "FROM " . join(" ", @base_tables);
    
    &::PushGlobalSQLState();
    &::SendSQL("$select_clause $from_clause WHERE flagtypes.id = $id");
    my @data = &::FetchSQLData();
    my $type = perlify_record(@data);
    &::PopGlobalSQLState();

    return $type;
}

147 148 149 150 151 152 153 154 155 156 157 158
=pod

=over

=item C<get_inclusions($id)>

Someone please document this

=back

=cut

159 160 161 162 163
sub get_inclusions {
    my ($id) = @_;
    return get_clusions($id, "in");
}

164 165 166 167 168 169 170 171 172 173 174 175
=pod

=over

=item C<get_exclusions($id)>

Someone please document this

=back

=cut

176 177 178 179 180
sub get_exclusions {
    my ($id) = @_;
    return get_clusions($id, "ex");
}

181 182 183 184 185 186
=pod

=over

=item C<get_clusions($id, $type)>

187 188 189
Return a hash of product/component IDs and names
associated with the flagtype:
$clusions{'product_name:component_name'} = "product_ID:component_ID"
190 191 192 193 194

=back

=cut

195 196
sub get_clusions {
    my ($id, $type) = @_;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    my $dbh = Bugzilla->dbh;

    my $list =
        $dbh->selectall_arrayref("SELECT products.id, products.name, " .
                                 "       components.id, components.name " . 
                                 "FROM flagtypes, flag${type}clusions " . 
                                 "LEFT OUTER JOIN products " .
                                 "  ON flag${type}clusions.product_id = products.id " . 
                                 "LEFT OUTER JOIN components " .
                                 "  ON flag${type}clusions.component_id = components.id " . 
                                 "WHERE flagtypes.id = ? " .
                                 " AND flag${type}clusions.type_id = flagtypes.id",
                                 undef, $id);
    my %clusions;
    foreach my $data (@$list) {
        my ($product_id, $product_name, $component_id, $component_name) = @$data;
        $product_id ||= 0;
        $product_name ||= "__Any__";
        $component_id ||= 0;
        $component_name ||= "__Any__";
        $clusions{"$product_name:$component_name"} = "$product_id:$component_id";
218
    }
219
    return \%clusions;
220 221
}

222
=pod
223

224 225 226 227 228 229 230 231 232 233 234 235
=over

=item C<match($criteria, $include_count)>

Queries the database for flag types matching the given criteria
and returns the set of matching types.

=back

=cut

sub match {
236 237 238 239
    my ($criteria, $include_count) = @_;

    my @tables = @base_tables;
    my @columns = @base_columns;
240 241
    my $dbh = Bugzilla->dbh;

242 243 244 245 246 247 248
    # Include a count of the number of flags per type if requested.
    if ($include_count) { 
        push(@columns, "COUNT(flags.id)");
        push(@tables, "LEFT OUTER JOIN flags ON flagtypes.id = flags.type_id");
    }
    
    # Generate the SQL WHERE criteria.
249
    my @criteria = sqlify_criteria($criteria, \@tables);
250 251
    
    # Build the query, grouping the types if we are counting flags.
252 253 254
    # DISTINCT is used in order to count flag types only once when
    # they appear several times in the flaginclusions table.
    my $select_clause = "SELECT DISTINCT " . join(", ", @columns);
255 256 257 258
    my $from_clause = "FROM " . join(" ", @tables);
    my $where_clause = "WHERE " . join(" AND ", @criteria);
    
    my $query = "$select_clause $from_clause $where_clause";
259 260
    $query .= " " . $dbh->sql_group_by('flagtypes.id',
              join(', ', @base_columns[2..$#base_columns]))
261
                    if $include_count;
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    $query .= " ORDER BY flagtypes.sortkey, flagtypes.name";
    
    # Execute the query and retrieve the results.
    &::PushGlobalSQLState();
    &::SendSQL($query);
    my @types;
    while (&::MoreSQLData()) {
        my @data = &::FetchSQLData();
        my $type = perlify_record(@data);
        push(@types, $type);
    }
    &::PopGlobalSQLState();

    return \@types;
}

278 279 280 281 282 283 284 285 286 287 288 289
=pod

=over

=item C<count($criteria)>

Returns the total number of flag types matching the given criteria.

=back

=cut

290 291 292 293 294
sub count {
    my ($criteria) = @_;

    # Generate query components.
    my @tables = @base_tables;
295
    my @criteria = sqlify_criteria($criteria, \@tables);
296 297
    
    # Build the query.
298
    my $select_clause = "SELECT COUNT(flagtypes.id)";
299 300 301 302 303 304 305 306 307 308 309 310 311
    my $from_clause = "FROM " . join(" ", @tables);
    my $where_clause = "WHERE " . join(" AND ", @criteria);
    my $query = "$select_clause $from_clause $where_clause";
        
    # Execute the query and get the results.
    &::PushGlobalSQLState();
    &::SendSQL($query);
    my $count = &::FetchOneColumn();
    &::PopGlobalSQLState();

    return $count;
}

312 313 314 315
=pod

=over

316
=item C<validate($cgi, $bug_id, $attach_id)>
317 318 319 320 321 322

Get a list of flag types to validate.  Uses the "map" function
to extract flag type IDs from form field names by matching columns
whose name looks like "flag_type-nnn", where "nnn" is the ID,
and returning just the ID portion of matching field names.

323 324 325
If the attachment is new, it has no ID yet and $attach_id is set
to -1 to force its check anyway.

326 327 328 329
=back

=cut

330
sub validate {
331
    my ($cgi, $bug_id, $attach_id) = @_;
332 333 334 335

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

336
    my @ids = map(/^flag_type-(\d+)$/ ? $1 : (), $cgi->param());
337
  
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    return unless scalar(@ids);
    
    # No flag reference should exist when changing several bugs at once.
    ThrowCodeError("flags_not_available", { type => 'b' }) unless $bug_id;

    # We don't check that these flag types are valid for
    # this bug/attachment. This check will be done later when
    # processing new flags, see Flag::FormToNewFlags().

    # All flag types have to be active
    my $inactive_flagtypes =
        $dbh->selectrow_array("SELECT 1 FROM flagtypes
                               WHERE id IN (" . join(',', @ids) . ")
                               AND is_active = 0 " .
                               $dbh->sql_limit(1));

    ThrowCodeError("flag_type_inactive") if $inactive_flagtypes;

    foreach my $id (@ids) {
357
        my $status = $cgi->param("flag_type-$id");
358
        my @requestees = $cgi->param("requestee_type-$id");
359 360 361 362
        
        # Don't bother validating types the user didn't touch.
        next if $status eq "X";

363 364 365
        # Make sure the flag type exists.
        my $flag_type = get($id);
        $flag_type 
366
          || ThrowCodeError("flag_type_nonexistent", { id => $id });
367 368 369

        # Make sure the value of the field is a valid status.
        grep($status eq $_, qw(X + - ?))
370 371 372
          || ThrowCodeError("flag_status_invalid", 
                            { id => $id , status => $status });

373 374 375 376 377 378
        # Make sure the user didn't request the flag unless it's requestable.
        if ($status eq '?' && !$flag_type->{is_requestable}) {
            ThrowCodeError("flag_status_invalid", 
                           { id => $id , status => $status });
        }
        
379 380 381 382
        # Make sure the user didn't specify a requestee unless the flag
        # is specifically requestable.
        if ($status eq '?'
            && !$flag_type->{is_requesteeble}
383
            && scalar(@requestees) > 0)
384
        {
385
            ThrowCodeError("flag_requestee_disabled", { type => $flag_type });
386 387
        }

388 389
        # Make sure the user didn't enter multiple requestees for a flag
        # that can't be requested from more than one person at a time.
390
        if ($status eq '?'
391 392
            && !$flag_type->{is_multiplicable}
            && scalar(@requestees) > 1)
393
        {
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
            ThrowUserError("flag_not_multiplicable", { type => $flag_type });
        }

        # Make sure the requestees are authorized to access the bug
        # (and attachment, if this installation is using the "insider group"
        # feature and the attachment is marked private).
        if ($status eq '?' && $flag_type->{is_requesteeble}) {
            foreach my $login (@requestees) {
                # We know the requestee exists because we ran
                # Bugzilla::User::match_field before getting here.
                my $requestee = Bugzilla::User->new_from_login($login);
    
                # Throw an error if the user can't see the bug.
                if (!$requestee->can_see_bug($bug_id)) {
                    ThrowUserError("flag_requestee_unauthorized",
                                   { flag_type => $flag_type,
                                     requestee => $requestee,
                                     bug_id    => $bug_id,
                                     attach_id => $attach_id });
                }
                
                # Throw an error if the target is a private attachment and
                # the requestee isn't in the group of insiders who can see it.
                if ($attach_id
                    && Param("insidergroup")
                    && $cgi->param('isprivate')
                    && !$requestee->in_group(Param("insidergroup")))
                {
                    ThrowUserError("flag_requestee_unauthorized_attachment",
                                   { flag_type => $flag_type,
                                     requestee => $requestee,
                                     bug_id    => $bug_id,
                                     attach_id => $attach_id });
                }
428 429
            }
        }
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

        # Make sure the user is authorized to modify flags, see bug 180879
        # - User in the $grant_gid group can set flags, including "+" and "-"
        next if (!$flag_type->{grant_gid}
                 || $user->in_group(&::GroupIdToName($flag_type->{grant_gid})));

        # - User in the $request_gid group can request flags
        next if ($status eq '?'
                 && (!$flag_type->{request_gid}
                     || $user->in_group(&::GroupIdToName($flag_type->{request_gid}))));

        # - Any other flag modification is denied
        ThrowUserError("flag_update_denied",
                        { name       => $flag_type->{name},
                          status     => $status,
                          old_status => "X" });
446 447 448
    }
}

449 450 451 452 453 454 455 456 457 458 459 460 461
=pod

=over

=item C<normalize(@ids)>

Given a list of flag types, checks its flags to make sure they should
still exist after a change to the inclusions/exclusions lists.

=back

=cut

462 463 464 465 466 467 468 469 470
sub normalize {
    # A list of IDs of flag types to normalize.
    my (@ids) = @_;
    
    my $ids = join(", ", @ids);
    
    # Check for flags whose product/component is no longer included.
    &::SendSQL("
        SELECT flags.id 
471 472 473
        FROM (flags INNER JOIN bugs ON flags.bug_id = bugs.bug_id)
          LEFT OUTER JOIN flaginclusions AS i
            ON (flags.type_id = i.type_id
474 475 476
            AND (bugs.product_id = i.product_id OR i.product_id IS NULL)
            AND (bugs.component_id = i.component_id OR i.component_id IS NULL))
        WHERE flags.type_id IN ($ids)
477
        AND flags.is_active = 1
478 479 480 481 482 483 484 485 486 487
        AND i.type_id IS NULL
    ");
    Bugzilla::Flag::clear(&::FetchOneColumn()) while &::MoreSQLData();
    
    &::SendSQL("
        SELECT flags.id 
        FROM flags, bugs, flagexclusions AS e
        WHERE flags.type_id IN ($ids)
        AND flags.bug_id = bugs.bug_id
        AND flags.type_id = e.type_id 
488
        AND flags.is_active = 1
489 490 491 492 493 494
        AND (bugs.product_id = e.product_id OR e.product_id IS NULL)
        AND (bugs.component_id = e.component_id OR e.component_id IS NULL)
    ");
    Bugzilla::Flag::clear(&::FetchOneColumn()) while &::MoreSQLData();
}

495
######################################################################
496
# Private Functions
497 498 499 500 501 502 503 504
######################################################################

=begin private

=head1 PRIVATE FUNCTIONS

=over

505
=item C<sqlify_criteria($criteria, $tables)>
506 507 508 509

Converts a hash of criteria into a list of SQL criteria.
$criteria is a reference to the criteria (field => value), 
$tables is a reference to an array of tables being accessed 
510
by the query.
511 512 513 514

=back

=cut
515 516

sub sqlify_criteria {
517
    my ($criteria, $tables) = @_;
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

    # the generated list of SQL criteria; "1=1" is a clever way of making sure
    # there's something in the list so calling code doesn't have to check list
    # size before building a WHERE clause out of it
    my @criteria = ("1=1");

    if ($criteria->{name}) {
        push(@criteria, "flagtypes.name = " . &::SqlQuote($criteria->{name}));
    }
    if ($criteria->{target_type}) {
        # The target type is stored in the database as a one-character string
        # ("a" for attachment and "b" for bug), but this function takes complete
        # names ("attachment" and "bug") for clarity, so we must convert them.
        my $target_type = &::SqlQuote(substr($criteria->{target_type}, 0, 1));
        push(@criteria, "flagtypes.target_type = $target_type");
    }
    if (exists($criteria->{is_active})) {
        my $is_active = $criteria->{is_active} ? "1" : "0";
        push(@criteria, "flagtypes.is_active = $is_active");
    }
    if ($criteria->{product_id} && $criteria->{'component_id'}) {
        my $product_id = $criteria->{product_id};
        my $component_id = $criteria->{component_id};
        
        # Add inclusions to the query, which simply involves joining the table
        # by flag type ID and target product/component.
544
        push(@$tables, "INNER JOIN flaginclusions ON " .
545
                       "flagtypes.id = flaginclusions.type_id");
546 547 548 549 550 551 552 553 554
        push(@criteria, "(flaginclusions.product_id = $product_id " . 
                        " OR flaginclusions.product_id IS NULL)");
        push(@criteria, "(flaginclusions.component_id = $component_id " . 
                        " OR flaginclusions.component_id IS NULL)");
        
        # Add exclusions to the query, which is more complicated.  First of all,
        # we do a LEFT JOIN so we don't miss flag types with no exclusions.
        # Then, as with inclusions, we join on flag type ID and target product/
        # component.  However, since we want flag types that *aren't* on the
555 556
        # exclusions list, we add a WHERE criteria to use only records with
        # NULL exclusion type, i.e. without any exclusions.
557 558 559 560 561 562
        my $join_clause = "flagtypes.id = flagexclusions.type_id " . 
                          "AND (flagexclusions.product_id = $product_id " . 
                          "OR flagexclusions.product_id IS NULL) " . 
                          "AND (flagexclusions.component_id = $component_id " .
                          "OR flagexclusions.component_id IS NULL)";
        push(@$tables, "LEFT JOIN flagexclusions ON ($join_clause)");
563
        push(@criteria, "flagexclusions.type_id IS NULL");
564
    }
565 566 567 568 569 570
    if ($criteria->{group}) {
        my $gid = $criteria->{group};
        detaint_natural($gid);
        push(@criteria, "(flagtypes.grant_group_id = $gid " .
                        " OR flagtypes.request_group_id = $gid)");
    }
571 572 573 574
    
    return @criteria;
}

575 576 577 578 579 580 581 582 583 584 585 586 587
=pod

=over

=item C<perlify_record()>

Converts data retrieved from the database into a Perl record.  Depends on the
formatting as described in @base_columns.

=back

=cut

588 589 590 591 592 593 594 595 596 597 598 599 600 601
sub perlify_record {
    my $type = {};
    
    $type->{'exists'} = $_[0];
    $type->{'id'} = $_[1];
    $type->{'name'} = $_[2];
    $type->{'description'} = $_[3];
    $type->{'cc_list'} = $_[4];
    $type->{'target_type'} = $_[5] eq "b" ? "bug" : "attachment";
    $type->{'sortkey'} = $_[6];
    $type->{'is_active'} = $_[7];
    $type->{'is_requestable'} = $_[8];
    $type->{'is_requesteeble'} = $_[9];
    $type->{'is_multiplicable'} = $_[10];
602 603 604
    $type->{'grant_gid'} = $_[11];
    $type->{'request_gid'} = $_[12];
    $type->{'flag_count'} = $_[13];
605 606 607 608
        
    return $type;
}

609 610
1;

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
=end private

=head1 SEE ALSO

=over

=item B<Bugzilla::Flags>

=back

=head1 CONTRIBUTORS

=over

=item Myk Melez <myk@mozilla.org>

=item Kevin Benton <kevin.benton@amd.com>

=back

=cut