Flag.pm 36.6 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 28 29 30 31 32 33 34 35 36 37 38 39
=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 *

Prior to calling routines in this module, it's assumed that you have
40
already done a C<require globals.pl>.
41 42 43

=item *

44
Import relevant functions from that script.
45 46 47 48 49 50 51 52 53 54 55 56 57

=item *

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

=back

=cut

######################################################################
58
# Module Initialization
59
######################################################################
60 61 62 63 64 65 66 67 68

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

# This module implements bug and attachment flags.
package Bugzilla::Flag;

use Bugzilla::FlagType;
use Bugzilla::User;
69
use Bugzilla::Config;
70
use Bugzilla::Util;
71
use Bugzilla::Error;
72
use Bugzilla::Attachment;
73
use Bugzilla::BugMail;
74
use Bugzilla::Constants;
75
use Bugzilla::Field;
76

77
######################################################################
78
# Global Variables
79
######################################################################
80 81 82

# basic sets of columns and tables for getting flags from the database

83 84 85 86 87 88 89 90 91 92 93 94 95
=begin private

=head1 PRIVATE VARIABLES/CONSTANTS

=over

=item C<@base_columns>

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

=cut

96
my @base_columns = 
97 98
  ("is_active", "id", "type_id", "bug_id", "attach_id", "requestee_id", 
   "setter_id", "status");
99

100 101 102 103 104 105 106
=pod

=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 
107 108 109
(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.
110 111 112 113 114 115 116
B<Used by get, match, sqlify_criteria and perlify_record>

=back

=end private

=cut
117 118 119

my @base_tables = ("flags");

120
######################################################################
121
# Searching/Retrieving Flags
122 123 124 125
######################################################################

=head1 PUBLIC FUNCTIONS

126 127 128
=over

=item C<get($id)>
129 130 131

Retrieves and returns a flag from the database.

132 133
=back

134
=cut
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

# !!! Implement a cache for this function!
sub get {
    my ($id) = @_;

    my $select_clause = "SELECT " . join(", ", @base_columns);
    my $from_clause = "FROM " . join(" ", @base_tables);
    
    # Execute the query, retrieve the result, and write it into a record.
    &::PushGlobalSQLState();
    &::SendSQL("$select_clause $from_clause WHERE flags.id = $id");
    my $flag = perlify_record(&::FetchSQLData());
    &::PopGlobalSQLState();

    return $flag;
}

152 153 154 155 156
=pod

=over

=item C<match($criteria)>
157

158 159 160 161 162 163 164 165 166
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 {
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    my ($criteria) = @_;

    my $select_clause = "SELECT " . join(", ", @base_columns);
    my $from_clause = "FROM " . join(" ", @base_tables);
    
    my @criteria = sqlify_criteria($criteria);
    
    my $where_clause = "WHERE " . join(" AND ", @criteria);
    
    # Execute the query, retrieve the results, and write them into records.
    &::PushGlobalSQLState();
    &::SendSQL("$select_clause $from_clause $where_clause");
    my @flags;
    while (&::MoreSQLData()) {
        my $flag = perlify_record(&::FetchSQLData());
        push(@flags, $flag);
    }
    &::PopGlobalSQLState();

    return \@flags;
}

189 190 191 192 193 194 195 196 197 198 199
=pod

=over

=item C<count($criteria)>

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
200

201 202 203
=cut

sub count {
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    my ($criteria) = @_;

    my @criteria = sqlify_criteria($criteria);
    
    my $where_clause = "WHERE " . join(" AND ", @criteria);
    
    # Execute the query, retrieve the result, and write it into a record.
    &::PushGlobalSQLState();
    &::SendSQL("SELECT COUNT(id) FROM flags $where_clause");
    my $count = &::FetchOneColumn();
    &::PopGlobalSQLState();

    return $count;
}

219
######################################################################
220
# Creating and Modifying
221
######################################################################
222

223 224 225 226
=pod

=over

227
=item C<validate($cgi, $bug_id, $attach_id)>
228

229 230
Validates fields containing flag modifications.

231 232 233
If the attachment is new, it has no ID yet and $attach_id is set
to -1 to force its check anyway.

234 235 236 237 238
=back

=cut

sub validate {
239 240
    my ($cgi, $bug_id, $attach_id) = @_;

241
    my $user = Bugzilla->user;
242 243
    my $dbh = Bugzilla->dbh;

244 245 246 247
    # 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.
248
    my @ids = map(/^flag-(\d+)$/ ? $1 : (), $cgi->param());
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 277 278 279

    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) {
280
        my $status = $cgi->param("flag-$id");
281
        my @requestees = $cgi->param("requestee-$id");
282 283 284
        
        # Make sure the flag exists.
        my $flag = get($id);
285
        $flag || ThrowCodeError("flag_nonexistent", { id => $id });
286

287 288 289 290 291
        # Note that the deletedness of the flag (is_active or not) is not 
        # checked here; we do want to allow changes to deleted flags in
        # certain cases. Flag::modify() will revive the modified flags.
        # See bug 223878 for details.

292 293
        # Make sure the user chose a valid status.
        grep($status eq $_, qw(X + - ?))
294 295
          || ThrowCodeError("flag_status_invalid", 
                            { id => $id, status => $status });
296 297
                
        # Make sure the user didn't request the flag unless it's requestable.
298 299 300 301 302 303
        # If the flag was requested before it became unrequestable, leave it
        # as is.
        if ($status eq '?'
            && $flag->{status} ne '?'
            && !$flag->{type}->{is_requestable})
        {
304
            ThrowCodeError("flag_status_invalid", 
305
                           { id => $id, status => $status });
306
        }
307 308 309

        # Make sure the user didn't specify a requestee unless the flag
        # is specifically requestable. If the requestee was set before
310 311 312 313 314 315 316 317 318 319 320 321
        # 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.
        if ($status eq '?' && !$flag->{type}->{is_requesteeble}) {
            my $old_requestee =
                $flag->{'requestee'} ? $flag->{'requestee'}->login : '';
            my $new_requestee = join('', @requestees);
            if ($new_requestee && $new_requestee ne $old_requestee) {
                ThrowCodeError("flag_requestee_disabled",
                               { type => $flag->{type} });
            }
        }
322

323 324
        # 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.
325
        if ($status eq '?'
326 327
            && !$flag->{type}->{is_multiplicable}
            && scalar(@requestees) > 1)
328
        {
329
            ThrowUserError("flag_not_multiplicable", { type => $flag->{type} });
330 331
        }

332
        # Make sure the requestees are authorized to access the bug.
333 334
        # (and attachment, if this installation is using the "insider group"
        # feature and the attachment is marked private).
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        if ($status eq '?' && $flag->{type}->{is_requesteeble}) {
            my $old_requestee =
                $flag->{'requestee'} ? $flag->{'requestee'}->login : '';
            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.
                my $requestee = Bugzilla::User->new_from_login($login);
                
                # 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",
350 351 352 353 354
                                   { flag_type  => $flag->{'type'},
                                     requestee  => $requestee,
                                     bug_id     => $bug_id,
                                     attachment => $flag->{target}->{attachment}
                                   });
355 356 357 358
                }
    
                # Throw an error if the target is a private attachment and
                # the requestee isn't in the group of insiders who can see it.
359
                if ($flag->{target}->{attachment}
360 361 362 363 364
                    && $cgi->param('isprivate')
                    && Param("insidergroup")
                    && !$requestee->in_group(Param("insidergroup")))
                {
                    ThrowUserError("flag_requestee_unauthorized_attachment",
365 366 367 368 369
                                   { flag_type  => $flag->{'type'},
                                     requestee  => $requestee,
                                     bug_id     => $bug_id,
                                     attachment => $flag->{target}->{attachment}
                                   });
370
                }
371 372
            }
        }
373 374 375 376 377

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

378 379 380
        # - User in the $request_gid group can clear pending requests and set flags
        #   and can rerequest set flags.
        next if (($status eq 'X' || $status eq '?')
381 382
                 && (!$flag->{type}->{request_gid}
                     || $user->in_group(&::GroupIdToName($flag->{type}->{request_gid}))));
383 384 385 386 387 388 389 390 391 392 393

        # - User in the $grant_gid group can set/clear flags,
        #   including "+" and "-"
        next if (!$flag->{type}->{grant_gid}
                 || $user->in_group(&::GroupIdToName($flag->{type}->{grant_gid})));

        # - Any other flag modification is denied
        ThrowUserError("flag_update_denied",
                        { name       => $flag->{type}->{name},
                          status     => $status,
                          old_status => $flag->{status} });
394 395 396
    }
}

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
sub snapshot {
    my ($bug_id, $attach_id) = @_;

    my $flags = match({ 'bug_id'    => $bug_id,
                        'attach_id' => $attach_id,
                        'is_active' => 1 });
    my @summaries;
    foreach my $flag (@$flags) {
        my $summary = $flag->{'type'}->{'name'} . $flag->{'status'};
        $summary .= "(" . $flag->{'requestee'}->login . ")" if $flag->{'requestee'};
        push(@summaries, $summary);
    }
    return @summaries;
}

412

413 414 415 416
=pod

=over

417
=item C<process($target, $timestamp, $cgi)>
418 419 420 421 422

Processes changes to flags.

The target is the bug or attachment this flag is about, the timestamp
is the date/time the bug was last touched (so that changes to the flag
423 424
can be stamped with the same date/time), the cgi is the CGI object
used to obtain the flag fields that the user submitted.
425 426 427 428 429 430

=back

=cut

sub process {
431
    my ($bug_id, $attach_id, $timestamp, $cgi) = @_;
432 433

    my $dbh = Bugzilla->dbh;
434 435 436
    my $target = get_target($bug_id, $attach_id);
    # Make sure the target exists.
    return unless $target->{'exists'};
437 438 439 440 441 442

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
    $timestamp = ($timestamp ? &::SqlQuote($timestamp) : "NOW()");
    
    # Take a snapshot of flags before any changes.
443
    my @old_summaries = snapshot($bug_id, $attach_id);
444
    
445
    # Cancel pending requests if we are obsoleting an attachment.
446
    if ($attach_id && $cgi->param('isobsolete')) {
447 448 449
        CancelRequests($bug_id, $attach_id);
    }

450
    # Create new flags and update existing flags.
451
    my $new_flags = FormToNewFlags($target, $cgi);
452
    foreach my $flag (@$new_flags) { create($flag, $timestamp) }
453
    modify($cgi, $timestamp);
454 455 456
    
    # In case the bug's product/component has changed, clear flags that are
    # no longer valid.
457 458
    my $flag_ids = $dbh->selectcol_arrayref(
        "SELECT flags.id 
459 460 461 462 463
           FROM flags
     INNER JOIN bugs
             ON flags.bug_id = bugs.bug_id
      LEFT JOIN flaginclusions AS i
             ON flags.type_id = i.type_id 
464
            AND (bugs.product_id = i.product_id OR i.product_id IS NULL)
465 466 467 468
            AND (bugs.component_id = i.component_id OR i.component_id IS NULL)
          WHERE bugs.bug_id = ?
            AND flags.is_active = 1
            AND i.type_id IS NULL",
469 470
        undef, $bug_id);

471
    foreach my $flag_id (@$flag_ids) { clear($flag_id) }
472 473 474

    $flag_ids = $dbh->selectcol_arrayref(
        "SELECT flags.id 
475
        FROM flags, bugs, flagexclusions e
476
        WHERE bugs.bug_id = ?
477
        AND flags.bug_id = bugs.bug_id
478 479
        AND flags.type_id = e.type_id
        AND flags.is_active = 1 
480
        AND (bugs.product_id = e.product_id OR e.product_id IS NULL)
481 482 483
        AND (bugs.component_id = e.component_id OR e.component_id IS NULL)",
        undef, $bug_id);

484
    foreach my $flag_id (@$flag_ids) { clear($flag_id) }
485

486 487 488 489 490 491 492 493 494
    # 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;
495
    my $user_id = Bugzilla->user->id;
496 497 498 499

    $attach_id ||= 'NULL';
    $old_summaries = join(", ", @$old_summaries);
    $new_summaries = join(", ", @$new_summaries);
500
    my ($removed, $added) = diff_strings($old_summaries, $new_summaries);
501 502 503
    if ($removed ne $added) {
        my $sql_removed = &::SqlQuote($removed);
        my $sql_added = &::SqlQuote($added);
504
        my $field_id = get_field_id('flagtypes.name');
505 506
        $dbh->do("INSERT INTO bugs_activity
                  (bug_id, attach_id, who, bug_when, fieldid, removed, added)
507
                  VALUES ($bug_id, $attach_id, $user_id, $timestamp,
508
                  $field_id, $sql_removed, $sql_added)");
509 510 511

        $dbh->do("UPDATE bugs SET delta_ts = $timestamp WHERE bug_id = ?",
                 undef, $bug_id);
512 513 514
    }
}

515 516 517 518 519 520 521
=pod

=over

=item C<create($flag, $timestamp)>

Creates a flag record in the database.
522

523 524 525 526 527
=back

=cut

sub create {
528 529 530 531 532 533 534 535
    my ($flag, $timestamp) = @_;

    # Determine the ID for the flag record by retrieving the last ID used
    # and incrementing it.
    &::SendSQL("SELECT MAX(id) FROM flags");
    $flag->{'id'} = (&::FetchOneColumn() || 0) + 1;
    
    # Insert a record for the flag into the flags table.
536 537 538
    my $attach_id =
      $flag->{target}->{attachment} ? $flag->{target}->{attachment}->{id}
                                    : "NULL";
539
    my $requestee_id = $flag->{'requestee'} ? $flag->{'requestee'}->id : "NULL";
540 541 542 543 544 545 546 547 548
    &::SendSQL("INSERT INTO flags (id, type_id, 
                                      bug_id, attach_id, 
                                      requestee_id, setter_id, status, 
                                      creation_date, modification_date)
                VALUES ($flag->{'id'}, 
                        $flag->{'type'}->{'id'}, 
                        $flag->{'target'}->{'bug'}->{'id'}, 
                        $attach_id,
                        $requestee_id,
549
                        " . $flag->{'setter'}->id . ",
550 551 552 553 554
                        '$flag->{'status'}', 
                        $timestamp,
                        $timestamp)");
    
    # Send an email notifying the relevant parties about the flag creation.
555 556
    if ($flag->{'requestee'} 
          && $flag->{'requestee'}->wants_mail([EVT_FLAG_REQUESTED]))
557
    {
558
        $flag->{'addressee'} = $flag->{'requestee'};
559
    }
560 561

    notify($flag, "request/email.txt.tmpl");
562 563
}

564
=pod
565

566 567 568 569 570 571 572 573 574 575 576 577
=over

=item C<migrate($old_attach_id, $new_attach_id, $timestamp)>

Moves a flag from one attachment to another.  Useful for migrating
a flag from an obsolete attachment to the attachment that obsoleted it.

=back

=cut

sub migrate {
578 579 580 581 582
    my ($old_attach_id, $new_attach_id, $timestamp) = @_;

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
    $timestamp = ($timestamp ? &::SqlQuote($timestamp) : "NOW()");
583 584 585 586

    # Update the record in the flags table to point to the new attachment.
    &::SendSQL("UPDATE flags " . 
               "SET    attach_id = $new_attach_id , " . 
587
               "       modification_date = $timestamp " . 
588 589 590
               "WHERE  attach_id = $old_attach_id");
}

591 592 593 594
=pod

=over

595
=item C<modify($cgi, $timestamp)>
596

597 598 599 600 601 602 603 604 605 606
Modifies flags in the database when a user changes them.
Note that modified flags are always set active (is_active = 1) -
this will revive deleted flags that get changed through 
attachment.cgi midairs. See bug 223878 for details.

=back

=cut

sub modify {
607
    my ($cgi, $timestamp) = @_;
608
    my $setter = Bugzilla->user;
609 610 611

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
612
    my $sql_timestamp = ($timestamp ? &::SqlQuote($timestamp) : "NOW()");
613 614
    
    # Extract a list of flags from the form data.
615
    my @ids = map(/^flag-(\d+)$/ ? $1 : (), $cgi->param());
616
    
617 618 619 620
    # 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.
621 622 623
    my @flags;
    foreach my $id (@ids) {
        my $flag = get($id);
624

625
        my $status = $cgi->param("flag-$id");
626

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
        # 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
            && $flag->{type}->{is_multiplicable})
        {
            # The first person, for which we'll reuse the existing flag.
            $requestee_email = shift(@requestees);
  
            # Create new flags like the existing one for each additional person.
            foreach my $login (@requestees) {
                create({ type      => $flag->{type} ,
                         target    => $flag->{target} , 
644
                         setter    => $setter, 
645 646 647 648 649 650 651 652 653
                         status    => "?",
                         requestee => new Bugzilla::User(login_to_id($login)) },
                       $timestamp);
            }
        }
        else {
            $requestee_email = trim($cgi->param("requestee-$id") || '');
        }

654 655 656 657 658
        # 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.

        my $status_changed = ($status ne $flag->{'status'});
659
        
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        # 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.
        
        my $old_requestee = 
          $flag->{'requestee'} ? $flag->{'requestee'}->login : '';

        my $requestee_changed = 
          ($status eq "?" && 
           $flag->{'type'}->{'is_requesteeble'} &&
           $old_requestee ne $requestee_email);
           
        next unless ($status_changed || $requestee_changed);

676
        
677 678 679
        # 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.
        &::trick_taint($status);
680
        
681 682
        if ($status eq '+' || $status eq '-') {
            &::SendSQL("UPDATE flags 
683
                        SET    setter_id = " . $setter->id . ", 
684
                               requestee_id = NULL , 
685
                               status = '$status' , 
686
                               modification_date = $sql_timestamp ,
687
                               is_active = 1
688
                        WHERE  id = $flag->{'id'}");
689 690 691 692 693 694

            # If the status of the flag was "?", we have to notify
            # the requester (if he wants to).
            my $requester;
            if ($flag->{'status'} eq '?') {
                $requester = $flag->{'setter'};
695
            }
696 697 698 699 700 701 702 703 704 705 706 707
            # 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;
            }

            notify($flag, "request/email.txt.tmpl");
708 709
        }
        elsif ($status eq '?') {
710 711 712
            # Get the requestee, if any.
            my $requestee_id = "NULL";
            if ($requestee_email) {
713
                $requestee_id = login_to_id($requestee_email);
714 715
                $flag->{'requestee'} = new Bugzilla::User($requestee_id);
            }
716 717 718 719 720
            else {
                # If the status didn't change but we only removed the
                # requestee, we have to clear the requestee field.
                $flag->{'requestee'} = undef;
            }
721 722

            # Update the database with the changes.
723
            &::SendSQL("UPDATE flags 
724
                        SET    setter_id = " . $setter->id . ", 
725 726
                               requestee_id = $requestee_id , 
                               status = '$status' , 
727
                               modification_date = $sql_timestamp ,
728
                               is_active = 1
729
                        WHERE  id = $flag->{'id'}");
730 731 732 733 734

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

735
            # Send an email notifying the relevant parties about the request.
736 737
            if ($flag->{'requestee'}
                  && $flag->{'requestee'}->wants_mail([EVT_FLAG_REQUESTED]))
738
            {
739
                $flag->{'addressee'} = $flag->{'requestee'};
740
            }
741 742

            notify($flag, "request/email.txt.tmpl");
743
        }
744
        # The user unset the flag; set is_active = 0
745 746 747 748 749 750 751 752 753 754
        elsif ($status eq 'X') {
            clear($flag->{'id'});
        }
        
        push(@flags, $flag);
    }
    
    return \@flags;
}

755 756 757 758 759 760 761 762 763 764 765 766
=pod

=over

=item C<clear($id)>

Deactivate a flag.

=back

=cut

767 768 769 770 771 772
sub clear {
    my ($id) = @_;
    
    my $flag = get($id);
    
    &::PushGlobalSQLState();
773
    &::SendSQL("UPDATE flags SET is_active = 0 WHERE id = $id");
774
    &::PopGlobalSQLState();
775

776 777 778 779 780 781 782 783 784 785
    # If we cancel a pending request, we have to notify the requester
    # (if he wants to).
    my $requester;
    if ($flag->{'status'} eq '?') {
        $requester = $flag->{'setter'};
    }

    # 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.
786
    $flag->{'exists'} = 0;    
787
    $flag->{'status'} = "X";
788 789 790 791 792 793

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

    notify($flag, "request/email.txt.tmpl");
794 795 796
}


797
######################################################################
798
# Utility Functions
799 800 801 802 803 804
######################################################################

=pod

=over

805
=item C<FormToNewFlags($target, $cgi)>
806

807 808
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().
809 810 811 812

=back

=cut
813 814

sub FormToNewFlags {
815
    my ($target, $cgi) = @_;
816
    my $dbh = Bugzilla->dbh;
817
    my $setter = Bugzilla->user;
818
    
819
    # Extract a list of flag type IDs from field names.
820 821
    my @type_ids = map(/^flag_type-(\d+)$/ ? $1 : (), $cgi->param());
    @type_ids = grep($cgi->param("flag_type-$_") ne 'X', @type_ids);
822

823
    return () unless scalar(@type_ids);
824 825 826 827 828 829 830 831

    # Get a list of active flag types available for this target.
    my $flag_types = Bugzilla::FlagType::match(
        { 'target_type'  => $target->{'type'},
          'product_id'   => $target->{'product_id'},
          'component_id' => $target->{'component_id'},
          'is_active'    => 1 });

832
    my @flags;
833 834 835 836 837 838 839 840 841 842 843
    foreach my $flag_type (@$flag_types) {
        my $type_id = $flag_type->{'id'};

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

        # Get the number of active flags of this type already set for this target.
        my $has_flags = count(
            { 'type_id'     => $type_id,
              'target_type' => $target->{'type'},
              'bug_id'      => $target->{'bug'}->{'id'},
844 845
              'attach_id'   => $target->{'attachment'} ?
                                 $target->{'attachment'}->{'id'} : undef,
846 847 848 849 850 851
              'is_active'   => 1 });

        # Do not create a new flag of this type if this flag type is
        # not multiplicable and already has an active flag set.
        next if (!$flag_type->{'is_multiplicable'} && $has_flags);

852
        my $status = $cgi->param("flag_type-$type_id");
853
        trick_taint($status);
854

855 856 857
        my @logins = $cgi->param("requestee_type-$type_id");
        if ($status eq "?" && scalar(@logins) > 0) {
            foreach my $login (@logins) {
858 859 860 861 862 863 864
                my $requestee = new Bugzilla::User(login_to_id($login));
                push (@flags, { type      => $flag_type ,
                                target    => $target , 
                                setter    => $setter , 
                                status    => $status ,
                                requestee => $requestee });
                last if !$flag_type->{'is_multiplicable'};
865
            }
866
        }
867 868 869 870 871 872
        else {
            push (@flags, { type   => $flag_type ,
                            target => $target , 
                            setter => $setter , 
                            status => $status });
        }
873 874 875 876 877 878
    }

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

879 880 881 882 883 884 885 886 887 888 889 890
=pod

=over

=item C<GetBug($id)>

Returns a hash of information about a target bug.

=back

=cut

891 892 893 894 895 896
# Ideally, we'd use Bug.pm, but it's way too heavyweight, and it can't be
# made lighter without totally rewriting it, so we'll use this function
# until that one gets rewritten.
sub GetBug {
    my ($id) = @_;

897 898
    my $dbh = Bugzilla->dbh;

899 900 901
    # Save the currently running query (if any) so we do not overwrite it.
    &::PushGlobalSQLState();

902 903 904 905
    &::SendSQL("SELECT    1, short_desc, product_id, component_id,
                          COUNT(bug_group_map.group_id)
                FROM      bugs LEFT JOIN bug_group_map
                            ON (bugs.bug_id = bug_group_map.bug_id)
906 907 908
                WHERE     bugs.bug_id = $id " .
                $dbh->sql_group_by('bugs.bug_id',
                                   'short_desc, product_id, component_id'));
909 910 911 912

    my $bug = { 'id' => $id };
    
    ($bug->{'exists'}, $bug->{'summary'}, $bug->{'product_id'}, 
913
     $bug->{'component_id'}, $bug->{'restricted'}) = &::FetchSQLData();
914 915 916 917 918 919 920

    # Restore the previously running query (if any).
    &::PopGlobalSQLState();

    return $bug;
}

921 922 923 924
=pod

=over

925
=item C<get_target($bug_id, $attach_id)>
926 927 928 929 930 931 932

Someone please document this function.

=back

=cut

933
sub get_target {
934 935 936 937 938 939
    my ($bug_id, $attach_id) = @_;
    
    # Create an object representing the target bug/attachment.
    my $target = { 'exists' => 0 };

    if ($attach_id) {
940
        $target->{'attachment'} = Bugzilla::Attachment->get($attach_id);
941 942 943
        if ($bug_id) {
            # Make sure the bug and attachment IDs correspond to each other
            # (i.e. this is the bug to which this attachment is attached).
944 945 946 947 948
            if (!$target->{'attachment'}
                || $target->{'attachment'}->{'bug_id'} != $bug_id)
            {
              return { 'exists' => 0 };
            }
949
        }
950 951
        $target->{'bug'} = GetBug($bug_id);
        $target->{'exists'} = 1;
952 953 954 955 956 957 958 959 960 961 962
        $target->{'type'} = "attachment";
    }
    elsif ($bug_id) {
        $target->{'bug'} = GetBug($bug_id);
        $target->{'exists'} = $target->{'bug'}->{'exists'};
        $target->{'type'} = "bug";
    }

    return $target;
}

963 964 965 966 967 968
=pod

=over

=item C<notify($flag, $template_file)>

969 970
Sends an email notification about a flag being created, fulfilled
or deleted.
971 972 973 974 975

=back

=cut

976 977
sub notify {
    my ($flag, $template_file) = @_;
978

979
    my $template = Bugzilla->template;
980 981 982 983

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

984 985 986
    my $attachment_is_private = $flag->{'target'}->{'attachment'} ?
      $flag->{'target'}->{'attachment'}->{'isprivate'} : undef;

987 988 989 990
    # 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.
991
    if ($flag->{'target'}->{'bug'}->{'restricted'} || $attachment_is_private) {
992 993
        my @new_cc_list;
        foreach my $cc (split(/[, ]+/, $flag->{'type'}->{'cc_list'})) {
994
            my $ccuser = Bugzilla::User->new_from_login($cc) || next;
995

996
            next if $flag->{'target'}->{'bug'}->{'restricted'}
997
              && !$ccuser->can_see_bug($flag->{'target'}->{'bug'}->{'id'});
998
            next if $attachment_is_private
999
              && Param("insidergroup")
1000
              && !$ccuser->in_group(Param("insidergroup"));
1001
            push(@new_cc_list, $cc);
1002 1003 1004 1005
        }
        $flag->{'type'}->{'cc_list'} = join(", ", @new_cc_list);
    }

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

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    # Process and send notification for each recipient
    foreach my $to ($flag->{'addressee'} ? $flag->{'addressee'}->email : '',
                    split(/[, ]+/, $flag->{'type'}->{'cc_list'}))
    {
        next unless $to;
        my $vars = { 'flag' => $flag, 'to' => $to };
        my $message;
        my $rv = $template->process($template_file, $vars, \$message);
        if (!$rv) {
            Bugzilla->cgi->header();
            ThrowTemplateError($template->error());
        }
1021

1022 1023
        Bugzilla::BugMail::MessageToMTA($message);
    }
1024 1025
}

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
# Cancel all request flags from the attachment being obsoleted.
sub CancelRequests {
    my ($bug_id, $attach_id, $timestamp) = @_;
    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 flags.is_active = 1
                                  AND attachments.isobsolete = 0",
                                  undef, $attach_id);

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

    # Take a snapshot of flags before any changes.
    my @old_summaries = snapshot($bug_id, $attach_id) if ($timestamp);
1045
    foreach my $flag (@$request_ids) { clear($flag) }
1046 1047 1048 1049 1050 1051 1052 1053 1054

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

    # Take a snapshot of flags after any changes.
    my @new_summaries = snapshot($bug_id, $attach_id);
    update_activity($bug_id, $attach_id, $timestamp, \@old_summaries, \@new_summaries);
}

1055
######################################################################
1056
# Private Functions
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
######################################################################

=begin private

=head1 PRIVATE FUNCTIONS

=over

=item C<sqlify_criteria($criteria)>

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

=back

=cut
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

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'") }
1099
        elsif ($field eq 'is_active')    { push(@criteria, "is_active    = $value") }
1100 1101 1102 1103 1104
    }
    
    return @criteria;
}

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
=pod

=over

=item C<perlify_record($exists, $id, $type_id, $bug_id, $attach_id, $requestee_id, $setter_id, $status)>

Converts a row from the database into a Perl record.

=back

1115 1116
=end private

1117 1118
=cut

1119 1120 1121 1122
sub perlify_record {
    my ($exists, $id, $type_id, $bug_id, $attach_id, 
        $requestee_id, $setter_id, $status) = @_;
    
1123 1124
    return undef unless defined($exists);
    
1125 1126 1127 1128 1129
    my $flag =
      {
        exists    => $exists , 
        id        => $id ,
        type      => Bugzilla::FlagType::get($type_id) ,
1130
        target    => get_target($bug_id, $attach_id) , 
1131
        requestee => $requestee_id ? new Bugzilla::User($requestee_id) : undef,
1132 1133 1134 1135 1136 1137 1138
        setter    => new Bugzilla::User($setter_id) ,
        status    => $status , 
      };
    
    return $flag;
}

1139 1140 1141 1142 1143 1144 1145 1146
=head1 SEE ALSO

=over

=item B<Bugzilla::FlagType>

=back

1147

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
=head1 CONTRIBUTORS

=over

=item Myk Melez <myk@mozilla.org>

=item Jouni Heikniemi <jouni@heikniemi.net>

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

=back

=cut

1162
1;