Search.pm 73.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 22 23 24 25 26
# -*- 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): Gervase Markham <gerv@gerv.net>
#                 Terry Weissman <terry@mozilla.org>
#                 Dan Mosedale <dmose@mozilla.org>
#                 Stephan Niemz <st.n@gmx.net>
#                 Andreas Franke <afranke@mathweb.org>
#                 Myk Melez <myk@mozilla.org>
#                 Michael Schindler <michael@compressconsult.com>
27
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
28
#                 Joel Peshkin <bugreport@peshkin.net>
29
#                 Lance Larsh <lance.larsh@oracle.com>
30
#                 Jesse Clark <jjclark1982@gmail.com>
31 32 33 34

use strict;

package Bugzilla::Search;
35 36
use base qw(Exporter);
@Bugzilla::Search::EXPORT = qw(IsValidQueryType);
37

38
use Bugzilla::Error;
39
use Bugzilla::Util;
40
use Bugzilla::Constants;
41
use Bugzilla::Group;
42
use Bugzilla::User;
43
use Bugzilla::Field;
44
use Bugzilla::Status;
45
use Bugzilla::Keyword;
46

47
use Date::Format;
48
use Date::Parse;
49

50 51 52 53
# Some fields are not sorted on themselves, but on other fields. 
# We need to have a list of these fields and what they map to.
# Each field points to an array that contains the fields mapped 
# to, in order.
54
use constant SPECIAL_ORDER => {
55
    'bugs.target_milestone' => [ 'ms_order.sortkey','ms_order.value' ],
56
};
57 58 59

# When we add certain fields to the ORDER BY, we need to then add a
# table join to the FROM statement. This hash maps input fields to 
60
# the join statements that need to be added.
61
use constant SPECIAL_ORDER_JOIN => {
62
    'bugs.target_milestone' => 'LEFT JOIN milestones AS ms_order ON ms_order.value = bugs.target_milestone AND ms_order.product_id = bugs.product_id',
63
};
64

65
# Create a new Search
66
# Note that the param argument may be modified by Bugzilla::Search
67 68 69 70
sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
  
71
    my $self = { @_ };
72
    bless($self, $class);
73

74
    $self->init();
75
 
76 77 78 79 80 81
    return $self;
}

sub init {
    my $self = shift;
    my $fieldsref = $self->{'fields'};
82
    my $params = $self->{'params'};
83 84
    $self->{'user'} ||= Bugzilla->user;
    my $user = $self->{'user'};
85

86 87 88 89 90
    my $orderref = $self->{'order'} || 0;
    my @inputorder;
    @inputorder = @$orderref if $orderref;
    my @orderby;

91 92 93
    my @fields;
    my @supptables;
    my @wherepart;
94
    my @having;
95
    my @groupby;
96 97 98
    @fields = @$fieldsref if $fieldsref;
    my @specialchart;
    my @andlist;
99
    my %chartfields;
100

101 102 103
    my %special_order      = %{SPECIAL_ORDER()};
    my %special_order_join = %{SPECIAL_ORDER_JOIN()};

104 105
    my @select_fields = 
        Bugzilla->get_fields({ type => FIELD_TYPE_SINGLE_SELECT });
106
    
107 108 109
    my @multi_select_fields = Bugzilla->get_fields({
        type     => [FIELD_TYPE_MULTI_SELECT, FIELD_TYPE_BUG_URLS],
        obsolete => 0 });
110 111 112 113 114 115 116
    foreach my $field (@select_fields) {
        my $name = $field->name;
        $special_order{"bugs.$name"} = [ "$name.sortkey", "$name.value" ],
        $special_order_join{"bugs.$name"} =
            "LEFT JOIN $name ON $name.value = bugs.$name";
    }

117 118
    my $dbh = Bugzilla->dbh;

119
    # First, deal with all the old hard-coded non-chart-based poop.
120
    if (grep(/map_assigned_to/, @$fieldsref)) {
121 122
        push @supptables, "INNER JOIN profiles AS map_assigned_to " .
                          "ON bugs.assigned_to = map_assigned_to.userid";
123 124
    }

125
    if (grep(/map_reporter/, @$fieldsref)) {
126 127
        push @supptables, "INNER JOIN profiles AS map_reporter " .
                          "ON bugs.reporter = map_reporter.userid";
128 129
    }

130
    if (grep(/map_qa_contact/, @$fieldsref)) {
131 132
        push @supptables, "LEFT JOIN profiles AS map_qa_contact " .
                          "ON bugs.qa_contact = map_qa_contact.userid";
133 134
    }

135
    if (lsearch($fieldsref, 'map_products.name') >= 0) {
136 137
        push @supptables, "INNER JOIN products AS map_products " .
                          "ON bugs.product_id = map_products.id";
138 139
    }

140
    if (lsearch($fieldsref, 'map_classifications.name') >= 0) {
141 142
        push @supptables, "INNER JOIN products AS map_products " .
                          "ON bugs.product_id = map_products.id";
143 144 145
        push @supptables,
                "INNER JOIN classifications AS map_classifications " .
                "ON map_products.classification_id = map_classifications.id";
146 147
    }

148
    if (lsearch($fieldsref, 'map_components.name') >= 0) {
149 150
        push @supptables, "INNER JOIN components AS map_components " .
                          "ON bugs.component_id = map_components.id";
151
    }
152 153
    
    if (grep($_ =~/AS (actual_time|percentage_complete)$/, @$fieldsref)) {
154
        push(@supptables, "LEFT JOIN longdescs AS ldtime " .
155 156
                          "ON ldtime.bug_id = bugs.bug_id");
    }
157 158

    my $minvotes;
159 160
    if (defined $params->param('votes')) {
        my $c = trim($params->param('votes'));
161 162
        if ($c ne "") {
            if ($c !~ /^[0-9]*$/) {
163
                ThrowUserError("illegal_at_least_x_votes",
164
                                  { value => $c });
165 166 167 168 169
            }
            push(@specialchart, ["votes", "greaterthan", $c - 1]);
        }
    }

170
    if ($params->param('bug_id')) {
171
        my $type = "anyexact";
172
        if ($params->param('bugidtype') && $params->param('bugidtype') eq 'exclude') {
173 174
            $type = "nowords";
        }
175
        push(@specialchart, ["bug_id", $type, join(',', $params->param('bug_id'))]);
176 177
    }

178 179
    # If the user has selected all of either status or resolution, change to
    # selecting none. This is functionally equivalent, but quite a lot faster.
180 181
    # Also, if the status is __open__ or __closed__, translate those
    # into their equivalent lists of open and closed statuses.
182 183
    if ($params->param('bug_status')) {
        my @bug_statuses = $params->param('bug_status');
184 185
        my @legal_statuses = @{get_legal_field_values('bug_status')};
        if (scalar(@bug_statuses) == scalar(@legal_statuses)
186 187
            || $bug_statuses[0] eq "__all__")
        {
188 189
            $params->delete('bug_status');
        }
190
        elsif ($bug_statuses[0] eq '__open__') {
191 192
            $params->param('bug_status', grep(is_open_state($_), 
                                              @legal_statuses));
193 194
        }
        elsif ($bug_statuses[0] eq "__closed__") {
195 196
            $params->param('bug_status', grep(!is_open_state($_), 
                                              @legal_statuses));
197
        }
198 199 200 201
    }
    
    if ($params->param('resolution')) {
        my @resolutions = $params->param('resolution');
202 203
        my $legal_resolutions = get_legal_field_values('resolution');
        if (scalar(@resolutions) == scalar(@$legal_resolutions)) {
204 205 206 207
            $params->delete('resolution');
        }
    }
    
208 209 210
    my @legal_fields = ("product", "version", "assigned_to", "reporter", 
                        "component", "classification", "target_milestone",
                        "bug_group");
211

212 213
    # Include custom select fields.
    push(@legal_fields, map { $_->name } @select_fields);
214
    push(@legal_fields, map { $_->name } @multi_select_fields);
215

216
    foreach my $field ($params->param()) {
217
        if (lsearch(\@legal_fields, $field) != -1) {
218
            push(@specialchart, [$field, "anyexact",
219
                                 join(',', $params->param($field))]);
220 221 222
        }
    }

223 224
    if ($params->param('keywords')) {
        my $t = $params->param('keywords_type');
225 226 227
        if (!$t || $t eq "or") {
            $t = "anywords";
        }
228
        push(@specialchart, ["keywords", $t, $params->param('keywords')]);
229 230 231
    }

    foreach my $id ("1", "2") {
232
        if (!defined ($params->param("email$id"))) {
233 234
            next;
        }
235
        my $email = trim($params->param("email$id"));
236 237 238
        if ($email eq "") {
            next;
        }
239
        my $type = $params->param("emailtype$id");
240
        $type = "anyexact" if ($type eq "exact");
241 242 243

        my @clist;
        foreach my $field ("assigned_to", "reporter", "cc", "qa_contact") {
244
            if ($params->param("email$field$id")) {
245 246 247
                push(@clist, $field, $type, $email);
            }
        }
248
        if ($params->param("emaillongdesc$id")) {
249
                push(@clist, "commenter", $type, $email);
250 251 252 253
        }
        if (@clist) {
            push(@specialchart, \@clist);
        }
254 255 256 257 258 259 260 261 262 263 264
        else {
            # No field is selected. Nothing to see here.
            next;
        }

        if ($type eq "anyexact") {
            foreach my $name (split(',', $email)) {
                $name = trim($name);
                login_to_id($name, THROW_ERROR) if $name;
            }
        }
265 266
    }

267 268 269 270 271 272 273
    my $chfieldfrom = trim(lc($params->param('chfieldfrom'))) || '';
    my $chfieldto = trim(lc($params->param('chfieldto'))) || '';
    $chfieldfrom = '' if ($chfieldfrom eq 'now');
    $chfieldto = '' if ($chfieldto eq 'now');
    my @chfield = $params->param('chfield');
    my $chvalue = trim($params->param('chfieldvalue')) || '';

274 275
    # 2003-05-20: The 'changedin' field is no longer in the UI, but we continue
    # to process it because it will appear in stored queries and bookmarks.
276
    my $changedin = trim($params->param('changedin')) || '';
277 278 279 280
    if ($changedin) {
        if ($changedin !~ /^[0-9]*$/) {
            ThrowUserError("illegal_changed_in_last_x_days",
                              { value => $changedin });
281 282
        }

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        if (!$chfieldfrom
            && !$chfieldto
            && scalar(@chfield) == 1
            && $chfield[0] eq "[Bug creation]")
        {
            # Deal with the special case where the query is using changedin
            # to get bugs created in the last n days by converting the value
            # into its equivalent for the chfieldfrom parameter.
            $chfieldfrom = "-" . ($changedin - 1) . "d";
        }
        else {
            # Oh boy, the general case.  Who knows why the user included
            # the changedin parameter, but do our best to comply.
            push(@specialchart, ["changedin", "lessthan", $changedin + 1]);
        }
    }
299

300
    if ($chfieldfrom ne '' || $chfieldto ne '') {
301 302 303 304
        my $sql_chfrom = $chfieldfrom ? $dbh->quote(SqlifyDate($chfieldfrom)):'';
        my $sql_chto   = $chfieldto   ? $dbh->quote(SqlifyDate($chfieldto))  :'';
        my $sql_chvalue = $chvalue ne '' ? $dbh->quote($chvalue) : '';
        trick_taint($sql_chvalue);
305
        if(!@chfield) {
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
            if ($sql_chfrom) {
                my $term = "bugs.delta_ts >= $sql_chfrom";
                push(@wherepart, $term);
                $self->search_description({
                    field => 'delta_ts', type => 'greaterthaneq',
                    value => $chfieldfrom, term => $term,
                });
            }
            if ($sql_chto) {
                my $term = "bugs.delta_ts <= $sql_chto";
                push(@wherepart, $term);
                $self->search_description({
                    field => 'delta_ts', type => 'lessthaneq',
                    value => $chfieldto, term => $term,
                });
            }
322
        } else {
323
            my $bug_creation_clause;
324
            my @list;
325
            my @actlist;
326 327
            foreach my $f (@chfield) {
                if ($f eq "[Bug creation]") {
328 329
                    # Treat [Bug creation] differently because we need to look
                    # at bugs.creation_ts rather than the bugs_activity table.
330
                    my @l;
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
                    if ($sql_chfrom) {
                        my $term = "bugs.creation_ts >= $sql_chfrom";
                        push(@l, $term);
                        $self->search_description({
                            field => 'creation_ts', type => 'greaterthaneq',
                            value => $chfieldfrom, term => $term,
                        });
                    }
                    if ($sql_chto) {
                        my $term = "bugs.creation_ts <= $sql_chto";
                        push(@l, $term);
                        $self->search_description({
                            field => 'creation_ts', type => 'lessthaneq',
                            value => $chfieldto, term => $term,
                        });
                    }
347
                    $bug_creation_clause = "(" . join(' AND ', @l) . ")";
348
                } else {
349
                    push(@actlist, get_field_id($f));
350 351
                }
            }
352

353
            # @actlist won't have any elements if the only field being searched
354
            # is [Bug creation] (in which case we don't need bugs_activity).
355
            if(@actlist) {
356
                my $extra = " actcheck.bug_id = bugs.bug_id";
357
                push(@list, "(actcheck.bug_when IS NOT NULL)");
358 359 360 361 362 363 364 365

                my $from_term = " AND actcheck.bug_when >= $sql_chfrom";
                $extra .= $from_term if $sql_chfrom;
                my $to_term = " AND actcheck.bug_when <= $sql_chto";
                $extra .= $to_term if $sql_chto;
                my $value_term = " AND actcheck.added = $sql_chvalue";
                $extra .= $value_term if $sql_chvalue;

366
                push(@supptables, "LEFT JOIN bugs_activity AS actcheck " .
367 368
                                  "ON $extra AND " 
                                 . $dbh->sql_in('actcheck.fieldid', \@actlist));
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

                foreach my $field (@chfield) {
                    next if $field eq "[Bug creation]";
                    if ($sql_chvalue) {
                        $self->search_description({
                            field => $field, type => 'changedto',
                            value => $chvalue, term  => $value_term,
                        });
                    }
                    if ($sql_chfrom) {
                        $self->search_description({
                            field => $field, type => 'changedafter',
                            value => $chfieldfrom, term => $from_term,
                        });
                    }
                    if ($sql_chvalue) {
                        $self->search_description({
                            field => $field, type => 'changedbefore',
                            value => $chfieldto, term => $to_term,
                        });
                    }
                }
391
            }
392 393 394 395 396 397 398 399

            # Now that we're done using @list to determine if there are any
            # regular fields to search (and thus we need bugs_activity),
            # add the [Bug creation] criterion to the list so we can OR it
            # together with the others.
            push(@list, $bug_creation_clause) if $bug_creation_clause;

            push(@wherepart, "(" . join(" OR ", @list) . ")");
400 401 402
        }
    }

403 404
    my $sql_deadlinefrom;
    my $sql_deadlineto;
405
    if ($user->is_timetracker) {
406 407 408 409 410
      my $deadlinefrom;
      my $deadlineto;
            
      if ($params->param('deadlinefrom')){
        $deadlinefrom = $params->param('deadlinefrom');
411 412 413
        validate_date($deadlinefrom)
          || ThrowUserError('illegal_date', {date => $deadlinefrom,
                                             format => 'YYYY-MM-DD'});
414 415
        $sql_deadlinefrom = $dbh->quote($deadlinefrom);
        trick_taint($sql_deadlinefrom);
416 417 418 419 420 421
        my $term = "bugs.deadline >= $sql_deadlinefrom";
        push(@wherepart, $term);
        $self->search_description({
            field => 'deadline', type => 'greaterthaneq',
            value => $deadlinefrom, term => $term,
        });
422 423 424 425
      }
      
      if ($params->param('deadlineto')){
        $deadlineto = $params->param('deadlineto');
426 427 428
        validate_date($deadlineto)
          || ThrowUserError('illegal_date', {date => $deadlineto,
                                             format => 'YYYY-MM-DD'});
429 430
        $sql_deadlineto = $dbh->quote($deadlineto);
        trick_taint($sql_deadlineto);
431 432 433 434 435 436
        my $term = "bugs.deadline <= $sql_deadlineto";
        push(@wherepart, $term);
        $self->search_description({
            field => 'deadline', type => 'lessthaneq',
            value => $deadlineto, term => $term,
        });
437 438 439
      }
    }  

440
    foreach my $f ("short_desc", "longdesc", "bug_file_loc",
441
                   "status_whiteboard") {
442 443
        if (defined $params->param($f)) {
            my $s = trim($params->param($f));
444 445
            if ($s ne "") {
                my $n = $f;
446 447
                my $q = $dbh->quote($s);
                trick_taint($q);
448
                my $type = $params->param($f . "_type");
449 450 451 452 453
                push(@specialchart, [$f, $type, $s]);
            }
        }
    }

454
    if (defined $params->param('content')) {
455
        push(@specialchart, ['content', 'matches', $params->param('content')]);
456 457
    }

458 459
    my $multi_fields = join('|', map($_->name, @multi_select_fields));

460
    my $chartid;
461
    my $sequence = 0;
462 463 464 465 466 467 468
    my $f;
    my $ff;
    my $t;
    my $q;
    my $v;
    my $term;
    my %funcsbykey;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    my %func_args = (
        'chartid' => \$chartid,
        'sequence' => \$sequence,
        'f' => \$f,
        'ff' => \$ff,
        't' => \$t,
        'v' => \$v,
        'q' => \$q,
        'term' => \$term,
        'funcsbykey' => \%funcsbykey,
        'supptables' => \@supptables,
        'wherepart' => \@wherepart,
        'having' => \@having,
        'groupby' => \@groupby,
        'chartfields' => \%chartfields,
        'fields' => \@fields,
    );
    my @funcdefs = (
        "^(?:assigned_to|reporter|qa_contact),(?:notequals|equals|anyexact),%group\\.([^%]+)%" => \&_contact_exact_group,
        "^(?:assigned_to|reporter|qa_contact),(?:equals|anyexact),(%\\w+%)" => \&_contact_exact,
        "^(?:assigned_to|reporter|qa_contact),(?:notequals),(%\\w+%)" => \&_contact_notequals,
        "^(assigned_to|reporter),(?!changed)" => \&_assigned_to_reporter_nonchanged,
        "^qa_contact,(?!changed)" => \&_qa_contact_nonchanged,
        "^(?:cc),(?:notequals|equals|anyexact),%group\\.([^%]+)%" => \&_cc_exact_group,
        "^cc,(?:equals|anyexact),(%\\w+%)" => \&_cc_exact,
        "^cc,(?:notequals),(%\\w+%)" => \&_cc_notequals,
        "^cc,(?!changed)" => \&_cc_nonchanged,
        "^long_?desc,changedby" => \&_long_desc_changedby,
497 498
        "^long_?desc,changedbefore" => \&_long_desc_changedbefore_after,
        "^long_?desc,changedafter" => \&_long_desc_changedbefore_after,
499 500 501 502 503
        "^content,matches" => \&_content_matches,
        "^content," => sub { ThrowUserError("search_content_without_matches"); },
        "^(?:deadline|creation_ts|delta_ts),(?:lessthan|greaterthan|equals|notequals),(?:-|\\+)?(?:\\d+)(?:[dDwWmMyY])\$" => \&_timestamp_compare,
        "^commenter,(?:equals|anyexact),(%\\w+%)" => \&_commenter_exact,
        "^commenter," => \&_commenter,
504
        # The _ is allowed for backwards-compatibility with 3.2 and lower.
505 506 507
        "^long_?desc," => \&_long_desc,
        "^longdescs\.isprivate," => \&_longdescs_isprivate,
        "^work_time,changedby" => \&_work_time_changedby,
508 509
        "^work_time,changedbefore" => \&_work_time_changedbefore_after,
        "^work_time,changedafter" => \&_work_time_changedbefore_after,
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
        "^work_time," => \&_work_time,
        "^percentage_complete," => \&_percentage_complete,
        "^bug_group,(?!changed)" => \&_bug_group_nonchanged,
        "^attach_data\.thedata,changed" => \&_attach_data_thedata_changed,
        "^attach_data\.thedata," => \&_attach_data_thedata,
        "^attachments\.submitter," => \&_attachments_submitter,
        "^attachments\..*," => \&_attachments,
        "^flagtypes.name," => \&_flagtypes_name,
        "^requestees.login_name," => \&_requestees_login_name,
        "^setters.login_name," => \&_setters_login_name,
        "^(changedin|days_elapsed)," => \&_changedin_days_elapsed,
        "^component,(?!changed)" => \&_component_nonchanged,
        "^product,(?!changed)" => \&_product_nonchanged,
        "^classification,(?!changed)" => \&_classification_nonchanged,
        "^keywords,(?!changed)" => \&_keywords_nonchanged,
        "^dependson,(?!changed)" => \&_dependson_nonchanged,
        "^blocked,(?!changed)" => \&_blocked_nonchanged,
        "^alias,(?!changed)" => \&_alias_nonchanged,
        "^owner_idle_time,(greaterthan|lessthan)" => \&_owner_idle_time_greater_less,
529 530 531
        "^($multi_fields),(?:notequals|notregexp|notsubstring|nowords|nowordssubstr)" => \&_multiselect_negative,
        "^($multi_fields),(?:allwords|allwordssubstr|anyexact)" => \&_multiselect_multiple,
        "^($multi_fields),(?!changed)" => \&_multiselect_nonchanged,
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        ",equals" => \&_equals,
        ",notequals" => \&_notequals,
        ",casesubstring" => \&_casesubstring,
        ",substring" => \&_substring,
        ",substr" => \&_substring,
        ",notsubstring" => \&_notsubstring,
        ",regexp" => \&_regexp,
        ",notregexp" => \&_notregexp,
        ",lessthan" => \&_lessthan,
        ",matches" => sub { ThrowUserError("search_content_without_matches"); },
        ",greaterthan" => \&_greaterthan,
        ",anyexact" => \&_anyexact,
        ",anywordssubstr" => \&_anywordsubstr,
        ",allwordssubstr" => \&_allwordssubstr,
        ",nowordssubstr" => \&_nowordssubstr,
        ",anywords" => \&_anywords,
        ",allwords" => \&_allwords,
        ",nowords" => \&_nowords,
        ",(changedbefore|changedafter)" => \&_changedbefore_changedafter,
        ",(changedfrom|changedto)" => \&_changedfrom_changedto,
        ",changedby" => \&_changedby,
    );
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    my @funcnames;
    while (@funcdefs) {
        my $key = shift(@funcdefs);
        my $value = shift(@funcdefs);
        if ($key =~ /^[^,]*$/) {
            die "All defs in %funcs must have a comma in their name: $key";
        }
        if (exists $funcsbykey{$key}) {
            die "Duplicate key in %funcs: $key";
        }
        $funcsbykey{$key} = $value;
        push(@funcnames, $key);
    }

    # first we delete any sign of "Chart #-1" from the HTML form hash
    # since we want to guarantee the user didn't hide something here
570
    my @badcharts = grep /^(field|type|value)-1-/, $params->param();
571
    foreach my $field (@badcharts) {
572
        $params->delete($field);
573 574 575 576 577 578 579 580
    }

    # now we take our special chart and stuff it into the form hash
    my $chart = -1;
    my $row = 0;
    foreach my $ref (@specialchart) {
        my $col = 0;
        while (@$ref) {
581 582 583
            $params->param("field$chart-$row-$col", shift(@$ref));
            $params->param("type$chart-$row-$col", shift(@$ref));
            $params->param("value$chart-$row-$col", shift(@$ref));
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
            $col++;

        }
        $row++;
    }


# A boolean chart is a way of representing the terms in a logical
# expression.  Bugzilla builds SQL queries depending on how you enter
# terms into the boolean chart. Boolean charts are represented in
# urls as tree-tuples of (chart id, row, column). The query form
# (query.cgi) may contain an arbitrary number of boolean charts where
# each chart represents a clause in a SQL query.
#
# The query form starts out with one boolean chart containing one
# row and one column.  Extra rows can be created by pressing the
# AND button at the bottom of the chart.  Extra columns are created
# by pressing the OR button at the right end of the chart. Extra
# charts are created by pressing "Add another boolean chart".
#
604
# Each chart consists of an arbitrary number of rows and columns.
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
# The terms within a row are ORed together. The expressions represented
# by each row are ANDed together. The expressions represented by each
# chart are ANDed together.
#
#        ----------------------
#        | col2 | col2 | col3 |
# --------------|------|------|
# | row1 |  a1  |  a2  |      |
# |------|------|------|------|  => ((a1 OR a2) AND (b1 OR b2 OR b3) AND (c1))
# | row2 |  b1  |  b2  |  b3  |
# |------|------|------|------|
# | row3 |  c1  |      |      |
# -----------------------------
#
#        --------
#        | col2 |
# --------------|
# | row1 |  d1  | => (d1)
# ---------------
#
# Together, these two charts represent a SQL expression like this
# SELECT blah FROM blah WHERE ( (a1 OR a2)AND(b1 OR b2 OR b3)AND(c1)) AND (d1)
#
# The terms within a single row of a boolean chart are all constraints
# on a single piece of data.  If you're looking for a bug that has two
# different people cc'd on it, then you need to use two boolean charts.
631
# This will find bugs with one CC matching 'foo@blah.org' and and another
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
# CC matching 'bar@blah.org'.
#
# --------------------------------------------------------------
# CC    | equal to
# foo@blah.org
# --------------------------------------------------------------
# CC    | equal to
# bar@blah.org
#
# If you try to do this query by pressing the AND button in the
# original boolean chart then what you'll get is an expression that
# looks for a single CC where the login name is both "foo@blah.org",
# and "bar@blah.org". This is impossible.
#
# --------------------------------------------------------------
# CC    | equal to
# foo@blah.org
# AND
# CC    | equal to
# bar@blah.org
# --------------------------------------------------------------

654
# $chartid is the number of the current chart whose SQL we're constructing
655 656 657 658 659 660 661 662 663 664
# $row is the current row of the current chart

# names for table aliases are constructed using $chartid and $row
#   SELECT blah  FROM $table "$table_$chartid_$row" WHERE ....

# $f  = field of table in bug db (e.g. bug_id, reporter, etc)
# $ff = qualified field name (field name prefixed by table)
#       e.g. bugs_activity.bug_id
# $t  = type of query. e.g. "equal to", "changed after", case sensitive substr"
# $v  = value - value the user typed in to the form
665
# $q  = sanitized version of user input trick_taint(($dbh->quote($v)))
666 667 668
# @supptables = Tables and/or table aliases used in query
# %suppseen   = A hash used to store all the tables in supptables to weed
#               out duplicates.
669 670
# @supplist   = A list used to accumulate all the JOIN clauses for each
#               chart to merge the ON sections of each.
671 672 673
# $suppstring = String which is pasted into query containing all table names

    # get a list of field names to verify the user-submitted chart fields against
674
    %chartfields = @{$dbh->selectcol_arrayref(
675
        q{SELECT name, id FROM fielddefs}, { Columns=>[1,2] })};
676 677 678

    $row = 0;
    for ($chart=-1 ;
679
         $chart < 0 || $params->param("field$chart-0-0") ;
680 681
         $chart++) {
        $chartid = $chart >= 0 ? $chart : "";
682
        my @chartandlist = ();
683
        for ($row = 0 ;
684
             $params->param("field$chart-$row-0") ;
685 686 687
             $row++) {
            my @orlist;
            for (my $col = 0 ;
688
                 $params->param("field$chart-$row-$col") ;
689
                 $col++) {
690
                $f = $params->param("field$chart-$row-$col") || "noop";
691
                my $original_f = $f; # Saved for search_description
692 693
                $t = $params->param("type$chart-$row-$col") || "noop";
                $v = $params->param("value$chart-$row-$col");
694
                $v = "" if !defined $v;
695
                $v = trim($v);
696 697 698 699 700 701
                if ($f eq "noop" || $t eq "noop" || $v eq "") {
                    next;
                }
                # chart -1 is generated by other code above, not from the user-
                # submitted form, so we'll blindly accept any values in chart -1
                if ((!$chartfields{$f}) && ($chart != -1)) {
702
                    ThrowCodeError("invalid_field_name", {field => $f});
703 704 705 706
                }

                # This is either from the internal chart (in which case we
                # already know about it), or it was in %chartfields, so it is
707
                # a valid field name, which means that it's ok.
708
                trick_taint($f);
709 710
                $q = $dbh->quote($v);
                trick_taint($q);
711 712
                my $rhs = $v;
                $rhs =~ tr/,//;
713 714 715
                my $func;
                $term = undef;
                foreach my $key (@funcnames) {
716
                    if ("$f,$t,$rhs" =~ m/$key/) {
717 718 719 720 721
                        my $ref = $funcsbykey{$key};
                        $ff = $f;
                        if ($f !~ /\./) {
                            $ff = "bugs.$f";
                        }
722
                        $self->$ref(%func_args);
723 724 725 726 727 728
                        if ($term) {
                            last;
                        }
                    }
                }
                if ($term) {
729 730 731 732
                    $self->search_description({
                        field => $original_f, type  => $t, value => $v,
                        term  => $term,
                    });
733 734 735
                    push(@orlist, $term);
                }
                else {
736
                    # This field and this type don't work together.
737 738 739 740
                    ThrowCodeError("field_type_mismatch",
                                   { field => $params->param("field$chart-$row-$col"),
                                     type => $params->param("type$chart-$row-$col"),
                                   });
741 742 743
                }
            }
            if (@orlist) {
744
                @orlist = map("($_)", @orlist) if (scalar(@orlist) > 1);
745 746 747 748 749 750 751 752
                push(@chartandlist, "(" . join(" OR ", @orlist) . ")");
            }
        }
        if (@chartandlist) {
            if ($params->param("negate$chart")) {
                push(@andlist, "NOT(" . join(" AND ", @chartandlist) . ")");
            } else {
                push(@andlist, "(" . join(" AND ", @chartandlist) . ")");
753 754 755
            }
        }
    }
756 757 758 759 760

    # The ORDER BY clause goes last, but can require modifications
    # to other parts of the query, so we want to create it before we
    # write the FROM clause.
    foreach my $orderitem (@inputorder) {
761 762 763 764 765 766 767
        # Some fields have 'AS' aliases. The aliases go in the ORDER BY,
        # not the whole fields.
        # XXX - Ideally, we would get just the aliases in @inputorder,
        # and we'd never have to deal with this.
        if ($orderitem =~ /\s+AS\s+(.+)$/i) {
            $orderitem = $1;
        }
768
        BuildOrderBy(\%special_order, $orderitem, \@orderby);
769 770 771 772 773 774 775
    }
    # Now JOIN the correct tables in the FROM clause.
    # This is done separately from the above because it's
    # cleaner to do it this way.
    foreach my $orderitem (@inputorder) {
        # Grab the part without ASC or DESC.
        my @splitfield = split(/\s+/, $orderitem);
776 777
        if ($special_order_join{$splitfield[0]}) {
            push(@supptables, $special_order_join{$splitfield[0]});
778 779 780
        }
    }

781 782
    my %suppseen = ("bugs" => 1);
    my $suppstring = "bugs";
783
    my @supplist = (" ");
784
    foreach my $str (@supptables) {
785 786 787 788 789 790

        if ($str =~ /^(LEFT|INNER|RIGHT)\s+JOIN/i) {
            $str =~ /^(.*?)\s+ON\s+(.*)$/i;
            my ($leftside, $rightside) = ($1, $2);
            if (defined $suppseen{$leftside}) {
                $supplist[$suppseen{$leftside}] .= " AND ($rightside)";
791
            } else {
792 793
                $suppseen{$leftside} = scalar @supplist;
                push @supplist, " $leftside ON ($rightside)";
794
            }
795 796 797 798
        } else {
            # Do not accept implicit joins using comma operator
            # as they are not DB agnostic
            ThrowCodeError("comma_operator_deprecated");
799 800
        }
    }
801
    $suppstring .= join('', @supplist);
802 803 804
    
    # Make sure we create a legal SQL query.
    @andlist = ("1 = 1") if !@andlist;
805

806 807 808 809 810
    my $query = "SELECT " . join(', ', @fields) .
                " FROM $suppstring" .
                " LEFT JOIN bug_group_map " .
                " ON bug_group_map.bug_id = bugs.bug_id ";

811
    if ($user->id) {
812 813 814
        if (scalar @{ $user->groups }) {
            $query .= " AND bug_group_map.group_id NOT IN (" 
                   . $user->groups_as_string . ") ";
815
        }
816

817
        $query .= " LEFT JOIN cc ON cc.bug_id = bugs.bug_id AND cc.who = " . $user->id;
818 819 820
    }

    $query .= " WHERE " . join(' AND ', (@wherepart, @andlist)) .
821
              " AND bugs.creation_ts IS NOT NULL AND ((bug_group_map.group_id IS NULL)";
822

823
    if ($user->id) {
824 825
        my $userid = $user->id;
        $query .= "    OR (bugs.reporter_accessible = 1 AND bugs.reporter = $userid) " .
826
              "    OR (bugs.cclist_accessible = 1 AND cc.who IS NOT NULL) " .
827
              "    OR (bugs.assigned_to = $userid) ";
828
        if (Bugzilla->params->{'useqacontact'}) {
829
            $query .= "OR (bugs.qa_contact = $userid) ";
830 831 832
        }
    }

833
    foreach my $field (@fields, @orderby) {
834
        next if ($field =~ /(AVG|SUM|COUNT|MAX|MIN|VARIANCE)\s*\(/i ||
835
                 $field =~ /^\d+$/ || $field eq "bugs.bug_id" ||
836
                 $field =~ /^(relevance|actual_time|percentage_complete)/);
837 838
        # The structure of fields is of the form:
        # [foo AS] {bar | bar.baz} [ASC | DESC]
839 840 841 842
        # Only the mandatory part bar OR bar.baz is of interest.
        # But for Oracle, it needs the real name part instead.
        my $regexp = $dbh->GROUPBY_REGEXP;
        if ($field =~ /$regexp/i) {
843 844 845 846 847
            push(@groupby, $1) if !grep($_ eq $1, @groupby);
        }
    }
    $query .= ") " . $dbh->sql_group_by("bugs.bug_id", join(', ', @groupby));

848 849 850 851 852

    if (@having) {
        $query .= " HAVING " . join(" AND ", @having);
    }

853 854 855 856
    if (@orderby) {
        $query .= " ORDER BY " . join(',', @orderby);
    }

857 858 859 860 861 862 863 864 865
    $self->{'sql'} = $query;
}

###############################################################################
# Helper functions for the init() method.
###############################################################################
sub SqlifyDate {
    my ($str) = @_;
    $str = "" if !defined $str;
866 867 868 869
    if ($str eq "") {
        my ($sec, $min, $hour, $mday, $month, $year, $wday) = localtime(time());
        return sprintf("%4d-%02d-%02d 00:00:00", $year+1900, $month+1, $mday);
    }
870 871


872
    if ($str =~ /^(-|\+)?(\d+)([hHdDwWmMyY])$/) {   # relative date
873
        my ($sign, $amount, $unit, $date) = ($1, $2, lc $3, time);
874
        my ($sec, $min, $hour, $mday, $month, $year, $wday)  = localtime($date);
875
        if ($sign && $sign eq '+') { $amount = -$amount; }
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
        if ($unit eq 'w') {                  # convert weeks to days
            $amount = 7*$amount + $wday;
            $unit = 'd';
        }
        if ($unit eq 'd') {
            $date -= $sec + 60*$min + 3600*$hour + 24*3600*$amount;
            return time2str("%Y-%m-%d %H:%M:%S", $date);
        }
        elsif ($unit eq 'y') {
            return sprintf("%4d-01-01 00:00:00", $year+1900-$amount);
        }
        elsif ($unit eq 'm') {
            $month -= $amount;
            while ($month<0) { $year--; $month += 12; }
            return sprintf("%4d-%02d-01 00:00:00", $year+1900, $month+1);
        }
892 893 894 895 896 897 898 899 900
        elsif ($unit eq 'h') {
            # Special case 0h for 'beginning of this hour'
            if ($amount == 0) {
                $date -= $sec + 60*$min;
            } else {
                $date -= 3600*$amount;
            }
            return time2str("%Y-%m-%d %H:%M:%S", $date);
        }
901 902 903 904
        return undef;                      # should not happen due to regexp at top
    }
    my $date = str2time($str);
    if (!defined($date)) {
905
        ThrowUserError("illegal_date", { date => $str });
906 907 908 909
    }
    return time2str("%Y-%m-%d %H:%M:%S", $date);
}

910 911 912 913
sub build_subselect {
    my ($outer, $inner, $table, $cond) = @_;
    my $q = "SELECT $inner FROM $table WHERE $cond";
    #return "$outer IN ($q)";
914 915 916
    my $dbh = Bugzilla->dbh;
    my $list = $dbh->selectcol_arrayref($q);
    return "1=2" unless @$list; # Could use boolean type on dbs which support it
917
    return $dbh->sql_in($outer, $list);}
918

919 920 921
sub GetByWordList {
    my ($field, $strs) = (@_);
    my @list;
922
    my $dbh = Bugzilla->dbh;
923 924 925 926 927

    foreach my $w (split(/[\s,]+/, $strs)) {
        my $word = $w;
        if ($word ne "") {
            $word =~ tr/A-Z/a-z/;
928
            $word = $dbh->quote('(^|[^a-z0-9])' . quotemeta($word) . '($|[^a-z0-9])');
929
            trick_taint($word);
930
            push(@list, $dbh->sql_regexp($field, $word));
931 932 933 934 935 936 937 938 939 940
        }
    }

    return \@list;
}

# Support for "any/all/nowordssubstr" comparison type ("words as substrings")
sub GetByWordListSubstr {
    my ($field, $strs) = (@_);
    my @list;
941
    my $dbh = Bugzilla->dbh;
942
    my $sql_word;
943 944 945

    foreach my $word (split(/[\s,]+/, $strs)) {
        if ($word ne "") {
946
            $sql_word = $dbh->quote($word);
947
            trick_taint($sql_word);
948
            push(@list, $dbh->sql_iposition($sql_word, $field) . " > 0");
949 950 951 952 953 954 955 956 957 958 959
        }
    }

    return \@list;
}

sub getSQL {
    my $self = shift;
    return $self->{'sql'};
}

960 961 962 963 964 965 966
sub search_description {
    my ($self, $params) = @_;
    my $desc = $self->{'search_description'} ||= [];
    if ($params) {
        push(@$desc, $params);
    }
    return $self->{'search_description'};
967 968
}

969 970 971
sub pronoun {
    my ($noun, $user) = (@_);
    if ($noun eq "%user%") {
972
        if ($user->id) {
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
            return $user->id;
        } else {
            ThrowUserError('login_required_for_pronoun');
        }
    }
    if ($noun eq "%reporter%") {
        return "bugs.reporter";
    }
    if ($noun eq "%assignee%") {
        return "bugs.assigned_to";
    }
    if ($noun eq "%qacontact%") {
        return "bugs.qa_contact";
    }
    return 0;
}
989

990 991 992 993 994 995 996 997 998
# Validate that the query type is one we can deal with
sub IsValidQueryType
{
    my ($queryType) = @_;
    if (grep { $_ eq $queryType } qw(specific advanced)) {
        return 1;
    }
    return 0;
}
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

# BuildOrderBy - Private Subroutine
# This function converts the input order to an "output" order,
# suitable for concatenation to form an ORDER BY clause. Basically,
# it just handles fields that have non-standard sort orders from
# %specialorder.
# Arguments:
#  $orderitem - A string. The next value to append to the ORDER BY clause,
#      in the format of an item in the 'order' parameter to
#      Bugzilla::Search.
#  $stringlist - A reference to the list of strings that will be join()'ed
#      to make ORDER BY. This is what the subroutine modifies.
#  $reverseorder - (Optional) A boolean. TRUE if we should reverse the order
#      of the field that we are given (from ASC to DESC or vice-versa).
#
# Explanation of $reverseorder
# ----------------------------
# The role of $reverseorder is to handle things like sorting by
# "target_milestone DESC".
# Let's say that we had a field "A" that normally translates to a sort 
# order of "B ASC, C DESC". If we sort by "A DESC", what we really then
# mean is "B DESC, C ASC". So $reverseorder is only used if we call 
# BuildOrderBy recursively, to let it know that we're "reversing" the 
# order. That is, that we wanted "A DESC", not "A".
sub BuildOrderBy {
1024
    my ($special_order, $orderitem, $stringlist, $reverseorder) = (@_);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

    my @twopart = split(/\s+/, $orderitem);
    my $orderfield = $twopart[0];
    my $orderdirection = $twopart[1] || "";

    if ($reverseorder) {
        # If orderdirection is empty or ASC...
        if (!$orderdirection || $orderdirection =~ m/asc/i) {
            $orderdirection = "DESC";
        } else {
            # This has the minor side-effect of making any reversed invalid
            # direction into ASC.
            $orderdirection = "ASC";
        }
    }

    # Handle fields that have non-standard sort orders, from $specialorder.
1042 1043
    if ($special_order->{$orderfield}) {
        foreach my $subitem (@{$special_order->{$orderfield}}) {
1044 1045
            # DESC on a field with non-standard sort order means
            # "reverse the normal order for each field that we map to."
1046 1047
            BuildOrderBy($special_order, $subitem, $stringlist,
                         $orderdirection =~ m/desc/i);
1048 1049 1050 1051
        }
        return;
    }

1052
    push(@$stringlist, trim($orderfield . ' ' . $orderdirection));
1053
}
1054

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

sub _contact_exact_group {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f, $t, $v, $term) =
        @func_args{qw(chartid supptables f t v term)};
    my $user = $self->{'user'};
    
    $$v =~ m/%group\\.([^%]+)%/;
    my $group = $1;
    my $groupid = Bugzilla::Group::ValidateGroupName( $group, ($user));
    $groupid || ThrowUserError('invalid_group_name',{name => $group});
1070
    my @childgroups = @{Bugzilla::Group->flatten_group_membership($groupid)};
1071 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 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    my $table = "user_group_map_$$chartid";
    push (@$supptables, "LEFT JOIN user_group_map AS $table " .
                        "ON $table.user_id = bugs.$$f " .
                        "AND $table.group_id IN(" .
                        join(',', @childgroups) . ") " .
                        "AND $table.isbless = 0 " .
                        "AND $table.grant_type IN(" .
                        GRANT_DIRECT . "," . GRANT_REGEXP . ")"
         );
    if ($$t =~ /^not/) {
        $$term = "$table.group_id IS NULL";
    } else {
        $$term = "$table.group_id IS NOT NULL";
    }
}

sub _contact_exact {
    my $self = shift;
    my %func_args = @_;
    my ($term, $f, $v) = @func_args{qw(term f v)};
    my $user = $self->{'user'};
    
    $$v =~ m/(%\\w+%)/;
    $$term = "bugs.$$f = " . pronoun($1, $user);
}

sub _contact_notequals {
    my $self = shift;
    my %func_args = @_;
    my ($term, $f, $v) = @func_args{qw(term f v)};
    my $user = $self->{'user'};
    
    $$v =~ m/(%\\w+%)/;
    $$term = "bugs.$$f <> " . pronoun($1, $user);
}

sub _assigned_to_reporter_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $funcsbykey, $t, $term) =
        @func_args{qw(f ff funcsbykey t term)};
    
    my $real_f = $$f;
    $$f = "login_name";
    $$ff = "profiles.login_name";
    $$funcsbykey{",$$t"}($self, %func_args);
    $$term = "bugs.$real_f IN (SELECT userid FROM profiles WHERE $$term)";
}

sub _qa_contact_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($supptables, $f) =
        @func_args{qw(supptables f)};
    
    push(@$supptables, "LEFT JOIN profiles AS map_qa_contact " .
                       "ON bugs.qa_contact = map_qa_contact.userid");
    $$f = "COALESCE(map_$$f.login_name,'')";
}

sub _cc_exact_group {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $supptables, $t, $v, $term) =
        @func_args{qw(chartid sequence supptables t v term)};
    my $user = $self->{'user'};
    
    $$v =~ m/%group\\.([^%]+)%/;
    my $group = $1;
    my $groupid = Bugzilla::Group::ValidateGroupName( $group, ($user));
    $groupid || ThrowUserError('invalid_group_name',{name => $group});
1142
    my @childgroups = @{Bugzilla::Group->flatten_group_membership($groupid)};
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "CC$$sequence";
        $$sequence++;
    }
    my $table = "user_group_map_$chartseq";
    push(@$supptables, "LEFT JOIN cc AS cc_$chartseq " .
                       "ON bugs.bug_id = cc_$chartseq.bug_id");
    push(@$supptables, "LEFT JOIN user_group_map AS $table " .
                        "ON $table.user_id = cc_$chartseq.who " .
                        "AND $table.group_id IN(" .
                        join(',', @childgroups) . ") " .
                        "AND $table.isbless = 0 " .
                        "AND $table.grant_type IN(" .
                        GRANT_DIRECT . "," . GRANT_REGEXP . ")"
         );
    if ($$t =~ /^not/) {
        $$term = "$table.group_id IS NULL";
    } else {
        $$term = "$table.group_id IS NOT NULL";
    }
}

sub _cc_exact {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $supptables, $term, $v) =
        @func_args{qw(chartid sequence supptables term v)};
    my $user = $self->{'user'};
    
    $$v =~ m/(%\\w+%)/;
    my $match = pronoun($1, $user);
    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "CC$$sequence";
        $$sequence++;
    }
    push(@$supptables, "LEFT JOIN cc AS cc_$chartseq " .
                       "ON bugs.bug_id = cc_$chartseq.bug_id " .
                       "AND cc_$chartseq.who = $match");
    $$term = "cc_$chartseq.who IS NOT NULL";
}

sub _cc_notequals {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $supptables, $term, $v) =
        @func_args{qw(chartid sequence supptables term v)};
    my $user = $self->{'user'};
    
    $$v =~ m/(%\\w+%)/;
    my $match = pronoun($1, $user);
    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "CC$$sequence";
        $$sequence++;
    }
    push(@$supptables, "LEFT JOIN cc AS cc_$chartseq " .
                       "ON bugs.bug_id = cc_$chartseq.bug_id " .
                       "AND cc_$chartseq.who = $match");
    $$term = "cc_$chartseq.who IS NULL";
}

sub _cc_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $f, $ff, $t, $funcsbykey, $supptables, $term, $v) =
        @func_args{qw(chartid sequence f ff t funcsbykey supptables term v)};

    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "CC$$sequence";
        $$sequence++;
    }
    $$f = "login_name";
    $$ff = "profiles.login_name";
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables, "LEFT JOIN cc AS cc_$chartseq " .
                       "ON bugs.bug_id = cc_$chartseq.bug_id " .
                       "AND cc_$chartseq.who IN" .
                       "(SELECT userid FROM profiles WHERE $$term)"
                       );
    $$term = "cc_$chartseq.who IS NOT NULL";
}

sub _long_desc_changedby {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $term, $v) =
        @func_args{qw(chartid supptables term v)};
    
    my $table = "longdescs_$$chartid";
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                       "ON $table.bug_id = bugs.bug_id");
    my $id = login_to_id($$v, THROW_ERROR);
    $$term = "$table.who = $id";
}

1241
sub _long_desc_changedbefore_after {
1242 1243
    my $self = shift;
    my %func_args = @_;
1244
    my ($chartid, $t, $v, $supptables, $term) =
1245
        @func_args{qw(chartid t v supptables term)};
1246 1247
    my $dbh = Bugzilla->dbh;
    
1248
    my $operator = ($$t =~ /before/) ? '<' : '>';
1249 1250
    my $table = "longdescs_$$chartid";
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
1251
                              "ON $table.bug_id = bugs.bug_id " .
1252 1253
                                 "AND $table.bug_when $operator " .
                                  $dbh->quote(SqlifyDate($$v)) );
1254
    $$term = "($table.bug_when IS NOT NULL)";
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
}

sub _content_matches {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $term, $groupby, $fields, $v) =
        @func_args{qw(chartid supptables term groupby fields v)};
    my $dbh = Bugzilla->dbh;
    
    # "content" is an alias for columns containing text for which we
    # can search a full-text index and retrieve results by relevance, 
    # currently just bug comments (and summaries to some degree).
    # There's only one way to search a full-text index, so we only
    # accept the "matches" operator, which is specific to full-text
    # index searches.

1271 1272 1273 1274 1275 1276 1277
    # Add the fulltext table to the query so we can search on it.
    my $table = "bugs_fulltext_$$chartid";
    my $comments_col = "comments";
    $comments_col = "comments_noprivate" unless $self->{'user'}->is_insider;
    push(@$supptables, "LEFT JOIN bugs_fulltext AS $table " .
                       "ON bugs.bug_id = $table.bug_id");
    
1278
    # Create search terms to add to the SELECT and WHERE clauses.
1279 1280 1281 1282 1283 1284 1285
    my ($term1, $rterm1) = $dbh->sql_fulltext_search("$table.$comments_col", 
                                                        $$v, 1);
    my ($term2, $rterm2) = $dbh->sql_fulltext_search("$table.short_desc", 
                                                        $$v, 2);
    $rterm1 = $term1 if !$rterm1;
    $rterm2 = $term2 if !$rterm2;

1286
    # The term to use in the WHERE clause.
1287 1288
    $$term = "$term1 > 0 OR $term2 > 0";
    
1289 1290 1291
    # In order to sort by relevance (in case the user requests it),
    # we SELECT the relevance value and give it an alias so we can
    # add it to the SORT BY clause when we build it in buglist.cgi.
1292
    my $select_term = "($rterm1 + $rterm2) AS relevance";
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

    # Users can specify to display the relevance field, in which case
    # it'll show up in the list of fields being selected, and we need
    # to replace that occurrence with our select term.  Otherwise
    # we can just add the term to the list of fields being selected.
    if (grep($_ eq "relevance", @$fields)) {
        @$fields = map($_ eq "relevance" ? $select_term : $_ , @$fields);
    }
    else {
        push(@$fields, $select_term);
    }
}

sub _timestamp_compare {
    my $self = shift;
    my %func_args = @_;
    my ($v, $q) = @func_args{qw(v q)};
    my $dbh = Bugzilla->dbh;
    
    $$v = SqlifyDate($$v);
    $$q = $dbh->quote($$v);
}

sub _commenter_exact {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $supptables, $term, $v) =
        @func_args{qw(chartid sequence supptables term v)};
    my $user = $self->{'user'};
    
    $$v =~ m/(%\\w+%)/;
    my $match = pronoun($1, $user);
    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "LD$$sequence";
        $$sequence++;
    }
    my $table = "longdescs_$chartseq";
1331
    my $extra = $user->is_insider ? "" : "AND $table.isprivate < 1";
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                       "ON $table.bug_id = bugs.bug_id $extra " .
                       "AND $table.who IN ($match)");
    $$term = "$table.who IS NOT NULL";
}

sub _commenter {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $sequence, $supptables, $f, $ff, $t, $funcsbykey, $term) =
        @func_args{qw(chartid sequence supptables f ff t funcsbykey term)};

    my $chartseq = $$chartid;
    if ($$chartid eq "") {
        $chartseq = "LD$$sequence";
        $$sequence++;
    }
    my $table = "longdescs_$chartseq";
1350
    my $extra = $self->{'user'}->is_insider ? "" : "AND $table.isprivate < 1";
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    $$f = "login_name";
    $$ff = "profiles.login_name";
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                       "ON $table.bug_id = bugs.bug_id $extra " .
                       "AND $table.who IN" .
                       "(SELECT userid FROM profiles WHERE $$term)"
                       );
    $$term = "$table.who IS NOT NULL";
}

sub _long_desc {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f) =
        @func_args{qw(chartid supptables f)};
    
    my $table = "longdescs_$$chartid";
1369
    my $extra = $self->{'user'}->is_insider ? "" : "AND $table.isprivate < 1";
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                       "ON $table.bug_id = bugs.bug_id $extra");
    $$f = "$table.thetext";
}

sub _longdescs_isprivate {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f) =
        @func_args{qw(chartid supptables f)};
    
    my $table = "longdescs_$$chartid";
1382
    my $extra = $self->{'user'}->is_insider ? "" : "AND $table.isprivate < 1";
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                      "ON $table.bug_id = bugs.bug_id $extra");
    $$f = "$table.isprivate";
}

sub _work_time_changedby {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $v, $term) =
        @func_args{qw(chartid supptables v term)};
    
    my $table = "longdescs_$$chartid";
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                       "ON $table.bug_id = bugs.bug_id");
    my $id = login_to_id($$v, THROW_ERROR);
    $$term = "(($table.who = $id";
    $$term .= ") AND ($table.work_time <> 0))";
}

1402
sub _work_time_changedbefore_after {
1403 1404
    my $self = shift;
    my %func_args = @_;
1405
    my ($chartid, $t, $v, $supptables, $term) =
1406
        @func_args{qw(chartid t v supptables term)};
1407 1408
    my $dbh = Bugzilla->dbh;
    
1409
    my $operator = ($$t =~ /before/) ? '<' : '>';
1410 1411
    my $table = "longdescs_$$chartid";
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
1412
                              "ON $table.bug_id = bugs.bug_id " .
1413
                                 "AND $table.work_time <> 0 " .
1414 1415
                                 "AND $table.bug_when $operator " .
                                  $dbh->quote(SqlifyDate($$v)) );
1416
    $$term = "($table.bug_when IS NOT NULL)";
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
}

sub _work_time {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f) =
        @func_args{qw(chartid supptables f)};
    
    my $table = "longdescs_$$chartid";
    push(@$supptables, "LEFT JOIN longdescs AS $table " .
                      "ON $table.bug_id = bugs.bug_id");
    $$f = "$table.work_time";
}

sub _percentage_complete {
    my $self = shift;
    my %func_args = @_;
    my ($t, $chartid, $supptables, $fields, $q, $v, $having, $groupby, $term) =
        @func_args{qw(t chartid supptables fields q v having groupby term)};
    my $dbh = Bugzilla->dbh;
    
    my $oper;
    if ($$t eq "equals") {
        $oper = "=";
    } elsif ($$t eq "greaterthan") {
        $oper = ">";
    } elsif ($$t eq "lessthan") {
        $oper = "<";
    } elsif ($$t eq "notequal") {
        $oper = "<>";
    } elsif ($$t eq "regexp") {
        # This is just a dummy to help catch bugs- $oper won't be used
        # since "regexp" is treated as a special case below.  But
        # leaving $oper uninitialized seems risky...
        $oper = "sql_regexp";
    } elsif ($$t eq "notregexp") {
        # This is just a dummy to help catch bugs- $oper won't be used
        # since "notregexp" is treated as a special case below.  But
        # leaving $oper uninitialized seems risky...
        $oper = "sql_not_regexp";
    } else {
        $oper = "noop";
    }
    if ($oper ne "noop") {
        my $table = "longdescs_$$chartid";
1462
        if(lsearch($fields, "bugs.remaining_time") == -1) {
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
            push(@$fields, "bugs.remaining_time");                  
        }
        push(@$supptables, "LEFT JOIN longdescs AS $table " .
                           "ON $table.bug_id = bugs.bug_id");
        my $expression = "(100 * ((SUM($table.work_time) *
                                    COUNT(DISTINCT $table.bug_when) /
                                    COUNT(bugs.bug_id)) /
                                   ((SUM($table.work_time) *
                                     COUNT(DISTINCT $table.bug_when) /
                                     COUNT(bugs.bug_id)) +
                                    bugs.remaining_time)))";
        $$q = $dbh->quote($$v);
        trick_taint($$q);
        if ($$t eq "regexp") {
            push(@$having, $dbh->sql_regexp($expression, $$q));
        } elsif ($$t eq "notregexp") {
            push(@$having, $dbh->sql_not_regexp($expression, $$q));
        } else {
            push(@$having, "$expression $oper " . $$q);
        }
        push(@$groupby, "bugs.remaining_time");
    }
    $$term = "0=0";
}

sub _bug_group_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($supptables, $chartid, $ff, $f, $t, $funcsbykey, $term) =
        @func_args{qw(supptables chartid ff f t funcsbykey term)};
    
    push(@$supptables,
            "LEFT JOIN bug_group_map AS bug_group_map_$$chartid " .
            "ON bugs.bug_id = bug_group_map_$$chartid.bug_id");
    $$ff = $$f = "groups_$$chartid.name";
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables,
            "LEFT JOIN groups AS groups_$$chartid " .
            "ON groups_$$chartid.id = bug_group_map_$$chartid.group_id " .
            "AND $$term");
    $$term = "$$ff IS NOT NULL";
}

sub _attach_data_thedata_changed {
    my $self = shift;
    my %func_args = @_;
    my ($f) = @func_args{qw(f)};
    
    # Searches for attachment data's change must search
    # the creation timestamp of the attachment instead.
    $$f = "attachments.whocares";
}

sub _attach_data_thedata {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f) =
        @func_args{qw(chartid supptables f)};
    
    my $atable = "attachments_$$chartid";
    my $dtable = "attachdata_$$chartid";
1524
    my $extra = $self->{'user'}->is_insider ? "" : "AND $atable.isprivate = 0";
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    push(@$supptables, "INNER JOIN attachments AS $atable " .
                       "ON bugs.bug_id = $atable.bug_id $extra");
    push(@$supptables, "INNER JOIN attach_data AS $dtable " .
                       "ON $dtable.id = $atable.attach_id");
    $$f = "$dtable.thedata";
}

sub _attachments_submitter {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f) =
        @func_args{qw(chartid supptables f)};
    
    my $atable = "map_attachment_submitter_$$chartid";
1539
    my $extra = $self->{'user'}->is_insider ? "" : "AND $atable.isprivate = 0";
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    push(@$supptables, "INNER JOIN attachments AS $atable " .
                       "ON bugs.bug_id = $atable.bug_id $extra");
    push(@$supptables, "LEFT JOIN profiles AS attachers_$$chartid " .
                       "ON $atable.submitter_id = attachers_$$chartid.userid");
    $$f = "attachers_$$chartid.login_name";
}

sub _attachments {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $supptables, $f, $t, $v, $q) =
        @func_args{qw(chartid supptables f t v q)};
    my $dbh = Bugzilla->dbh;
    
    my $table = "attachments_$$chartid";
1555
    my $extra = $self->{'user'}->is_insider ? "" : "AND $table.isprivate = 0";
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
    push(@$supptables, "INNER JOIN attachments AS $table " .
                       "ON bugs.bug_id = $table.bug_id $extra");
    $$f =~ m/^attachments\.(.*)$/;
    my $field = $1;
    if ($$t eq "changedby") {
        $$v = login_to_id($$v, THROW_ERROR);
        $$q = $dbh->quote($$v);
        $field = "submitter_id";
        $$t = "equals";
    } elsif ($$t eq "changedbefore") {
        $$v = SqlifyDate($$v);
        $$q = $dbh->quote($$v);
        $field = "creation_ts";
        $$t = "lessthan";
    } elsif ($$t eq "changedafter") {
        $$v = SqlifyDate($$v);
        $$q = $dbh->quote($$v);
        $field = "creation_ts";
        $$t = "greaterthan";
    }
    if ($field eq "ispatch" && $$v ne "0" && $$v ne "1") {
        ThrowUserError("illegal_attachment_is_patch");
    }
    if ($field eq "isobsolete" && $$v ne "0" && $$v ne "1") {
        ThrowUserError("illegal_is_obsolete");
    }
    $$f = "$table.$field";
}

sub _flagtypes_name {
    my $self = shift;
    my %func_args = @_;
    my ($t, $chartid, $supptables, $ff, $funcsbykey, $having, $term) =
        @func_args{qw(t chartid supptables ff funcsbykey having term)};
    my $dbh = Bugzilla->dbh;
    
    # Matches bugs by flag name/status.
    # Note that--for the purposes of querying--a flag comprises
    # its name plus its status (i.e. a flag named "review" 
    # with a status of "+" can be found by searching for "review+").
    
    # Don't do anything if this condition is about changes to flags,
    # as the generic change condition processors can handle those.
    return if ($$t =~ m/^changed/);
    
    # Add the flags and flagtypes tables to the query.  We do 
    # a left join here so bugs without any flags still match 
    # negative conditions (f.e. "flag isn't review+").
    my $flags = "flags_$$chartid";
    push(@$supptables, "LEFT JOIN flags AS $flags " . 
                       "ON bugs.bug_id = $flags.bug_id ");
    my $flagtypes = "flagtypes_$$chartid";
    push(@$supptables, "LEFT JOIN flagtypes AS $flagtypes " . 
                       "ON $flags.type_id = $flagtypes.id");
    
    # Generate the condition by running the operator-specific
    # function. Afterwards the condition resides in the global $term
    # variable.
    $$ff = $dbh->sql_string_concat("${flagtypes}.name",
                                   "$flags.status");
    $$funcsbykey{",$$t"}($self, %func_args);
    
    # If this is a negative condition (f.e. flag isn't "review+"),
    # we only want bugs where all flags match the condition, not 
    # those where any flag matches, which needs special magic.
    # Instead of adding the condition to the WHERE clause, we select
    # the number of flags matching the condition and the total number
    # of flags on each bug, then compare them in a HAVING clause.
    # If the numbers are the same, all flags match the condition,
    # so this bug should be included.
    if ($$t =~ m/not/) {
       push(@$having,
            "SUM(CASE WHEN $$ff IS NOT NULL THEN 1 ELSE 0 END) = " .
            "SUM(CASE WHEN $$term THEN 1 ELSE 0 END)");
       $$term = "0=0";
    }
}

sub _requestees_login_name {
    my $self = shift;
    my %func_args = @_;
    my ($f, $chartid, $supptables) = @func_args{qw(f chartid supptables)};
    
    my $flags = "flags_$$chartid";
    push(@$supptables, "LEFT JOIN flags AS $flags " .
                       "ON bugs.bug_id = $flags.bug_id ");
    push(@$supptables, "LEFT JOIN profiles AS requestees_$$chartid " .
                       "ON $flags.requestee_id = requestees_$$chartid.userid");
    $$f = "requestees_$$chartid.login_name";
}

sub _setters_login_name {
    my $self = shift;
    my %func_args = @_;
    my ($f, $chartid, $supptables) = @func_args{qw(f chartid supptables)};
    
    my $flags = "flags_$$chartid";
    push(@$supptables, "LEFT JOIN flags AS $flags " .
                       "ON bugs.bug_id = $flags.bug_id ");
    push(@$supptables, "LEFT JOIN profiles AS setters_$$chartid " .
                       "ON $flags.setter_id = setters_$$chartid.userid");
    $$f = "setters_$$chartid.login_name";
}

sub _changedin_days_elapsed {
    my $self = shift;
    my %func_args = @_;
    my ($f) = @func_args{qw(f)};
    my $dbh = Bugzilla->dbh;
    
    $$f = "(" . $dbh->sql_to_days('NOW()') . " - " .
                $dbh->sql_to_days('bugs.delta_ts') . ")";
}

sub _component_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $t, $funcsbykey, $term) =
        @func_args{qw(f ff t funcsbykey term)};
    
    $$f = $$ff = "components.name";
    $$funcsbykey{",$$t"}($self, %func_args);
    $$term = build_subselect("bugs.component_id",
                             "components.id",
                             "components",
                             $$term);
}
sub _product_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $t, $funcsbykey, $term) =
        @func_args{qw(f ff t funcsbykey term)};
    
    # Generate the restriction condition
    $$f = $$ff = "products.name";
    $$funcsbykey{",$$t"}($self, %func_args);
    $$term = build_subselect("bugs.product_id",
                             "products.id",
                             "products",
                             $$term);
}

sub _classification_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $v, $ff, $f, $funcsbykey, $t, $supptables, $term) =
        @func_args{qw(chartid v ff f funcsbykey t supptables term)};
    
    # Generate the restriction condition
    push @$supptables, "INNER JOIN products AS map_products " .
                      "ON bugs.product_id = map_products.id";
    $$f = $$ff = "classifications.name";
    $$funcsbykey{",$$t"}($self, %func_args);
    $$term = build_subselect("map_products.classification_id",
                             "classifications.id",
                             "classifications",
                              $$term);
}

sub _keywords_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $v, $ff, $f, $t, $term, $supptables) =
1719
        @func_args{qw(chartid v ff f t term supptables)};
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    
    my @list;
    my $table = "keywords_$$chartid";
    foreach my $value (split(/[\s,]+/, $$v)) {
        if ($value eq '') {
            next;
        }
        my $keyword = new Bugzilla::Keyword({name => $value});
        if ($keyword) {
            push(@list, "$table.keywordid = " . $keyword->id);
        }
        else {
            ThrowUserError("unknown_keyword",
                           { keyword => $$v });
        }
    }
    my $haveawordterm;
    if (@list) {
        $haveawordterm = "(" . join(' OR ', @list) . ")";
        if ($$t eq "anywords") {
            $$term = $haveawordterm;
        } elsif ($$t eq "allwords") {
            $self->_allwords;
            if ($$term && $haveawordterm) {
                $$term = "(($$term) AND $haveawordterm)";
            }
        }
    }
    if ($$term) {
        push(@$supptables, "LEFT JOIN keywords AS $table " .
                           "ON $table.bug_id = bugs.bug_id");
    }
}

sub _dependson_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $ff, $f, $funcsbykey, $t, $term, $supptables) =
        @func_args{qw(chartid ff f funcsbykey t term supptables)};
    
    my $table = "dependson_" . $$chartid;
    $$ff = "$table.$$f";
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables, "LEFT JOIN dependencies AS $table " .
                       "ON $table.blocked = bugs.bug_id " .
                       "AND ($$term)");
    $$term = "$$ff IS NOT NULL";
}

sub _blocked_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $ff, $f, $funcsbykey, $t, $term, $supptables) =
        @func_args{qw(chartid ff f funcsbykey t term supptables)};

    my $table = "blocked_" . $$chartid;
    $$ff = "$table.$$f";
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables, "LEFT JOIN dependencies AS $table " .
                       "ON $table.dependson = bugs.bug_id " .
                       "AND ($$term)");
    $$term = "$$ff IS NOT NULL";
}

sub _alias_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $funcsbykey, $t, $term) =
        @func_args{qw(ff funcsbykey t term)};
    
    $$ff = "COALESCE(bugs.alias, '')";
    
    $$funcsbykey{",$$t"}($self, %func_args);
}

sub _owner_idle_time_greater_less {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $v, $supptables, $t, $wherepart, $term) =
        @func_args{qw(chartid v supptables t wherepart term)};
    my $dbh = Bugzilla->dbh;
    
    my $table = "idle_" . $$chartid;
    $$v =~ /^(\d+)\s*([hHdDwWmMyY])?$/;
    my $quantity = $1;
    my $unit = lc $2;
    my $unitinterval = 'DAY';
    if ($unit eq 'h') {
        $unitinterval = 'HOUR';
    } elsif ($unit eq 'w') {
        $unitinterval = ' * 7 DAY';
    } elsif ($unit eq 'm') {
        $unitinterval = 'MONTH';
    } elsif ($unit eq 'y') {
        $unitinterval = 'YEAR';
    }
    my $cutoff = "NOW() - " .
                 $dbh->sql_interval($quantity, $unitinterval);
    my $assigned_fieldid = get_field_id('assigned_to');
    push(@$supptables, "LEFT JOIN longdescs AS comment_$table " .
                       "ON comment_$table.who = bugs.assigned_to " .
                       "AND comment_$table.bug_id = bugs.bug_id " .
                       "AND comment_$table.bug_when > $cutoff");
    push(@$supptables, "LEFT JOIN bugs_activity AS activity_$table " .
                       "ON (activity_$table.who = bugs.assigned_to " .
                       "OR activity_$table.fieldid = $assigned_fieldid) " .
                       "AND activity_$table.bug_id = bugs.bug_id " .
                       "AND activity_$table.bug_when > $cutoff");
    if ($$t =~ /greater/) {
        push(@$wherepart, "(comment_$table.who IS NULL " .
                          "AND activity_$table.who IS NULL)");
    } else {
        push(@$wherepart, "(comment_$table.who IS NOT NULL " .
                          "OR activity_$table.who IS NOT NULL)");
    }
    $$term = "0=0";
}

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
sub _multiselect_negative {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $t, $funcsbykey, $term) = @func_args{qw(f ff t funcsbykey term)};
    
    my %map = (
        notequals => 'equals',
        notregexp => 'regexp',
        notsubstring => 'substring',
        nowords => 'anywords',
        nowordssubstr => 'anywordssubstr',
    );

    my $table = "bug_$$f";
    $$ff = "$table.value";
    
    $$funcsbykey{",".$map{$$t}}($self, %func_args);
    $$term = "bugs.bug_id NOT IN (SELECT bug_id FROM $table WHERE $$term)";
}

sub _multiselect_multiple {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $t, $v, $funcsbykey, $term) = @func_args{qw(f ff t v funcsbykey term)};
    
    my @terms;
    my $table = "bug_$$f";
    $$ff = "$table.value";
    
    foreach my $word (split(/[\s,]+/, $$v)) {
        $$v = $word;
        $$funcsbykey{",".$$t}($self, %func_args);
        push(@terms, "bugs.bug_id IN
                      (SELECT bug_id FROM $table WHERE $$term)");
    }
    
    if ($$t eq 'anyexact') {
        $$term = "(" . join(" OR ", @terms) . ")";
    }
    else {
        $$term = "(" . join(" AND ", @terms) . ")";
    }
}

sub _multiselect_nonchanged {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $f, $ff, $t, $funcsbykey, $supptables) =
        @func_args{qw(chartid f ff t funcsbykey supptables)};

    my $table = $$f."_".$$chartid;
    $$ff = "$table.value";
    
    $$funcsbykey{",$$t"}($self, %func_args);
    push(@$supptables, "LEFT JOIN bug_$$f AS $table " .
                       "ON $table.bug_id = bugs.bug_id ");
}

1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
sub _equals {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    
    $$term = "$$ff = $$q";
}

sub _notequals {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    
    $$term = "$$ff != $$q";
}

sub _casesubstring {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    my $dbh = Bugzilla->dbh;
    
    $$term = $dbh->sql_position($$q, $$ff) . " > 0";
}

sub _substring {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    my $dbh = Bugzilla->dbh;
    
1927
    $$term = $dbh->sql_iposition($$q, $$ff) . " > 0";
1928 1929 1930 1931 1932 1933 1934 1935
}

sub _notsubstring {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    my $dbh = Bugzilla->dbh;
    
1936
    $$term = $dbh->sql_iposition($$q, $$ff) . " = 0";
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
}

sub _regexp {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    my $dbh = Bugzilla->dbh;
    
    $$term = $dbh->sql_regexp($$ff, $$q);
}

sub _notregexp {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    my $dbh = Bugzilla->dbh;
    
    $$term = $dbh->sql_not_regexp($$ff, $$q);
}

sub _lessthan {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};

    $$term = "$$ff < $$q";
}

sub _greaterthan {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $q, $term) = @func_args{qw(ff q term)};
    
    $$term = "$$ff > $$q";
}

sub _anyexact {
    my $self = shift;
    my %func_args = @_;
    my ($f, $ff, $v, $q, $term) = @func_args{qw(f ff v q term)};
    my $dbh = Bugzilla->dbh;
    
    my @list;
    foreach my $w (split(/,/, $$v)) {
1981
        if ($w eq "---" && $$f =~ /resolution/) {
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
            $w = "";
        }
        $$q = $dbh->quote($w);
        trick_taint($$q);
        push(@list, $$q);
    }
    if (@list) {
        $$term = $dbh->sql_in($$ff, \@list);
    }
}

sub _anywordsubstr {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    $$term = join(" OR ", @{GetByWordListSubstr($$ff, $$v)});
}

sub _allwordssubstr {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    $$term = join(" AND ", @{GetByWordListSubstr($$ff, $$v)});
}

sub _nowordssubstr {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    my @list = @{GetByWordListSubstr($$ff, $$v)};
    if (@list) {
        $$term = "NOT (" . join(" OR ", @list) . ")";
    }
}

sub _anywords {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    $$term = join(" OR ", @{GetByWordList($$ff, $$v)});
}

sub _allwords {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    $$term = join(" AND ", @{GetByWordList($$ff, $$v)});
}

sub _nowords {
    my $self = shift;
    my %func_args = @_;
    my ($ff, $v, $term) = @func_args{qw(ff v term)};
    
    my @list = @{GetByWordList($$ff, $$v)};
    if (@list) {
        $$term = "NOT (" . join(" OR ", @list) . ")";
    }
}

sub _changedbefore_changedafter {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $f, $ff, $t, $v, $chartfields, $supptables, $term) =
        @func_args{qw(chartid f ff t v chartfields supptables term)};
    my $dbh = Bugzilla->dbh;
    
    my $operator = ($$t =~ /before/) ? '<' : '>';
    my $table = "act_$$chartid";
    my $fieldid = $$chartfields{$$f};
    if (!$fieldid) {
        ThrowCodeError("invalid_field_name", {field => $$f});
    }
    push(@$supptables, "LEFT JOIN bugs_activity AS $table " .
                      "ON $table.bug_id = bugs.bug_id " .
                      "AND $table.fieldid = $fieldid " .
                      "AND $table.bug_when $operator " . 
                      $dbh->quote(SqlifyDate($$v)) );
    $$term = "($table.bug_when IS NOT NULL)";
}

sub _changedfrom_changedto {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $chartfields, $f, $t, $v, $q, $supptables, $term) =
        @func_args{qw(chartid chartfields f t v q supptables term)};
    
    my $operator = ($$t =~ /from/) ? 'removed' : 'added';
    my $table = "act_$$chartid";
    my $fieldid = $$chartfields{$$f};
    if (!$fieldid) {
        ThrowCodeError("invalid_field_name", {field => $$f});
    }
    push(@$supptables, "LEFT JOIN bugs_activity AS $table " .
                      "ON $table.bug_id = bugs.bug_id " .
                      "AND $table.fieldid = $fieldid " .
                      "AND $table.$operator = $$q");
    $$term = "($table.bug_when IS NOT NULL)";
}

sub _changedby {
    my $self = shift;
    my %func_args = @_;
    my ($chartid, $chartfields, $f, $v, $supptables, $term) =
        @func_args{qw(chartid chartfields f v supptables term)};
    
    my $table = "act_$$chartid";
    my $fieldid = $$chartfields{$$f};
    if (!$fieldid) {
        ThrowCodeError("invalid_field_name", {field => $$f});
    }
    my $id = login_to_id($$v, THROW_ERROR);
    push(@$supptables, "LEFT JOIN bugs_activity AS $table " .
                      "ON $table.bug_id = bugs.bug_id " .
                      "AND $table.fieldid = $fieldid " .
                      "AND $table.who = $id");
    $$term = "($table.bug_when IS NOT NULL)";
}

2106
1;