Search.pm 96.2 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7 8 9 10

use strict;

package Bugzilla::Search;
11
use base qw(Exporter);
12 13 14 15
@Bugzilla::Search::EXPORT = qw(
    IsValidQueryType
    split_order_term
);
16

17
use Bugzilla::Error;
18
use Bugzilla::Util;
19
use Bugzilla::Constants;
20
use Bugzilla::Group;
21
use Bugzilla::User;
22
use Bugzilla::Field;
23
use Bugzilla::Search::Clause;
24
use Bugzilla::Search::Condition qw(condition);
25
use Bugzilla::Status;
26
use Bugzilla::Keyword;
27

28
use Data::Dumper;
29
use Date::Format;
30
use Date::Parse;
31
use Scalar::Util qw(blessed);
32
use List::MoreUtils qw(all part uniq);
33
use POSIX qw(INT_MAX);
34 35
use Storable qw(dclone);

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
# Description Of Boolean Charts
# -----------------------------
#
# 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 three-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".
#
# Each chart consists of an arbitrary number of rows and columns.
# 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.
# This will find bugs with one CC matching 'foo@blah.org' and and another
# 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
# --------------------------------------------------------------

102 103 104 105
#############
# Constants #
#############

106 107 108
# When doing searches, NULL datetimes are treated as this date.
use constant EMPTY_DATETIME => '1970-01-01 00:00:00';

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
# This is the regex for real numbers from Regexp::Common, modified to be
# more readable.
use constant NUMBER_REGEX => qr/
    ^[+-]?      # A sign, optionally.

    (?=\d|\.)   # Then either a digit or "."
    \d*         # Followed by many other digits
    (?:
        \.      # Followed possibly by some decimal places
        (?:\d*)
    )?
 
    (?:         # Followed possibly by an exponent.
        [Ee]
        [+-]?
        \d+
    )?
    $
/x;

129 130 131
# If you specify a search type in the boolean charts, this describes
# which operator maps to which internal function here.
use constant OPERATORS => {
132 133
    equals         => \&_simple_operator,
    notequals      => \&_simple_operator,
134 135 136 137 138 139
    casesubstring  => \&_casesubstring,
    substring      => \&_substring,
    substr         => \&_substring,
    notsubstring   => \&_notsubstring,
    regexp         => \&_regexp,
    notregexp      => \&_notregexp,
140 141
    lessthan       => \&_simple_operator,
    lessthaneq     => \&_simple_operator,
142 143
    matches        => sub { ThrowUserError("search_content_without_matches"); },
    notmatches     => sub { ThrowUserError("search_content_without_matches"); },
144 145
    greaterthan    => \&_simple_operator,
    greaterthaneq  => \&_simple_operator,
146 147 148 149 150 151 152 153 154 155 156
    anyexact       => \&_anyexact,
    anywordssubstr => \&_anywordsubstr,
    allwordssubstr => \&_allwordssubstr,
    nowordssubstr  => \&_nowordssubstr,
    anywords       => \&_anywords,
    allwords       => \&_allwords,
    nowords        => \&_nowords,
    changedbefore  => \&_changedbefore_changedafter,
    changedafter   => \&_changedbefore_changedafter,
    changedfrom    => \&_changedfrom_changedto,
    changedto      => \&_changedfrom_changedto,
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    changedby      => \&_changedby,
};

# Some operators are really just standard SQL operators, and are
# all implemented by the _simple_operator function, which uses this
# constant.
use constant SIMPLE_OPERATORS => {
    equals        => '=',
    notequals     => '!=',
    greaterthan   => '>',
    greaterthaneq => '>=',
    lessthan      => '<',
    lessthaneq    => "<=",
};

# Most operators just reverse by removing or adding "not" from/to them.
# However, some operators reverse in a different way, so those are listed
# here.
use constant OPERATOR_REVERSE => {
    nowords        => 'anywords',
    nowordssubstr  => 'anywordssubstr',
    anywords       => 'nowords',
    anywordssubstr => 'nowordssubstr',
    lessthan       => 'greaterthaneq',
    lessthaneq     => 'greaterthan',
    greaterthan    => 'lessthaneq',
    greaterthaneq  => 'lessthan',
    # The following don't currently have reversals:
    # casesubstring, anyexact, allwords, allwordssubstr
186 187
};

188 189 190 191 192 193 194 195 196 197 198
# For these operators, even if a field is numeric (is_numeric returns true),
# we won't treat the input like a number.
use constant NON_NUMERIC_OPERATORS => qw(
    changedafter
    changedbefore
    changedfrom
    changedto
    regexp
    notregexp
);

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
use constant MULTI_SELECT_OVERRIDE => {
    notequals      => \&_multiselect_negative,
    notregexp      => \&_multiselect_negative,
    notsubstring   => \&_multiselect_negative,
    nowords        => \&_multiselect_negative,
    nowordssubstr  => \&_multiselect_negative,
    
    allwords       => \&_multiselect_multiple,
    allwordssubstr => \&_multiselect_multiple,
    anyexact       => \&_multiselect_multiple,
    anywords       => \&_multiselect_multiple,
    anywordssubstr => \&_multiselect_multiple,
    
    _non_changed    => \&_multiselect_nonchanged,
};

215 216 217
use constant OPERATOR_FIELD_OVERRIDE => {
    # User fields
    'attachments.submitter' => {
218
        _non_changed => \&_user_nonchanged,
219 220
    },
    assigned_to => {
221
        _non_changed => \&_user_nonchanged,
222 223
    },
    cc => {
224
        _non_changed => \&_user_nonchanged,
225 226
    },
    commenter => {
227
        _non_changed => \&_user_nonchanged,
228
    },
229
    reporter => {
230
        _non_changed => \&_user_nonchanged,
231
    },
232
    'requestees.login_name' => {
233
        _non_changed => \&_user_nonchanged,
234 235
    },
    'setters.login_name' => {
236 237
        _non_changed => \&_user_nonchanged,    
    },
238
    qa_contact => {
239
        _non_changed => \&_user_nonchanged,
240 241 242
    },
    
    # General Bug Fields
243
    alias        => { _non_changed => \&_nullable },
244
    'attach_data.thedata' => MULTI_SELECT_OVERRIDE,
245 246 247 248 249
    # We check all attachment fields against this.
    attachments  => MULTI_SELECT_OVERRIDE,
    blocked      => MULTI_SELECT_OVERRIDE,
    bug_file_loc => { _non_changed => \&_nullable },
    bug_group    => MULTI_SELECT_OVERRIDE,
250 251 252 253 254 255 256 257 258 259 260 261
    classification => {
        _non_changed => \&_classification_nonchanged,
    },
    component => {
        _non_changed => \&_component_nonchanged,
    },
    content => {
        matches    => \&_content_matches,
        notmatches => \&_content_matches,
        _default   => sub { ThrowUserError("search_content_without_matches"); },
    },
    days_elapsed => {
262
        _default => \&_days_elapsed,
263
    },
264 265 266
    dependson        => MULTI_SELECT_OVERRIDE,
    keywords         => MULTI_SELECT_OVERRIDE,
    'flagtypes.name' => MULTI_SELECT_OVERRIDE,
267
    longdesc => {
268
        %{ MULTI_SELECT_OVERRIDE() },
269 270 271 272
        changedby     => \&_long_desc_changedby,
        changedbefore => \&_long_desc_changedbefore_after,
        changedafter  => \&_long_desc_changedbefore_after,
    },
273 274 275 276 277 278 279 280
    'longdescs.count' => {
        changedby     => \&_long_desc_changedby,
        changedbefore => \&_long_desc_changedbefore_after,
        changedafter  => \&_long_desc_changedbefore_after,
        changedfrom   => \&_invalid_combination,
        changedto     => \&_invalid_combination,
        _default      => \&_long_descs_count,
    },
281
    'longdescs.isprivate' => MULTI_SELECT_OVERRIDE,
282 283 284 285 286
    owner_idle_time => {
        greaterthan   => \&_owner_idle_time_greater_less,
        greaterthaneq => \&_owner_idle_time_greater_less,
        lessthan      => \&_owner_idle_time_greater_less,
        lessthaneq    => \&_owner_idle_time_greater_less,
287
        _default      => \&_invalid_combination,
288 289 290 291
    },
    product => {
        _non_changed => \&_product_nonchanged,
    },
292
    tag => MULTI_SELECT_OVERRIDE,
293 294
    
    # Timetracking Fields
295
    deadline => { _non_changed => \&_deadline },
296
    percentage_complete => {
297
        _non_changed => \&_percentage_complete,
298 299 300 301 302 303 304 305
    },
    work_time => {
        changedby     => \&_work_time_changedby,
        changedbefore => \&_work_time_changedbefore_after,
        changedafter  => \&_work_time_changedbefore_after,
        _default      => \&_work_time,
    },
    
306 307 308 309 310 311 312
    # Custom Fields
    FIELD_TYPE_FREETEXT, { _non_changed => \&_nullable },
    FIELD_TYPE_BUG_ID,   { _non_changed => \&_nullable_int },
    FIELD_TYPE_DATETIME, { _non_changed => \&_nullable_datetime },
    FIELD_TYPE_TEXTAREA, { _non_changed => \&_nullable },
    FIELD_TYPE_MULTI_SELECT, MULTI_SELECT_OVERRIDE,
    FIELD_TYPE_BUG_URLS,     MULTI_SELECT_OVERRIDE,    
313 314 315 316 317 318 319
};

# These are fields where special action is taken depending on the
# *value* passed in to the chart, sometimes.
use constant SPECIAL_PARSING => {
    # Pronoun Fields (Ones that can accept %user%, etc.)
    assigned_to => \&_contact_pronoun,
320 321
    cc          => \&_contact_pronoun,
    commenter   => \&_contact_pronoun,
322 323
    qa_contact  => \&_contact_pronoun,
    reporter    => \&_contact_pronoun,
324 325 326
    'setters.login_name' => \&_contact_pronoun,
    'requestees.login_name' => \&_contact_pronoun,

327 328 329 330 331 332
    # Date Fields that accept the 1d, 1w, 1m, 1y, etc. format.
    creation_ts => \&_timestamp_translate,
    deadline    => \&_timestamp_translate,
    delta_ts    => \&_timestamp_translate,
};

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
# Information about fields that represent "users", used by _user_nonchanged.
# There are other user fields than the ones listed here, but those use
# defaults in _user_nonchanged.
use constant USER_FIELDS => {
    'attachments.submitter' => {
        field    => 'submitter_id',
        join     => { table => 'attachments' },
        isprivate => 1,
    },
    cc => {
        field => 'who',
        join  => { table => 'cc' },
    },
    commenter => {
        field => 'who',
        join  => { table => 'longdescs', join => 'INNER' },
        isprivate => 1,
    },
    qa_contact => {
        nullable => 1,
    },
    'requestees.login_name' => {
        nullable => 1,
        field    => 'requestee_id',
        join     => { table => 'flags' },
    },
    'setters.login_name' => {
        field    => 'setter_id',
        join     => { table => 'flags' },
    },
};

365 366
# Backwards compatibility for times that we changed the names of fields
# or URL parameters.
367
use constant FIELD_MAP => {
368
    'attachments.thedata' => 'attach_data.thedata',
369
    bugidtype => 'bug_id_type',
370
    changedin => 'days_elapsed',
371 372 373
    long_desc => 'longdesc',
};

374
# Some fields are not sorted on themselves, but on other fields.
375
# We need to have a list of these fields and what they map to.
376
use constant SPECIAL_ORDER => {
377 378 379 380 381 382
    'target_milestone' => {
        order => ['map_target_milestone.sortkey','map_target_milestone.value'],
        join  => {
            table => 'milestones',
            from  => 'target_milestone',
            to    => 'value',
383
            extra => ['bugs.product_id = map_target_milestone.product_id'],
384 385 386
            join  => 'INNER',
        }
    },
387
};
388

389
# Certain columns require other columns to come before them
390
# in _select_columns, and should be put there if they're not there.
391 392 393 394 395 396 397 398 399
use constant COLUMN_DEPENDS => {
    classification      => ['product'],
    percentage_complete => ['actual_time', 'remaining_time'],
};

# This describes tables that must be joined when you want to display
# certain columns in the buglist. For the most part, Search.pm uses
# DB::Schema to figure out what needs to be joined, but for some
# fields it needs a little help.
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
sub COLUMN_JOINS {
    my $invocant = shift;
    my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;

    my $joins = {
        actual_time => {
            table => '(SELECT bug_id, SUM(work_time) AS total'
                     . ' FROM longdescs GROUP BY bug_id)',
            join  => 'INNER',
        },
        assigned_to => {
            from  => 'assigned_to',
            to    => 'userid',
            table => 'profiles',
            join  => 'INNER',
        },
        reporter => {
            from  => 'reporter',
            to    => 'userid',
            table => 'profiles',
            join  => 'INNER',
        },
        qa_contact => {
            from  => 'qa_contact',
            to    => 'userid',
            table => 'profiles',
        },
        component => {
            from  => 'component_id',
429
            to    => 'id',
430 431
            table => 'components',
            join  => 'INNER',
432
        },
433 434
        product => {
            from  => 'product_id',
435
            to    => 'id',
436 437
            table => 'products',
            join  => 'INNER',
438
        },
439 440 441 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
        classification => {
            table => 'classifications',
            from  => 'map_product.classification_id',
            to    => 'id',
            join  => 'INNER',
        },
        'flagtypes.name' => {
            as    => 'map_flags',
            table => 'flags',
            extra => ['map_flags.attach_id IS NULL'],
            then_to => {
                as    => 'map_flagtypes',
                table => 'flagtypes',
                from  => 'map_flags.type_id',
                to    => 'id',
            },
        },
        keywords => {
            table => 'keywords',
            then_to => {
                as    => 'map_keyworddefs',
                table => 'keyworddefs',
                from  => 'map_keywords.keywordid',
                to    => 'id',
            },
        },
        'longdescs.count' => {
            table => 'longdescs',
            join  => 'INNER',
        },
        tag => {
            as => 'map_bug_tag',
            table => 'bug_tag',
            then_to => {
                as => 'map_tag',
                table => 'tag',
                extra => ['map_tag.user_id = ' . $user->id],
                from => 'map_bug_tag.tag_id',
                to => 'id',
            },
        }
    };
    return $joins;
482 483
};

484 485 486 487 488 489 490 491 492 493 494 495
# This constant defines the columns that can be selected in a query 
# and/or displayed in a bug list.  Column records include the following
# fields:
#
# 1. id: a unique identifier by which the column is referred in code;
#
# 2. name: The name of the column in the database (may also be an expression
#          that returns the value of the column);
#
# 3. title: The title of the column as displayed to users.
# 
# Note: There are a few hacks in the code that deviate from these definitions.
496 497
#       In particular, the redundant short_desc column is removed when the
#       client requests "all" columns.
498 499 500 501 502 503 504
#
# This is really a constant--that is, once it's been called once, the value
# will always be the same unless somebody adds a new custom field. But
# we have to do a lot of work inside the subroutine to get the data,
# and we don't want it to happen at compile time, so we have it as a
# subroutine.
sub COLUMNS {
505 506
    my $invocant = shift;
    my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;
507 508
    my $dbh = Bugzilla->dbh;
    my $cache = Bugzilla->request_cache;
509 510 511 512

    if (defined $cache->{search_columns}->{$user->id}) {
        return $cache->{search_columns}->{$user->id};
    }
513 514 515 516 517 518 519 520 521 522 523 524 525

    # These are columns that don't exist in fielddefs, but are valid buglist
    # columns. (Also see near the bottom of this function for the definition
    # of short_short_desc.)
    my %columns = (
        relevance            => { title => 'Relevance'  },
        assigned_to_realname => { title => 'Assignee'   },
        reporter_realname    => { title => 'Reporter'   },
        qa_contact_realname  => { title => 'QA Contact' },
    );

    # Next we define columns that have special SQL instead of just something
    # like "bugs.bug_id".
526
    my $total_time = "(map_actual_time.total + bugs.remaining_time)";
527 528
    my %special_sql = (
        deadline    => $dbh->sql_date_format('bugs.deadline', '%Y-%m-%d'),
529
        actual_time => 'map_actual_time.total',
530

531 532 533 534
        # "FLOOR" is in there to turn this into an integer, making searches
        # totally predictable. Otherwise you get floating-point numbers that
        # are rather hard to search reliably if you're asking for exact
        # numbers.
535
        percentage_complete =>
536 537 538 539
            "(CASE WHEN $total_time = 0"
               . " THEN 0"
               . " ELSE FLOOR(100 * (map_actual_time.total / $total_time))"
                . " END)",
540

541
        'flagtypes.name' => $dbh->sql_group_concat('DISTINCT ' 
542
            . $dbh->sql_string_concat('map_flagtypes.name', 'map_flags.status')),
543

544
        'keywords' => $dbh->sql_group_concat('DISTINCT map_keyworddefs.name'),
545 546
        
        'longdescs.count' => 'COUNT(DISTINCT map_longdescs_count.comment_id)',
547

548
        tag => $dbh->sql_group_concat('DISTINCT map_tag.name'),
549 550 551
    );

    # Backward-compatibility for old field names. Goes new_name => old_name.
552
    # These are here and not in _translate_old_column because the rest of the
553
    # code actually still uses the old names, while the fielddefs table uses
554 555
    # the new names (which is not the case for the fields handled by
    # _translate_old_column).
556 557 558 559 560 561 562 563 564 565 566 567 568 569
    my %old_names = (
        creation_ts => 'opendate',
        delta_ts    => 'changeddate',
        work_time   => 'actual_time',
    );

    # Fields that are email addresses
    my @email_fields = qw(assigned_to reporter qa_contact);
    # Other fields that are stored in the bugs table as an id, but
    # should be displayed using their name.
    my @id_fields = qw(product component classification);

    foreach my $col (@email_fields) {
        my $sql = "map_${col}.login_name";
570
        if (!$user->id) {
571 572 573 574 575 576 577
             $sql = $dbh->sql_string_until($sql, $dbh->quote('@'));
        }
        $special_sql{$col} = $sql;
        $columns{"${col}_realname"}->{name} = "map_${col}.realname";
    }

    foreach my $col (@id_fields) {
578
        $special_sql{$col} = "map_${col}.name";
579 580 581
    }

    # Do the actual column-getting from fielddefs, now.
582 583
    my @fields = @{ Bugzilla->fields({ obsolete => 0, buglist => 1 }) };
    foreach my $field (@fields) {
584 585
        my $id = $field->name;
        $id = $old_names{$id} if exists $old_names{$id};
586 587 588 589 590 591
        my $sql;
        if (exists $special_sql{$id}) {
            $sql = $special_sql{$id};
        }
        elsif ($field->type == FIELD_TYPE_MULTI_SELECT) {
            $sql = $dbh->sql_group_concat(
592
                'DISTINCT map_' . $field->name . '.value');
593 594 595 596
        }
        else {
            $sql = 'bugs.' . $field->name;
        }
597 598 599 600 601 602
        $columns{$id} = { name => $sql, title => $field->description };
    }

    # The short_short_desc column is identical to short_desc
    $columns{'short_short_desc'} = $columns{'short_desc'};

603
    Bugzilla::Hook::process('buglist_columns', { columns => \%columns });
604

605 606
    $cache->{search_columns}->{$user->id} = \%columns;
    return $cache->{search_columns}->{$user->id};
607 608
}

609
sub REPORT_COLUMNS {
610 611 612 613
    my $invocant = shift;
    my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;

    my $columns = dclone(blessed($invocant) ? $invocant->COLUMNS : COLUMNS);
614 615 616 617 618 619 620 621
    # There's no reason to support reporting on unique fields.
    # Also, some other fields don't make very good reporting axises,
    # or simply don't work with the current reporting system.
    my @no_report_columns = 
        qw(bug_id alias short_short_desc opendate changeddate
           flagtypes.name keywords relevance);

    # Multi-select fields are not currently supported.
622 623
    my @multi_selects = @{Bugzilla->fields(
        { obsolete => 0, type => FIELD_TYPE_MULTI_SELECT })};
624 625 626 627
    push(@no_report_columns, map { $_->name } @multi_selects);

    # If you're not a time-tracker, you can't use time-tracking
    # columns.
628
    if (!$user->is_timetracker) {
629 630 631 632 633 634 635 636 637
        push(@no_report_columns, TIMETRACKING_FIELDS);
    }

    foreach my $name (@no_report_columns) {
        delete $columns->{$name};
    }
    return $columns;
}

638 639 640
# These are fields that never go into the GROUP BY on any DB. bug_id
# is here because it *always* goes into the GROUP BY as the first item,
# so it should be skipped when determining extra GROUP BY columns.
641
use constant GROUP_BY_SKIP => qw(
642 643 644
    bug_id
    flagtypes.name
    keywords
645
    longdescs.count
646
    percentage_complete
Frédéric Buclin's avatar
Frédéric Buclin committed
647
    tag
648 649
);

650 651 652 653 654 655 656 657 658 659 660 661
###############
# Constructor #
###############

# Note that the params argument may be modified by Bugzilla::Search
sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
  
    my $self = { @_ };
    bless($self, $class);
    $self->{'user'} ||= Bugzilla->user;
662 663 664 665 666 667 668 669 670 671 672 673 674
    
    # There are certain behaviors of the CGI "Vars" hash that we don't want.
    # In particular, if you put a single-value arrayref into it, later you
    # get back out a string, which breaks anyexact charts (because they
    # need arrays even for individual items, or we will re-trigger bug 67036).
    #
    # We can't just untie the hash--that would give us a hash with no values.
    # We have to manually copy the hash into a new one, and we have to always
    # do it, because there's no way to know if we were passed a tied hash
    # or not.
    my $params_in = $self->_params;
    my %params = map { $_ => $params_in->{$_} } keys %$params_in;
    $self->{params} = \%params;
675 676 677 678 679 680 681 682 683 684 685 686 687 688

    return $self;
}


####################
# Public Accessors #
####################

sub sql {
    my ($self) = @_;
    return $self->{sql} if $self->{sql};
    my $dbh = Bugzilla->dbh;
    
689
    my ($joins, $clause) = $self->_charts_to_conditions();
690 691
    my $select = join(', ', $self->_sql_select);
    my $from = $self->_sql_from($joins);
692
    my $where = $self->_sql_where($clause);
693 694 695
    my $group_by = $dbh->sql_group_by($self->_sql_group_by);
    my $order_by = $self->_sql_order_by
                   ? "\nORDER BY " . join(', ', $self->_sql_order_by) : '';
696 697
    my $limit = $self->_sql_limit;
    $limit = "\n$limit" if $limit;
698 699 700 701 702
    
    my $query = <<END;
SELECT $select
  FROM $from
 WHERE $where
703
$group_by$order_by$limit
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
END
    $self->{sql} = $query;
    return $self->{sql};
}

sub search_description {
    my ($self, $params) = @_;
    my $desc = $self->{'search_description'} ||= [];
    if ($params) {
        push(@$desc, $params);
    }
    # Make sure that the description has actually been generated if
    # people are asking for the whole thing.
    else {
        $self->sql;
    }
    return $self->{'search_description'};
}

723 724
sub boolean_charts_to_custom_search {
    my ($self, $cgi_buffer) = @_;
725 726
    my $boolean_charts = $self->_boolean_charts;
    my @as_params = $boolean_charts ? $boolean_charts->as_params : ();
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

    # We need to start our new ids after the last custom search "f" id.
    # We can just pick the last id in the array because they are sorted
    # numerically.
    my $last_id = ($self->_field_ids)[-1];
    my $count = defined($last_id) ? $last_id + 1 : 0;
    foreach my $param_set (@as_params) {
        foreach my $name (keys %$param_set) {
            my $value = $param_set->{$name};
            next if !defined $value;
            $cgi_buffer->param($name . $count, $value);
        }
        $count++;
    }
}

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
sub invalid_order_columns {
   my ($self) = @_;
   my @invalid_columns;
   foreach my $order ($self->_input_order) {
       next if defined $self->_validate_order_column($order);
       push(@invalid_columns, $order);
   }
   return \@invalid_columns;
}

sub order {
   my ($self) = @_;
   return $self->_valid_order;
}

758 759 760 761
######################
# Internal Accessors #
######################

762
# Fields that are legal for boolean charts of any kind.
763 764 765 766 767 768
sub _chart_fields {
    my ($self) = @_;

    if (!$self->{chart_fields}) {
        my $chart_fields = Bugzilla->fields({ by_name => 1 });

769
        if (!$self->_user->is_timetracker) {
770 771 772 773 774 775 776 777 778
            foreach my $tt_field (TIMETRACKING_FIELDS) {
                delete $chart_fields->{$tt_field};
            }
        }
        $self->{chart_fields} = $chart_fields;
    }
    return $self->{chart_fields};
}

779 780 781
# There are various places in Search.pm that we need to know the list of
# valid multi-select fields--or really, fields that are stored like
# multi-selects, which includes BUG_URLS fields.
782 783 784
sub _multi_select_fields {
    my ($self) = @_;
    $self->{multi_select_fields} ||= Bugzilla->fields({
785 786
        by_name => 1,
        type    => [FIELD_TYPE_MULTI_SELECT, FIELD_TYPE_BUG_URLS]});
787 788 789
    return $self->{multi_select_fields};
}

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
# $self->{params} contains values that could be undef, could be a string,
# or could be an arrayref. Sometimes we want that value as an array,
# always.
sub _param_array {
    my ($self, $name) = @_;
    my $value = $self->_params->{$name};
    if (!defined $value) {
        return ();
    }
    if (ref($value) eq 'ARRAY') {
        return @$value;
    }
    return ($value);
}

sub _params { $_[0]->{params} }
806
sub _user { return $_[0]->{user} }
807
sub _sharer_id { $_[0]->{sharer} }
808

809 810 811
##############################
# Internal Accessors: SELECT #
##############################
812 813 814 815 816 817 818 819 820 821

# These are the fields the user has chosen to display on the buglist,
# exactly as they were passed to new().
sub _input_columns { @{ $_[0]->{'fields'} || [] } }

# These are columns that are also going to be in the SELECT for one reason
# or another, but weren't actually requested by the caller.
sub _extra_columns {
    my ($self) = @_;
    # Everything that's going to be in the ORDER BY must also be
822
    # in the SELECT.
823
    push(@{ $self->{extra_columns} }, $self->_valid_order_columns);
824 825 826 827 828 829 830 831 832 833 834 835
    return @{ $self->{extra_columns} };
}

# For search functions to modify extra_columns. It doesn't matter if
# people push the same column onto this array multiple times, because
# _select_columns will call "uniq" on its final result.
sub _add_extra_column {
    my ($self, $column) = @_;
    push(@{ $self->{extra_columns} }, $column);
}

# These are the columns that we're going to be actually SELECTing.
836 837
sub _display_columns {
    my ($self) = @_;
838 839 840 841 842 843 844 845 846 847 848 849 850
    return @{ $self->{display_columns} } if $self->{display_columns};

    # Do not alter the list from _input_columns at all, even if there are
    # duplicated columns. Those are passed by the caller, and the caller
    # expects to get them back in the exact same order.
    my @columns = $self->_input_columns;

    # Only add columns which are not already listed.
    my %list = map { $_ => 1 } @columns;
    foreach my $column ($self->_extra_columns) {
        push(@columns, $column) unless $list{$column}++;
    }
    $self->{display_columns} = \@columns;
851 852 853 854
    return @{ $self->{display_columns} };
}

# These are the columns that are involved in the query.
855 856 857 858 859
sub _select_columns {
    my ($self) = @_;
    return @{ $self->{select_columns} } if $self->{select_columns};

    my @select_columns;
860
    foreach my $column ($self->_display_columns) {
861 862
        if (my $add_first = COLUMN_DEPENDS->{$column}) {
            push(@select_columns, @$add_first);
863
        }
864
        push(@select_columns, $column);
865
    }
866
    # Remove duplicated columns.
867 868
    $self->{select_columns} = [uniq @select_columns];
    return @{ $self->{select_columns} };
869 870
}

871
# This takes _display_columns and translates it into the actual SQL that
872 873 874 875
# will go into the SELECT clause.
sub _sql_select {
    my ($self) = @_;
    my @sql_fields;
876
    foreach my $column ($self->_display_columns) {
877 878 879
        my $alias = $column;
        # Aliases cannot contain dots in them. We convert them to underscores.
        $alias =~ s/\./_/g;
880
        my $sql = $self->COLUMNS->{$column}->{name} . " AS $alias";
881 882 883 884 885
        push(@sql_fields, $sql);
    }
    return @sql_fields;
}

886 887 888
################################
# Internal Accessors: ORDER BY #
################################
889 890 891 892

# The "order" that was requested by the consumer, exactly as it was
# requested.
sub _input_order { @{ $_[0]->{'order'} || [] } }
893 894 895 896 897 898 899
# Requested order with invalid values removed and old names translated
sub _valid_order {
    my ($self) = @_;
    return map { ($self->_validate_order_column($_)) } $self->_input_order;
}
# The valid order with just the column names, and no ASC or DESC.
sub _valid_order_columns {
900
    my ($self) = @_;
901 902 903 904 905 906 907 908
    return map { (split_order_term($_))[0] } $self->_valid_order;
}

sub _validate_order_column {
    my ($self, $order_item) = @_;

    # Translate old column names
    my ($field, $direction) = split_order_term($order_item);
909
    $field = $self->_translate_old_column($field);
910 911

    # Only accept valid columns
912
    return if (!exists $self->COLUMNS->{$field});
913 914

    # Relevance column can be used only with one or more fulltext searches
915
    return if ($field eq 'relevance' && !$self->COLUMNS->{$field}->{name});
916 917 918

    $direction = " $direction" if $direction;
    return "$field$direction";
919
}
920 921 922

# A hashref that describes all the special stuff that has to be done
# for various fields if they go into the ORDER BY clause.
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
sub _special_order {
    my ($self) = @_;
    return $self->{special_order} if $self->{special_order};
    
    my %special_order = %{ SPECIAL_ORDER() };
    my $select_fields = Bugzilla->fields({ type => FIELD_TYPE_SINGLE_SELECT });
    foreach my $field (@$select_fields) {
        next if $field->is_abnormal;
        my $name = $field->name;
        $special_order{$name} = {
            order => ["map_$name.sortkey", "map_$name.value"],
            join  => {
                table => $name,
                from  => "bugs.$name",
                to    => "value",
                join  => 'INNER',
            }
        };
    }
    $self->{special_order} = \%special_order;
    return $self->{special_order};
}

946 947 948 949
sub _sql_order_by {
    my ($self) = @_;
    if (!$self->{sql_order_by}) {
        my @order_by = map { $self->_translate_order_by_column($_) }
950
                           $self->_valid_order;
951 952 953 954 955
        $self->{sql_order_by} = \@order_by;
    }
    return @{ $self->{sql_order_by} };
}

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
sub _translate_order_by_column {
    my ($self, $order_by_item) = @_;

    my ($field, $direction) = split_order_term($order_by_item);
    
    $direction = '' if lc($direction) eq 'asc';
    my $special_order = $self->_special_order->{$field}->{order};
    # Standard fields have underscores in their SELECT alias instead
    # of a period (because aliases can't have periods).
    $field =~ s/\./_/g;
    my @items = $special_order ? @$special_order : $field;
    if (lc($direction) eq 'desc') {
        @items = map { "$_ DESC" } @items;
    }
    return @items;
}

973 974 975 976 977 978 979 980
#############################
# Internal Accessors: LIMIT #
#############################

sub _sql_limit {
    my ($self) = @_;
    my $limit = $self->_params->{limit};
    my $offset = $self->_params->{offset};
981 982 983 984 985 986
    
    my $max_results = Bugzilla->params->{'max_search_results'};
    if (!$self->{allow_unlimited} && (!$limit || $limit > $max_results)) {
        $limit = $max_results;
    }
    
987
    if (defined($offset) && !$limit) {
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        $limit = INT_MAX;
    }
    if (defined $limit) {
        detaint_natural($limit) 
            || ThrowCodeError('param_must_be_numeric', 
                              { function => 'Bugzilla::Search::new',
                                param    => 'limit' });
        if (defined $offset) {
            detaint_natural($offset)
                || ThrowCodeError('param_must_be_numeric',
                                  { function => 'Bugzilla::Search::new',
                                    param    => 'offset' });
        }
        return Bugzilla->dbh->sql_limit($limit, $offset);
    }
    return '';
}

1006 1007 1008
############################
# Internal Accessors: FROM #
############################
1009

1010 1011
sub _column_join {
    my ($self, $field) = @_;
1012 1013
    # The _realname fields require the same join as the username fields.
    $field =~ s/_realname$//;
1014 1015
    my $column_joins = $self->_get_column_joins();
    my $join_info = $column_joins->{$field};
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    if ($join_info) {
        # Don't allow callers to modify the constant.
        $join_info = dclone($join_info);
    }
    else {
        if ($self->_multi_select_fields->{$field}) {
            $join_info = { table => "bug_$field" };
        }
    }
    if ($join_info and !$join_info->{as}) {
        $join_info = dclone($join_info);
        $join_info->{as} = "map_$field";
    }
    return $join_info ? $join_info : ();
}

# Sometimes we join the same table more than once. In this case, we
# want to AND all the various critiera that were used in both joins.
sub _combine_joins {
    my ($self, $joins) = @_;
    my @result;
    while(my $join = shift @$joins) {
        my $name = $join->{as};
        my ($others_like_me, $the_rest) = part { $_->{as} eq $name ? 0 : 1 }
                                               @$joins;
        if ($others_like_me) {
            my $from = $join->{from};
            my $to   = $join->{to};
            # Sanity check to make sure that we have the same from and to
            # for all the same-named joins.
            if ($from) {
                all { $_->{from} eq $from } @$others_like_me
                  or die "Not all same-named joins have identical 'from': "
                         . Dumper($join, $others_like_me);
            }
            if ($to) {
                all { $_->{to} eq $to } @$others_like_me
                  or die "Not all same-named joins have identical 'to': "
                         . Dumper($join, $others_like_me);
            }
            
            # We don't need to call uniq here--translate_join will do that
            # for us.
            my @conditions = map { @{ $_->{extra} || [] } }
                                 ($join, @$others_like_me);
            $join->{extra} = \@conditions;
            $joins = $the_rest;
        }
        push(@result, $join);
    }
    
    return @result;
}

# Takes all the "then_to" items and just puts them as the next item in
# the array. Right now this only does one level of "then_to", but we
# could re-write this to handle then_to recursively if we need more levels.
sub _extract_then_to {
    my ($self, $joins) = @_;
    my @result;
    foreach my $join (@$joins) {
        push(@result, $join);
        if (my $then_to = $join->{then_to}) {
            push(@result, $then_to);
        }
    }
    return @result;
}

# JOIN statements for the SELECT and ORDER BY columns. This should not be
# called until the moment it is needed, because _select_columns might be
1087 1088
# modified by the charts.
sub _select_order_joins {
1089 1090
    my ($self) = @_;
    my @joins;
1091
    foreach my $field ($self->_select_columns) {
1092 1093 1094
        my @column_join = $self->_column_join($field);
        push(@joins, @column_join);
    }
1095
    foreach my $field ($self->_valid_order_columns) {
1096 1097
        my $join_info = $self->_special_order->{$field}->{join};
        if ($join_info) {
1098 1099 1100 1101 1102 1103
            # Don't let callers modify SPECIAL_ORDER.
            $join_info = dclone($join_info);
            if (!$join_info->{as}) {
                $join_info->{as} = "map_$field";
            }
            push(@joins, $join_info);
1104 1105 1106
        }
    }
    return @joins;
1107 1108
}

1109 1110 1111
# These are the joins that are *always* in the FROM clause.
sub _standard_joins {
    my ($self) = @_;
1112
    my $user = $self->_user;
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    my @joins;

    my $security_join = {
        table => 'bug_group_map',
        as    => 'security_map',
    };
    push(@joins, $security_join);

    if ($user->id) {
        $security_join->{extra} =
            ["NOT (" . $user->groups_in_sql('security_map.group_id') . ")"];
            
        my $security_cc_join = {
            table => 'cc',
            as    => 'security_cc',
            extra => ['security_cc.who = ' . $user->id],
        };
        push(@joins, $security_cc_join);
    }
    
    return @joins;
}

sub _sql_from {
    my ($self, $joins_input) = @_;
    my @joins = ($self->_standard_joins, $self->_select_order_joins,
                 @$joins_input);
    @joins = $self->_extract_then_to(\@joins);
    @joins = $self->_combine_joins(\@joins);
    my @join_sql = map { $self->_translate_join($_) } @joins;
    return "bugs\n" . join("\n", @join_sql);
}

1146
# This takes a join data structure and turns it into actual JOIN SQL.
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
sub _translate_join {
    my ($self, $join_info) = @_;
    
    die "join with no table: " . Dumper($join_info) if !$join_info->{table};
    die "join with no 'as': " . Dumper($join_info) if !$join_info->{as};
        
    my $from_table = "bugs";
    my $from  = $join_info->{from} || "bug_id";
    if ($from =~ /^(\w+)\.(\w+)$/) {
        ($from_table, $from) = ($1, $2);
    }
    my $table = $join_info->{table};
    my $name  = $join_info->{as};
    my $to    = $join_info->{to}    || "bug_id";
    my $join  = $join_info->{join}  || 'LEFT';
    my @extra = @{ $join_info->{extra} || [] };
    $name =~ s/\./_/g;
    
    # If a term contains ORs, we need to put parens around the condition.
    # This is a pretty weak test, but it's actually OK to put parens
    # around too many things.
    @extra = map { $_ =~ /\bOR\b/i ? "($_)" : $_ } @extra;
    my $extra_condition = join(' AND ', uniq @extra);
    if ($extra_condition) {
        $extra_condition = " AND $extra_condition";
    }

    my @join_sql = "$join JOIN $table AS $name"
                        . " ON $from_table.$from = $name.$to$extra_condition";
    return @join_sql;
}

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
#############################
# Internal Accessors: WHERE #
#############################

# Note: There's also quite a bit of stuff that affects the WHERE clause
# in the "Internal Accessors: Boolean Charts" section.

# The terms that are always in the WHERE clause. These implement bug
# group security.
sub _standard_where {
    my ($self) = @_;
    # If replication lags badly between the shadow db and the main DB,
    # it's possible for bugs to show up in searches before their group
    # controls are properly set. To prevent this, when initially creating
    # bugs we set their creation_ts to NULL, and don't give them a creation_ts
    # until their group controls are set. So if a bug has a NULL creation_ts,
    # it shouldn't show up in searches at all.
    my @where = ('bugs.creation_ts IS NOT NULL');
    
    my $security_term = 'security_map.group_id IS NULL';

    my $user = $self->_user;
    if ($user->id) {
        my $userid = $user->id;
1203
        # This indentation makes the resulting SQL more readable.
1204
        $security_term .= <<END;
1205 1206 1207 1208

        OR (bugs.reporter_accessible = 1 AND bugs.reporter = $userid)
        OR (bugs.cclist_accessible = 1 AND security_cc.who IS NOT NULL)
        OR bugs.assigned_to = $userid
1209 1210
END
        if (Bugzilla->params->{'useqacontact'}) {
1211
            $security_term.= "        OR bugs.qa_contact = $userid";
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        }
        $security_term = "($security_term)";
    }

    push(@where, $security_term);

    return @where;
}

sub _sql_where {
1222
    my ($self, $main_clause) = @_;
1223 1224
    # The newline and this particular spacing makes the resulting
    # SQL a bit more readable for debugging.
1225 1226 1227 1228 1229
    my $where = join("\n   AND ", $self->_standard_where);
    my $clause_sql = $main_clause->as_string;
    if ($clause_sql) {
        $where .= "\n   AND " . $clause_sql;
    }
1230 1231 1232 1233 1234
    elsif (!Bugzilla->params->{'search_allow_no_criteria'}
           && !$self->{allow_unlimited})
    {
        ThrowUserError('buglist_parameters_required');
    }
1235
    return $where;
1236 1237
}

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
################################
# Internal Accessors: GROUP BY #
################################

# And these are the fields that we have to do GROUP BY for in DBs
# that are more strict about putting everything into GROUP BY.
sub _sql_group_by {
    my ($self) = @_;

    # Strict DBs require every element from the SELECT to be in the GROUP BY,
    # unless that element is being used in an aggregate function.
    my @extra_group_by;
    foreach my $column ($self->_select_columns) {
        next if $self->_skip_group_by->{$column};
1252
        my $sql = $self->COLUMNS->{$column}->{name};
1253 1254 1255 1256 1257
        push(@extra_group_by, $sql);
    }

    # And all items from ORDER BY must be in the GROUP BY. The above loop 
    # doesn't catch items that were put into the ORDER BY from SPECIAL_ORDER.
1258
    foreach my $column ($self->_valid_order_columns) {
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
        my $special_order = $self->_special_order->{$column}->{order};
        next if !$special_order;
        push(@extra_group_by, @$special_order);
    }
    
    @extra_group_by = uniq @extra_group_by;
    
    # bug_id is the only field we actually group by.
    return ('bugs.bug_id', join(',', @extra_group_by));
}

# A helper for _sql_group_by.
sub _skip_group_by {
    my ($self) = @_;
    return $self->{skip_group_by} if $self->{skip_group_by};
    my @skip_list = GROUP_BY_SKIP;
    push(@skip_list, keys %{ $self->_multi_select_fields });
    my %skip_hash = map { $_ => 1 } @skip_list;
    $self->{skip_group_by} = \%skip_hash;
    return $self->{skip_group_by};
}

1281 1282 1283 1284
##############################################
# Internal Accessors: Special Params Parsing #
##############################################

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
# Backwards compatibility for old field names.
sub _convert_old_params {
    my ($self) = @_;
    my $params = $self->_params;
    
    # bugidtype has different values in modern Search.pm.
    if (defined $params->{'bugidtype'}) {
        my $value = $params->{'bugidtype'};
        $params->{'bugidtype'} = $value eq 'exclude' ? 'nowords' : 'anyexact';
    }
    
    foreach my $old_name (keys %{ FIELD_MAP() }) {
        if (defined $params->{$old_name}) {
            my $new_name = FIELD_MAP->{$old_name};
            $params->{$new_name} = delete $params->{$old_name};
        }
    }
}
1303

1304 1305 1306
# This parses all the standard search parameters except for the boolean
# charts.
sub _special_charts {
1307
    my ($self) = @_;
1308
    $self->_convert_old_params();
1309 1310
    $self->_special_parse_bug_status();
    $self->_special_parse_resolution();
1311 1312 1313 1314 1315 1316
    my $clause = new Bugzilla::Search::Clause();
    $clause->add( $self->_parse_basic_fields()     );
    $clause->add( $self->_special_parse_email()    );
    $clause->add( $self->_special_parse_chfield()  );
    $clause->add( $self->_special_parse_deadline() );
    return $clause;
1317 1318 1319 1320 1321 1322 1323
}

sub _parse_basic_fields {
    my ($self) = @_;
    my $params = $self->_params;
    my $chart_fields = $self->_chart_fields;
    
1324
    my $clause = new Bugzilla::Search::Clause();
1325 1326 1327 1328 1329
    foreach my $field_name (keys %$chart_fields) {
        # CGI params shouldn't have periods in them, so we only accept
        # period-separated fields with underscores where the periods go.
        my $param_name = $field_name;
        $param_name =~ s/\./_/g;
1330 1331
        my @values = $self->_param_array($param_name);
        next if !@values;
1332 1333
        my $default_op = $param_name eq 'content' ? 'matches' : 'anyexact';
        my $operator = $params->{"${param_name}_type"} || $default_op;
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
        # Fields that are displayed as multi-selects are passed as arrays,
        # so that they can properly search values that contain commas.
        # However, other fields are sent as strings, so that they are properly
        # split on commas if required.
        my $field = $chart_fields->{$field_name};
        my $pass_value;
        if ($field->is_select or $field->name eq 'version'
            or $field->name eq 'target_milestone')
        {
            $pass_value = \@values;
        }
        else {
            $pass_value = join(',', @values);
        }
1348
        $clause->add($field_name, $operator, $pass_value);
1349
    }
1350
    return @{$clause->children} ? $clause : undef;
1351 1352 1353 1354 1355
}

sub _special_parse_bug_status {
    my ($self) = @_;
    my $params = $self->_params;
1356
    return if !defined $params->{'bug_status'};
1357 1358 1359 1360 1361
    # We want to allow the bug_status_type parameter to work normally,
    # meaning that this special code should only be activated if we are
    # doing the normal "anyexact" search on bug_status.
    return if (defined $params->{'bug_status_type'}
               and $params->{'bug_status_type'} ne 'anyexact');
1362

1363
    my @bug_status = $self->_param_array('bug_status');
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    # Also include inactive bug statuses, as you can query them.
    my $legal_statuses = $self->_chart_fields->{'bug_status'}->legal_values;

    # If the status contains __open__ or __closed__, translate those
    # into their equivalent lists of open and closed statuses.
    if (grep { $_ eq '__open__' } @bug_status) {
        my @open = grep { $_->is_open } @$legal_statuses;
        @open = map { $_->name } @open;
        push(@bug_status, @open);
    }
    if (grep { $_ eq '__closed__' } @bug_status) {
        my @closed = grep { not $_->is_open } @$legal_statuses;
        @closed = map { $_->name } @closed;
        push(@bug_status, @closed);
    }

    @bug_status = uniq @bug_status;
1381 1382 1383
    my $all = grep { $_ eq "__all__" } @bug_status;
    # This will also handle removing __open__ and __closed__ for us
    # (__all__ too, which is why we check for it above, first).
1384 1385 1386
    @bug_status = _valid_values(\@bug_status, $legal_statuses);

    # If the user has selected every status, change to selecting none.
1387
    # This is functionally equivalent, but quite a lot faster.
1388
    if ($all or scalar(@bug_status) == scalar(@$legal_statuses)) {
1389
        delete $params->{'bug_status'};
1390 1391
    }
    else {
1392
        $params->{'bug_status'} = \@bug_status;
1393 1394 1395
    }
}

1396 1397 1398 1399
sub _special_parse_chfield {
    my ($self) = @_;
    my $params = $self->_params;
    
1400 1401
    my $date_from = trim(lc($params->{'chfieldfrom'} || ''));
    my $date_to = trim(lc($params->{'chfieldto'} || ''));
1402 1403
    $date_from = '' if $date_from eq 'now';
    $date_to = '' if $date_to eq 'now';
1404 1405
    my @fields = $self->_param_array('chfield');
    my $value_to = $params->{'chfieldvalue'};
1406 1407
    $value_to = '' if !defined $value_to;

1408 1409
    @fields = map { $_ eq '[Bug creation]' ? 'creation_ts' : $_ } @fields;

1410 1411
    my $clause = new Bugzilla::Search::Clause();

1412
    # It is always safe and useful to push delta_ts into the charts
1413
    # if there is a "from" date specified. It doesn't conflict with
1414 1415
    # searching [Bug creation], because a bug's delta_ts is set to
    # its creation_ts when it is created. So this just gives the
1416 1417
    # database an additional index to possibly choose, on a table that
    # is smaller than bugs_activity.
1418
    if ($date_from ne '') {
1419
        $clause->add('delta_ts', 'greaterthaneq', $date_from);
1420
    }
1421 1422 1423 1424 1425 1426 1427
    # It's not normally safe to do it for "to" dates, though--"chfieldto" means
    # "a field that changed before this date", and delta_ts could be either
    # later or earlier than that, if we're searching for the time that a field
    # changed. However, chfieldto all by itself, without any chfieldvalue or
    # chfield, means "just search delta_ts", and so we still want that to
    # work.
    if ($date_to ne '' and !@fields and $value_to eq '') {
1428
        $clause->add('delta_ts', 'lessthaneq', $date_to);
1429
    }
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

    # Basically, we construct the chart like:
    #
    # (added_for_field1 = value OR added_for_field2 = value)
    # AND (date_field1_changed >= date_from OR date_field2_changed >= date_from)
    # AND (date_field1_changed <= date_to OR date_field2_changed <= date_to)
    #
    # Theoretically, all we *really* would need to do is look for the field id
    # in the bugs_activity table, because we've already limited the search
    # by delta_ts above, but there's no chart to do that, so we check the
    # change date of the fields.
    
    if ($value_to ne '') {
1443
        my $value_clause = new Bugzilla::Search::Clause('OR');
1444
        foreach my $field (@fields) {
1445
            $value_clause->add($field, 'changedto', $value_to);
1446
        }
1447
        $clause->add($value_clause);
1448 1449 1450
    }

    if ($date_from ne '') {
1451
        my $from_clause = new Bugzilla::Search::Clause('OR');
1452
        foreach my $field (@fields) {
1453
            $from_clause->add($field, 'changedafter', $date_from);
1454
        }
1455
        $clause->add($from_clause);
1456 1457
    }
    if ($date_to ne '') {
1458 1459 1460 1461 1462
        # chfieldto is supposed to be a relative date or a date of the form
        # YYYY-MM-DD, i.e. without the time appended to it. We append the
        # time ourselves so that the end date is correctly taken into account.
        $date_to .= ' 23:59:59' if $date_to =~ /^\d{4}-\d{1,2}-\d{1,2}$/;

1463
        my $to_clause = new Bugzilla::Search::Clause('OR');
1464
        foreach my $field (@fields) {
1465
            $to_clause->add($field, 'changedbefore', $date_to);
1466
        }
1467
        $clause->add($to_clause);
1468 1469
    }

1470
    return @{$clause->children} ? $clause : undef;
1471 1472
}

1473 1474
sub _special_parse_deadline {
    my ($self) = @_;
1475
    return if !$self->_user->is_timetracker;
1476 1477
    my $params = $self->_params;
    
1478
    my $clause = new Bugzilla::Search::Clause();
1479
    if (my $from = $params->{'deadlinefrom'}) {
1480
        $clause->add('deadline', 'greaterthaneq', $from);
1481
    }
1482
    if (my $to = $params->{'deadlineto'}) {
1483
        $clause->add('deadline', 'lessthaneq', $to);
1484
    }
1485 1486

    return @{$clause->children} ? $clause : undef;
1487 1488
}

1489 1490 1491 1492
sub _special_parse_email {
    my ($self) = @_;
    my $params = $self->_params;
    
1493
    my @email_params = grep { $_ =~ /^email\d+$/ } keys %$params;
1494
    
1495
    my $clause = new Bugzilla::Search::Clause();
1496 1497 1498
    foreach my $param (@email_params) {
        $param =~ /(\d+)$/;
        my $id = $1;
1499 1500 1501
        my $email = trim($params->{"email$id"});
        next if !$email;
        my $type = $params->{"emailtype$id"} || 'anyexact';
1502 1503
        $type = "anyexact" if $type eq "exact";

1504
        my $or_clause = new Bugzilla::Search::Clause('OR');
1505
        foreach my $field (qw(assigned_to reporter cc qa_contact)) {
1506
            if ($params->{"email$field$id"}) {
1507
                $or_clause->add($field, $type, $email);
1508 1509
            }
        }
1510
        if ($params->{"emaillongdesc$id"}) {
1511
            $or_clause->add("commenter", $type, $email);
1512
        }
1513 1514
        
        $clause->add($or_clause);
1515
    }
1516 1517

    return @{$clause->children} ? $clause : undef;
1518 1519
}

1520 1521 1522
sub _special_parse_resolution {
    my ($self) = @_;
    my $params = $self->_params;
1523
    return if !defined $params->{'resolution'};
1524

1525
    my @resolution = $self->_param_array('resolution');
1526 1527 1528
    my $legal_resolutions = $self->_chart_fields->{resolution}->legal_values;
    @resolution = _valid_values(\@resolution, $legal_resolutions, '---');
    if (scalar(@resolution) == scalar(@$legal_resolutions)) {
1529
        delete $params->{'resolution'};
1530 1531 1532
    }
}

1533 1534 1535 1536
sub _valid_values {
    my ($input, $valid, $extra_value) = @_;
    my @result;
    foreach my $item (@$input) {
1537
        $item = trim($item);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
        if (defined $extra_value and $item eq $extra_value) {
            push(@result, $item);
        }
        elsif (grep { $_->name eq $item } @$valid) {
            push(@result, $item);
        }
    }
    return @result;
}

1548 1549 1550 1551 1552 1553 1554
######################################
# Internal Accessors: Boolean Charts #
######################################

sub _charts_to_conditions {
    my ($self) = @_;
    
1555 1556 1557 1558 1559 1560 1561 1562 1563
    my $clause = $self->_charts;
    my @joins;
    $clause->walk_conditions(sub {
        my ($condition) = @_;
        return if !$condition->translated;
        push(@joins, @{ $condition->translated->{joins} });
    });
    return (\@joins, $clause);
}
1564

1565 1566 1567 1568 1569 1570 1571
sub _charts {
    my ($self) = @_;
    
    my $clause = $self->_params_to_data_structure();
    my $chart_id = 0;
    $clause->walk_conditions(sub { $self->_handle_chart($chart_id++, @_) });
    return $clause;
1572 1573
}

1574
sub _params_to_data_structure {
1575
    my ($self) = @_;
1576 1577 1578 1579 1580 1581
    
    # First we get the "special" charts, representing all the normal
    # field son the search page. This may modify _params, so it needs to
    # happen first.
    my $clause = $self->_special_charts;

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    # Then we process the old Boolean Charts input format.
    $clause->add( $self->_boolean_charts );
    
    # And then process the modern "custom search" format.
    $clause->add( $self->_custom_search );
   
    return $clause;
}

sub _boolean_charts {
    my ($self) = @_;
    
1594
    my $params = $self->_params;
1595
    my @param_list = keys %$params;
1596 1597 1598 1599 1600
    
    my @all_field_params = grep { /^field-?\d+/ } @param_list;
    my @chart_ids = map { /^field(-?\d+)/; $1 } @all_field_params;
    @chart_ids = sort { $a <=> $b } uniq @chart_ids;
    
1601
    my $clause = new Bugzilla::Search::Clause();
1602 1603 1604 1605 1606
    foreach my $chart_id (@chart_ids) {
        my @all_and = grep { /^field$chart_id-\d+/ } @param_list;
        my @and_ids = map { /^field$chart_id-(\d+)/; $1 } @all_and;
        @and_ids = sort { $a <=> $b } uniq @and_ids;
        
1607
        my $and_clause = new Bugzilla::Search::Clause();
1608 1609 1610 1611 1612
        foreach my $and_id (@and_ids) {
            my @all_or = grep { /^field$chart_id-$and_id-\d+/ } @param_list;
            my @or_ids = map { /^field$chart_id-$and_id-(\d+)/; $1 } @all_or;
            @or_ids = sort { $a <=> $b } uniq @or_ids;
            
1613
            my $or_clause = new Bugzilla::Search::Clause('OR');
1614
            foreach my $or_id (@or_ids) {
1615 1616 1617 1618 1619
                my $identifier = "$chart_id-$and_id-$or_id";
                my $field = $params->{"field$identifier"};
                my $operator = $params->{"type$identifier"};
                my $value = $params->{"value$identifier"};                
                $or_clause->add($field, $operator, $value);
1620
            }
1621 1622
            $and_clause->add($or_clause);
            $and_clause->negate(1) if $params->{"negate$chart_id"};
1623
        }
1624
        $clause->add($and_clause);
1625
    }
1626 1627

    return @{$clause->children} ? $clause : undef;
1628 1629
}

1630 1631 1632
sub _custom_search {
    my ($self) = @_;
    my $params = $self->_params;
1633

1634 1635 1636
    my @field_ids = $self->_field_ids;
    return unless scalar @field_ids;

1637
    my $current_clause = new Bugzilla::Search::Clause($params->{j_top});
1638
    my @clause_stack;
1639
    foreach my $id (@field_ids) {
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
        my $field = $params->{"f$id"};
        if ($field eq 'OP') {
            my $joiner = $params->{"j$id"};
            my $new_clause = new Bugzilla::Search::Clause($joiner);
            $new_clause->negate($params->{"n$id"});
            $current_clause->add($new_clause);
            push(@clause_stack, $current_clause);
            $current_clause = $new_clause;
            next;
        }
        if ($field eq 'CP') {
            $current_clause = pop @clause_stack;
            ThrowCodeError('search_cp_without_op', { id => $id })
                if !$current_clause;
            next;
        }
        
        my $operator = $params->{"o$id"};
        my $value = $params->{"v$id"};
        my $condition = condition($field, $operator, $value);
        $condition->negate($params->{"n$id"});
        $current_clause->add($condition);
    }
    
    # We allow people to specify more OPs than CPs, so at the end of the
    # loop our top clause may be still in the stack instead of being
    # $current_clause.
    return $clause_stack[0] || $current_clause;
}

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
sub _field_ids {
    my ($self) = @_;
    my $params = $self->_params;
    my @param_list = keys %$params;
    
    my @field_params = grep { /^f\d+$/ } @param_list;
    my @field_ids = map { /(\d+)/; $1 } @field_params;
    @field_ids = sort { $a <=> $b } @field_ids;
    return @field_ids;
}

1681
sub _handle_chart {
1682
    my ($self, $chart_id, $condition) = @_;
1683 1684
    my $dbh = Bugzilla->dbh;
    my $params = $self->_params;
1685
    my ($field, $operator, $value) = $condition->fov;
1686

1687 1688
    $field = FIELD_MAP->{$field} || $field;

1689
    return if (!defined $field or !defined $operator or !defined $value);
1690
    
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
    my $string_value;
    if (ref $value eq 'ARRAY') {
        # Trim input and ignore blank values.
        @$value = map { trim($_) } @$value;
        @$value = grep { defined $_ and $_ ne '' } @$value;
        return if !@$value;
        $string_value = join(',', @$value);
    }
    else {
        return if $value eq '';
        $string_value = $value;
    }
    
1704 1705 1706
    $self->_chart_fields->{$field}
        or ThrowCodeError("invalid_field_name", { field => $field });
    trick_taint($field);
1707
    
1708 1709 1710
    # This is the field as you'd reference it in a SQL statement.
    my $full_field = $field =~ /\./ ? $field : "bugs.$field";

1711 1712 1713 1714 1715
    # "value" and "quoted" are for search functions that always operate
    # on a scalar string and never care if they were passed multiple
    # parameters. If the user does pass multiple parameters, they will
    # become a space-separated string for those search functions.
    #
1716
    # all_values is for search functions that do operate
1717
    # on multiple values, like anyexact.
1718
    
1719
    my %search_args = (
1720 1721
        chart_id   => $chart_id,
        sequence   => $chart_id,
1722 1723 1724
        field      => $field,
        full_field => $full_field,
        operator   => $operator,
1725 1726
        value      => $string_value,
        all_values => $value,
1727 1728
        joins      => [],
    );
1729
    $search_args{quoted} = $self->_quote_unless_numeric(\%search_args);
1730 1731
    # This should add a "term" selement to %search_args.
    $self->do_search_function(\%search_args);
1732 1733 1734 1735 1736

    # If term is left empty, then this means the criteria
    # has no effect and can be ignored.
    return unless $search_args{term};

1737 1738 1739 1740 1741
    # All the things here that don't get pulled out of
    # %search_args are their original values before
    # do_search_function modified them.   
    $self->search_description({
        field => $field, type => $operator,
1742
        value => $string_value, term => $search_args{term},
1743 1744
    });
    
1745
    $condition->translated(\%search_args);
1746
}
1747

1748
##################################
1749
# do_search_function And Helpers #
1750 1751
##################################

1752 1753 1754 1755
# This takes information about the current boolean chart and translates
# it into SQL, using the constants at the top of this file.
sub do_search_function {
    my ($self, $args) = @_;
1756
    my ($field, $operator) = @$args{qw(field operator)};
1757
    
1758
    if (my $parse_func = SPECIAL_PARSING->{$field}) {
1759
        $self->$parse_func($args);
1760 1761 1762
        # Some parsing functions set $term, though most do not.
        # For the ones that set $term, we don't need to do any further
        # parsing.
1763
        return if $args->{term};
1764 1765
    }
    
1766
    my $operator_field_override = $self->_get_operator_field_override();
1767
    my $override = $operator_field_override->{$field};
1768 1769
    # Attachment fields get special handling, if they don't have a specific
    # individual override.
1770
    if (!$override and $field =~ /^attachments\./) {
1771 1772 1773
        $override = $operator_field_override->{attachments};
    }
    # If there's still no override, check for an override on the field's type.
1774
    if (!$override) {
1775
        my $field_obj = $self->_chart_fields->{$field};
1776
        $override = $operator_field_override->{$field_obj->type};
1777 1778 1779
    }
    
    if ($override) {
1780 1781
        my $search_func = $self->_pick_override_function($override, $operator);
        $self->$search_func($args) if $search_func;
1782 1783 1784 1785 1786
    }

    # Some search functions set $term, and some don't. For the ones that
    # don't (or for fields that don't have overrides) we now call the
    # direct operator function from OPERATORS.
1787
    if (!defined $args->{term}) {
1788 1789
        $self->_do_operator_function($args);
    }
1790 1791 1792 1793 1794 1795 1796 1797
    
    if (!defined $args->{term}) {
        # This field and this type don't work together. Generally,
        # this should never be reached, because it should be handled
        # explicitly by OPERATOR_FIELD_OVERRIDE.
        ThrowUserError("search_field_operator_invalid",
                       { field => $field, operator => $operator });
    }
1798 1799 1800 1801 1802 1803
}

# A helper for various search functions that need to run operator
# functions directly.
sub _do_operator_function {
    my ($self, $func_args) = @_;
1804
    my $operator = $func_args->{operator};
1805 1806 1807
    my $operator_func = OPERATORS->{$operator}
      || ThrowCodeError("search_field_operator_unsupported",
                        { operator => $operator });
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    $self->$operator_func($func_args);
}

sub _reverse_operator {
    my ($self, $operator) = @_;
    my $reverse = OPERATOR_REVERSE->{$operator};
    return $reverse if $reverse;
    if ($operator =~ s/^not//) {
        return $operator;
    }
    return "not$operator";
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
}

sub _pick_override_function {
    my ($self, $override, $operator) = @_;
    my $search_func = $override->{$operator};

    if (!$search_func) {
        # If we don't find an override for one specific operator,
        # then there are some special override types:
        # _non_changed: For any operator that doesn't have the word
        #               "changed" in it
        # _default: Overrides all operators that aren't explicitly specified.
        if ($override->{_non_changed} and $operator !~ /changed/) {
            $search_func = $override->{_non_changed};
        }
        elsif ($override->{_default}) {
            $search_func = $override->{_default};
        }
    }

    return $search_func;
}

1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
sub _get_operator_field_override {
    my $self = shift;
    my $cache = Bugzilla->request_cache;

    return $cache->{operator_field_override} 
        if defined $cache->{operator_field_override};

    my %operator_field_override = %{ OPERATOR_FIELD_OVERRIDE() };
    Bugzilla::Hook::process('search_operator_field_override',
                            { search => $self, 
                              operators => \%operator_field_override });

    $cache->{operator_field_override} = \%operator_field_override;
    return $cache->{operator_field_override};
}

1858 1859 1860 1861 1862 1863
sub _get_column_joins {
    my $self = shift;
    my $cache = Bugzilla->request_cache;

    return $cache->{column_joins} if defined $cache->{column_joins};

1864
    my %column_joins = %{ $self->COLUMN_JOINS() };
1865 1866 1867 1868 1869 1870 1871
    Bugzilla::Hook::process('buglist_column_joins',
                            { column_joins => \%column_joins });

    $cache->{column_joins} = \%column_joins;
    return $cache->{column_joins};
}

1872 1873 1874
###########################
# Search Function Helpers #
###########################
1875

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
# When we're doing a numeric search against a numeric column, we want to
# just put a number into the SQL instead of a string. On most DBs, this
# is just a performance optimization, but on SQLite it actually changes
# the behavior of some searches.
sub _quote_unless_numeric {
    my ($self, $args, $value) = @_;
    if (!defined $value) {
        $value = $args->{value};
    }
    my ($field, $operator) = @$args{qw(field operator)};
    
    my $numeric_operator = !grep { $_ eq $operator } NON_NUMERIC_OPERATORS;
    my $numeric_field = $self->_chart_fields->{$field}->is_numeric;
    my $numeric_value = ($value =~ NUMBER_REGEX) ? 1 : 0;
    my $is_numeric = $numeric_operator && $numeric_field && $numeric_value;
    if ($is_numeric) {
        my $quoted = $value;
        trick_taint($quoted);
        return $quoted;
    }
    return Bugzilla->dbh->quote($value);
}

1899 1900
sub build_subselect {
    my ($outer, $inner, $table, $cond) = @_;
1901
    return "$outer IN (SELECT $inner FROM $table WHERE $cond)";
1902 1903
}

1904 1905 1906 1907
# Used by anyexact to get the list of input values. This allows us to
# support values with commas inside of them in the standard charts, and
# still accept string values for the boolean charts (and split them on
# commas).
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
sub _all_values {
    my ($self, $args, $split_on) = @_;
    $split_on ||= qr/[\s,]+/;
    my $dbh = Bugzilla->dbh;
    my $all_values = $args->{all_values};
    
    my @array;
    if (ref $all_values eq 'ARRAY') {
        @array = @$all_values;
    }
    else {
        @array = split($split_on, $all_values);
        @array = map { trim($_) } @array;
        @array = grep { defined $_ and $_ ne '' } @array;
    }
    
    if ($args->{field} eq 'resolution') {
        @array = map { $_ eq '---' ? '' : $_ } @array;
    }
    
    return @array;
}

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
# Support for "any/all/nowordssubstr" comparison type ("words as substrings")
sub _substring_terms {
    my ($self, $args) = @_;
    my $dbh = Bugzilla->dbh;

    # We don't have to (or want to) use _all_values, because we'd just
    # split each term on spaces and commas anyway.
    my @words = split(/[\s,]+/, $args->{value});
    @words = grep { defined $_ and $_ ne '' } @words;
    @words = map { $dbh->quote($_) } @words;
    my @terms = map { $dbh->sql_iposition($_, $args->{full_field}) . " > 0" }
                    @words;
    return @terms;
}

sub _word_terms {
    my ($self, $args) = @_;
    my $dbh = Bugzilla->dbh;
    
    my @values = split(/[\s,]+/, $args->{value});
    @values = grep { defined $_ and $_ ne '' } @values;
    my @substring_terms = $self->_substring_terms($args);
    
    my @terms;
    my $start = $dbh->WORD_START;
    my $end   = $dbh->WORD_END;
    foreach my $word (@values) {
        my $regex  = $start . quotemeta($word) . $end;
        my $quoted = $dbh->quote($regex);
        # We don't have to check the regexp, because we escaped it, so we're
        # sure it's valid.
        my $regex_term = $dbh->sql_regexp($args->{full_field}, $quoted,
                                          'no check');
        # Regular expressions are slow--substring searches are faster.
        # If we're searching for a word, we're also certain that the
        # substring will appear in the value. So we limit first by
        # substring and then by a regex that will match just words.
        my $substring_term = shift @substring_terms;
        push(@terms, "$substring_term AND $regex_term");
    }
    
    return @terms;
}

1975 1976 1977
#####################################
# "Special Parsing" Functions: Date #
#####################################
1978

1979 1980 1981 1982
sub _timestamp_translate {
    my ($self, $args) = @_;
    my $value = $args->{value};
    my $dbh = Bugzilla->dbh;
1983

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
    return if $value !~ /^(?:[\+\-]?\d+[hdwmy]s?|now)$/i;

    # By default, the time is appended to the date, which we don't want
    # for deadlines.
    $value = SqlifyDate($value);
    if ($args->{field} eq 'deadline') {
        ($value) = split(/\s/, $value);
    }
    $args->{value} = $value;
    $args->{quoted} = $dbh->quote($value);
1994 1995
}

1996 1997
sub SqlifyDate {
    my ($str) = @_;
1998
    my $fmt = "%Y-%m-%d %H:%M:%S";
1999
    $str = "" if (!defined $str || lc($str) eq 'now');
2000 2001 2002
    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);
2003
    }
2004

2005 2006
    if ($str =~ /^(-|\+)?(\d+)([hdwmy])(s?)$/i) {   # relative date
        my ($sign, $amount, $unit, $startof, $date) = ($1, $2, lc $3, lc $4, time);
2007 2008
        my ($sec, $min, $hour, $mday, $month, $year, $wday)  = localtime($date);
        if ($sign && $sign eq '+') { $amount = -$amount; }
2009
        $startof = 1 if $amount == 0;
2010
        if ($unit eq 'w') {                  # convert weeks to days
2011 2012
            $amount = 7*$amount;
            $amount += $wday if $startof;
2013 2014 2015
            $unit = 'd';
        }
        if ($unit eq 'd') {
2016 2017 2018 2019 2020 2021
            if ($startof) {
              $fmt = "%Y-%m-%d 00:00:00";
              $date -= $sec + 60*$min + 3600*$hour;
            }
            $date -= 24*3600*$amount;
            return time2str($fmt, $date);
2022 2023
        }
        elsif ($unit eq 'y') {
2024 2025 2026 2027 2028 2029 2030
            if ($startof) {
                return sprintf("%4d-01-01 00:00:00", $year+1900-$amount);
            } 
            else {
                return sprintf("%4d-%02d-%02d %02d:%02d:%02d", 
                               $year+1900-$amount, $month+1, $mday, $hour, $min, $sec);
            }
2031 2032 2033 2034
        }
        elsif ($unit eq 'm') {
            $month -= $amount;
            while ($month<0) { $year--; $month += 12; }
2035 2036 2037 2038 2039 2040 2041
            if ($startof) {
                return sprintf("%4d-%02d-01 00:00:00", $year+1900, $month+1);
            }
            else {
                return sprintf("%4d-%02d-%02d %02d:%02d:%02d", 
                               $year+1900, $month+1, $mday, $hour, $min, $sec);
            }
2042 2043
        }
        elsif ($unit eq 'h') {
2044 2045 2046 2047 2048 2049
            # Special case for 'beginning of an hour'
            if ($startof) {
                $fmt = "%Y-%m-%d %H:00:00";
            } 
            $date -= 3600*$amount;
            return time2str($fmt, $date);
2050 2051
        }
        return undef;                      # should not happen due to regexp at top
2052
    }
2053 2054 2055
    my $date = str2time($str);
    if (!defined($date)) {
        ThrowUserError("illegal_date", { date => $str });
2056
    }
2057
    return time2str($fmt, $date);
2058 2059
}

2060 2061 2062
######################################
# "Special Parsing" Functions: Users #
######################################
2063

2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
sub pronoun {
    my ($noun, $user) = (@_);
    if ($noun eq "%user%") {
        if ($user->id) {
            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%") {
2080
        return "COALESCE(bugs.qa_contact,0)";
2081 2082
    }
    return 0;
2083 2084
}

2085
sub _contact_pronoun {
2086
    my ($self, $args) = @_;
2087
    my $value = $args->{value};
2088
    my $user = $self->_user;
2089 2090

    if ($value =~ /^\%group\.[^%]+%$/) {
2091
        $self->_contact_exact_group($args);
2092
    }
2093 2094 2095
    elsif ($value =~ /^(%\w+%)$/) {
        $args->{value} = pronoun($1, $user);
        $args->{quoted} = $args->{value};
2096
        $args->{value_is_id} = 1;
2097 2098 2099
    }
}

2100
sub _contact_exact_group {
2101
    my ($self, $args) = @_;
2102 2103
    my ($value, $operator, $field, $chart_id, $joins, $sequence) =
        @$args{qw(value operator field chart_id joins sequence)};
2104
    my $dbh = Bugzilla->dbh;
2105
    my $user = $self->_user;
2106

2107
    # We already know $value will match this regexp, else we wouldn't be here.
2108
    $value =~ /\%group\.([^%]+)%/;
2109 2110 2111 2112
    my $group_name = $1;
    my $group = Bugzilla::Group->check({ name => $group_name, _error => 'invalid_group_name' });
    # Pass $group_name instead of $group->name to the error message
    # to not leak the existence of the group.
2113
    $user->in_group($group)
2114 2115 2116 2117
      || ThrowUserError('invalid_group_name', { name => $group_name });
    # Now that we know the user belongs to this group, it's safe
    # to disclose more information.
    $group->check_members_are_visible();
2118

2119
    my $group_ids = Bugzilla::Group->flatten_group_membership($group->id);
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136

    if ($field eq 'cc' && $chart_id eq '') {
        # This is for the email1, email2, email3 fields from query.cgi.
        $chart_id = "CC$$sequence";
        $args->{sequence}++;
    }

    my $from = $field;
    # These fields need an additional table.
    if ($field =~ /^(commenter|cc)$/) {
        my $join_table = $field;
        $join_table = 'longdescs' if $field eq 'commenter';
        my $join_table_alias = "${field}_$chart_id";
        push(@$joins, { table => $join_table, as => $join_table_alias });
        $from = "$join_table_alias.who";
    }

2137
    my $table = "user_group_map_$chart_id";
2138 2139 2140
    my $join = {
        table => 'user_group_map',
        as    => $table,
2141
        from  => $from,
2142 2143 2144 2145 2146
        to    => 'user_id',
        extra => [$dbh->sql_in("$table.group_id", $group_ids),
                  "$table.isbless = 0"],
    };
    push(@$joins, $join);
2147 2148 2149 2150 2151
    if ($operator =~ /^not/) {
        $args->{term} = "$table.group_id IS NULL";
    }
    else {
        $args->{term} = "$table.group_id IS NOT NULL";
2152 2153 2154
    }
}

2155 2156 2157 2158 2159 2160 2161 2162 2163
sub _get_user_id {
    my ($self, $value) = @_;

    if ($value =~ /^%\w+%$/) {
        return pronoun($value, $self->_user);
    }
    return login_to_id($value, THROW_ERROR);
}

2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
#####################################################################
# Search Functions
#####################################################################

sub _invalid_combination {
    my ($self, $args) = @_;
    my ($field, $operator) = @$args{qw(field operator)};
    ThrowUserError('search_field_operator_invalid',
                   { field => $field, operator => $operator });
}

2175 2176 2177
# For all the "user" fields--assigned_to, reporter, qa_contact,
# cc, commenter, requestee, etc.
sub _user_nonchanged {
2178
    my ($self, $args) = @_;
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
    my ($field, $operator, $chart_id, $sequence, $joins) =
        @$args{qw(field operator chart_id sequence joins)};

    my $is_in_other_table;
    if (my $join = USER_FIELDS->{$field}->{join}) {
        $is_in_other_table = 1;
        my $as = "${field}_$chart_id";
        # Needed for setters.login_name and requestees.login_name.
        # Otherwise when we try to join "profiles" below, we'd get
        # something like "setters.login_name.login_name" in the "from".
        $as =~ s/\./_/g;        
        # This helps implement the email1, email2, etc. parameters.
        if ($chart_id =~ /default/) {
            $as .= "_$sequence";
        }
        my $isprivate = USER_FIELDS->{$field}->{isprivate};
        my $extra = ($isprivate and !$self->_user->is_insider)
                    ? ["$as.isprivate = 0"] : [];
        # We want to copy $join so as not to modify USER_FIELDS.
        push(@$joins, { %$join, as => $as, extra => $extra });
        my $search_field = USER_FIELDS->{$field}->{field};
        $args->{full_field} = "$as.$search_field";
    }

    my $is_nullable = USER_FIELDS->{$field}->{nullable};
    my $null_alternate = "''";
    # When using a pronoun, we use the userid, and we don't have to
    # join the profiles table.
    if ($args->{value_is_id}) {
        $null_alternate = 0;
2209
    }
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
    else {
        my $as = "name_${field}_$chart_id";
        # For fields with periods in their name.
        $as =~ s/\./_/;
        my $join = {
            table => 'profiles',
            as    => $as,
            from  => $args->{full_field},
            to    => 'userid',
            join  => (!$is_in_other_table and !$is_nullable) ? 'INNER' : undef,
        };
        push(@$joins, $join);
        $args->{full_field} = "$as.login_name";
2223
    }
2224
    
2225 2226 2227 2228 2229 2230 2231
    # We COALESCE fields that can be NULL, to make "not"-style operators
    # continue to work properly. For example, "qa_contact is not equal to bob"
    # should also show bugs where the qa_contact is NULL. With COALESCE,
    # it does.
    if ($is_nullable) {
        $args->{full_field} = "COALESCE($args->{full_field}, $null_alternate)";
    }
2232
    
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
    # For fields whose values are stored in other tables, negation (NOT)
    # only works properly if we put the condition into the JOIN instead
    # of the WHERE.
    if ($is_in_other_table) {
        # Using the last join works properly whether we're searching based
        # on userid or login_name.
        my $last_join = $joins->[-1];
        
        # For negative operators, the system we're using here
        # only works properly if we reverse the operator and check IS NULL
        # in the WHERE.
        my $is_negative = $operator =~ /^no/ ? 1 : 0;
        if ($is_negative) {
            $args->{operator} = $self->_reverse_operator($operator);
        }
        $self->_do_operator_function($args);
        push(@{ $last_join->{extra} }, $args->{term});
        
        # For login_name searches, we only want a single join.
        # So we create a subselect table out of our two joins. This makes
        # negation (NOT) work properly for values that are in other
        # tables.
        if ($last_join->{table} eq 'profiles') {
            pop @$joins;
            $last_join->{join} = 'INNER';
            my ($join_sql) = $self->_translate_join($last_join);
            my $first_join = $joins->[-1];
            my $as = $first_join->{as};            
            my $table = $first_join->{table};
            my $columns = "bug_id";
            $columns .= ",isprivate" if @{ $first_join->{extra} };
            my $new_table = "SELECT $columns FROM $table AS $as $join_sql";
            $first_join->{table} = "($new_table)";
            # We always want to LEFT JOIN the generated table.
            delete $first_join->{join};
            # To support OR charts, we need multiple tables.
            my $new_as = $first_join->{as} . "_$sequence";
            $_ =~ s/\Q$as\E/$new_as/ foreach @{ $first_join->{extra} };
            $first_join->{as} = $new_as;
            $last_join = $first_join;
        }
        
        # If we're joining the first table (we're using a pronoun and
        # searching by user id) then we need to check $other_table->{field}.
        my $check_field = $last_join->{as} . '.bug_id';
        if ($is_negative) {
            $args->{term} = "$check_field IS NULL";
        }
        else {
            $args->{term} = "$check_field IS NOT NULL";
        }
    }
2285 2286
}

2287
# XXX This duplicates having Commenter as a search field.
2288
sub _long_desc_changedby {
2289 2290
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value) = @$args{qw(chart_id joins value)};
2291
    
2292
    my $table = "longdescs_$chart_id";
2293
    push(@$joins, { table => 'longdescs', as => $table });
2294
    my $user_id = $self->_get_user_id($value);
2295
    $args->{term} = "$table.who = $user_id";
2296 2297
}

2298
sub _long_desc_changedbefore_after {
2299 2300 2301
    my ($self, $args) = @_;
    my ($chart_id, $operator, $value, $joins) =
        @$args{qw(chart_id operator value joins)};
2302 2303
    my $dbh = Bugzilla->dbh;
    
2304
    my $sql_operator = ($operator =~ /before/) ? '<=' : '>=';
2305 2306
    my $table = "longdescs_$chart_id";
    my $sql_date = $dbh->quote(SqlifyDate($value));
2307 2308 2309 2310 2311 2312
    my $join = {
        table => 'longdescs',
        as    => $table,
        extra => ["$table.bug_when $sql_operator $sql_date"],
    };
    push(@$joins, $join);
2313
    $args->{term} = "$table.bug_when IS NOT NULL";
2314 2315 2316 2317 2318 2319

    # If the user is not part of the insiders group, they cannot see
    # private comments
    if (!$self->_user->is_insider) {
        $args->{term} .= " AND $table.isprivate = 0";
    }
2320 2321 2322
}

sub _content_matches {
2323
    my ($self, $args) = @_;
2324 2325
    my ($chart_id, $joins, $fields, $operator, $value) =
        @$args{qw(chart_id joins fields operator value)};
2326 2327 2328 2329 2330 2331 2332 2333 2334
    my $dbh = Bugzilla->dbh;
    
    # "content" is an alias for columns containing text for which we
    # can search a full-text index and retrieve results by relevance, 
    # currently just bug comments (and summaries to some degree).
    # There's only one way to search a full-text index, so we only
    # accept the "matches" operator, which is specific to full-text
    # index searches.

2335
    # Add the fulltext table to the query so we can search on it.
2336
    my $table = "bugs_fulltext_$chart_id";
2337
    my $comments_col = "comments";
2338
    $comments_col = "comments_noprivate" unless $self->_user->is_insider;
2339
    push(@$joins, { table => 'bugs_fulltext', as => $table });
2340
    
2341
    # Create search terms to add to the SELECT and WHERE clauses.
2342 2343 2344 2345
    my ($term1, $rterm1) =
        $dbh->sql_fulltext_search("$table.$comments_col", $value, 1);
    my ($term2, $rterm2) =
        $dbh->sql_fulltext_search("$table.short_desc", $value, 2);
2346 2347 2348
    $rterm1 = $term1 if !$rterm1;
    $rterm2 = $term2 if !$rterm2;

2349
    # The term to use in the WHERE clause.
2350
    my $term = "$term1 OR $term2";
2351 2352
    if ($operator =~ /not/i) {
        $term = "NOT($term)";
2353
    }
2354
    $args->{term} = $term;
2355
    
2356
    # In order to sort by relevance (in case the user requests it),
2357 2358
    # we SELECT the relevance value so we can add it to the ORDER BY
    # clause. Every time a new fulltext chart isadded, this adds more 
2359
    # terms to the relevance sql.
2360 2361 2362
    #
    # We build the relevance SQL by modifying the COLUMNS list directly,
    # which is kind of a hack but works.
2363
    my $current = $self->COLUMNS->{'relevance'}->{name};
2364
    $current = $current ? "$current + " : '';
2365
    # For NOT searches, we just add 0 to the relevance.
2366
    my $select_term = $operator =~ /not/ ? 0 : "($current$rterm1 + $rterm2)";
2367
    $self->COLUMNS->{'relevance'}->{name} = $select_term;
2368 2369
}

2370
sub _long_descs_count {
2371 2372
    my ($self, $args) = @_;
    my ($chart_id, $joins) = @$args{qw(chart_id joins)};
2373 2374
    my $table = "longdescs_count_$chart_id";
    my $extra =  $self->_user->is_insider ? "" : "WHERE isprivate = 0";
2375
    my $join = {
2376 2377
        table => "(SELECT bug_id, COUNT(*) AS num"
                 . " FROM longdescs $extra GROUP BY bug_id)",
2378 2379 2380
        as    => $table,
    };
    push(@$joins, $join);
2381 2382 2383
    $args->{full_field} = "${table}.num";
}

2384
sub _work_time_changedby {
2385 2386
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value) = @$args{qw(chart_id joins value)};
2387
    
2388
    my $table = "longdescs_$chart_id";
2389
    push(@$joins, { table => 'longdescs', as => $table });
2390
    my $user_id = $self->_get_user_id($value);
2391
    $args->{term} = "$table.who = $user_id AND $table.work_time != 0";
2392 2393
}

2394
sub _work_time_changedbefore_after {
2395 2396 2397
    my ($self, $args) = @_;
    my ($chart_id, $operator, $value, $joins) =
        @$args{qw(chart_id operator value joins)};
2398 2399
    my $dbh = Bugzilla->dbh;
    
2400
    my $table = "longdescs_$chart_id";
2401
    my $sql_operator = ($operator =~ /before/) ? '<=' : '>=';
2402
    my $sql_date = $dbh->quote(SqlifyDate($value));
2403 2404 2405 2406 2407 2408 2409
    my $join = {
        table => 'longdescs',
        as    => $table,
        extra => ["$table.work_time != 0",
                  "$table.bug_when $sql_operator $sql_date"],
    };
    push(@$joins, $join);
2410 2411
    
    $args->{term} = "$table.bug_when IS NOT NULL";
2412 2413 2414
}

sub _work_time {
2415
    my ($self, $args) = @_;
2416
    $self->_add_extra_column('actual_time');
2417
    $args->{full_field} = $self->COLUMNS->{actual_time}->{name};
2418 2419 2420
}

sub _percentage_complete {
2421
    my ($self, $args) = @_;
2422
    
2423
    $args->{full_field} = $self->COLUMNS->{percentage_complete}->{name};
2424

2425 2426 2427
    # We need actual_time in _select_columns, otherwise we can't use
    # it in the expression for searching percentage_complete.
    $self->_add_extra_column('actual_time');
2428 2429
}

2430
sub _days_elapsed {
2431
    my ($self, $args) = @_;
2432 2433
    my $dbh = Bugzilla->dbh;
    
2434 2435
    $args->{full_field} = "(" . $dbh->sql_to_days('NOW()') . " - " .
                                $dbh->sql_to_days('bugs.delta_ts') . ")";
2436 2437 2438
}

sub _component_nonchanged {
2439
    my ($self, $args) = @_;
2440
    
2441 2442 2443 2444 2445
    $args->{full_field} = "components.name";
    $self->_do_operator_function($args);
    my $term = $args->{term};
    $args->{term} = build_subselect("bugs.component_id",
        "components.id", "components", $args->{term});
2446
}
2447

2448
sub _product_nonchanged {
2449
    my ($self, $args) = @_;
2450 2451
    
    # Generate the restriction condition
2452 2453 2454 2455 2456
    $args->{full_field} = "products.name";
    $self->_do_operator_function($args);
    my $term = $args->{term};
    $args->{term} = build_subselect("bugs.product_id",
        "products.id", "products", $term);
2457 2458 2459
}

sub _classification_nonchanged {
2460 2461
    my ($self, $args) = @_;
    my $joins = $args->{joins};
2462
    
2463 2464 2465 2466
    # This joins the right tables for us.
    $self->_add_extra_column('product');
    
    # Generate the restriction condition    
2467 2468 2469
    $args->{full_field} = "classifications.name";
    $self->_do_operator_function($args);
    my $term = $args->{term};
2470
    $args->{term} = build_subselect("map_product.classification_id",
2471
        "classifications.id", "classifications", $term);
2472 2473
}

2474
sub _nullable {
2475
    my ($self, $args) = @_;
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
    my $field = $args->{full_field};
    $args->{full_field} = "COALESCE($field, '')";
}

sub _nullable_int {
    my ($self, $args) = @_;
    my $field = $args->{full_field};
    $args->{full_field} = "COALESCE($field, 0)";
}

sub _nullable_datetime {
    my ($self, $args) = @_;
    my $field = $args->{full_field};
    my $empty = Bugzilla->dbh->quote(EMPTY_DATETIME);
    $args->{full_field} = "COALESCE($field, $empty)";
}

sub _deadline {
    my ($self, $args) = @_;
    my $field = $args->{full_field};
    # This makes "equals" searches work on all DBs (even on MySQL, which
    # has a bug: http://bugs.mysql.com/bug.php?id=60324).
    $args->{full_field} = Bugzilla->dbh->sql_date_format($field, '%Y-%m-%d');
    $self->_nullable_datetime($args);
2500 2501 2502
}

sub _owner_idle_time_greater_less {
2503 2504 2505
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value, $operator) =
        @$args{qw(chart_id joins value operator)};
2506 2507
    my $dbh = Bugzilla->dbh;
    
2508 2509 2510 2511
    my $table = "idle_$chart_id";
    my $quoted = $dbh->quote(SqlifyDate($value));
    
    my $ld_table = "comment_$table";
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
    my $act_table = "activity_$table";    
    my $comments_join = {
        table => 'longdescs',
        as    => $ld_table,
        from  => 'assigned_to',
        to    => 'who',
        extra => ["$ld_table.bug_when > $quoted"],
    };
    my $activity_join = {
        table => 'bugs_activity',
        as    => $act_table,
        from  => 'assigned_to',
        to    => 'who',
        extra => ["$act_table.bug_when > $quoted"]
    };
    
    push(@$joins, $comments_join, $activity_join);
2529 2530 2531
    
    if ($operator =~ /greater/) {
        $args->{term} =
2532
            "$ld_table.who IS NULL AND $act_table.who IS NULL";
2533
    } else {
2534 2535
         $args->{term} =
            "$ld_table.who IS NOT NULL OR $act_table.who IS NOT NULL";
2536 2537 2538
    }
}

2539
sub _multiselect_negative {
2540 2541
    my ($self, $args) = @_;
    my ($field, $operator) = @$args{qw(field operator)};
2542

2543
    $args->{operator} = $self->_reverse_operator($operator);
2544
    $args->{term} = $self->_multiselect_term($args, 1);
2545 2546 2547
}

sub _multiselect_multiple {
2548
    my ($self, $args) = @_;
2549 2550
    my ($chart_id, $field, $operator, $value)
        = @$args{qw(chart_id field operator value)};
2551
    my $dbh = Bugzilla->dbh;
2552
    
2553 2554 2555 2556 2557 2558
    # We want things like "cf_multi_select=two+words" to still be
    # considered a search for two separate words, unless we're using
    # anyexact. (_all_values would consider that to be one "word" with a
    # space in it, because it's not in the Boolean Charts).
    my @words = $operator eq 'anyexact' ? $self->_all_values($args)
                                        : split(/[\s,]+/, $value);
2559
    
2560
    my @terms;
2561
    foreach my $word (@words) {
2562
        next if $word eq '';
2563
        $args->{value} = $word;
2564 2565
        $args->{quoted} = $dbh->quote($word);
        push(@terms, $self->_multiselect_term($args));
2566 2567
    }
    
2568
    # The spacing in the joins helps make the resulting SQL more readable.
2569
    if ($operator =~ /^any/) {
2570
        $args->{term} = join("\n        OR ", @terms);
2571 2572
    }
    else {
2573
        $args->{term} = join("\n        AND ", @terms);
2574 2575 2576
    }
}

2577 2578 2579 2580 2581 2582 2583
sub _multiselect_nonchanged {
    my ($self, $args) = @_;
    my ($chart_id, $joins, $field, $operator) =
        @$args{qw(chart_id joins field operator)};
    $args->{term} = $self->_multiselect_term($args)
}

2584 2585 2586
sub _multiselect_table {
    my ($self, $args) = @_;
    my ($field, $chart_id) = @$args{qw(field chart_id)};
2587 2588
    my $dbh = Bugzilla->dbh;
    
2589 2590 2591 2592 2593
    if ($field eq 'keywords') {
        $args->{full_field} = 'keyworddefs.name';
        return "keywords INNER JOIN keyworddefs".
                               " ON keywords.keywordid = keyworddefs.id";
    }
2594
    elsif ($field eq 'tag') {
2595
        $args->{full_field} = 'tag.name';
2596 2597
        return "bug_tag INNER JOIN tag ON bug_tag.tag_id = tag.id AND user_id = "
               . ($self->_sharer_id || $self->_user->id);
2598
    }
2599 2600 2601 2602 2603
    elsif ($field eq 'bug_group') {
        $args->{full_field} = 'groups.name';
        return "bug_group_map INNER JOIN groups
                                      ON bug_group_map.group_id = groups.id";
    }
2604 2605 2606
    elsif ($field eq 'blocked' or $field eq 'dependson') {
        my $select = $field eq 'blocked' ? 'dependson' : 'blocked';
        $args->{_select_field} = $select;
2607
        $args->{full_field} = $field;
2608 2609
        return "dependencies";
    }
2610 2611 2612 2613 2614 2615
    elsif ($field eq 'longdesc') {
        $args->{_extra_where} = " AND isprivate = 0"
            if !$self->_user->is_insider;
        $args->{full_field} = 'thetext';
        return "longdescs";
    }
2616 2617 2618 2619 2620 2621 2622 2623
    elsif ($field eq 'longdescs.isprivate') {
        ThrowUserError('auth_failure', { action => 'search',
                                         object => 'bug_fields',
                                         field => 'longdescs.isprivate' })
            if !$self->_user->is_insider;
        $args->{full_field} = 'isprivate';
        return "longdescs";
    }
2624 2625 2626 2627 2628 2629 2630
    elsif ($field =~ /^attachments/) {
        $args->{_extra_where} = " AND isprivate = 0"
            if !$self->_user->is_insider;
        $field =~ /^attachments\.(.+)$/;
        $args->{full_field} = $1;
        return "attachments";
    }
2631 2632 2633 2634 2635 2636
    elsif ($field eq 'attach_data.thedata') {
        $args->{_extra_where} = " AND attachments.isprivate = 0"
            if !$self->_user->is_insider;
        return "attachments INNER JOIN attach_data "
               . " ON attachments.attach_id = attach_data.id"
    }
2637 2638 2639 2640 2641
    elsif ($field eq 'flagtypes.name') {
        $args->{full_field} = $dbh->sql_string_concat("flagtypes.name",
                                                      "flags.status");
        return "flags INNER JOIN flagtypes ON flags.type_id = flagtypes.id";
    }
2642 2643 2644 2645 2646 2647
    my $table = "bug_$field";
    $args->{full_field} = "bug_$field.value";
    return $table;
}

sub _multiselect_term {
2648
    my ($self, $args, $not) = @_;
2649 2650 2651
    my $table = $self->_multiselect_table($args);
    $self->_do_operator_function($args);
    my $term = $args->{term};
2652
    $term .= $args->{_extra_where} || '';
2653
    my $select = $args->{_select_field} || 'bug_id';
2654 2655
    my $not_sql = $not ? "NOT " : '';
    return "bugs.bug_id ${not_sql}IN (SELECT $select FROM $table WHERE $term)";
2656 2657
}

2658 2659 2660 2661
###############################
# Standard Operator Functions #
###############################

2662 2663 2664 2665 2666 2667
sub _simple_operator {
    my ($self, $args) = @_;
    my ($full_field, $quoted, $operator) =
        @$args{qw(full_field quoted operator)};
    my $sql_operator = SIMPLE_OPERATORS->{$operator};
    $args->{term} = "$full_field $sql_operator $quoted";
2668 2669 2670
}

sub _casesubstring {
2671 2672
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
2673 2674
    my $dbh = Bugzilla->dbh;
    
2675
    $args->{term} = $dbh->sql_position($quoted, $full_field) . " > 0";
2676 2677 2678
}

sub _substring {
2679 2680
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
2681 2682
    my $dbh = Bugzilla->dbh;
    
2683 2684
    # XXX This should probably be changed to just use LIKE
    $args->{term} = $dbh->sql_iposition($quoted, $full_field) . " > 0";
2685 2686 2687
}

sub _notsubstring {
2688 2689
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
2690 2691
    my $dbh = Bugzilla->dbh;
    
2692 2693
    # XXX This should probably be changed to just use NOT LIKE
    $args->{term} = $dbh->sql_iposition($quoted, $full_field) . " = 0";
2694 2695 2696
}

sub _regexp {
2697 2698
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
2699 2700
    my $dbh = Bugzilla->dbh;
    
2701
    $args->{term} = $dbh->sql_regexp($full_field, $quoted);
2702 2703 2704
}

sub _notregexp {
2705 2706
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
2707 2708
    my $dbh = Bugzilla->dbh;
    
2709
    $args->{term} = $dbh->sql_not_regexp($full_field, $quoted);
2710 2711
}

2712
sub _anyexact {
2713
    my ($self, $args) = @_;
2714
    my ($field, $full_field) = @$args{qw(field full_field)};
2715 2716
    my $dbh = Bugzilla->dbh;
    
2717
    my @list = $self->_all_values($args, ',');
2718
    @list = map { $self->_quote_unless_numeric($args, $_) } @list;
2719
    
2720
    if (@list) {
2721 2722 2723
        $args->{term} = $dbh->sql_in($full_field, \@list);
    }
    else {
2724
        $args->{term} = '';
2725 2726 2727 2728
    }
}

sub _anywordsubstr {
2729
    my ($self, $args) = @_;
2730

2731 2732
    my @terms = $self->_substring_terms($args);
    $args->{term} = join("\n\tOR ", @terms);
2733 2734 2735
}

sub _allwordssubstr {
2736
    my ($self, $args) = @_;
2737

2738 2739
    my @terms = $self->_substring_terms($args);
    $args->{term} = join("\n\tAND ", @terms);
2740 2741 2742
}

sub _nowordssubstr {
2743 2744 2745 2746
    my ($self, $args) = @_;
    $self->_anywordsubstr($args);
    my $term = $args->{term};
    $args->{term} = "NOT($term)";
2747 2748 2749
}

sub _anywords {
2750
    my ($self, $args) = @_;
2751
    
2752 2753 2754 2755 2756
    my @terms = $self->_word_terms($args);
    # Because _word_terms uses AND, we need to parenthesize its terms
    # if there are more than one.
    @terms = map("($_)", @terms) if scalar(@terms) > 1;
    $args->{term} = join("\n\tOR ", @terms);
2757 2758 2759
}

sub _allwords {
2760
    my ($self, $args) = @_;
2761
    
2762 2763
    my @terms = $self->_word_terms($args);
    $args->{term} = join("\n\tAND ", @terms);
2764 2765 2766
}

sub _nowords {
2767 2768 2769 2770
    my ($self, $args) = @_;
    $self->_anywords($args);
    my $term = $args->{term};
    $args->{term} = "NOT($term)";
2771 2772 2773
}

sub _changedbefore_changedafter {
2774
    my ($self, $args) = @_;
2775 2776
    my ($chart_id, $joins, $field, $operator, $value) =
        @$args{qw(chart_id joins field operator value)};
2777
    my $dbh = Bugzilla->dbh;
2778

2779
    my $field_object = $self->_chart_fields->{$field}
2780
        || ThrowCodeError("invalid_field_name", { field => $field });
2781 2782 2783 2784 2785 2786 2787 2788 2789
    
    # Asking when creation_ts changed is just asking when the bug was created.
    if ($field_object->name eq 'creation_ts') {
        $args->{operator} =
            $operator eq 'changedbefore' ? 'lessthaneq' : 'greaterthaneq';
        return $self->_do_operator_function($args);
    }
    
    my $sql_operator = ($operator =~ /before/) ? '<=' : '>=';
2790
    my $field_id = $field_object->id;
2791 2792 2793 2794
    # Charts on changed* fields need to be field-specific. Otherwise,
    # OR chart rows make no sense if they contain multiple fields.
    my $table = "act_${field_id}_$chart_id";

2795
    my $sql_date = $dbh->quote(SqlifyDate($value));
2796 2797 2798 2799 2800 2801
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.bug_when $sql_operator $sql_date"],
    };
2802

2803
    $args->{term} = "$table.bug_when IS NOT NULL";
2804 2805
    $self->_changed_security_check($args, $join);
    push(@$joins, $join);
2806 2807 2808
}

sub _changedfrom_changedto {
2809
    my ($self, $args) = @_;
2810 2811
    my ($chart_id, $joins, $field, $operator, $quoted) =
        @$args{qw(chart_id joins field operator quoted)};
2812
    
2813
    my $column = ($operator =~ /from/) ? 'removed' : 'added';
2814
    my $field_object = $self->_chart_fields->{$field}
2815 2816
        || ThrowCodeError("invalid_field_name", { field => $field });
    my $field_id = $field_object->id;
2817
    my $table = "act_${field_id}_$chart_id";
2818 2819 2820 2821 2822 2823 2824
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.$column = $quoted"],
    };

2825
    $args->{term} = "$table.bug_when IS NOT NULL";
2826 2827
    $self->_changed_security_check($args, $join);
    push(@$joins, $join);
2828 2829 2830
}

sub _changedby {
2831
    my ($self, $args) = @_;
2832 2833
    my ($chart_id, $joins, $field, $operator, $value) =
        @$args{qw(chart_id joins field operator value)};
2834
    
2835
    my $field_object = $self->_chart_fields->{$field}
2836 2837
        || ThrowCodeError("invalid_field_name", { field => $field });
    my $field_id = $field_object->id;
2838
    my $table = "act_${field_id}_$chart_id";
2839
    my $user_id  = $self->_get_user_id($value);
2840 2841 2842 2843 2844 2845
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.who = $user_id"],
    };
2846

2847
    $args->{term} = "$table.bug_when IS NOT NULL";
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
    $self->_changed_security_check($args, $join);
    push(@$joins, $join);
}

sub _changed_security_check {
    my ($self, $args, $join) = @_;
    my ($chart_id, $field) = @$args{qw(chart_id field)};

    my $field_object = $self->_chart_fields->{$field}
        || ThrowCodeError("invalid_field_name", { field => $field });
    my $field_id = $field_object->id;

    # If the user is not part of the insiders group, they cannot see
    # changes to attachments (including attachment flags) that are private
    if ($field =~ /^(?:flagtypes\.name$|attach)/ and !$self->_user->is_insider) {
        $join->{then_to} = {
            as    => "attach_${field_id}_$chart_id",
            table => 'attachments',
            from  => "act_${field_id}_$chart_id.attach_id",
            to    => 'attach_id',
        };

        $args->{term} .= " AND COALESCE(attach_${field_id}_$chart_id.isprivate, 0) = 0";
    }
2872 2873
}

2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
######################
# Public Subroutines #
######################

# 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;
}

# Splits out "asc|desc" from a sort order item.
sub split_order_term {
    my $fragment = shift;
    $fragment =~ /^(.+?)(?:\s+(ASC|DESC))?$/i;
    my ($column_name, $direction) = (lc($1), uc($2 || ''));
    return wantarray ? ($column_name, $direction) : $column_name;
}

# Used to translate old SQL fragments from buglist.cgi's "order" argument
# into our modern field IDs.
2898 2899
sub _translate_old_column {
    my ($self, $column) = @_;
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
    # All old SQL fragments have a period in them somewhere.
    return $column if $column !~ /\./;

    if ($column =~ /\bAS\s+(\w+)$/i) {
        return $1;
    }
    # product, component, classification, assigned_to, qa_contact, reporter
    elsif ($column =~ /map_(\w+?)s?\.(login_)?name/i) {
        return $1;
    }
    
    # If it doesn't match the regexps above, check to see if the old 
    # SQL fragment matches the SQL of an existing column
2913 2914 2915
    foreach my $key (%{ $self->COLUMNS }) {
        next unless exists $self->COLUMNS->{$key}->{name};
        return $key if $self->COLUMNS->{$key}->{name} eq $column;
2916 2917 2918 2919 2920
    }

    return $column;
}

2921
1;