Search.pm 44.5 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 27 28 29
# -*- 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>

use strict;

30
# The caller MUST require CGI.pl and globals.pl before using this
31

32
use vars qw($userid);
33 34 35

package Bugzilla::Search;

36
use Bugzilla::Config;
37
use Bugzilla::Error;
38 39
use Bugzilla::Util;

40
use Date::Format;
41
use Date::Parse;
42

43
# Create a new Search
44
# Note that the param argument may be modified by Bugzilla::Search
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
  
    my $self = { @_ };  
    bless($self, $class);
    
    $self->init();
    
    return $self;
}

sub init {
    my $self = shift;
    my $fieldsref = $self->{'fields'};
60
    my $params = $self->{'params'};
61
    my $user = $self->{'user'} || Bugzilla->user;
62 63 64 65 66 67

    my $debug = 0;
        
    my @fields;
    my @supptables;
    my @wherepart;
68
    my @having;
69 70 71 72
    @fields = @$fieldsref if $fieldsref;
    my @specialchart;
    my @andlist;

73 74
    &::GetVersionTable();
    
75
    # First, deal with all the old hard-coded non-chart-based poop.
76 77
    if (lsearch($fieldsref, 'map_assigned_to.login_name') >= 0 || 
        lsearch($fieldsref, 'map_assigned_to.realname') >= 0) {
78 79 80 81
        push @supptables, "profiles AS map_assigned_to";
        push @wherepart, "bugs.assigned_to = map_assigned_to.userid";
    }

82 83
    if (lsearch($fieldsref, 'map_reporter.login_name') >= 0 || 
        lsearch($fieldsref, 'map_reporter.realname') >= 0) {
84
        push @supptables, "profiles AS map_reporter";
85
        push @wherepart, "bugs.reporter = map_reporter.userid";
86 87
    }

88 89
    if (lsearch($fieldsref, 'map_qa_contact.login_name') >= 0 || 
        lsearch($fieldsref, 'map_qa_contact.realname') >= 0) {
90 91 92
        push @supptables, "LEFT JOIN profiles map_qa_contact ON bugs.qa_contact = map_qa_contact.userid";
    }

93
    if (lsearch($fieldsref, 'map_products.name') >= 0) {
94 95 96 97
        push @supptables, "products AS map_products";
        push @wherepart, "bugs.product_id = map_products.id";
    }

98
    if (lsearch($fieldsref, 'map_components.name') >= 0) {
99 100 101
        push @supptables, "components AS map_components";
        push @wherepart, "bugs.component_id = map_components.id";
    }
102 103

    my $minvotes;
104 105
    if (defined $params->param('votes')) {
        my $c = trim($params->param('votes'));
106 107
        if ($c ne "") {
            if ($c !~ /^[0-9]*$/) {
108
                ThrowUserError("illegal_at_least_x_votes",
109
                                  { value => $c });
110 111 112 113 114
            }
            push(@specialchart, ["votes", "greaterthan", $c - 1]);
        }
    }

115
    if ($params->param('bug_id')) {
116
        my $type = "anyexact";
117
        if ($params->param('bugidtype') && $params->param('bugidtype') eq 'exclude') {
118 119
            $type = "nowords";
        }
120
        push(@specialchart, ["bug_id", $type, join(',', $params->param('bug_id'))]);
121 122
    }

123 124
    # If the user has selected all of either status or resolution, change to
    # selecting none. This is functionally equivalent, but quite a lot faster.
125 126
    # Also, if the status is __open__ or __closed__, translate those
    # into their equivalent lists of open and closed statuses.
127 128
    if ($params->param('bug_status')) {
        my @bug_statuses = $params->param('bug_status');
129 130 131
        if (scalar(@bug_statuses) == scalar(@::legal_bug_status) 
            || $bug_statuses[0] eq "__all__")
        {
132 133
            $params->delete('bug_status');
        }
134 135 136 137 138 139 140 141
        elsif ($bug_statuses[0] eq '__open__') {
            $params->param('bug_status', map(&::IsOpenedState($_) ? $_ : undef, 
                                             @::legal_bug_status));
        }
        elsif ($bug_statuses[0] eq "__closed__") {
            $params->param('bug_status', map(&::IsOpenedState($_) ? undef : $_, 
                                             @::legal_bug_status));
        }
142 143 144 145 146 147 148 149 150 151
    }
    
    if ($params->param('resolution')) {
        my @resolutions = $params->param('resolution');
        
        if (scalar(@resolutions) == scalar(@::legal_resolution)) {
            $params->delete('resolution');
        }
    }
    
152 153 154
    my @legal_fields = ("product", "version", "rep_platform", "op_sys",
                        "bug_status", "resolution", "priority", "bug_severity",
                        "assigned_to", "reporter", "component",
155
                        "target_milestone", "bug_group");
156

157
    foreach my $field ($params->param()) {
158
        if (lsearch(\@legal_fields, $field) != -1) {
159
            push(@specialchart, [$field, "anyexact",
160
                                 join(',', $params->param($field))]);
161 162 163
        }
    }

164 165
    if ($params->param('keywords')) {
        my $t = $params->param('keywords_type');
166 167 168
        if (!$t || $t eq "or") {
            $t = "anywords";
        }
169
        push(@specialchart, ["keywords", $t, $params->param('keywords')]);
170 171
    }

172 173 174 175 176
    if (lsearch($fieldsref, "(SUM(ldtime.work_time)*COUNT(DISTINCT ldtime.bug_when)/COUNT(bugs.bug_id)) AS actual_time") != -1) {
        push(@supptables, "longdescs AS ldtime");
        push(@wherepart, "ldtime.bug_id = bugs.bug_id");
    }

177
    foreach my $id ("1", "2") {
178
        if (!defined ($params->param("email$id"))) {
179 180
            next;
        }
181
        my $email = trim($params->param("email$id"));
182 183 184
        if ($email eq "") {
            next;
        }
185
        my $type = $params->param("emailtype$id");
186 187 188
        if ($type eq "exact") {
            $type = "anyexact";
            foreach my $name (split(',', $email)) {
189
                $name = trim($name);
190 191 192 193 194 195 196 197
                if ($name) {
                    &::DBNameToIdAndCheck($name);
                }
            }
        }

        my @clist;
        foreach my $field ("assigned_to", "reporter", "cc", "qa_contact") {
198
            if ($params->param("email$field$id")) {
199 200 201
                push(@clist, $field, $type, $email);
            }
        }
202
        if ($params->param("emaillongdesc$id")) {
203
            if (my $list = $self->ListIDsForEmail($type, $email)) {
204
                my $table = "longdescs_email_$id";
205
                push(@supptables, "LEFT JOIN longdescs $table ON bugs.bug_id = $table.bug_id AND $table.who IN($list)");
206 207 208 209
                push(@wherepart, "$table.who IS NOT NULL");
                # push something into @clist so that we don't trigger
                # the missing_email_type error below
                push(@clist, 'noop');
210
            } else {
211
                my $table = "longdescs_email_$id";
212 213
                push(@supptables, "longdescs $table");
                push(@wherepart, "$table.bug_id = bugs.bug_id");
214
                my $ptable = "longdescnames_email_$id";
215 216 217 218
                push(@supptables, "profiles $ptable");
                push(@wherepart, "$table.who = $ptable.userid");
                push(@clist, "$ptable.login_name", $type, $email);
            }
219 220 221 222
        }
        if (@clist) {
            push(@specialchart, \@clist);
        } else {
223 224
            ThrowUserError("missing_email_type",
                           { email => $email });
225 226 227
        }
    }

228 229 230 231 232 233 234 235
    # 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.
    my $changedin = $params->param('changedin') || '';
    $changedin = trim($changedin);
    if ($changedin) {
        if ($changedin !~ /^[0-9]*$/) {
            ThrowUserError("illegal_changed_in_last_x_days",
                              { value => $changedin });
236
        }
237
        push(@specialchart, ["changedin", "lessthan", $changedin + 1]);
238 239
    }

240 241
    my $chfieldfrom = $params->param('chfieldfrom') || '';
    my $chfieldto = $params->param('chfieldto') || '';
242
    my @chfield = $params->param('chfield');
243 244 245 246
    my $chvalue = $params->param('chfieldvalue') || '';
    my $lcchfieldfrom = trim(lc($chfieldfrom));
    my $lcchfieldto = trim(lc($chfieldto));
    $chvalue = trim($chvalue);
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    $lcchfieldfrom = '' if ($lcchfieldfrom eq 'now');
    $lcchfieldto = '' if ($lcchfieldto eq 'now');
    if ($lcchfieldfrom ne '' || $lcchfieldto ne '') {
        my $sql_chfrom = $lcchfieldfrom ? &::SqlQuote(SqlifyDate($lcchfieldfrom)):'';
        my $sql_chto   = $lcchfieldto   ? &::SqlQuote(SqlifyDate($lcchfieldto))  :'';
        my $sql_chvalue = $chvalue ne '' ? &::SqlQuote($chvalue) : '';
        if(!@chfield) {
            push(@wherepart, "bugs.delta_ts >= $sql_chfrom") if ($sql_chfrom);
            push(@wherepart, "bugs.delta_ts <= $sql_chto") if ($sql_chto);
        } else {
            push(@supptables, "bugs_activity actcheck");
            my $sql_bugschanged = '';
            my @list;
            foreach my $f (@chfield) {
                if ($f eq "[Bug creation]") {
                    my @l;
                    push(@l, "creation_ts >= $sql_chfrom") if($sql_chfrom);
                    push(@l, "creation_ts <= $sql_chto") if($sql_chto);
                    $sql_bugschanged = "(" . join(' AND ', @l) . ")";
                } else {
                    push(@list, "\nactcheck.fieldid = " . &::GetFieldID($f));
269 270
                }
            }
271 272 273 274 275 276 277 278 279 280 281 282 283 284
            if(@list) {
                $sql_bugschanged .= ' OR ' if($sql_bugschanged ne '');
                $sql_bugschanged .= "(actcheck.bug_id = bugs.bug_id AND " .
                                       "(" . join(' OR ', @list) . ")";
                if($sql_chfrom) {
                    $sql_bugschanged .= " AND actcheck.bug_when >= $sql_chfrom";
                }
                if($sql_chto) {
                    $sql_bugschanged .= " AND actcheck.bug_when <= $sql_chto";
                }
                if($sql_chvalue) {
                    $sql_bugschanged .= " AND actcheck.added = $sql_chvalue";
                }
                $sql_bugschanged .= ')';
285
            }
286
            push(@wherepart, "($sql_bugschanged)");
287 288 289 290 291
        }
    }

    foreach my $f ("short_desc", "long_desc", "bug_file_loc",
                   "status_whiteboard") {
292 293
        if (defined $params->param($f)) {
            my $s = trim($params->param($f));
294 295 296
            if ($s ne "") {
                my $n = $f;
                my $q = &::SqlQuote($s);
297
                my $type = $params->param($f . "_type");
298 299 300 301 302
                push(@specialchart, [$f, $type, $s]);
            }
        }
    }

303 304 305 306
    if (defined $params->param('content')) {
        push(@specialchart, ['content', 'matches', $params->param('content')]);
    }

307
    my $chartid;
308
    my $sequence = 0;
309 310
    # $type_id is used by the code that queries for attachment flags.
    my $type_id = 0;
311 312 313 314 315 316 317 318 319 320
    my $f;
    my $ff;
    my $t;
    my $q;
    my $v;
    my $term;
    my %funcsbykey;
    my @funcdefs =
        (
         "^(assigned_to|reporter)," => sub {
321
             push(@supptables, "profiles AS map_$f");
322 323 324 325 326 327 328 329 330
             push(@wherepart, "bugs.$f = map_$f.userid");
             $f = "map_$f.login_name";
         },
         "^qa_contact," => sub {
             push(@supptables,
                  "LEFT JOIN profiles map_qa_contact ON bugs.qa_contact = map_qa_contact.userid");
             $f = "map_$f.login_name";
         },

331 332 333
         "^cc,(anyexact|substring)" => sub {
             my $list;
             $list = $self->ListIDsForEmail($t, $v);
334 335 336 337 338 339
             my $chartseq;
             $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
340
             if ($list) {
341 342
                 push(@supptables, "LEFT JOIN cc cc_$chartseq ON bugs.bug_id = cc_$chartseq.bug_id AND cc_$chartseq.who IN($list)");
                 $term = "cc_$chartseq.who IS NOT NULL";
343
             } else {
344
                 push(@supptables, "LEFT JOIN cc cc_$chartseq ON bugs.bug_id = cc_$chartseq.bug_id");
345

346 347
                 push(@supptables, "LEFT JOIN profiles map_cc_$chartseq ON cc_$chartseq.who = map_cc_$chartseq.userid");
                 $ff = $f = "map_cc_$chartseq.login_name";
348
                 my $ref = $funcsbykey{",$t"};
349 350 351
                 &$ref;
             }
         },
352
         "^cc," => sub {
353 354 355 356 357 358 359
             my $chartseq;
             $chartseq = $chartid;
             if ($chartid eq "") {
                 $chartseq = "CC$sequence";
                 $sequence++;
             }
            push(@supptables, "LEFT JOIN cc cc_$chartseq ON bugs.bug_id = cc_$chartseq.bug_id");
360

361 362
            push(@supptables, "LEFT JOIN profiles map_cc_$chartseq ON cc_$chartseq.who = map_cc_$chartseq.userid");
            $f = "map_cc_$chartseq.login_name";
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
         },

         "^long_?desc,changedby" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             my $id = &::DBNameToIdAndCheck($v);
             $term = "$table.who = $id";
         },
         "^long_?desc,changedbefore" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $term = "$table.bug_when < " . &::SqlQuote(SqlifyDate($v));
         },
         "^long_?desc,changedafter" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $term = "$table.bug_when > " . &::SqlQuote(SqlifyDate($v));
         },
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
         "^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).
             # There's only one way to search a full-text index
             # ("MATCH (...) AGAINST (...)"), so we only accept the "matches"
             # operator, which is specific to full-text index searches.

             # Add the longdescs table to the query so we can search comments.
             my $table = "longdescs_$chartid";
             push(@supptables, "INNER JOIN longdescs $table ON bugs.bug_id " . 
                               "= $table.bug_id");
             if (Param("insidergroup") 
                 && !&::UserInGroup(Param("insidergroup")))
             {
                 push(@wherepart, "$table.isprivate < 1");
             }
             push(@wherepart, "$table.bug_id = bugs.bug_id");

             # 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.
             my $term1 = "MATCH($table.thetext) AGAINST(".&::SqlQuote($v).")";
             my $term2 = "MATCH(bugs.short_desc) AGAINST(".&::SqlQuote($v).")";

             # The term to use in the WHERE clause.
             $term = $term1;

             # In order to sort by relevance, we SELECT the relevance value
             # and give it an alias so we can add it to the SORT BY clause
             # when we build that clause in buglist.cgi.  We also flag the
             # query in Bugzilla with the "sorted_by_relevance" flag
             # so buglist.cgi knows to sort by relevance instead of anything
             # else the user selected.
             #
             # 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).
             push(@fields, "(SUM($term1)/COUNT($term1) + $term2) AS relevance");
             $self->{'sorted_by_relevance'} = 1;
         },
433 434 435
         "^long_?desc," => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
436
             if (Param("insidergroup") && !&::UserInGroup(Param("insidergroup"))) {
437 438
                 push(@wherepart, "$table.isprivate < 1") ;
             }
439 440 441
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $f = "$table.thetext";
         },
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 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 497
         "^work_time,changedby" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             my $id = &::DBNameToIdAndCheck($v);
             $term = "(($table.who = $id";
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time,changedbefore" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $term = "(($table.bug_when < " . &::SqlQuote(SqlifyDate($v));
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time,changedafter" => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $term = "(($table.bug_when > " . &::SqlQuote(SqlifyDate($v));
             $term .= ") AND ($table.work_time <> 0))";
         },
         "^work_time," => sub {
             my $table = "longdescs_$chartid";
             push(@supptables, "longdescs $table");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             $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") {
                 $oper = "REGEXP";
             } elsif ($t eq "notregexp") {
                 $oper = "NOT REGEXP";
             } else {
                 $oper = "noop";
             }
             if ($oper ne "noop") {
                 my $table = "longdescs_$chartid";
                 push(@supptables, "longdescs $table");
                 push(@wherepart, "$table.bug_id = bugs.bug_id");
                 my $field = "(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))) AS percentage_complete_$table";
                 push(@fields, $field);
                 push(@having, 
                      "percentage_complete_$table $oper " . &::SqlQuote($v));
             }
             $term = "0=0";
         },
498 499 500 501 502 503
         "^bug_group,(?!changed)" => sub {
            push(@supptables, "LEFT JOIN bug_group_map bug_group_map_$chartid ON bugs.bug_id = bug_group_map_$chartid.bug_id");

            push(@supptables, "LEFT JOIN groups groups_$chartid ON groups_$chartid.id = bug_group_map_$chartid.group_id");
            $f = "groups_$chartid.name";
         },
504 505 506
         "^attachments\..*," => sub {
             my $table = "attachments_$chartid";
             push(@supptables, "attachments $table");
507 508 509
             if (Param("insidergroup") && !&::UserInGroup(Param("insidergroup"))) {
                 push(@wherepart, "$table.isprivate = 0") ;
             }
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
             push(@wherepart, "bugs.bug_id = $table.bug_id");
             $f =~ m/^attachments\.(.*)$/;
             my $field = $1;
             if ($t eq "changedby") {
                 $v = &::DBNameToIdAndCheck($v);
                 $q = &::SqlQuote($v);
                 $field = "submitter_id";
                 $t = "equals";
             } elsif ($t eq "changedbefore") {
                 $v = SqlifyDate($v);
                 $q = &::SqlQuote($v);
                 $field = "creation_ts";
                 $t = "lessthan";
             } elsif ($t eq "changedafter") {
                 $v = SqlifyDate($v);
                 $q = &::SqlQuote($v);
                 $field = "creation_ts";
                 $t = "greaterthan";
             }
             if ($field eq "ispatch" && $v ne "0" && $v ne "1") {
530
                 ThrowUserError("illegal_attachment_is_patch");
531 532
             }
             if ($field eq "isobsolete" && $v ne "0" && $v ne "1") {
533
                 ThrowUserError("illegal_is_obsolete");
534 535 536
             }
             $f = "$table.$field";
         },
537 538 539 540 541 542 543 544
         "^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.
545
             return if ($t =~ m/^changed/);
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
             
             # 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 $flags " . 
                               "ON bugs.bug_id = $flags.bug_id");
             my $flagtypes = "flagtypes_$chartid";
             push(@supptables, "LEFT JOIN flagtypes $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 = "CONCAT($flagtypes.name, $flags.status)";
             &{$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/) {
                push(@fields, "SUM($ff IS NOT NULL) AS allflags_$chartid");
                push(@fields, "SUM($term) AS matchingflags_$chartid");
                push(@having, "allflags_$chartid = matchingflags_$chartid");
                $term = "0=0";
575 576
             }
         },
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
         "^requesters.login_name," => sub {
             push(@supptables, "flags flags_$chartid");
             push(@wherepart, "bugs.bug_id = flags_$chartid.bug_id");
             push(@supptables, "profiles requesters_$chartid");
             push(@wherepart, "flags_$chartid.requester_id = requesters_$chartid.userid");
             $f = "requesters_$chartid.login_name";
         },
         "^setters.login_name," => sub {
             push(@supptables, "flags flags_$chartid");
             push(@wherepart, "bugs.bug_id = flags_$chartid.bug_id");
             push(@supptables, "profiles setters_$chartid");
             push(@wherepart, "flags_$chartid.setter_id = setters_$chartid.userid");
             $f = "setters_$chartid.login_name";
         },
         
592 593 594 595
         "^changedin," => sub {
             $f = "(to_days(now()) - to_days(bugs.delta_ts))";
         },

596
         "^component,(?!changed)" => sub {
597 598 599 600 601 602
             $f = $ff = "components.name";
             $funcsbykey{",$t"}->();
             $term = build_subselect("bugs.component_id",
                                     "components.id",
                                     "components",
                                     $term);
603 604 605
         },

         "^product,(?!changed)" => sub {
606 607 608 609 610 611 612
             # Generate the restriction condition
             $f = $ff = "products.name";
             $funcsbykey{",$t"}->();
             $term = build_subselect("bugs.product_id",
                                     "products.id",
                                     "products",
                                     $term);
613 614
         },

615 616 617 618 619 620 621 622 623 624 625 626 627
         "^keywords," => sub {
             &::GetVersionTable();
             my @list;
             my $table = "keywords_$chartid";
             foreach my $value (split(/[\s,]+/, $v)) {
                 if ($value eq '') {
                     next;
                 }
                 my $id = &::GetKeywordIdFromName($value);
                 if ($id) {
                     push(@list, "$table.keywordid = $id");
                 }
                 else {
628 629
                     ThrowUserError("unknown_keyword",
                                    { keyword => $v });
630 631 632 633 634 635 636 637
                 }
             }
             my $haveawordterm;
             if (@list) {
                 $haveawordterm = "(" . join(' OR ', @list) . ")";
                 if ($t eq "anywords") {
                     $term = $haveawordterm;
                 } elsif ($t eq "allwords") {
638
                     my $ref = $funcsbykey{",$t"};
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
                     &$ref;
                     if ($term && $haveawordterm) {
                         $term = "(($term) AND $haveawordterm)";
                     }
                 }
             }
             if ($term) {
                 push(@supptables, "keywords $table");
                 push(@wherepart, "$table.bug_id = bugs.bug_id");
             }
         },

         "^dependson," => sub {
                my $table = "dependson_" . $chartid;
                push(@supptables, "dependencies $table");
                $ff = "$table.$f";
655
                my $ref = $funcsbykey{",$t"};
656 657 658 659 660 661 662 663
                &$ref;
                push(@wherepart, "$table.blocked = bugs.bug_id");
         },

         "^blocked," => sub {
                my $table = "blocked_" . $chartid;
                push(@supptables, "dependencies $table");
                $ff = "$table.$f";
664
                my $ref = $funcsbykey{",$t"};
665 666 667 668 669 670 671 672 673 674 675 676 677 678
                &$ref;
                push(@wherepart, "$table.dependson = bugs.bug_id");
         },


         ",equals" => sub {
             $term = "$ff = $q";
         },
         ",notequals" => sub {
             $term = "$ff != $q";
         },
         ",casesubstring" => sub {
             $term = "INSTR($ff, $q)";
         },
679
         ",substring" => sub {
680 681
             $term = "INSTR(LOWER($ff), " . lc($q) . ")";
         },
682 683 684
         ",substr" => sub {
             $funcsbykey{",substring"}->();
         },
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
         ",notsubstring" => sub {
             $term = "INSTR(LOWER($ff), " . lc($q) . ") = 0";
         },
         ",regexp" => sub {
             $term = "LOWER($ff) REGEXP $q";
         },
         ",notregexp" => sub {
             $term = "LOWER($ff) NOT REGEXP $q";
         },
         ",lessthan" => sub {
             $term = "$ff < $q";
         },
         ",greaterthan" => sub {
             $term = "$ff > $q";
         },
         ",anyexact" => sub {
             my @list;
             foreach my $w (split(/,/, $v)) {
                 if ($w eq "---" && $f !~ /milestone/) {
                     $w = "";
                 }
706 707 708 709
                 push(@list, &::SqlQuote($w));
             }
             if (@list) {
                 $term = "$ff IN (" . join (',', @list) . ")";
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
             }
         },
         ",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) . ")";
             }
         },
         ",changedbefore" => sub {
             my $table = "act_$chartid";
             my $ftable = "fielddefs_$chartid";
             push(@supptables, "bugs_activity $table");
             push(@supptables, "fielddefs $ftable");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             push(@wherepart, "$table.fieldid = $ftable.fieldid");
             $term = "($ftable.name = '$f' AND $table.bug_when < $q)";
         },
         ",changedafter" => sub {
             my $table = "act_$chartid";
             my $ftable = "fielddefs_$chartid";
             push(@supptables, "bugs_activity $table");
             push(@supptables, "fielddefs $ftable");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             push(@wherepart, "$table.fieldid = $ftable.fieldid");
             $term = "($ftable.name = '$f' AND $table.bug_when > $q)";
         },
         ",changedfrom" => sub {
             my $table = "act_$chartid";
             my $ftable = "fielddefs_$chartid";
             push(@supptables, "bugs_activity $table");
             push(@supptables, "fielddefs $ftable");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             push(@wherepart, "$table.fieldid = $ftable.fieldid");
             $term = "($ftable.name = '$f' AND $table.removed = $q)";
         },
         ",changedto" => sub {
             my $table = "act_$chartid";
             my $ftable = "fielddefs_$chartid";
             push(@supptables, "bugs_activity $table");
             push(@supptables, "fielddefs $ftable");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             push(@wherepart, "$table.fieldid = $ftable.fieldid");
             $term = "($ftable.name = '$f' AND $table.added = $q)";
         },
         ",changedby" => sub {
             my $table = "act_$chartid";
             my $ftable = "fielddefs_$chartid";
             push(@supptables, "bugs_activity $table");
             push(@supptables, "fielddefs $ftable");
             push(@wherepart, "$table.bug_id = bugs.bug_id");
             push(@wherepart, "$table.fieldid = $ftable.fieldid");
             my $id = &::DBNameToIdAndCheck($v);
             $term = "($ftable.name = '$f' AND $table.who = $id)";
         },
         );
    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
799
    my @badcharts = grep /^(field|type|value)-1-/, $params->param();
800
    foreach my $field (@badcharts) {
801
        $params->delete($field);
802 803 804 805 806 807 808 809
    }

    # 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) {
810 811 812
            $params->param("field$chart-$row-$col", shift(@$ref));
            $params->param("type$chart-$row-$col", shift(@$ref));
            $params->param("value$chart-$row-$col", shift(@$ref));
813
            if ($debug) {
814
                print qq{<p>$params->param("field$chart-$row-$col") | $params->param("type$chart-$row-$col") | $params->param("value$chart-$row-$col")*</p>\n};
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
            }
            $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".
#
836
# Each chart consists of an arbitrary number of rows and columns.
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
# 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.
863
# This will find bugs with one CC matching 'foo@blah.org' and and another
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
# 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
# --------------------------------------------------------------

886
# $chartid is the number of the current chart whose SQL we're constructing
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
# $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
# $q  = sanitized version of user input (SqlQuote($v))
# @supptables = Tables and/or table aliases used in query
# %suppseen   = A hash used to store all the tables in supptables to weed
#               out duplicates.
# $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
    my %chartfields;
    &::SendSQL("SELECT name FROM fielddefs");
    while (&::MoreSQLData()) {
        my ($name) = &::FetchSQLData();
        $chartfields{$name} = 1;
    }

    $row = 0;
    for ($chart=-1 ;
913
         $chart < 0 || $params->param("field$chart-0-0") ;
914 915 916
         $chart++) {
        $chartid = $chart >= 0 ? $chart : "";
        for ($row = 0 ;
917
             $params->param("field$chart-$row-0") ;
918 919 920
             $row++) {
            my @orlist;
            for (my $col = 0 ;
921
                 $params->param("field$chart-$row-$col") ;
922
                 $col++) {
923 924 925
                $f = $params->param("field$chart-$row-$col") || "noop";
                $t = $params->param("type$chart-$row-$col") || "noop";
                $v = $params->param("value$chart-$row-$col");
926
                $v = "" if !defined $v;
927
                $v = trim($v);
928 929 930 931 932 933
                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)) {
934
                    ThrowCodeError("invalid_field_name", {field => $f});
935 936 937 938
                }

                # This is either from the internal chart (in which case we
                # already know about it), or it was in %chartfields, so it is
939
                # a valid field name, which means that it's ok.
940
                trick_taint($f);
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
                $q = &::SqlQuote($v);
                my $func;
                $term = undef;
                foreach my $key (@funcnames) {
                    if ("$f,$t" =~ m/$key/) {
                        my $ref = $funcsbykey{$key};
                        if ($debug) {
                            print "<p>$key ($f , $t ) => ";
                        }
                        $ff = $f;
                        if ($f !~ /\./) {
                            $ff = "bugs.$f";
                        }
                        &$ref;
                        if ($debug) {
                            print "$f , $t , $term</p>";
                        }
                        if ($term) {
                            last;
                        }
                    }
                }
                if ($term) {
                    push(@orlist, $term);
                }
                else {
967
                    # This field and this type don't work together.
968 969 970 971
                    ThrowCodeError("field_type_mismatch",
                                   { field => $params->param("field$chart-$row-$col"),
                                     type => $params->param("type$chart-$row-$col"),
                                   });
972 973 974
                }
            }
            if (@orlist) {
975
                @orlist = map("($_)", @orlist) if (scalar(@orlist) > 1);
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
                push(@andlist, "(" . join(" OR ", @orlist) . ")");
            }
        }
    }
    my %suppseen = ("bugs" => 1);
    my $suppstring = "bugs";
    foreach my $str (@supptables) {
        if (!$suppseen{$str}) {
            if ($str !~ /^(LEFT|INNER) JOIN/i) {
                $suppstring .= ",";
            }
            $suppstring .= " $str";
            $suppseen{$str} = 1;
        }
    }
991 992 993
    
    # Make sure we create a legal SQL query.
    @andlist = ("1 = 1") if !@andlist;
994 995 996 997 998 999
   
    my $query = "SELECT " . join(', ', @fields) .
                " FROM $suppstring" .
                " LEFT JOIN bug_group_map " .
                " ON bug_group_map.bug_id = bugs.bug_id ";

1000 1001 1002 1003
    if ($user) {
        if (%{$user->groups}) {
            $query .= " AND bug_group_map.group_id NOT IN (" . join(',', values(%{$user->groups})) . ") ";
        }
1004

1005
        $query .= " LEFT JOIN cc ON cc.bug_id = bugs.bug_id AND cc.who = " . $user->id;
1006 1007 1008 1009 1010
    }

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

1011 1012 1013
    if ($user) {
        my $userid = $user->id;
        $query .= "    OR (bugs.reporter_accessible = 1 AND bugs.reporter = $userid) " .
1014
              "    OR (bugs.cclist_accessible = 1 AND cc.who IS NOT NULL) " .
1015
              "    OR (bugs.assigned_to = $userid) ";
1016
        if (Param('useqacontact')) {
1017
            $query .= "OR (bugs.qa_contact = $userid) ";
1018 1019 1020 1021 1022 1023 1024 1025 1026
        }
    }

    $query .= ") GROUP BY bugs.bug_id";

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

1027
    if ($debug) {
1028
        print "<p><code>" . value_quote($query) . "</code></p>\n";
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        exit;
    }
    
    $self->{'sql'} = $query;
}

###############################################################################
# Helper functions for the init() method.
###############################################################################
sub SqlifyDate {
    my ($str) = @_;
    $str = "" if !defined $str;
1041 1042 1043 1044
    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);
    }
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    if ($str =~ /^-?(\d+)([dDwWmMyY])$/) {   # relative date
        my ($amount, $unit, $date) = ($1, lc $2, time);
        my ($sec, $min, $hour, $mday, $month, $year, $wday)  = localtime($date);
        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);
        }
        return undef;                      # should not happen due to regexp at top
    }
    my $date = str2time($str);
    if (!defined($date)) {
1068
        ThrowUserError("illegal_date", { date => $str });
1069 1070 1071 1072
    }
    return time2str("%Y-%m-%d %H:%M:%S", $date);
}

1073 1074
# ListIDsForEmail returns a string with a comma-joined list
# of userids matching email addresses
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
# according to the type specified.
# Currently, this only supports anyexact and substring matches.
# Substring matches will return up to 50 matching userids
# 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;
    my @list = ();
    my $list = "---";
    if ($type eq 'anyexact') {
        foreach my $w (split(/,/, $email)) {
            $w = trim($w);
            my $id = &::DBname_to_id($w);
            if ($id > 0) {
                push(@list,$id)
            }
        }
        $list = join(',', @list);
    } elsif ($type eq 'substring') {
        &::SendSQL("SELECT userid FROM profiles WHERE INSTR(login_name, " .
            &::SqlQuote($email) . ") LIMIT 51");
        while (&::MoreSQLData()) {
            my ($id) = &::FetchSQLData();
            push(@list, $id);
        }
        if (@list < 50) {
            $list = join(',', @list);
        }
    }
    $self->{"emailcache"}{"$type,$email"} = $list;
    return undef if ($list eq "---");
    return $list;
}

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
sub build_subselect {
    my ($outer, $inner, $table, $cond) = @_;
    my $q = "SELECT $inner FROM $table WHERE $cond";
    #return "$outer IN ($q)";
    &::SendSQL($q);
    my @list;
    while (&::MoreSQLData()) {
        push (@list, &::FetchOneColumn());
    }
    return "1=2" unless @list; # Could use boolean type on dbs which support it
    return "$outer IN (" . join(',', @list) . ")";
}

1125 1126 1127 1128 1129 1130 1131 1132
sub GetByWordList {
    my ($field, $strs) = (@_);
    my @list;

    foreach my $w (split(/[\s,]+/, $strs)) {
        my $word = $w;
        if ($word ne "") {
            $word =~ tr/A-Z/a-z/;
1133
            $word = &::SqlQuote(quotemeta($word));
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
            $word =~ s/^'//;
            $word =~ s/'$//;
            $word = '(^|[^a-z0-9])' . $word . '($|[^a-z0-9])';
            push(@list, "lower($field) regexp '$word'");
        }
    }

    return \@list;
}

# Support for "any/all/nowordssubstr" comparison type ("words as substrings")
sub GetByWordListSubstr {
    my ($field, $strs) = (@_);
    my @list;

    foreach my $word (split(/[\s,]+/, $strs)) {
        if ($word ne "") {
1151
            push(@list, "INSTR(LOWER($field), " . lc(&::SqlQuote($word)) . ")");
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        }
    }

    return \@list;
}

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

1;