Flag.pm 30.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Myk Melez <myk@mozilla.org>
21
#                 Jouni Heikniemi <jouni@heikniemi.net>
22
#                 Frédéric Buclin <LpSolit@gmail.com>
23

24 25 26 27
use strict;

package Bugzilla::Flag;

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
=head1 NAME

Bugzilla::Flag - A module to deal with Bugzilla flag values.

=head1 SYNOPSIS

Flag.pm provides an interface to flags as stored in Bugzilla.
See below for more information.

=head1 NOTES

=over

=item *

43
Import relevant functions from that script.
44 45 46 47

=item *

Use of private functions / variables outside this module may lead to
48
unexpected results after an upgrade.  Please avoid using private
49 50 51 52 53 54 55
functions in other files/modules.  Private functions are functions
whose names start with _ or a re specifically noted as being private.

=back

=cut

56 57
use Bugzilla::FlagType;
use Bugzilla::User;
58
use Bugzilla::Util;
59
use Bugzilla::Error;
60
use Bugzilla::Mailer;
61
use Bugzilla::Constants;
62
use Bugzilla::Field;
63

64 65 66 67 68
use base qw(Bugzilla::Object);

###############################
####    Initialization     ####
###############################
69

70 71 72 73 74 75 76 77 78
use constant DB_COLUMNS => qw(
    flags.id
    flags.type_id
    flags.bug_id
    flags.attach_id
    flags.requestee_id
    flags.setter_id
    flags.status
);
79

80 81
use constant DB_TABLE => 'flags';
use constant LIST_ORDER => 'id';
82

83 84 85
###############################
####      Accessors      ######
###############################
86

87
=head2 METHODS
88

89 90
=over

91 92 93 94 95 96 97
=item C<id>

Returns the ID of the flag.

=item C<name>

Returns the name of the flagtype the flag belongs to.
98

99 100 101
=item C<status>

Returns the status '+', '-', '?' of the flag.
102

103 104
=back

105
=cut
106

107 108 109
sub id     { return $_[0]->{'id'};     }
sub name   { return $_[0]->type->name; }
sub status { return $_[0]->{'status'}; }
110 111 112 113 114 115 116 117 118 119 120

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

=pod

=over

=item C<type>

121
Returns the type of the flag, as a Bugzilla::FlagType object.
122

123
=item C<setter>
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138
Returns the user who set the flag, as a Bugzilla::User object.

=item C<requestee>

Returns the user who has been requested to set the flag, as a
Bugzilla::User object.

=back

=cut

sub type {
    my $self = shift;

139
    $self->{'type'} ||= new Bugzilla::FlagType($self->{'type_id'});
140
    return $self->{'type'};
141 142
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
sub setter {
    my $self = shift;

    $self->{'setter'} ||= new Bugzilla::User($self->{'setter_id'});
    return $self->{'setter'};
}

sub requestee {
    my $self = shift;

    if (!defined $self->{'requestee'} && $self->{'requestee_id'}) {
        $self->{'requestee'} = new Bugzilla::User($self->{'requestee_id'});
    }
    return $self->{'requestee'};
}

################################
## Searching/Retrieving Flags ##
################################

163 164 165 166 167
=pod

=over

=item C<match($criteria)>
168

169 170 171 172 173 174 175 176 177
Queries the database for flags matching the given criteria
(specified as a hash of field names and their matching values)
and returns an array of matching records.

=back

=cut

sub match {
178
    my ($criteria) = @_;
179
    my $dbh = Bugzilla->dbh;
180 181

    my @criteria = sqlify_criteria($criteria);
182 183
    $criteria = join(' AND ', @criteria);

184 185
    my $flag_ids = $dbh->selectcol_arrayref("SELECT id FROM flags
                                             WHERE $criteria");
186

187
    return Bugzilla::Flag->new_from_list($flag_ids);
188 189
}

190 191 192 193 194 195
=pod

=over

=item C<count($criteria)>

196
Queries the database for flags matching the given criteria
197 198 199 200
(specified as a hash of field names and their matching values)
and returns an array of matching records.

=back
201

202 203 204
=cut

sub count {
205
    my ($criteria) = @_;
206
    my $dbh = Bugzilla->dbh;
207 208

    my @criteria = sqlify_criteria($criteria);
209 210 211
    $criteria = join(' AND ', @criteria);

    my $count = $dbh->selectrow_array("SELECT COUNT(*) FROM flags WHERE $criteria");
212 213 214 215

    return $count;
}

216
######################################################################
217
# Creating and Modifying
218
######################################################################
219

220 221 222 223
=pod

=over

224
=item C<validate($cgi, $bug_id, $attach_id)>
225

226 227
Validates fields containing flag modifications.

228 229 230
If the attachment is new, it has no ID yet and $attach_id is set
to -1 to force its check anyway.

231 232 233 234 235
=back

=cut

sub validate {
236 237
    my ($cgi, $bug_id, $attach_id) = @_;

238
    my $user = Bugzilla->user;
239 240
    my $dbh = Bugzilla->dbh;

241 242 243 244
    # Get a list of flags to validate.  Uses the "map" function
    # to extract flag IDs from form field names by matching fields
    # whose name looks like "flag-nnn", where "nnn" is the ID,
    # and returning just the ID portion of matching field names.
245
    my @ids = map(/^flag-(\d+)$/ ? $1 : (), $cgi->param());
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

    return unless scalar(@ids);
    
    # No flag reference should exist when changing several bugs at once.
    ThrowCodeError("flags_not_available", { type => 'b' }) unless $bug_id;

    # No reference to existing flags should exist when creating a new
    # attachment.
    if ($attach_id && ($attach_id < 0)) {
        ThrowCodeError("flags_not_available", { type => 'a' });
    }

    # Make sure all flags belong to the bug/attachment they pretend to be.
    my $field = ($attach_id) ? "attach_id" : "bug_id";
    my $field_id = $attach_id || $bug_id;
    my $not = ($attach_id) ? "" : "NOT";

    my $invalid_data =
        $dbh->selectrow_array("SELECT 1 FROM flags
                               WHERE id IN (" . join(',', @ids) . ")
                               AND ($field != ? OR attach_id IS $not NULL) " .
                               $dbh->sql_limit(1),
                               undef, $field_id);

    if ($invalid_data) {
        ThrowCodeError("invalid_flag_association",
                       { bug_id    => $bug_id,
                         attach_id => $attach_id });
    }

    foreach my $id (@ids) {
277
        my $status = $cgi->param("flag-$id");
278
        my @requestees = $cgi->param("requestee-$id");
279

280
        # Make sure the flag exists.
281
        my $flag = new Bugzilla::Flag($id);
282
        $flag || ThrowCodeError("flag_nonexistent", { id => $id });
283 284 285

        # Make sure the user chose a valid status.
        grep($status eq $_, qw(X + - ?))
286 287
          || ThrowCodeError("flag_status_invalid", 
                            { id => $id, status => $status });
288

289
        # Make sure the user didn't request the flag unless it's requestable.
290 291 292
        # If the flag was requested before it became unrequestable, leave it
        # as is.
        if ($status eq '?'
293
            && $flag->status ne '?'
294
            && !$flag->type->is_requestable)
295
        {
296
            ThrowCodeError("flag_status_invalid", 
297
                           { id => $id, status => $status });
298
        }
299 300 301

        # Make sure the user didn't specify a requestee unless the flag
        # is specifically requestable. If the requestee was set before
302 303 304
        # the flag became specifically unrequestable, don't let the user
        # change the requestee, but let the user remove it by entering
        # an empty string for the requestee.
305
        if ($status eq '?' && !$flag->type->is_requesteeble) {
306
            my $old_requestee = $flag->requestee ? $flag->requestee->login : '';
307 308 309
            my $new_requestee = join('', @requestees);
            if ($new_requestee && $new_requestee ne $old_requestee) {
                ThrowCodeError("flag_requestee_disabled",
310
                               { type => $flag->type });
311 312
            }
        }
313

314 315
        # 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.
316
        if ($status eq '?'
317
            && !$flag->type->is_multiplicable
318
            && scalar(@requestees) > 1)
319
        {
320
            ThrowUserError("flag_not_multiplicable", { type => $flag->type });
321 322
        }

323
        # Make sure the requestees are authorized to access the bug.
324 325
        # (and attachment, if this installation is using the "insider group"
        # feature and the attachment is marked private).
326
        if ($status eq '?' && $flag->type->is_requesteeble) {
327
            my $old_requestee = $flag->requestee ? $flag->requestee->login : '';
328 329 330 331 332
            foreach my $login (@requestees) {
                next if $login eq $old_requestee;

                # We know the requestee exists because we ran
                # Bugzilla::User::match_field before getting here.
333
                my $requestee = new Bugzilla::User({ name => $login });
334 335 336 337 338 339
                
                # Throw an error if the user can't see the bug.
                # Note that if permissions on this bug are changed,
                # can_see_bug() will refer to old settings.
                if (!$requestee->can_see_bug($bug_id)) {
                    ThrowUserError("flag_requestee_unauthorized",
340
                                   { flag_type  => $flag->type,
341 342
                                     requestee  => $requestee,
                                     bug_id     => $bug_id,
343
                                     attach_id  => $attach_id
344
                                   });
345 346 347 348
                }
    
                # Throw an error if the target is a private attachment and
                # the requestee isn't in the group of insiders who can see it.
349
                if ($attach_id
350
                    && $cgi->param('isprivate')
351 352
                    && Bugzilla->params->{"insidergroup"}
                    && !$requestee->in_group(Bugzilla->params->{"insidergroup"}))
353 354
                {
                    ThrowUserError("flag_requestee_unauthorized_attachment",
355
                                   { flag_type  => $flag->type,
356 357
                                     requestee  => $requestee,
                                     bug_id     => $bug_id,
358
                                     attach_id  => $attach_id
359
                                   });
360
                }
361 362
            }
        }
363 364 365

        # Make sure the user is authorized to modify flags, see bug 180879
        # - The flag is unchanged
366
        next if ($status eq $flag->status);
367

368
        # - User in the request_group can clear pending requests and set flags
369 370
        #   and can rerequest set flags.
        next if (($status eq 'X' || $status eq '?')
371 372
                 && (!$flag->type->request_group
                     || $user->in_group_id($flag->type->request_group->id)));
373

374 375 376
        # - User in the grant_group can set/clear flags, including "+" and "-".
        next if (!$flag->type->grant_group
                 || $user->in_group_id($flag->type->grant_group->id));
377 378 379

        # - Any other flag modification is denied
        ThrowUserError("flag_update_denied",
380
                        { name       => $flag->type->name,
381
                          status     => $status,
382
                          old_status => $flag->status });
383 384 385
    }
}

386 387 388 389
sub snapshot {
    my ($bug_id, $attach_id) = @_;

    my $flags = match({ 'bug_id'    => $bug_id,
390
                        'attach_id' => $attach_id });
391 392
    my @summaries;
    foreach my $flag (@$flags) {
393
        my $summary = $flag->type->name . $flag->status;
394
        $summary .= "(" . $flag->requestee->login . ")" if $flag->requestee;
395 396 397 398 399
        push(@summaries, $summary);
    }
    return @summaries;
}

400

401 402 403 404
=pod

=over

405
=item C<process($bug, $attachment, $timestamp, $cgi)>
406 407 408

Processes changes to flags.

409 410 411 412
The bug and/or the attachment objects are the ones this flag is about,
the timestamp is the date/time the bug was last touched (so that changes
to the flag can be stamped with the same date/time), the cgi is the CGI
object used to obtain the flag fields that the user submitted.
413 414 415 416 417 418

=back

=cut

sub process {
419
    my ($bug, $attachment, $timestamp, $cgi) = @_;
420
    my $dbh = Bugzilla->dbh;
421 422 423 424 425 426 427 428

    # Make sure the bug (and attachment, if given) exists and is accessible
    # to the current user. Moreover, if an attachment object is passed,
    # make sure it belongs to the given bug.
    return if ($bug->error || ($attachment && $bug->bug_id != $attachment->bug_id));

    my $bug_id = $bug->bug_id;
    my $attach_id = $attachment ? $attachment->id : undef;
429 430 431

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
432 433
    $timestamp ||= $dbh->selectrow_array('SELECT NOW()');

434
    # Take a snapshot of flags before any changes.
435
    my @old_summaries = snapshot($bug_id, $attach_id);
436

437
    # Cancel pending requests if we are obsoleting an attachment.
438 439
    if ($attachment && $cgi->param('isobsolete')) {
        CancelRequests($bug, $attachment);
440 441
    }

442
    # Create new flags and update existing flags.
443 444 445
    my $new_flags = FormToNewFlags($bug, $attachment, $cgi);
    foreach my $flag (@$new_flags) { create($flag, $bug, $attachment, $timestamp) }
    modify($bug, $attachment, $cgi, $timestamp);
446

447 448
    # In case the bug's product/component has changed, clear flags that are
    # no longer valid.
449
    my $flag_ids = $dbh->selectcol_arrayref(
450
        "SELECT DISTINCT flags.id
451 452 453 454 455
           FROM flags
     INNER JOIN bugs
             ON flags.bug_id = bugs.bug_id
      LEFT JOIN flaginclusions AS i
             ON flags.type_id = i.type_id 
456
            AND (bugs.product_id = i.product_id OR i.product_id IS NULL)
457 458 459
            AND (bugs.component_id = i.component_id OR i.component_id IS NULL)
          WHERE bugs.bug_id = ?
            AND i.type_id IS NULL",
460 461
        undef, $bug_id);

462
    foreach my $flag_id (@$flag_ids) { clear($flag_id, $bug, $attachment) }
463 464

    $flag_ids = $dbh->selectcol_arrayref(
465
        "SELECT DISTINCT flags.id
466
        FROM flags, bugs, flagexclusions e
467
        WHERE bugs.bug_id = ?
468
        AND flags.bug_id = bugs.bug_id
469
        AND flags.type_id = e.type_id
470
        AND (bugs.product_id = e.product_id OR e.product_id IS NULL)
471 472 473
        AND (bugs.component_id = e.component_id OR e.component_id IS NULL)",
        undef, $bug_id);

474
    foreach my $flag_id (@$flag_ids) { clear($flag_id, $bug, $attachment) }
475

476 477 478 479 480 481 482 483 484 485 486 487
    # Take a snapshot of flags after changes.
    my @new_summaries = snapshot($bug_id, $attach_id);

    update_activity($bug_id, $attach_id, $timestamp, \@old_summaries, \@new_summaries);
}

sub update_activity {
    my ($bug_id, $attach_id, $timestamp, $old_summaries, $new_summaries) = @_;
    my $dbh = Bugzilla->dbh;

    $old_summaries = join(", ", @$old_summaries);
    $new_summaries = join(", ", @$new_summaries);
488
    my ($removed, $added) = diff_strings($old_summaries, $new_summaries);
489
    if ($removed ne $added) {
490
        my $field_id = get_field_id('flagtypes.name');
491
        $dbh->do('INSERT INTO bugs_activity
492
                  (bug_id, attach_id, who, bug_when, fieldid, removed, added)
493 494 495
                  VALUES (?, ?, ?, ?, ?, ?, ?)',
                  undef, ($bug_id, $attach_id, Bugzilla->user->id,
                  $timestamp, $field_id, $removed, $added));
496

497 498
        $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
                  undef, ($timestamp, $bug_id));
499 500 501
    }
}

502 503 504 505
=pod

=over

506
=item C<create($flag, $bug, $attachment, $timestamp)>
507 508

Creates a flag record in the database.
509

510 511 512 513 514
=back

=cut

sub create {
515
    my ($flag, $bug, $attachment, $timestamp) = @_;
516 517
    my $dbh = Bugzilla->dbh;

518
    my $attach_id = $attachment ? $attachment->id : undef;
519
    my $requestee_id;
520
    # Be careful! At this point, $flag is *NOT* yet an object!
521 522 523 524 525
    $requestee_id = $flag->{'requestee'}->id if $flag->{'requestee'};

    $dbh->do('INSERT INTO flags (type_id, bug_id, attach_id, requestee_id,
                                 setter_id, status, creation_date, modification_date)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
526
              undef, ($flag->{'type'}->id, $bug->bug_id,
527 528
                      $attach_id, $requestee_id, $flag->{'setter'}->id,
                      $flag->{'status'}, $timestamp, $timestamp));
529

530 531 532 533 534
    # Now that the new flag has been added to the DB, create a real flag object.
    # This is required to call notify() correctly.
    my $flag_id = $dbh->bz_last_key('flags', 'id');
    $flag = new Bugzilla::Flag($flag_id);

535
    # Send an email notifying the relevant parties about the flag creation.
536 537
    if ($flag->requestee && $flag->requestee->wants_mail([EVT_FLAG_REQUESTED])) {
        $flag->{'addressee'} = $flag->requestee;
538
    }
539

540
    notify($flag, $bug, $attachment);
541 542 543

    # Return the new flag object.
    return $flag;
544 545
}

546
=pod
547

548 549
=over

550
=item C<modify($bug, $attachment, $cgi, $timestamp)>
551

552 553 554 555 556 557 558
Modifies flags in the database when a user changes them.

=back

=cut

sub modify {
559
    my ($bug, $attachment, $cgi, $timestamp) = @_;
560
    my $setter = Bugzilla->user;
561
    my $dbh = Bugzilla->dbh;
562 563

    # Extract a list of flags from the form data.
564
    my @ids = map(/^flag-(\d+)$/ ? $1 : (), $cgi->param());
565

566 567 568 569
    # Loop over flags and update their record in the database if necessary.
    # Two kinds of changes can happen to a flag: it can be set to a different
    # state, and someone else can be asked to set it.  We take care of both
    # those changes.
570 571
    my @flags;
    foreach my $id (@ids) {
572
        my $flag = new Bugzilla::Flag($id);
573 574
        # If the flag no longer exists, ignore it.
        next unless $flag;
575

576
        my $status = $cgi->param("flag-$id");
577

578 579 580 581 582 583 584 585
        # If the user entered more than one name into the requestee field
        # (i.e. they want more than one person to set the flag) we can reuse
        # the existing flag for the first person (who may well be the existing
        # requestee), but we have to create new flags for each additional.
        my @requestees = $cgi->param("requestee-$id");
        my $requestee_email;
        if ($status eq "?"
            && scalar(@requestees) > 1
586
            && $flag->type->is_multiplicable)
587 588 589
        {
            # The first person, for which we'll reuse the existing flag.
            $requestee_email = shift(@requestees);
590

591 592
            # Create new flags like the existing one for each additional person.
            foreach my $login (@requestees) {
593
                create({ type      => $flag->type,
594
                         setter    => $setter, 
595
                         status    => "?",
596
                         requestee => new Bugzilla::User({ name => $login }) },
597
                       $bug, $attachment, $timestamp);
598 599 600 601 602 603
            }
        }
        else {
            $requestee_email = trim($cgi->param("requestee-$id") || '');
        }

604 605 606 607
        # Ignore flags the user didn't change. There are two components here:
        # either the status changes (trivial) or the requestee changes.
        # Change of either field will cause full update of the flag.

608
        my $status_changed = ($status ne $flag->status);
609

610 611 612 613 614
        # Requestee is considered changed, if all of the following apply:
        # 1. Flag status is '?' (requested)
        # 2. Flag can have a requestee
        # 3. The requestee specified on the form is different from the 
        #    requestee specified in the db.
615

616
        my $old_requestee = $flag->requestee ? $flag->requestee->login : '';
617 618 619

        my $requestee_changed = 
          ($status eq "?" && 
620
           $flag->type->is_requesteeble &&
621
           $old_requestee ne $requestee_email);
622

623 624
        next unless ($status_changed || $requestee_changed);

625 626
        # Since the status is validated, we know it's safe, but it's still
        # tainted, so we have to detaint it before using it in a query.
627 628
        trick_taint($status);

629
        if ($status eq '+' || $status eq '-') {
630 631 632 633
            $dbh->do('UPDATE flags
                         SET setter_id = ?, requestee_id = NULL,
                             status = ?, modification_date = ?
                       WHERE id = ?',
634
                       undef, ($setter->id, $status, $timestamp, $flag->id));
635 636 637 638

            # If the status of the flag was "?", we have to notify
            # the requester (if he wants to).
            my $requester;
639 640
            if ($flag->status eq '?') {
                $requester = $flag->setter;
641
            }
642 643 644 645 646 647 648 649 650 651 652
            # Now update the flag object with its new values.
            $flag->{'setter'} = $setter;
            $flag->{'requestee'} = undef;
            $flag->{'status'} = $status;

            # Send an email notifying the relevant parties about the fulfillment,
            # including the requester.
            if ($requester && $requester->wants_mail([EVT_REQUESTED_FLAG])) {
                $flag->{'addressee'} = $requester;
            }

653
            notify($flag, $bug, $attachment);
654 655
        }
        elsif ($status eq '?') {
656
            # Get the requestee, if any.
657
            my $requestee_id;
658
            if ($requestee_email) {
659
                $requestee_id = login_to_id($requestee_email);
660 661
                $flag->{'requestee'} = new Bugzilla::User($requestee_id);
            }
662 663 664 665 666
            else {
                # If the status didn't change but we only removed the
                # requestee, we have to clear the requestee field.
                $flag->{'requestee'} = undef;
            }
667 668

            # Update the database with the changes.
669 670 671 672 673
            $dbh->do('UPDATE flags
                         SET setter_id = ?, requestee_id = ?,
                             status = ?, modification_date = ?
                       WHERE id = ?',
                       undef, ($setter->id, $requestee_id, $status,
674
                               $timestamp, $flag->id));
675 676 677 678 679

            # Now update the flag object with its new values.
            $flag->{'setter'} = $setter;
            $flag->{'status'} = $status;

680
            # Send an email notifying the relevant parties about the request.
681 682
            if ($flag->requestee && $flag->requestee->wants_mail([EVT_FLAG_REQUESTED])) {
                $flag->{'addressee'} = $flag->requestee;
683
            }
684

685
            notify($flag, $bug, $attachment);
686 687
        }
        elsif ($status eq 'X') {
688
            clear($flag->id, $bug, $attachment);
689
        }
690

691 692
        push(@flags, $flag);
    }
693

694 695 696
    return \@flags;
}

697 698 699 700
=pod

=over

701
=item C<clear($id, $bug, $attachment)>
702

703
Remove a flag from the DB.
704 705 706 707 708

=back

=cut

709
sub clear {
710
    my ($id, $bug, $attachment) = @_;
711 712
    my $dbh = Bugzilla->dbh;

713
    my $flag = new Bugzilla::Flag($id);
714
    $dbh->do('DELETE FROM flags WHERE id = ?', undef, $id);
715

716 717 718
    # If we cancel a pending request, we have to notify the requester
    # (if he wants to).
    my $requester;
719 720
    if ($flag->status eq '?') {
        $requester = $flag->setter;
721 722 723 724 725
    }

    # Now update the flag object to its new values. The last
    # requester/setter and requestee are kept untouched (for the
    # record). Else we could as well delete the flag completely.
726
    $flag->{'exists'} = 0;    
727
    $flag->{'status'} = "X";
728 729 730 731 732

    if ($requester && $requester->wants_mail([EVT_REQUESTED_FLAG])) {
        $flag->{'addressee'} = $requester;
    }

733
    notify($flag, $bug, $attachment);
734 735 736
}


737
######################################################################
738
# Utility Functions
739 740 741 742 743 744
######################################################################

=pod

=over

745
=item C<FormToNewFlags($bug, $attachment, $cgi)>
746

747 748
Checks whether or not there are new flags to create and returns an
array of flag objects. This array is then passed to Flag::create().
749 750 751 752

=back

=cut
753 754

sub FormToNewFlags {
755
    my ($bug, $attachment, $cgi) = @_;
756
    my $dbh = Bugzilla->dbh;
757
    my $setter = Bugzilla->user;
758
    
759
    # Extract a list of flag type IDs from field names.
760 761
    my @type_ids = map(/^flag_type-(\d+)$/ ? $1 : (), $cgi->param());
    @type_ids = grep($cgi->param("flag_type-$_") ne 'X', @type_ids);
762

763
    return () unless scalar(@type_ids);
764 765 766

    # Get a list of active flag types available for this target.
    my $flag_types = Bugzilla::FlagType::match(
767 768 769
        { 'target_type'  => $attachment ? 'attachment' : 'bug',
          'product_id'   => $bug->{'product_id'},
          'component_id' => $bug->{'component_id'},
770 771
          'is_active'    => 1 });

772
    my @flags;
773
    foreach my $flag_type (@$flag_types) {
774
        my $type_id = $flag_type->id;
775 776 777 778

        # We are only interested in flags the user tries to create.
        next unless scalar(grep { $_ == $type_id } @type_ids);

779
        # Get the number of flags of this type already set for this target.
780 781
        my $has_flags = count(
            { 'type_id'     => $type_id,
782 783 784
              'target_type' => $attachment ? 'attachment' : 'bug',
              'bug_id'      => $bug->bug_id,
              'attach_id'   => $attachment ? $attachment->id : undef });
785 786

        # Do not create a new flag of this type if this flag type is
787
        # not multiplicable and already has a flag set.
788
        next if (!$flag_type->is_multiplicable && $has_flags);
789

790
        my $status = $cgi->param("flag_type-$type_id");
791
        trick_taint($status);
792

793 794 795
        my @logins = $cgi->param("requestee_type-$type_id");
        if ($status eq "?" && scalar(@logins) > 0) {
            foreach my $login (@logins) {
796 797 798
                push (@flags, { type      => $flag_type ,
                                setter    => $setter , 
                                status    => $status ,
799 800
                                requestee => 
                                    new Bugzilla::User({ name => $login }) });
801
                last unless $flag_type->is_multiplicable;
802
            }
803
        }
804 805 806 807 808
        else {
            push (@flags, { type   => $flag_type ,
                            setter => $setter , 
                            status => $status });
        }
809 810 811 812 813 814
    }

    # Return the list of flags.
    return \@flags;
}

815 816 817 818
=pod

=over

819
=item C<notify($flag, $bug, $attachment)>
820

821 822
Sends an email notification about a flag being created, fulfilled
or deleted.
823 824 825 826 827

=back

=cut

828
sub notify {
829
    my ($flag, $bug, $attachment) = @_;
830

831
    my $template = Bugzilla->template;
832 833

    # There is nobody to notify.
834
    return unless ($flag->{'addressee'} || $flag->type->cc_list);
835

836
    my $attachment_is_private = $attachment ? $attachment->isprivate : undef;
837

838 839 840 841
    # If the target bug is restricted to one or more groups, then we need
    # to make sure we don't send email about it to unauthorized users
    # on the request type's CC: list, so we have to trawl the list for users
    # not in those groups or email addresses that don't have an account.
842 843 844
    my @bug_in_groups = grep {$_->{'ison'} || $_->{'mandatory'}} @{$bug->groups};

    if (scalar(@bug_in_groups) || $attachment_is_private) {
845
        my @new_cc_list;
846
        foreach my $cc (split(/[, ]+/, $flag->type->cc_list)) {
847
            my $ccuser = new Bugzilla::User({ name => $cc }) || next;
848

849
            next if (scalar(@bug_in_groups) && !$ccuser->can_see_bug($bug->bug_id));
850
            next if $attachment_is_private
851 852
              && Bugzilla->params->{"insidergroup"}
              && !$ccuser->in_group(Bugzilla->params->{"insidergroup"});
853
            push(@new_cc_list, $cc);
854
        }
855
        $flag->type->{'cc_list'} = join(", ", @new_cc_list);
856 857
    }

858
    # If there is nobody left to notify, return.
859
    return unless ($flag->{'addressee'} || $flag->type->cc_list);
860

861 862
    # Process and send notification for each recipient
    foreach my $to ($flag->{'addressee'} ? $flag->{'addressee'}->email : '',
863
                    split(/[, ]+/, $flag->type->cc_list))
864 865
    {
        next unless $to;
866 867 868 869
        my $vars = { 'flag'       => $flag,
                     'to'         => $to,
                     'bug'        => $bug,
                     'attachment' => $attachment};
870
        my $message;
871
        my $rv = $template->process("request/email.txt.tmpl", $vars, \$message);
872 873 874 875
        if (!$rv) {
            Bugzilla->cgi->header();
            ThrowTemplateError($template->error());
        }
876

877
        MessageToMTA($message);
878
    }
879 880
}

881 882
# Cancel all request flags from the attachment being obsoleted.
sub CancelRequests {
883
    my ($bug, $attachment, $timestamp) = @_;
884 885 886 887 888 889 890 891 892
    my $dbh = Bugzilla->dbh;

    my $request_ids =
        $dbh->selectcol_arrayref("SELECT flags.id
                                  FROM flags
                                  LEFT JOIN attachments ON flags.attach_id = attachments.attach_id
                                  WHERE flags.attach_id = ?
                                  AND flags.status = '?'
                                  AND attachments.isobsolete = 0",
893
                                  undef, $attachment->id);
894 895 896 897

    return if (!scalar(@$request_ids));

    # Take a snapshot of flags before any changes.
898 899
    my @old_summaries = snapshot($bug->bug_id, $attachment->id) if ($timestamp);
    foreach my $flag (@$request_ids) { clear($flag, $bug, $attachment) }
900 901 902 903 904

    # If $timestamp is undefined, do not update the activity table
    return unless ($timestamp);

    # Take a snapshot of flags after any changes.
905 906 907
    my @new_summaries = snapshot($bug->bug_id, $attachment->id);
    update_activity($bug->bug_id, $attachment->id, $timestamp,
                    \@old_summaries, \@new_summaries);
908 909
}

910
######################################################################
911
# Private Functions
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
######################################################################

=begin private

=head1 PRIVATE FUNCTIONS

=over

=item C<sqlify_criteria($criteria)>

Converts a hash of criteria into a list of SQL criteria.

=back

=cut
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

sub sqlify_criteria {
    # a reference to a hash containing the criteria (field => value)
    my ($criteria) = @_;

    # 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 the caller specified only bug or attachment flags,
    # limit the query to those kinds of flags.
    if (defined($criteria->{'target_type'})) {
        if    ($criteria->{'target_type'} eq 'bug')        { push(@criteria, "attach_id IS NULL") }
        elsif ($criteria->{'target_type'} eq 'attachment') { push(@criteria, "attach_id IS NOT NULL") }
    }
    
    # Go through each criterion from the calling code and add it to the query.
    foreach my $field (keys %$criteria) {
        my $value = $criteria->{$field};
        next unless defined($value);
        if    ($field eq 'type_id')      { push(@criteria, "type_id      = $value") }
        elsif ($field eq 'bug_id')       { push(@criteria, "bug_id       = $value") }
        elsif ($field eq 'attach_id')    { push(@criteria, "attach_id    = $value") }
        elsif ($field eq 'requestee_id') { push(@criteria, "requestee_id = $value") }
        elsif ($field eq 'setter_id')    { push(@criteria, "setter_id    = $value") }
        elsif ($field eq 'status')       { push(@criteria, "status       = '$value'") }
    }
    
    return @criteria;
}

959 960 961 962 963 964 965 966
=head1 SEE ALSO

=over

=item B<Bugzilla::FlagType>

=back

967

968 969 970 971 972 973 974 975 976 977
=head1 CONTRIBUTORS

=over

=item Myk Melez <myk@mozilla.org>

=item Jouni Heikniemi <jouni@heikniemi.net>

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

978 979
=item Frédéric Buclin <LpSolit@gmail.com>

980 981 982 983
=back

=cut

984
1;