Search.pm 68.2 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 31 32 33

use strict;

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

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

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

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.
our %specialorder = (
54 55 56 57 58 59 60
    'bugs.target_milestone' => [ 'ms_order.sortkey','ms_order.value' ],
    'bugs.bug_status' => [ 'bug_status.sortkey','bug_status.value' ],
    'bugs.rep_platform' => [ 'rep_platform.sortkey','rep_platform.value' ],
    'bugs.priority' => [ 'priority.sortkey','priority.value' ],
    'bugs.op_sys' => [ 'op_sys.sortkey','op_sys.value' ],
    'bugs.resolution' => [ 'resolution.sortkey', 'resolution.value' ],
    'bugs.bug_severity' => [ 'bug_severity.sortkey','bug_severity.value' ]
61 62 63 64
);

# 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 
65
# the join statements that need to be added.
66
our %specialorderjoin = (
67 68 69 70 71 72 73
    'bugs.target_milestone' => 'LEFT JOIN milestones AS ms_order ON ms_order.value = bugs.target_milestone AND ms_order.product_id = bugs.product_id',
    'bugs.bug_status' => 'LEFT JOIN bug_status ON bug_status.value = bugs.bug_status',
    'bugs.rep_platform' => 'LEFT JOIN rep_platform ON rep_platform.value = bugs.rep_platform',
    'bugs.priority' => 'LEFT JOIN priority ON priority.value = bugs.priority',
    'bugs.op_sys' => 'LEFT JOIN op_sys ON op_sys.value = bugs.op_sys',
    'bugs.resolution' => 'LEFT JOIN resolution ON resolution.value = bugs.resolution',
    'bugs.bug_severity' => 'LEFT JOIN bug_severity ON bug_severity.value = bugs.bug_severity'
74 75
);

76
# Create a new Search
77
# Note that the param argument may be modified by Bugzilla::Search
78 79 80 81
sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
  
82
    my $self = { @_ };
83
    bless($self, $class);
84

85
    $self->init();
86
 
87 88 89 90 91 92
    return $self;
}

sub init {
    my $self = shift;
    my $fieldsref = $self->{'fields'};
93
    my $params = $self->{'params'};
94
    my $user = $self->{'user'} || Bugzilla->user;
95

96 97 98 99 100
    my $orderref = $self->{'order'} || 0;
    my @inputorder;
    @inputorder = @$orderref if $orderref;
    my @orderby;

101
    my $debug = 0;
102 103
    my @debugdata;
    if ($params->param('debug')) { $debug = 1; }
104

105 106 107
    my @fields;
    my @supptables;
    my @wherepart;
108
    my @having;
109
    my @groupby;
110 111 112
    @fields = @$fieldsref if $fieldsref;
    my @specialchart;
    my @andlist;
113
    my %chartfields;
114

115 116
    my $dbh = Bugzilla->dbh;

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

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

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

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

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

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

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

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

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

211
    foreach my $field ($params->param()) {
212
        if (lsearch(\@legal_fields, $field) != -1) {
213
            push(@specialchart, [$field, "anyexact",
214
                                 join(',', $params->param($field))]);
215 216 217
        }
    }

218 219
    if ($params->param('keywords')) {
        my $t = $params->param('keywords_type');
220 221 222
        if (!$t || $t eq "or") {
            $t = "anywords";
        }
223
        push(@specialchart, ["keywords", $t, $params->param('keywords')]);
224 225 226
    }

    foreach my $id ("1", "2") {
227
        if (!defined ($params->param("email$id"))) {
228 229
            next;
        }
230
        my $email = trim($params->param("email$id"));
231 232 233
        if ($email eq "") {
            next;
        }
234
        my $type = $params->param("emailtype$id");
235 236 237
        if ($type eq "exact") {
            $type = "anyexact";
            foreach my $name (split(',', $email)) {
238
                $name = trim($name);
239
                if ($name) {
240
                    login_to_id($name, THROW_ERROR);
241 242 243 244 245 246
                }
            }
        }

        my @clist;
        foreach my $field ("assigned_to", "reporter", "cc", "qa_contact") {
247
            if ($params->param("email$field$id")) {
248 249 250
                push(@clist, $field, $type, $email);
            }
        }
251
        if ($params->param("emaillongdesc$id")) {
252
                push(@clist, "commenter", $type, $email);
253 254 255 256
        }
        if (@clist) {
            push(@specialchart, \@clist);
        } else {
257 258
            ThrowUserError("missing_email_type",
                           { email => $email });
259 260 261
        }
    }

262 263 264 265 266 267 268
    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')) || '';

269 270
    # 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.
271
    my $changedin = trim($params->param('changedin')) || '';
272 273 274 275
    if ($changedin) {
        if ($changedin !~ /^[0-9]*$/) {
            ThrowUserError("illegal_changed_in_last_x_days",
                              { value => $changedin });
276 277
        }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        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]);
        }
    }
294

295
    if ($chfieldfrom ne '' || $chfieldto ne '') {
296 297 298 299
        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);
300 301 302 303
        if(!@chfield) {
            push(@wherepart, "bugs.delta_ts >= $sql_chfrom") if ($sql_chfrom);
            push(@wherepart, "bugs.delta_ts <= $sql_chto") if ($sql_chto);
        } else {
304
            my $bug_creation_clause;
305 306 307
            my @list;
            foreach my $f (@chfield) {
                if ($f eq "[Bug creation]") {
308 309
                    # Treat [Bug creation] differently because we need to look
                    # at bugs.creation_ts rather than the bugs_activity table.
310
                    my @l;
311 312
                    push(@l, "bugs.creation_ts >= $sql_chfrom") if($sql_chfrom);
                    push(@l, "bugs.creation_ts <= $sql_chto") if($sql_chto);
313
                    $bug_creation_clause = "(" . join(' AND ', @l) . ")";
314
                } else {
315
                    push(@list, "\nactcheck.fieldid = " . get_field_id($f));
316 317
                }
            }
318 319 320

            # @list won't have any elements if the only field being searched
            # is [Bug creation] (in which case we don't need bugs_activity).
321
            if(@list) {
322
                my $extra = "";
323
                if($sql_chfrom) {
324
                    $extra .= " AND actcheck.bug_when >= $sql_chfrom";
325 326
                }
                if($sql_chto) {
327
                    $extra .= " AND actcheck.bug_when <= $sql_chto";
328 329
                }
                if($sql_chvalue) {
330
                    $extra .= " AND actcheck.added = $sql_chvalue";
331
                }
332 333
                push(@supptables, "INNER JOIN bugs_activity AS actcheck " .
                                   "ON actcheck.bug_id = bugs.bug_id $extra");
334
            }
335 336 337 338 339 340 341 342

            # 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) . ")");
343 344 345
        }
    }

346 347
    my $sql_deadlinefrom;
    my $sql_deadlineto;
348
    if (Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'})){
349 350 351 352 353
      my $deadlinefrom;
      my $deadlineto;
            
      if ($params->param('deadlinefrom')){
        $deadlinefrom = $params->param('deadlinefrom');
354 355 356
        validate_date($deadlinefrom)
          || ThrowUserError('illegal_date', {date => $deadlinefrom,
                                             format => 'YYYY-MM-DD'});
357 358
        $sql_deadlinefrom = $dbh->quote($deadlinefrom);
        trick_taint($sql_deadlinefrom);
359 360 361 362 363
        push(@wherepart, "bugs.deadline >= $sql_deadlinefrom");
      }
      
      if ($params->param('deadlineto')){
        $deadlineto = $params->param('deadlineto');
364 365 366
        validate_date($deadlineto)
          || ThrowUserError('illegal_date', {date => $deadlineto,
                                             format => 'YYYY-MM-DD'});
367 368
        $sql_deadlineto = $dbh->quote($deadlineto);
        trick_taint($sql_deadlineto);
369 370 371 372
        push(@wherepart, "bugs.deadline <= $sql_deadlineto");
      }
    }  

373 374
    foreach my $f ("short_desc", "long_desc", "bug_file_loc",
                   "status_whiteboard") {
375 376
        if (defined $params->param($f)) {
            my $s = trim($params->param($f));
377 378
            if ($s ne "") {
                my $n = $f;
379 380
                my $q = $dbh->quote($s);
                trick_taint($q);
381
                my $type = $params->param($f . "_type");
382 383 384 385 386
                push(@specialchart, [$f, $type, $s]);
            }
        }
    }

387
    if (defined $params->param('content')) {
388 389 390 391 392 393 394 395 396
        # Append a new chart implementing content quicksearch
        my $chart;
        for ($chart = 0 ; $params->param("field$chart-0-0") ; $chart++) {};
        $params->param("field$chart-0-0", 'content');
        $params->param("type$chart-0-0", 'matches');
        $params->param("value$chart-0-0", $params->param('content'));
        $params->param("field$chart-0-1", 'short_desc');
        $params->param("type$chart-0-1", 'allwords');
        $params->param("value$chart-0-1", $params->param('content'));
397 398
    }

399
    my $chartid;
400
    my $sequence = 0;
401 402
    # $type_id is used by the code that queries for attachment flags.
    my $type_id = 0;
403 404 405 406 407 408 409 410 411
    my $f;
    my $ff;
    my $t;
    my $q;
    my $v;
    my $term;
    my %funcsbykey;
    my @funcdefs =
        (
412
         "^(?:assigned_to|reporter|qa_contact),(?:notequals|equals|anyexact),%group\\.([^%]+)%" => sub {
413
             my $group = $1;
414
             my $groupid = Bugzilla::Group::ValidateGroupName( $group, ($user));
415 416 417
             $groupid || ThrowUserError('invalid_group_name',{name => $group});
             my @childgroups = @{$user->flatten_group_membership($groupid)};
             my $table = "user_group_map_$chartid";
418
             push (@supptables, "LEFT JOIN user_group_map AS $table " .
419 420 421 422 423 424 425 426 427 428 429 430 431
                                "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";
             }
          },
432 433 434 435 436 437
         "^(?:assigned_to|reporter|qa_contact),(?:equals|anyexact),(%\\w+%)" => sub {
             $term = "bugs.$f = " . pronoun($1, $user);
          },
         "^(?:assigned_to|reporter|qa_contact),(?:notequals),(%\\w+%)" => sub {
             $term = "bugs.$f <> " . pronoun($1, $user);
          },
438
         "^(assigned_to|reporter),(?!changed)" => sub {
439 440 441 442 443 444 445 446
             my $list = $self->ListIDsForEmail($t, $v);
             if ($list) {
                 $term = "bugs.$f IN ($list)"; 
             } else {
                 push(@supptables, "INNER JOIN profiles AS map_$f " .
                                   "ON bugs.$f = map_$f.userid");
                 $f = "map_$f.login_name";
             }
447
         },
448
         "^qa_contact,(?!changed)" => sub {
449 450
             push(@supptables, "LEFT JOIN profiles AS map_qa_contact " .
                               "ON bugs.qa_contact = map_qa_contact.userid");
451
             $f = "COALESCE(map_$f.login_name,'')";
452 453
         },

454
         "^(?:cc),(?:notequals|equals|anyexact),%group\\.([^%]+)%" => sub {
455
             my $group = $1;
456
             my $groupid = Bugzilla::Group::ValidateGroupName( $group, ($user));
457 458 459 460 461 462 463 464
             $groupid || ThrowUserError('invalid_group_name',{name => $group});
             my @childgroups = @{$user->flatten_group_membership($groupid)};
             my $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
             my $table = "user_group_map_$chartseq";
465
             push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
466
                               "ON bugs.bug_id = cc_$chartseq.bug_id");
467
             push(@supptables, "LEFT JOIN user_group_map AS $table " .
468 469 470 471 472 473 474 475 476 477 478 479 480 481
                                "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";
             }
          },

482 483 484 485 486 487 488
         "^cc,(?:equals|anyexact),(%\\w+%)" => sub {
             my $match = pronoun($1, $user);
             my $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
489 490 491
             push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
                               "ON bugs.bug_id = cc_$chartseq.bug_id " .
                               "AND cc_$chartseq.who = $match");
492 493 494 495 496 497 498 499 500
             $term = "cc_$chartseq.who IS NOT NULL";
         },
         "^cc,(?:notequals),(%\\w+%)" => sub {
             my $match = pronoun($1, $user);
             my $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
501 502 503
             push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
                               "ON bugs.bug_id = cc_$chartseq.bug_id " .
                               "AND cc_$chartseq.who = $match");
504 505
             $term = "cc_$chartseq.who IS NULL";
         },
506
         "^cc,(anyexact|substring|regexp)" => sub {
507 508
             my $list;
             $list = $self->ListIDsForEmail($t, $v);
509
             my $chartseq = $chartid;
510 511 512 513
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
514
             if ($list) {
515 516 517
                 push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
                                   "ON bugs.bug_id = cc_$chartseq.bug_id " .
                                   "AND cc_$chartseq.who IN($list)");
518
                 $term = "cc_$chartseq.who IS NOT NULL";
519
             } else {
520 521 522 523 524
                 push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
                                   "ON bugs.bug_id = cc_$chartseq.bug_id");
                 push(@supptables,
                            "LEFT JOIN profiles AS map_cc_$chartseq " .
                            "ON cc_$chartseq.who = map_cc_$chartseq.userid");
525

526
                 $ff = $f = "map_cc_$chartseq.login_name";
527
                 my $ref = $funcsbykey{",$t"};
528 529 530
                 &$ref;
             }
         },
531
         "^cc,(?!changed)" => sub {
532
             my $chartseq = $chartid;
533 534 535 536
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
537 538
            push(@supptables, "LEFT JOIN cc AS cc_$chartseq " .
                              "ON bugs.bug_id = cc_$chartseq.bug_id");
539

540 541 542 543
            $ff = $f = "map_cc_$chartseq.login_name";
            my $ref = $funcsbykey{",$t"};
            &$ref;
            push(@supptables, 
544 545 546
                        "LEFT JOIN profiles AS map_cc_$chartseq " .
                        "ON (cc_$chartseq.who = map_cc_$chartseq.userid " .
                        "AND ($term))"
547 548
                );
            $term = "$f IS NOT NULL";
549 550 551 552
         },

         "^long_?desc,changedby" => sub {
             my $table = "longdescs_$chartid";
553 554
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
555
             my $id = login_to_id($v, THROW_ERROR);
556 557 558 559
             $term = "$table.who = $id";
         },
         "^long_?desc,changedbefore" => sub {
             my $table = "longdescs_$chartid";
560 561
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
562
             $term = "$table.bug_when < " . $dbh->quote(SqlifyDate($v));
563 564 565
         },
         "^long_?desc,changedafter" => sub {
             my $table = "longdescs_$chartid";
566 567
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
568
             $term = "$table.bug_when > " . $dbh->quote(SqlifyDate($v));
569
         },
570 571 572 573
         "^content,matches" => sub {
             # "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).
574 575 576
             # 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.
577 578 579

             # Add the longdescs table to the query so we can search comments.
             my $table = "longdescs_$chartid";
580
             my $extra = "";
581 582
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"}))
583
             {
584
                 $extra = "AND $table.isprivate < 1";
585
             }
586 587
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON bugs.bug_id = $table.bug_id $extra");
588 589 590 591 592

             # Create search terms to add to the SELECT and WHERE clauses.
             # $term1 searches comments.
             # $term2 searches summaries, which contributes to the relevance
             # ranking in SELECT but doesn't limit which bugs get retrieved.
593 594
             my $term1 = $dbh->sql_fulltext_search("${table}.thetext", $v);
             my $term2 = $dbh->sql_fulltext_search("bugs.short_desc", $v);
595 596

             # The term to use in the WHERE clause.
597
             $term = "$term1 > 0";
598

599 600 601
             # 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.
602 603 604 605 606 607 608 609 610 611 612
             #
             # Note: MySQL calculates relevance for each comment separately,
             # so we need to do some additional calculations to get an overall
             # relevance value, which we do by calculating the average (mean)
             # comment relevance and then adding the summary relevance, if any.
             # This weights summary relevance heavily, which makes sense
             # since summaries are short and thus highly significant.
             #
             # Note: We should be calculating the average relevance of all
             # comments for a bug, not just matching comments, but that's hard
             # (see http://bugzilla.mozilla.org/show_bug.cgi?id=145588#c35).
613 614
             my $select_term =
               "(SUM($term1)/COUNT($term1) + $term2) AS relevance";
615 616

             # add the column not used in aggregate function explicitly
617
             push(@groupby, 'bugs.short_desc');
618 619 620 621 622 623 624 625 626 627 628

             # 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);
             }
629
         },
630 631 632
         "^content," => sub {
             ThrowUserError("search_content_without_matches");
         },
633 634
         "^deadline,(?:lessthan|greaterthan|equals|notequals),(-|\\+)?(\\d+)([dDwWmMyY])\$" => sub {
             $v = SqlifyDate($v);
635
             $q = $dbh->quote($v);
636
        },
637 638 639 640 641 642 643 644 645
         "^commenter,(?:equals|anyexact),(%\\w+%)" => sub {
             my $match = pronoun($1, $user);
             my $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "LD$sequence";
                 $sequence++;
             }
             my $table = "longdescs_$chartseq";
             my $extra = "";
646 647 648
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"})) 
             {
649 650
                 $extra = "AND $table.isprivate < 1";
             }
651 652 653
             push(@supptables, "LEFT JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id $extra " .
                               "AND $table.who IN ($match)");
654 655 656 657
             $term = "$table.who IS NOT NULL";
         },
         "^commenter," => sub {
             my $chartseq = $chartid;
658 659 660 661 662 663 664 665
             my $list;
             $list = $self->ListIDsForEmail($t, $v);
             if ($chartid eq "") {
                 $chartseq = "LD$sequence";
                 $sequence++;
             }
             my $table = "longdescs_$chartseq";
             my $extra = "";
666 667 668
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"})) 
             {
669 670 671
                 $extra = "AND $table.isprivate < 1";
             }
             if ($list) {
672 673 674
                 push(@supptables, "LEFT JOIN longdescs AS $table " .
                                   "ON $table.bug_id = bugs.bug_id $extra " .
                                   "AND $table.who IN ($list)");
675 676
                 $term = "$table.who IS NOT NULL";
             } else {
677 678 679 680
                 push(@supptables, "LEFT JOIN longdescs AS $table " .
                                   "ON $table.bug_id = bugs.bug_id $extra");
                 push(@supptables, "LEFT JOIN profiles AS map_$table " .
                                   "ON $table.who = map_$table.userid");
681 682 683 684 685
                 $ff = $f = "map_$table.login_name";
                 my $ref = $funcsbykey{",$t"};
                 &$ref;
             }
         },
686 687
         "^long_?desc," => sub {
             my $table = "longdescs_$chartid";
688
             my $extra = "";
689 690 691
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"})) 
             {
692
                 $extra = "AND $table.isprivate < 1";
693
             }
694 695
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id $extra");
696 697
             $f = "$table.thetext";
         },
698 699
         "^work_time,changedby" => sub {
             my $table = "longdescs_$chartid";
700 701
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
702
             my $id = login_to_id($v, THROW_ERROR);
703 704 705 706 707
             $term = "(($table.who = $id";
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time,changedbefore" => sub {
             my $table = "longdescs_$chartid";
708 709
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
710
             $term = "(($table.bug_when < " . $dbh->quote(SqlifyDate($v));
711 712 713 714
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time,changedafter" => sub {
             my $table = "longdescs_$chartid";
715 716
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
717
             $term = "(($table.bug_when > " . $dbh->quote(SqlifyDate($v));
718 719 720 721
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time," => sub {
             my $table = "longdescs_$chartid";
722 723
             push(@supptables, "INNER JOIN longdescs AS $table " .
                               "ON $table.bug_id = bugs.bug_id");
724 725 726 727 728 729 730 731 732 733 734 735 736
             $f = "$table.work_time";
         },
         "^percentage_complete," => sub {
             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") {
737 738 739 740
                 # 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";
741
             } elsif ($t eq "notregexp") {
742 743 744 745
                 # 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";
746 747 748 749 750
             } else {
                 $oper = "noop";
             }
             if ($oper ne "noop") {
                 my $table = "longdescs_$chartid";
751 752 753
                 if(lsearch(\@fields, "bugs.remaining_time") == -1) {
                     push(@fields, "bugs.remaining_time");                  
                 }
754 755
                 push(@supptables, "INNER JOIN longdescs AS $table " .
                                   "ON $table.bug_id = bugs.bug_id");
756 757 758 759 760 761 762
                 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)))";
763 764
                 $q = $dbh->quote($v);
                 trick_taint($q);
765
                 if ($t eq "regexp") {
766
                     push(@having, $dbh->sql_regexp($expression, $q));
767
                 } elsif ($t eq "notregexp") {
768
                     push(@having, $dbh->sql_not_regexp($expression, $q));
769
                 } else {
770
                     push(@having, "$expression $oper " . $q);
771
                 }
772
                 push(@groupby, "bugs.remaining_time");
773 774 775
             }
             $term = "0=0";
         },
776
         "^bug_group,(?!changed)" => sub {
777 778 779
            push(@supptables,
                    "LEFT JOIN bug_group_map AS bug_group_map_$chartid " .
                    "ON bugs.bug_id = bug_group_map_$chartid.bug_id");
780 781 782
            $ff = $f = "groups_$chartid.name";
            my $ref = $funcsbykey{",$t"};
            &$ref;
783 784
            push(@supptables,
                    "LEFT JOIN groups AS groups_$chartid " .
785 786 787
                    "ON groups_$chartid.id = bug_group_map_$chartid.group_id " .
                    "AND $term");
            $term = "$ff IS NOT NULL";
788
         },
789 790 791 792 793
         "^attach_data\.thedata,changed" => sub {
            # Searches for attachment data's change must search
            # the creation timestamp of the attachment instead.
            $f = "attachments.whocares";
         },
794 795 796 797
         "^attach_data\.thedata," => sub {
             my $atable = "attachments_$chartid";
             my $dtable = "attachdata_$chartid";
             my $extra = "";
798 799 800
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"})) 
             {
801 802 803 804 805 806 807 808
                 $extra = "AND $atable.isprivate = 0";
             }
             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";
         },
809 810
         "^attachments\..*," => sub {
             my $table = "attachments_$chartid";
811
             my $extra = "";
812 813 814
             if (Bugzilla->params->{"insidergroup"} 
                 && !UserInGroup(Bugzilla->params->{"insidergroup"})) 
             {
815
                 $extra = "AND $table.isprivate = 0";
816
             }
817 818
             push(@supptables, "INNER JOIN attachments AS $table " .
                               "ON bugs.bug_id = $table.bug_id $extra");
819 820 821
             $f =~ m/^attachments\.(.*)$/;
             my $field = $1;
             if ($t eq "changedby") {
822
                 $v = login_to_id($v, THROW_ERROR);
823
                 $q = $dbh->quote($v);
824 825 826 827
                 $field = "submitter_id";
                 $t = "equals";
             } elsif ($t eq "changedbefore") {
                 $v = SqlifyDate($v);
828
                 $q = $dbh->quote($v);
829 830 831 832
                 $field = "creation_ts";
                 $t = "lessthan";
             } elsif ($t eq "changedafter") {
                 $v = SqlifyDate($v);
833
                 $q = $dbh->quote($v);
834 835 836 837
                 $field = "creation_ts";
                 $t = "greaterthan";
             }
             if ($field eq "ispatch" && $v ne "0" && $v ne "1") {
838
                 ThrowUserError("illegal_attachment_is_patch");
839 840
             }
             if ($field eq "isobsolete" && $v ne "0" && $v ne "1") {
841
                 ThrowUserError("illegal_is_obsolete");
842 843 844
             }
             $f = "$table.$field";
         },
845 846 847 848 849 850 851 852
         "^flagtypes.name," => sub {
             # 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.
853
             return if ($t =~ m/^changed/);
854 855 856 857 858
             
             # 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";
859
             push(@supptables, "LEFT JOIN flags AS $flags " . 
860
                               "ON bugs.bug_id = $flags.bug_id ");
861
             my $flagtypes = "flagtypes_$chartid";
862
             push(@supptables, "LEFT JOIN flagtypes AS $flagtypes " . 
863 864
                               "ON $flags.type_id = $flagtypes.id");
             
865 866 867 868 869
             # 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");
870 871 872 873 874 875 876 877 878 879 880
             &{$funcsbykey{",$t"}};
             
             # 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/) {
881 882 883
                push(@having,
                     "SUM(CASE WHEN $ff IS NOT NULL THEN 1 ELSE 0 END) = " .
                     "SUM(CASE WHEN $term THEN 1 ELSE 0 END)");
884
                $term = "0=0";
885 886
             }
         },
887
         "^requestees.login_name," => sub {
888
             my $flags = "flags_$chartid";
889
             push(@supptables, "LEFT JOIN flags AS $flags " .
890
                               "ON bugs.bug_id = $flags.bug_id ");
891
             push(@supptables, "LEFT JOIN profiles AS requestees_$chartid " .
892
                               "ON $flags.requestee_id = requestees_$chartid.userid");
893
             $f = "requestees_$chartid.login_name";
894 895
         },
         "^setters.login_name," => sub {
896
             my $flags = "flags_$chartid";
897
             push(@supptables, "LEFT JOIN flags AS $flags " .
898
                               "ON bugs.bug_id = $flags.bug_id ");
899
             push(@supptables, "LEFT JOIN profiles AS setters_$chartid " .
900
                               "ON $flags.setter_id = setters_$chartid.userid");
901 902 903
             $f = "setters_$chartid.login_name";
         },
         
904
         "^(changedin|days_elapsed)," => sub {
905 906
             $f = "(" . $dbh->sql_to_days('NOW()') . " - " .
                        $dbh->sql_to_days('bugs.delta_ts') . ")";
907 908
         },

909
         "^component,(?!changed)" => sub {
910 911 912 913 914 915
             $f = $ff = "components.name";
             $funcsbykey{",$t"}->();
             $term = build_subselect("bugs.component_id",
                                     "components.id",
                                     "components",
                                     $term);
916 917 918
         },

         "^product,(?!changed)" => sub {
919 920 921 922 923 924 925
             # Generate the restriction condition
             $f = $ff = "products.name";
             $funcsbykey{",$t"}->();
             $term = build_subselect("bugs.product_id",
                                     "products.id",
                                     "products",
                                     $term);
926 927
         },

928 929
         "^classification,(?!changed)" => sub {
             # Generate the restriction condition
930 931
             push @supptables, "INNER JOIN products AS map_products " .
                               "ON bugs.product_id = map_products.id";
932 933 934 935 936 937 938 939
             $f = $ff = "classifications.name";
             $funcsbykey{",$t"}->();
             $term = build_subselect("map_products.classification_id",
                                     "classifications.id",
                                     "classifications",
                                     $term);
         },

940
         "^keywords,(?!changed)" => sub {
941 942 943 944 945 946
             my @list;
             my $table = "keywords_$chartid";
             foreach my $value (split(/[\s,]+/, $v)) {
                 if ($value eq '') {
                     next;
                 }
947 948 949
                 my $keyword = new Bugzilla::Keyword({name => $value});
                 if ($keyword) {
                     push(@list, "$table.keywordid = " . $keyword->id);
950 951
                 }
                 else {
952 953
                     ThrowUserError("unknown_keyword",
                                    { keyword => $v });
954 955 956 957 958 959 960 961
                 }
             }
             my $haveawordterm;
             if (@list) {
                 $haveawordterm = "(" . join(' OR ', @list) . ")";
                 if ($t eq "anywords") {
                     $term = $haveawordterm;
                 } elsif ($t eq "allwords") {
962
                     my $ref = $funcsbykey{",$t"};
963 964 965 966 967 968 969
                     &$ref;
                     if ($term && $haveawordterm) {
                         $term = "(($term) AND $haveawordterm)";
                     }
                 }
             }
             if ($term) {
970 971
                 push(@supptables, "LEFT JOIN keywords AS $table " .
                                   "ON $table.bug_id = bugs.bug_id");
972 973 974
             }
         },

975
         "^dependson,(?!changed)" => sub {
976 977
                my $table = "dependson_" . $chartid;
                $ff = "$table.$f";
978
                my $ref = $funcsbykey{",$t"};
979
                &$ref;
980
                push(@supptables, "LEFT JOIN dependencies AS $table " .
981 982 983
                                  "ON $table.blocked = bugs.bug_id " .
                                  "AND ($term)");
                $term = "$ff IS NOT NULL";
984 985
         },

986
         "^blocked,(?!changed)" => sub {
987 988
                my $table = "blocked_" . $chartid;
                $ff = "$table.$f";
989
                my $ref = $funcsbykey{",$t"};
990
                &$ref;
991
                push(@supptables, "LEFT JOIN dependencies AS $table " .
992 993 994
                                  "ON $table.dependson = bugs.bug_id " .
                                  "AND ($term)");
                $term = "$ff IS NOT NULL";
995 996
         },

997
         "^alias,(?!changed)" => sub {
998 999 1000 1001 1002
             $ff = "COALESCE(bugs.alias, '')";
             my $ref = $funcsbykey{",$t"};
             &$ref;
         },

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
         "^owner_idle_time,(greaterthan|lessthan)" => sub {
                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';
                }
1018
                my $cutoff = "NOW() - " .
1019
                             $dbh->sql_interval($quantity, $unitinterval);
1020
                my $assigned_fieldid = get_field_id('assigned_to');
1021
                push(@supptables, "LEFT JOIN longdescs AS comment_$table " .
1022 1023 1024
                                  "ON comment_$table.who = bugs.assigned_to " .
                                  "AND comment_$table.bug_id = bugs.bug_id " .
                                  "AND comment_$table.bug_when > $cutoff");
1025
                push(@supptables, "LEFT JOIN bugs_activity AS activity_$table " .
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
                                  "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";
         },
1039 1040 1041 1042 1043 1044 1045 1046

         ",equals" => sub {
             $term = "$ff = $q";
         },
         ",notequals" => sub {
             $term = "$ff != $q";
         },
         ",casesubstring" => sub {
1047
             $term = $dbh->sql_position($q, $ff) . " > 0";
1048
         },
1049
         ",substring" => sub {
1050
             $term = $dbh->sql_position(lc($q), "LOWER($ff)") . " > 0";
1051
         },
1052 1053 1054
         ",substr" => sub {
             $funcsbykey{",substring"}->();
         },
1055
         ",notsubstring" => sub {
1056
             $term = $dbh->sql_position(lc($q), "LOWER($ff)") . " = 0";
1057 1058
         },
         ",regexp" => sub {
1059
             $term = $dbh->sql_regexp($ff, $q);
1060 1061
         },
         ",notregexp" => sub {
1062
             $term = $dbh->sql_not_regexp($ff, $q);
1063 1064 1065 1066
         },
         ",lessthan" => sub {
             $term = "$ff < $q";
         },
1067 1068 1069
         ",matches" => sub {
             ThrowUserError("search_content_without_matches");
         },
1070 1071 1072 1073 1074 1075 1076 1077 1078
         ",greaterthan" => sub {
             $term = "$ff > $q";
         },
         ",anyexact" => sub {
             my @list;
             foreach my $w (split(/,/, $v)) {
                 if ($w eq "---" && $f !~ /milestone/) {
                     $w = "";
                 }
1079 1080 1081
                 $q = $dbh->quote($w);
                 trick_taint($q);
                 push(@list, $q);
1082 1083 1084
             }
             if (@list) {
                 $term = "$ff IN (" . join (',', @list) . ")";
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
             }
         },
         ",anywordssubstr" => sub {
             $term = join(" OR ", @{GetByWordListSubstr($ff, $v)});
         },
         ",allwordssubstr" => sub {
             $term = join(" AND ", @{GetByWordListSubstr($ff, $v)});
         },
         ",nowordssubstr" => sub {
             my @list = @{GetByWordListSubstr($ff, $v)};
             if (@list) {
                 $term = "NOT (" . join(" OR ", @list) . ")";
             }
         },
         ",anywords" => sub {
             $term = join(" OR ", @{GetByWordList($ff, $v)});
         },
         ",allwords" => sub {
             $term = join(" AND ", @{GetByWordList($ff, $v)});
         },
         ",nowords" => sub {
             my @list = @{GetByWordList($ff, $v)};
             if (@list) {
                 $term = "NOT (" . join(" OR ", @list) . ")";
             }
         },
1111 1112
         ",(changedbefore|changedafter)" => sub {
             my $operator = ($t =~ /before/) ? '<' : '>';
1113
             my $table = "act_$chartid";
1114 1115 1116 1117
             my $fieldid = $chartfields{$f};
             if (!$fieldid) {
                 ThrowCodeError("invalid_field_name", {field => $f});
             }
1118
             push(@supptables, "LEFT JOIN bugs_activity AS $table " .
1119 1120 1121
                               "ON $table.bug_id = bugs.bug_id " .
                               "AND $table.fieldid = $fieldid " .
                               "AND $table.bug_when $operator " . 
1122
                               $dbh->quote(SqlifyDate($v)) );
1123
             $term = "($table.bug_when IS NOT NULL)";
1124
         },
1125 1126
         ",(changedfrom|changedto)" => sub {
             my $operator = ($t =~ /from/) ? 'removed' : 'added';
1127
             my $table = "act_$chartid";
1128 1129 1130 1131
             my $fieldid = $chartfields{$f};
             if (!$fieldid) {
                 ThrowCodeError("invalid_field_name", {field => $f});
             }
1132
             push(@supptables, "LEFT JOIN bugs_activity AS $table " .
1133 1134 1135 1136
                               "ON $table.bug_id = bugs.bug_id " .
                               "AND $table.fieldid = $fieldid " .
                               "AND $table.$operator = $q");
             $term = "($table.bug_when IS NOT NULL)";
1137 1138 1139
         },
         ",changedby" => sub {
             my $table = "act_$chartid";
1140 1141 1142 1143
             my $fieldid = $chartfields{$f};
             if (!$fieldid) {
                 ThrowCodeError("invalid_field_name", {field => $f});
             }
1144
             my $id = login_to_id($v, THROW_ERROR);
1145
             push(@supptables, "LEFT JOIN bugs_activity AS $table " .
1146 1147 1148 1149
                               "ON $table.bug_id = bugs.bug_id " .
                               "AND $table.fieldid = $fieldid " .
                               "AND $table.who = $id");
             $term = "($table.bug_when IS NOT NULL)";
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
         },
         );
    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
1168
    my @badcharts = grep /^(field|type|value)-1-/, $params->param();
1169
    foreach my $field (@badcharts) {
1170
        $params->delete($field);
1171 1172 1173 1174 1175 1176 1177 1178
    }

    # 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) {
1179 1180 1181
            $params->param("field$chart-$row-$col", shift(@$ref));
            $params->param("type$chart-$row-$col", shift(@$ref));
            $params->param("value$chart-$row-$col", shift(@$ref));
1182
            if ($debug) {
1183
                push(@debugdata, "$row-$col = " .
1184 1185
                               $params->param("field$chart-$row-$col") . ' | ' .
                               $params->param("type$chart-$row-$col") . ' | ' .
1186
                               $params->param("value$chart-$row-$col") . ' *');
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
            }
            $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".
#
1208
# Each chart consists of an arbitrary number of rows and columns.
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
# 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.
1235
# This will find bugs with one CC matching 'foo@blah.org' and and another
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
# 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
# --------------------------------------------------------------

1258
# $chartid is the number of the current chart whose SQL we're constructing
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
# $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
1269
# $q  = sanitized version of user input trick_taint(($dbh->quote($v)))
1270 1271 1272
# @supptables = Tables and/or table aliases used in query
# %suppseen   = A hash used to store all the tables in supptables to weed
#               out duplicates.
1273 1274
# @supplist   = A list used to accumulate all the JOIN clauses for each
#               chart to merge the ON sections of each.
1275 1276 1277
# $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
1278
    %chartfields = @{$dbh->selectcol_arrayref(
1279
        q{SELECT name, id FROM fielddefs}, { Columns=>[1,2] })};
1280 1281 1282

    $row = 0;
    for ($chart=-1 ;
1283
         $chart < 0 || $params->param("field$chart-0-0") ;
1284 1285
         $chart++) {
        $chartid = $chart >= 0 ? $chart : "";
1286
        my @chartandlist = ();
1287
        for ($row = 0 ;
1288
             $params->param("field$chart-$row-0") ;
1289 1290 1291
             $row++) {
            my @orlist;
            for (my $col = 0 ;
1292
                 $params->param("field$chart-$row-$col") ;
1293
                 $col++) {
1294 1295 1296
                $f = $params->param("field$chart-$row-$col") || "noop";
                $t = $params->param("type$chart-$row-$col") || "noop";
                $v = $params->param("value$chart-$row-$col");
1297
                $v = "" if !defined $v;
1298
                $v = trim($v);
1299 1300 1301 1302 1303 1304
                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)) {
1305
                    ThrowCodeError("invalid_field_name", {field => $f});
1306 1307 1308 1309
                }

                # This is either from the internal chart (in which case we
                # already know about it), or it was in %chartfields, so it is
1310
                # a valid field name, which means that it's ok.
1311
                trick_taint($f);
1312 1313
                $q = $dbh->quote($v);
                trick_taint($q);
1314 1315
                my $rhs = $v;
                $rhs =~ tr/,//;
1316 1317 1318
                my $func;
                $term = undef;
                foreach my $key (@funcnames) {
1319
                    if ("$f,$t,$rhs" =~ m/$key/) {
1320 1321
                        my $ref = $funcsbykey{$key};
                        if ($debug) {
1322
                            push(@debugdata, "$key ($f / $t / $rhs) =>");
1323 1324 1325 1326 1327 1328 1329
                        }
                        $ff = $f;
                        if ($f !~ /\./) {
                            $ff = "bugs.$f";
                        }
                        &$ref;
                        if ($debug) {
1330 1331
                            push(@debugdata, "$f / $t / $v / " .
                                             ($term || "undef") . " *");
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
                        }
                        if ($term) {
                            last;
                        }
                    }
                }
                if ($term) {
                    push(@orlist, $term);
                }
                else {
1342
                    # This field and this type don't work together.
1343 1344 1345 1346
                    ThrowCodeError("field_type_mismatch",
                                   { field => $params->param("field$chart-$row-$col"),
                                     type => $params->param("type$chart-$row-$col"),
                                   });
1347 1348 1349
                }
            }
            if (@orlist) {
1350
                @orlist = map("($_)", @orlist) if (scalar(@orlist) > 1);
1351 1352 1353 1354 1355 1356 1357 1358
                push(@chartandlist, "(" . join(" OR ", @orlist) . ")");
            }
        }
        if (@chartandlist) {
            if ($params->param("negate$chart")) {
                push(@andlist, "NOT(" . join(" AND ", @chartandlist) . ")");
            } else {
                push(@andlist, "(" . join(" AND ", @chartandlist) . ")");
1359 1360 1361
            }
        }
    }
1362 1363 1364 1365 1366

    # 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) {
1367 1368 1369 1370 1371 1372 1373
        # 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;
        }
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
        BuildOrderBy($orderitem, \@orderby);
    }
    # 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);
        if ($specialorderjoin{$splitfield[0]}) {
            push(@supptables, $specialorderjoin{$splitfield[0]});
        }
    }

1387 1388
    my %suppseen = ("bugs" => 1);
    my $suppstring = "bugs";
1389
    my @supplist = (" ");
1390 1391
    foreach my $str (@supptables) {
        if (!$suppseen{$str}) {
1392
            if ($str =~ /^(LEFT|INNER|RIGHT)\s+JOIN/i) {
1393 1394 1395 1396 1397 1398 1399 1400 1401
                $str =~ /^(.*?)\s+ON\s+(.*)$/i;
                my ($leftside, $rightside) = ($1, $2);
                if ($suppseen{$leftside}) {
                    $supplist[$suppseen{$leftside}] .= " AND ($rightside)";
                } else {
                    $suppseen{$leftside} = scalar @supplist;
                    push @supplist, " $leftside ON ($rightside)";
                }
            } else {
1402 1403 1404
                # Do not accept implicit joins using comma operator
                # as they are not DB agnostic
                ThrowCodeError("comma_operator_deprecated");
1405 1406 1407
            }
        }
    }
1408
    $suppstring .= join('', @supplist);
1409 1410 1411
    
    # Make sure we create a legal SQL query.
    @andlist = ("1 = 1") if !@andlist;
1412

1413 1414 1415 1416 1417
    my $query = "SELECT " . join(', ', @fields) .
                " FROM $suppstring" .
                " LEFT JOIN bug_group_map " .
                " ON bug_group_map.bug_id = bugs.bug_id ";

1418
    if ($user->id) {
1419 1420 1421
        if (%{$user->groups}) {
            $query .= " AND bug_group_map.group_id NOT IN (" . join(',', values(%{$user->groups})) . ") ";
        }
1422

1423
        $query .= " LEFT JOIN cc ON cc.bug_id = bugs.bug_id AND cc.who = " . $user->id;
1424 1425 1426
    }

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

1429
    if ($user->id) {
1430 1431
        my $userid = $user->id;
        $query .= "    OR (bugs.reporter_accessible = 1 AND bugs.reporter = $userid) " .
1432
              "    OR (bugs.cclist_accessible = 1 AND cc.who IS NOT NULL) " .
1433
              "    OR (bugs.assigned_to = $userid) ";
1434
        if (Bugzilla->params->{'useqacontact'}) {
1435
            $query .= "OR (bugs.qa_contact = $userid) ";
1436 1437 1438
        }
    }

1439
    foreach my $field (@fields, @orderby) {
1440
        next if ($field =~ /(AVG|SUM|COUNT|MAX|MIN|VARIANCE)\s*\(/i ||
1441
                 $field =~ /^\d+$/ || $field eq "bugs.bug_id" ||
1442
                 $field =~ /^(relevance|actual_time|percentage_complete)/);
1443 1444 1445 1446
        # The structure of fields is of the form:
        # [foo AS] {bar | bar.baz} [ASC | DESC]
        # Only the mandatory part bar OR bar.baz is of interest
        if ($field =~ /(?:.*\s+AS\s+)?(\w+(\.\w+)?)(?:\s+(ASC|DESC))?$/i) {
1447 1448 1449 1450 1451
            push(@groupby, $1) if !grep($_ eq $1, @groupby);
        }
    }
    $query .= ") " . $dbh->sql_group_by("bugs.bug_id", join(', ', @groupby));

1452 1453 1454 1455 1456

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

1457 1458 1459 1460
    if (@orderby) {
        $query .= " ORDER BY " . join(',', @orderby);
    }

1461
    $self->{'sql'} = $query;
1462
    $self->{'debugdata'} = \@debugdata;
1463 1464 1465 1466 1467 1468 1469 1470
}

###############################################################################
# Helper functions for the init() method.
###############################################################################
sub SqlifyDate {
    my ($str) = @_;
    $str = "" if !defined $str;
1471 1472 1473 1474
    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);
    }
1475 1476


1477
    if ($str =~ /^(-|\+)?(\d+)([hHdDwWmMyY])$/) {   # relative date
1478
        my ($sign, $amount, $unit, $date) = ($1, $2, lc $3, time);
1479
        my ($sec, $min, $hour, $mday, $month, $year, $wday)  = localtime($date);
1480
        if ($sign && $sign eq '+') { $amount = -$amount; }
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        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);
        }
1497 1498 1499 1500 1501 1502 1503 1504 1505
        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);
        }
1506 1507 1508 1509
        return undef;                      # should not happen due to regexp at top
    }
    my $date = str2time($str);
    if (!defined($date)) {
1510
        ThrowUserError("illegal_date", { date => $str });
1511 1512 1513 1514
    }
    return time2str("%Y-%m-%d %H:%M:%S", $date);
}

1515 1516
# ListIDsForEmail returns a string with a comma-joined list
# of userids matching email addresses
1517
# according to the type specified.
1518 1519
# Currently, this only supports regexp, exact, anyexact, and substring matches.
# Matches will return up to 50 matching userids
1520 1521 1522 1523 1524 1525 1526
# If a match type is unsupported or returns too many matches,
# ListIDsForEmail returns an undef.
sub ListIDsForEmail {
    my ($self, $type, $email) = (@_);
    my $old = $self->{"emailcache"}{"$type,$email"};
    return undef if ($old && $old eq "---");
    return $old if $old;
1527 1528
    
    my $dbh = Bugzilla->dbh;
1529 1530 1531 1532 1533
    my @list = ();
    my $list = "---";
    if ($type eq 'anyexact') {
        foreach my $w (split(/,/, $email)) {
            $w = trim($w);
1534
            my $id = login_to_id($w);
1535 1536 1537 1538 1539 1540
            if ($id > 0) {
                push(@list,$id)
            }
        }
        $list = join(',', @list);
    } elsif ($type eq 'substring') {
1541 1542 1543 1544 1545 1546 1547
        my $sql_email = $dbh->quote($email);
        trick_taint($sql_email);
        my $result = $dbh->selectcol_arrayref(
                    q{SELECT userid FROM profiles WHERE } .
                    $dbh->sql_position(lc($sql_email), q{LOWER(login_name)}) .
                    q{ > 0 } . $dbh->sql_limit(51));
        @list = @{$result};
1548 1549 1550 1551
        if (scalar(@list) < 50) {
            $list = join(',', @list);
        }
    } elsif ($type eq 'regexp') {
1552 1553 1554 1555 1556 1557 1558
        my $sql_email = $dbh->quote($email);
        trick_taint($sql_email);
        my $result = $dbh->selectcol_arrayref(
                        qq{SELECT userid FROM profiles WHERE } .
                        $dbh->sql_regexp("login_name", $sql_email) .
                        q{ } . $dbh->sql_limit(51));
        @list = @{$result};
1559
        if (scalar(@list) < 50) {
1560 1561 1562 1563 1564 1565 1566 1567
            $list = join(',', @list);
        }
    }
    $self->{"emailcache"}{"$type,$email"} = $list;
    return undef if ($list eq "---");
    return $list;
}

1568 1569 1570 1571
sub build_subselect {
    my ($outer, $inner, $table, $cond) = @_;
    my $q = "SELECT $inner FROM $table WHERE $cond";
    #return "$outer IN ($q)";
1572 1573 1574 1575
    my $dbh = Bugzilla->dbh;
    my $list = $dbh->selectcol_arrayref($q);
    return "1=2" unless @$list; # Could use boolean type on dbs which support it
    return "$outer IN (" . join(',', @$list) . ")";
1576 1577
}

1578 1579 1580
sub GetByWordList {
    my ($field, $strs) = (@_);
    my @list;
1581
    my $dbh = Bugzilla->dbh;
1582 1583 1584 1585 1586

    foreach my $w (split(/[\s,]+/, $strs)) {
        my $word = $w;
        if ($word ne "") {
            $word =~ tr/A-Z/a-z/;
1587 1588
            $word = $dbh->quote(quotemeta($word));
            trick_taint($word);
1589 1590 1591
            $word =~ s/^'//;
            $word =~ s/'$//;
            $word = '(^|[^a-z0-9])' . $word . '($|[^a-z0-9])';
1592
            push(@list, $dbh->sql_regexp($field, "'$word'"));
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        }
    }

    return \@list;
}

# Support for "any/all/nowordssubstr" comparison type ("words as substrings")
sub GetByWordListSubstr {
    my ($field, $strs) = (@_);
    my @list;
1603
    my $dbh = Bugzilla->dbh;
1604
    my $sql_word;
1605 1606 1607

    foreach my $word (split(/[\s,]+/, $strs)) {
        if ($word ne "") {
1608 1609 1610
            $sql_word = $dbh->quote($word);
            trick_taint($word);
            push(@list, $dbh->sql_position(lc($sql_word),
1611
                                           "LOWER($field)") . " > 0");
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
        }
    }

    return \@list;
}

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

1623 1624 1625 1626 1627
sub getDebugData {
    my $self = shift;
    return $self->{'debugdata'};
}

1628 1629 1630
sub pronoun {
    my ($noun, $user) = (@_);
    if ($noun eq "%user%") {
1631
        if ($user->id) {
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
            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;
}
1648

1649 1650 1651 1652 1653 1654 1655 1656 1657
# 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;
}
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

# 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 {
    my ($orderitem, $stringlist, $reverseorder) = (@_);

    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.
    if ($specialorder{$orderfield}) {
        foreach my $subitem (@{$specialorder{$orderfield}}) {
            # DESC on a field with non-standard sort order means
            # "reverse the normal order for each field that we map to."
            BuildOrderBy($subitem, $stringlist, $orderdirection =~ m/desc/i);
        }
        return;
    }

1710
    push(@$stringlist, trim($orderfield . ' ' . $orderdirection));
1711
}
1712
1;