Search.pm 117 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
package Bugzilla::Search;

use 5.10.1;
11
use strict;
12
use warnings;
13

14
use parent qw(Exporter);
15 16 17 18
@Bugzilla::Search::EXPORT = qw(
    IsValidQueryType
    split_order_term
);
19

20
use Bugzilla::Error;
21
use Bugzilla::Util;
22
use Bugzilla::Constants;
23
use Bugzilla::Group;
24
use Bugzilla::User;
25
use Bugzilla::Field;
26
use Bugzilla::Search::Clause;
27
use Bugzilla::Search::ClauseGroup;
28
use Bugzilla::Search::Condition qw(condition);
29
use Bugzilla::Status;
30
use Bugzilla::Keyword;
31

32
use Data::Dumper;
33
use Date::Format;
34
use Date::Parse;
35
use Scalar::Util qw(blessed);
36
use List::MoreUtils qw(all firstidx part uniq);
37
use POSIX qw(INT_MAX floor);
38
use Storable qw(dclone);
39
use Time::HiRes qw(gettimeofday tv_interval);
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 102 103 104 105 106
# 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
# --------------------------------------------------------------

107 108 109 110
#############
# Constants #
#############

111 112
# When doing searches, NULL datetimes are treated as this date.
use constant EMPTY_DATETIME => '1970-01-01 00:00:00';
113
use constant EMPTY_DATE     => '1970-01-01';
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
# 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;

135 136 137
# If you specify a search type in the boolean charts, this describes
# which operator maps to which internal function here.
use constant OPERATORS => {
138 139
    equals         => \&_simple_operator,
    notequals      => \&_simple_operator,
140 141 142 143 144 145
    casesubstring  => \&_casesubstring,
    substring      => \&_substring,
    substr         => \&_substring,
    notsubstring   => \&_notsubstring,
    regexp         => \&_regexp,
    notregexp      => \&_notregexp,
146 147
    lessthan       => \&_simple_operator,
    lessthaneq     => \&_simple_operator,
148 149
    matches        => sub { ThrowUserError("search_content_without_matches"); },
    notmatches     => sub { ThrowUserError("search_content_without_matches"); },
150 151
    greaterthan    => \&_simple_operator,
    greaterthaneq  => \&_simple_operator,
152 153 154 155 156 157 158 159 160 161 162
    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,
163
    changedby      => \&_changedby,
164 165
    isempty        => \&_isempty,
    isnotempty     => \&_isnotempty,
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
};

# 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',
192 193
    isempty        => 'isnotempty',
    isnotempty     => 'isempty',
194 195
    # The following don't currently have reversals:
    # casesubstring, anyexact, allwords, allwordssubstr
196 197
};

198 199 200 201 202 203 204 205 206 207 208
# 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
);

209 210 211 212 213 214
# These operators ignore the entered value
use constant NO_VALUE_OPERATORS => qw(
    isempty
    isnotempty
);

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
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,
};

231 232 233
use constant OPERATOR_FIELD_OVERRIDE => {
    # User fields
    'attachments.submitter' => {
234
        _non_changed => \&_user_nonchanged,
235 236
    },
    assigned_to => {
237
        _non_changed => \&_user_nonchanged,
238
    },
239 240 241
    assigned_to_realname => {
        _non_changed => \&_user_nonchanged,
    },
242
    cc => {
243
        _non_changed => \&_user_nonchanged,
244 245
    },
    commenter => {
246
        _non_changed => \&_user_nonchanged,
247
    },
248
    reporter => {
249
        _non_changed => \&_user_nonchanged,
250
    },
251 252 253
    reporter_realname => {
        _non_changed => \&_user_nonchanged,
    },
254
    'requestees.login_name' => {
255
        _non_changed => \&_user_nonchanged,
256 257
    },
    'setters.login_name' => {
258 259
        _non_changed => \&_user_nonchanged,    
    },
260
    qa_contact => {
261
        _non_changed => \&_user_nonchanged,
262
    },
263 264 265 266
    qa_contact_realname => {
        _non_changed => \&_user_nonchanged,
    },

267
    # General Bug Fields
268
    alias        => { _non_changed => \&_alias_nonchanged },
269
    'attach_data.thedata' => MULTI_SELECT_OVERRIDE,
270 271 272 273 274
    # 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,
275 276 277 278 279 280 281 282 283 284 285 286
    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 => {
287
        _default => \&_days_elapsed,
288
    },
289 290
    dependson        => MULTI_SELECT_OVERRIDE,
    keywords         => MULTI_SELECT_OVERRIDE,
291 292 293
    'flagtypes.name' => {
        _non_changed => \&_flagtypes_nonchanged,
    },
294 295 296 297
    longdesc => {
        changedby     => \&_long_desc_changedby,
        changedbefore => \&_long_desc_changedbefore_after,
        changedafter  => \&_long_desc_changedbefore_after,
298
        _non_changed  => \&_long_desc_nonchanged,
299
    },
300 301 302 303 304 305 306 307
    '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,
    },
308
    'longdescs.isprivate' => MULTI_SELECT_OVERRIDE,
309 310 311 312 313
    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,
314
        _default      => \&_invalid_combination,
315 316 317 318
    },
    product => {
        _non_changed => \&_product_nonchanged,
    },
319
    tag => MULTI_SELECT_OVERRIDE,
320 321
    comment_tag => MULTI_SELECT_OVERRIDE,

322
    # Timetracking Fields
323
    deadline => { _non_changed => \&_deadline },
324
    percentage_complete => {
325
        _non_changed => \&_percentage_complete,
326 327 328 329 330 331 332
    },
    work_time => {
        changedby     => \&_work_time_changedby,
        changedbefore => \&_work_time_changedbefore_after,
        changedafter  => \&_work_time_changedbefore_after,
        _default      => \&_work_time,
    },
333 334 335 336
    last_visit_ts => {
        _non_changed => \&_last_visit_ts,
        _default     => \&_last_visit_ts_invalid_operator,
    },
337
    
338 339 340 341
    # Custom Fields
    FIELD_TYPE_FREETEXT, { _non_changed => \&_nullable },
    FIELD_TYPE_BUG_ID,   { _non_changed => \&_nullable_int },
    FIELD_TYPE_DATETIME, { _non_changed => \&_nullable_datetime },
342
    FIELD_TYPE_DATE,     { _non_changed => \&_nullable_date },
343 344 345
    FIELD_TYPE_TEXTAREA, { _non_changed => \&_nullable },
    FIELD_TYPE_MULTI_SELECT, MULTI_SELECT_OVERRIDE,
    FIELD_TYPE_BUG_URLS,     MULTI_SELECT_OVERRIDE,    
346 347 348 349
};

# These are fields where special action is taken depending on the
# *value* passed in to the chart, sometimes.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
# This is a sub because custom fields are dynamic
sub SPECIAL_PARSING {
    my $map = {
        # Pronoun Fields (Ones that can accept %user%, etc.)
        assigned_to => \&_contact_pronoun,
        cc          => \&_contact_pronoun,
        commenter   => \&_contact_pronoun,
        qa_contact  => \&_contact_pronoun,
        reporter    => \&_contact_pronoun,
        'setters.login_name' => \&_contact_pronoun,
        'requestees.login_name' => \&_contact_pronoun,

        # Date Fields that accept the 1d, 1w, 1m, 1y, etc. format.
        creation_ts => \&_datetime_translate,
        deadline    => \&_date_translate,
        delta_ts    => \&_datetime_translate,
366 367 368 369

        # last_visit field that accept both a 1d, 1w, 1m, 1y format and the
        # %last_changed% pronoun.
        last_visit_ts => \&_last_visit_datetime,
370 371 372 373 374 375 376 377 378
    };
    foreach my $field (Bugzilla->active_custom_fields) {
        if ($field->type == FIELD_TYPE_DATETIME) {
            $map->{$field->name} = \&_datetime_translate;
        } elsif ($field->type == FIELD_TYPE_DATE) {
            $map->{$field->name} = \&_date_translate;
        }
    }
    return $map;
379 380
};

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
# 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' },
    },
};

413 414
# Backwards compatibility for times that we changed the names of fields
# or URL parameters.
415
use constant FIELD_MAP => {
416
    'attachments.thedata' => 'attach_data.thedata',
417
    bugidtype => 'bug_id_type',
418
    changedin => 'days_elapsed',
419
    long_desc => 'longdesc',
420
    tags      => 'tag',
421 422
};

423
# Some fields are not sorted on themselves, but on other fields.
424
# We need to have a list of these fields and what they map to.
425
use constant SPECIAL_ORDER => {
426 427 428 429 430 431
    'target_milestone' => {
        order => ['map_target_milestone.sortkey','map_target_milestone.value'],
        join  => {
            table => 'milestones',
            from  => 'target_milestone',
            to    => 'value',
432
            extra => ['bugs.product_id = map_target_milestone.product_id'],
433 434 435
            join  => 'INNER',
        }
    },
436
};
437

438
# Certain columns require other columns to come before them
439
# in _select_columns, and should be put there if they're not there.
440 441 442 443 444 445 446 447 448
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.
449 450 451 452 453 454 455 456 457 458
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',
        },
459 460 461 462
        alias => {
            table => 'bugs_aliases',
            as => 'map_alias',
        },
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        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',
482
            to    => 'id',
483 484
            table => 'components',
            join  => 'INNER',
485
        },
486 487
        product => {
            from  => 'product_id',
488
            to    => 'id',
489 490
            table => 'products',
            join  => 'INNER',
491
        },
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        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',
            },
        },
518 519 520 521 522 523 524 525
        blocked => {
            table => 'dependencies',
            to => 'dependson',
        },
        dependson => {
            table => 'dependencies',
            to => 'blocked',
        },
526 527 528 529 530 531 532 533 534 535 536 537 538 539
        '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',
            },
540 541 542 543 544 545 546 547
        },
        last_visit_ts => {
            as    => 'bug_user_last_visit',
            table => 'bug_user_last_visit',
            extra => ['bug_user_last_visit.user_id = ' . $user->id],
            from  => 'bug_id',
            to    => 'bug_id',
        },
548 549
    };
    return $joins;
550 551
};

552 553 554 555 556 557 558 559 560 561 562 563
# 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.
564 565
#       In particular, the redundant short_desc column is removed when the
#       client requests "all" columns.
566 567 568 569 570 571 572
#
# 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 {
573 574
    my $invocant = shift;
    my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;
575 576
    my $dbh = Bugzilla->dbh;
    my $cache = Bugzilla->request_cache;
577 578 579 580

    if (defined $cache->{search_columns}->{$user->id}) {
        return $cache->{search_columns}->{$user->id};
    }
581 582 583 584 585 586 587 588 589 590

    # 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'  },
    );

    # Next we define columns that have special SQL instead of just something
    # like "bugs.bug_id".
591
    my $total_time = "(map_actual_time.total + bugs.remaining_time)";
592
    my %special_sql = (
593
        alias       => $dbh->sql_group_concat('DISTINCT map_alias.alias'),
594
        deadline    => $dbh->sql_date_format('bugs.deadline', '%Y-%m-%d'),
595
        actual_time => 'map_actual_time.total',
596

597 598 599 600
        # "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.
601
        percentage_complete =>
602 603 604 605
            "(CASE WHEN $total_time = 0"
               . " THEN 0"
               . " ELSE FLOOR(100 * (map_actual_time.total / $total_time))"
                . " END)",
606

607
        'flagtypes.name' => $dbh->sql_group_concat('DISTINCT ' 
608 609
            . $dbh->sql_string_concat('map_flagtypes.name', 'map_flags.status'),
            undef, undef, 'map_flagtypes.sortkey, map_flagtypes.name'),
610

611
        'keywords' => $dbh->sql_group_concat('DISTINCT map_keyworddefs.name'),
612 613 614

        blocked => $dbh->sql_group_concat('DISTINCT map_blocked.blocked'),
        dependson => $dbh->sql_group_concat('DISTINCT map_dependson.dependson'),
615 616
        
        'longdescs.count' => 'COUNT(DISTINCT map_longdescs_count.comment_id)',
617

618
        tag => $dbh->sql_group_concat('DISTINCT map_tag.name'),
619
        last_visit_ts => 'bug_user_last_visit.last_visit_ts',
620 621 622
    );

    # Backward-compatibility for old field names. Goes new_name => old_name.
623
    # These are here and not in _translate_old_column because the rest of the
624
    # code actually still uses the old names, while the fielddefs table uses
625 626
    # the new names (which is not the case for the fields handled by
    # _translate_old_column).
627 628 629 630 631 632 633 634 635 636 637 638 639 640
    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";
641
        if (!$user->id) {
642 643 644
             $sql = $dbh->sql_string_until($sql, $dbh->quote('@'));
        }
        $special_sql{$col} = $sql;
645
        $special_sql{"${col}_realname"} = "map_${col}.realname";
646 647 648
    }

    foreach my $col (@id_fields) {
649
        $special_sql{$col} = "map_${col}.name";
650 651 652
    }

    # Do the actual column-getting from fielddefs, now.
653 654
    my @fields = @{ Bugzilla->fields({ obsolete => 0, buglist => 1 }) };
    foreach my $field (@fields) {
655 656
        my $id = $field->name;
        $id = $old_names{$id} if exists $old_names{$id};
657 658 659 660 661 662
        my $sql;
        if (exists $special_sql{$id}) {
            $sql = $special_sql{$id};
        }
        elsif ($field->type == FIELD_TYPE_MULTI_SELECT) {
            $sql = $dbh->sql_group_concat(
663
                'DISTINCT map_' . $field->name . '.value');
664 665 666 667
        }
        else {
            $sql = 'bugs.' . $field->name;
        }
668 669 670 671 672 673
        $columns{$id} = { name => $sql, title => $field->description };
    }

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

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

676 677
    $cache->{search_columns}->{$user->id} = \%columns;
    return $cache->{search_columns}->{$user->id};
678 679
}

680
sub REPORT_COLUMNS {
681 682 683 684
    my $invocant = shift;
    my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;

    my $columns = dclone(blessed($invocant) ? $invocant->COLUMNS : COLUMNS);
685 686 687 688 689
    # 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
690
           flagtypes.name relevance);
691 692 693

    # If you're not a time-tracker, you can't use time-tracking
    # columns.
694
    if (!$user->is_timetracker) {
695 696 697 698 699 700 701 702 703
        push(@no_report_columns, TIMETRACKING_FIELDS);
    }

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

704 705 706
# 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.
707
use constant GROUP_BY_SKIP => qw(
708
    alias
709
    blocked
710
    bug_id
711
    dependson
712 713
    flagtypes.name
    keywords
714
    longdescs.count
715
    percentage_complete
Frédéric Buclin's avatar
Frédéric Buclin committed
716
    tag
717 718
);

719 720 721 722 723 724 725 726 727 728 729 730
###############
# 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;
731 732 733 734 735 736 737 738 739 740 741 742 743
    
    # 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;
744 745 746 747 748 749 750 751 752

    return $self;
}


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

753 754 755 756 757 758 759 760 761 762 763 764
sub data {
    my $self = shift;
    return $self->{data} if $self->{data};
    my $dbh = Bugzilla->dbh;

    # If all fields belong to the 'bugs' table, there is no need to split
    # the original query into two pieces. Else we override the 'fields'
    # argument to first get bug IDs based on the search criteria defined
    # by the caller, and the desired fields are collected in the 2nd query.
    my @orig_fields = $self->_input_columns;
    my $all_in_bugs_table = 1;
    foreach my $field (@orig_fields) {
765
        next if ($self->COLUMNS->{$field}->{name} // $field) =~ /^bugs\.\w+$/;
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        $self->{fields} = ['bug_id'];
        $all_in_bugs_table = 0;
        last;
    }

    my $start_time = [gettimeofday()];
    my $sql = $self->_sql;
    # Do we just want bug IDs to pass to the 2nd query or all the data immediately?
    my $func = $all_in_bugs_table ? 'selectall_arrayref' : 'selectcol_arrayref';
    my $bug_ids = $dbh->$func($sql);
    my @extra_data = ({sql => $sql, time => tv_interval($start_time)});
    # Restore the original 'fields' argument, just in case.
    $self->{fields} = \@orig_fields unless $all_in_bugs_table;

    # If there are no bugs found, or all fields are in the 'bugs' table,
    # there is no need for another query.
    if (!scalar @$bug_ids || $all_in_bugs_table) {
        $self->{data} = $bug_ids;
        return wantarray ? ($self->{data}, \@extra_data) : $self->{data};
    }

    # Make sure the bug_id will be returned. If not, append it to the list.
    my $pos = firstidx { $_ eq 'bug_id' } @orig_fields;
    if ($pos < 0) {
        push(@orig_fields, 'bug_id');
        $pos = $#orig_fields;
    }

    # Now create a query with the buglist above as the single criteria
    # and the fields that the caller wants. No need to redo security checks;
    # the list has already been validated above.
    my $search = $self->new('fields' => \@orig_fields,
                            'params' => {bug_id => $bug_ids, bug_id_type => 'anyexact'},
                            'sharer' => $self->_sharer_id,
                            'user'   => $self->_user,
                            'allow_unlimited'    => 1,
                            '_no_security_check' => 1);

    $start_time = [gettimeofday()];
    $sql = $search->_sql;
    my $unsorted_data = $dbh->selectall_arrayref($sql);
    push(@extra_data, {sql => $sql, time => tv_interval($start_time)});
    # Let's sort the data. We didn't do it in the query itself because
    # we already know in which order to sort bugs thanks to the first query,
    # and this avoids additional table joins in the SQL query.
    my %data = map { $_->[$pos] => $_ } @$unsorted_data;
    $self->{data} = [map { $data{$_} } @$bug_ids];
    return wantarray ? ($self->{data}, \@extra_data) : $self->{data};
}

sub _sql {
817 818 819
    my ($self) = @_;
    return $self->{sql} if $self->{sql};
    my $dbh = Bugzilla->dbh;
820

821
    my ($joins, $clause) = $self->_charts_to_conditions();
822 823 824 825 826 827 828 829

    if (!$clause->as_string
        && !Bugzilla->params->{'search_allow_no_criteria'}
        && !$self->{allow_unlimited})
    {
        ThrowUserError('buglist_parameters_required');
    }

830 831
    my $select = join(', ', $self->_sql_select);
    my $from = $self->_sql_from($joins);
832
    my $where = $self->_sql_where($clause);
833 834 835
    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) : '';
836 837
    my $limit = $self->_sql_limit;
    $limit = "\n$limit" if $limit;
838 839 840 841 842
    
    my $query = <<END;
SELECT $select
  FROM $from
 WHERE $where
843
$group_by$order_by$limit
844 845 846 847 848 849 850 851 852 853 854 855 856 857
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 {
858
        $self->_sql;
859 860 861 862
    }
    return $self->{'search_description'};
}

863 864
sub boolean_charts_to_custom_search {
    my ($self, $cgi_buffer) = @_;
865 866
    my $boolean_charts = $self->_boolean_charts;
    my @as_params = $boolean_charts ? $boolean_charts->as_params : ();
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

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

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
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;
}

898 899 900 901
######################
# Internal Accessors #
######################

902
# Fields that are legal for boolean charts of any kind.
903 904 905 906 907 908
sub _chart_fields {
    my ($self) = @_;

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

909
        if (!$self->_user->is_timetracker) {
910 911 912 913 914 915 916 917 918
            foreach my $tt_field (TIMETRACKING_FIELDS) {
                delete $chart_fields->{$tt_field};
            }
        }
        $self->{chart_fields} = $chart_fields;
    }
    return $self->{chart_fields};
}

919 920 921
# 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.
922 923 924
sub _multi_select_fields {
    my ($self) = @_;
    $self->{multi_select_fields} ||= Bugzilla->fields({
925 926
        by_name => 1,
        type    => [FIELD_TYPE_MULTI_SELECT, FIELD_TYPE_BUG_URLS]});
927 928 929
    return $self->{multi_select_fields};
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
# $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} }
946
sub _user { return $_[0]->{user} }
947
sub _sharer_id { $_[0]->{sharer} }
948

949 950 951
##############################
# Internal Accessors: SELECT #
##############################
952 953 954 955 956 957 958 959 960 961

# 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
962
    # in the SELECT.
963
    push(@{ $self->{extra_columns} }, $self->_valid_order_columns);
964 965 966 967 968 969 970 971 972 973 974 975
    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.
976 977
sub _display_columns {
    my ($self) = @_;
978 979 980 981 982 983 984 985 986 987 988 989 990
    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;
991 992 993 994
    return @{ $self->{display_columns} };
}

# These are the columns that are involved in the query.
995 996 997 998 999
sub _select_columns {
    my ($self) = @_;
    return @{ $self->{select_columns} } if $self->{select_columns};

    my @select_columns;
1000
    foreach my $column ($self->_display_columns) {
1001 1002
        if (my $add_first = COLUMN_DEPENDS->{$column}) {
            push(@select_columns, @$add_first);
1003
        }
1004
        push(@select_columns, $column);
1005
    }
1006
    # Remove duplicated columns.
1007 1008
    $self->{select_columns} = [uniq @select_columns];
    return @{ $self->{select_columns} };
1009 1010
}

1011
# This takes _display_columns and translates it into the actual SQL that
1012 1013 1014 1015
# will go into the SELECT clause.
sub _sql_select {
    my ($self) = @_;
    my @sql_fields;
1016
    foreach my $column ($self->_display_columns) {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        my $sql = $self->COLUMNS->{$column}->{name} // '';
        if ($sql) {
            my $alias = $column;
            # Aliases cannot contain dots in them. We convert them to underscores.
            $alias =~ tr/./_/;
            $sql .= " AS $alias";
        }
        else {
            $sql = $column;
        }
1027 1028 1029 1030 1031
        push(@sql_fields, $sql);
    }
    return @sql_fields;
}

1032 1033 1034
################################
# Internal Accessors: ORDER BY #
################################
1035 1036 1037 1038

# The "order" that was requested by the consumer, exactly as it was
# requested.
sub _input_order { @{ $_[0]->{'order'} || [] } }
1039 1040 1041 1042 1043 1044 1045
# 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 {
1046
    my ($self) = @_;
1047 1048 1049 1050 1051 1052 1053 1054
    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);
1055
    $field = $self->_translate_old_column($field);
1056 1057

    # Only accept valid columns
1058
    return if (!exists $self->COLUMNS->{$field});
1059 1060

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

    $direction = " $direction" if $direction;
    return "$field$direction";
1065
}
1066 1067 1068

# A hashref that describes all the special stuff that has to be done
# for various fields if they go into the ORDER BY clause.
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
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};
}

1092 1093 1094 1095
sub _sql_order_by {
    my ($self) = @_;
    if (!$self->{sql_order_by}) {
        my @order_by = map { $self->_translate_order_by_column($_) }
1096
                           $self->_valid_order;
1097 1098 1099 1100 1101
        $self->{sql_order_by} = \@order_by;
    }
    return @{ $self->{sql_order_by} };
}

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
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;
}

1119 1120 1121 1122 1123 1124 1125 1126
#############################
# Internal Accessors: LIMIT #
#############################

sub _sql_limit {
    my ($self) = @_;
    my $limit = $self->_params->{limit};
    my $offset = $self->_params->{offset};
1127 1128 1129 1130 1131 1132
    
    my $max_results = Bugzilla->params->{'max_search_results'};
    if (!$self->{allow_unlimited} && (!$limit || $limit > $max_results)) {
        $limit = $max_results;
    }
    
1133
    if (defined($offset) && !$limit) {
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        $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 '';
}

1152 1153 1154
############################
# Internal Accessors: FROM #
############################
1155

1156 1157
sub _column_join {
    my ($self, $field) = @_;
1158 1159
    # The _realname fields require the same join as the username fields.
    $field =~ s/_realname$//;
1160 1161
    my $column_joins = $self->_get_column_joins();
    my $join_info = $column_joins->{$field};
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    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
1233 1234
# modified by the charts.
sub _select_order_joins {
1235 1236
    my ($self) = @_;
    my @joins;
1237
    foreach my $field ($self->_select_columns) {
1238 1239 1240
        my @column_join = $self->_column_join($field);
        push(@joins, @column_join);
    }
1241
    foreach my $field ($self->_valid_order_columns) {
1242 1243
        my $join_info = $self->_special_order->{$field}->{join};
        if ($join_info) {
1244 1245 1246 1247 1248 1249
            # 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);
1250 1251 1252
        }
    }
    return @joins;
1253 1254
}

1255 1256 1257
# These are the joins that are *always* in the FROM clause.
sub _standard_joins {
    my ($self) = @_;
1258
    my $user = $self->_user;
1259
    my @joins;
1260
    return () if $self->{_no_security_check};
1261 1262 1263 1264 1265 1266 1267 1268

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

    if ($user->id) {
1269 1270 1271 1272 1273 1274
        # See also _standard_joins for the other half of the below statement
        if (!Bugzilla->params->{'or_groups'}) {
            $security_join->{extra} =
                ["NOT (" . $user->groups_in_sql('security_map.group_id') . ")"];
        }

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
        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);
}

1296
# This takes a join data structure and turns it into actual JOIN SQL.
1297 1298 1299 1300 1301
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};
1302 1303

    my $from_table = $join_info->{bugs_table} || "bugs";
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    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;
}

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
#############################
# 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) = @_;
1340
    return ('1=1') if $self->{_no_security_check};
1341 1342 1343 1344 1345 1346 1347 1348 1349
    # 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 $user = $self->_user;
1350 1351 1352 1353 1354 1355 1356 1357 1358
    my $security_term = '';
    # See also _standard_joins for the other half of the below statement
    if (Bugzilla->params->{'or_groups'}) {
        $security_term .= " (security_map.group_id IS NULL OR security_map.group_id IN (" . $user->groups_as_string . "))";
    }
    else {
        $security_term = 'security_map.group_id IS NULL';
    }

1359 1360
    if ($user->id) {
        my $userid = $user->id;
1361
        # This indentation makes the resulting SQL more readable.
1362
        $security_term .= <<END;
1363 1364 1365 1366

        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
1367 1368
END
        if (Bugzilla->params->{'useqacontact'}) {
1369
            $security_term.= "        OR bugs.qa_contact = $userid";
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        }
        $security_term = "($security_term)";
    }

    push(@where, $security_term);

    return @where;
}

sub _sql_where {
1380
    my ($self, $main_clause) = @_;
1381 1382
    # The newline and this particular spacing makes the resulting
    # SQL a bit more readable for debugging.
1383 1384
    my $where = join("\n   AND ", $self->_standard_where);
    my $clause_sql = $main_clause->as_string;
1385
    $where .= "\n   AND " . $clause_sql if $clause_sql;
1386
    return $where;
1387 1388
}

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
################################
# 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};
1403
        my $sql = $self->COLUMNS->{$column}->{name} // $column;
1404 1405 1406 1407 1408
        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.
1409
    foreach my $column ($self->_valid_order_columns) {
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        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};
}

1432 1433 1434 1435
##############################################
# Internal Accessors: Special Params Parsing #
##############################################

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
# 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};
        }
    }
}
1454

1455 1456 1457
# This parses all the standard search parameters except for the boolean
# charts.
sub _special_charts {
1458
    my ($self) = @_;
1459
    $self->_convert_old_params();
1460 1461
    $self->_special_parse_bug_status();
    $self->_special_parse_resolution();
1462 1463 1464 1465 1466 1467
    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;
1468 1469 1470 1471 1472 1473 1474
}

sub _parse_basic_fields {
    my ($self) = @_;
    my $params = $self->_params;
    my $chart_fields = $self->_chart_fields;
    
1475
    my $clause = new Bugzilla::Search::Clause();
1476 1477 1478 1479 1480
    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;
1481 1482
        my @values = $self->_param_array($param_name);
        next if !@values;
1483 1484
        my $default_op = $param_name eq 'content' ? 'matches' : 'anyexact';
        my $operator = $params->{"${param_name}_type"} || $default_op;
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        # 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);
        }
1499
        $clause->add($field_name, $operator, $pass_value);
1500
    }
1501
    return @{$clause->children} ? $clause : undef;
1502 1503 1504 1505 1506
}

sub _special_parse_bug_status {
    my ($self) = @_;
    my $params = $self->_params;
1507
    return if !defined $params->{'bug_status'};
1508 1509 1510 1511 1512
    # 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');
1513

1514
    my @bug_status = $self->_param_array('bug_status');
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    # 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;
1532 1533 1534
    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).
1535 1536 1537
    @bug_status = _valid_values(\@bug_status, $legal_statuses);

    # If the user has selected every status, change to selecting none.
1538
    # This is functionally equivalent, but quite a lot faster.
1539
    if ($all or scalar(@bug_status) == scalar(@$legal_statuses)) {
1540
        delete $params->{'bug_status'};
1541 1542
    }
    else {
1543
        $params->{'bug_status'} = \@bug_status;
1544 1545 1546
    }
}

1547 1548 1549 1550
sub _special_parse_chfield {
    my ($self) = @_;
    my $params = $self->_params;
    
1551 1552
    my $date_from = trim(lc($params->{'chfieldfrom'} || ''));
    my $date_to = trim(lc($params->{'chfieldto'} || ''));
1553 1554
    $date_from = '' if $date_from eq 'now';
    $date_to = '' if $date_to eq 'now';
1555 1556
    my @fields = $self->_param_array('chfield');
    my $value_to = $params->{'chfieldvalue'};
1557 1558
    $value_to = '' if !defined $value_to;

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

1561 1562
    return undef unless ($date_from ne '' || $date_to ne '' || $value_to ne '');

1563 1564
    my $clause = new Bugzilla::Search::Clause();

1565
    # It is always safe and useful to push delta_ts into the charts
1566
    # if there is a "from" date specified. It doesn't conflict with
1567 1568
    # searching [Bug creation], because a bug's delta_ts is set to
    # its creation_ts when it is created. So this just gives the
1569 1570
    # database an additional index to possibly choose, on a table that
    # is smaller than bugs_activity.
1571
    if ($date_from ne '') {
1572
        $clause->add('delta_ts', 'greaterthaneq', $date_from);
1573
    }
1574 1575 1576 1577 1578 1579 1580
    # 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 '') {
1581
        $clause->add('delta_ts', 'lessthaneq', $date_to);
1582
    }
1583

1584 1585 1586 1587
    # 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}$/;
1588

1589 1590 1591 1592 1593 1594 1595 1596
    my $join_clause = new Bugzilla::Search::Clause('OR');

    foreach my $field (@fields) {
        my $sub_clause = new Bugzilla::Search::ClauseGroup();
        $sub_clause->add(condition($field, 'changedto', $value_to)) if $value_to ne '';
        $sub_clause->add(condition($field, 'changedafter', $date_from)) if $date_from ne '';
        $sub_clause->add(condition($field, 'changedbefore', $date_to)) if $date_to ne '';
        $join_clause->add($sub_clause);
1597
    }
1598
    $clause->add($join_clause);
1599

1600
    return @{$clause->children} ? $clause : undef;
1601 1602
}

1603 1604 1605
sub _special_parse_deadline {
    my ($self) = @_;
    my $params = $self->_params;
1606

1607
    my $clause = new Bugzilla::Search::Clause();
1608
    if (my $from = $params->{'deadlinefrom'}) {
1609
        $clause->add('deadline', 'greaterthaneq', $from);
1610
    }
1611
    if (my $to = $params->{'deadlineto'}) {
1612
        $clause->add('deadline', 'lessthaneq', $to);
1613
    }
1614 1615

    return @{$clause->children} ? $clause : undef;
1616 1617
}

1618 1619 1620 1621
sub _special_parse_email {
    my ($self) = @_;
    my $params = $self->_params;
    
1622
    my @email_params = grep { $_ =~ /^email\d+$/ } keys %$params;
1623
    
1624
    my $clause = new Bugzilla::Search::Clause();
1625 1626 1627
    foreach my $param (@email_params) {
        $param =~ /(\d+)$/;
        my $id = $1;
1628 1629 1630
        my $email = trim($params->{"email$id"});
        next if !$email;
        my $type = $params->{"emailtype$id"} || 'anyexact';
1631 1632
        $type = "anyexact" if $type eq "exact";

1633
        my $or_clause = new Bugzilla::Search::Clause('OR');
1634
        foreach my $field (qw(assigned_to reporter cc qa_contact)) {
1635
            if ($params->{"email$field$id"}) {
1636
                $or_clause->add($field, $type, $email);
1637 1638
            }
        }
1639
        if ($params->{"emaillongdesc$id"}) {
1640
            $or_clause->add("commenter", $type, $email);
1641
        }
1642 1643
        
        $clause->add($or_clause);
1644
    }
1645 1646

    return @{$clause->children} ? $clause : undef;
1647 1648
}

1649 1650 1651
sub _special_parse_resolution {
    my ($self) = @_;
    my $params = $self->_params;
1652
    return if !defined $params->{'resolution'};
1653

1654
    my @resolution = $self->_param_array('resolution');
1655 1656 1657
    my $legal_resolutions = $self->_chart_fields->{resolution}->legal_values;
    @resolution = _valid_values(\@resolution, $legal_resolutions, '---');
    if (scalar(@resolution) == scalar(@$legal_resolutions)) {
1658
        delete $params->{'resolution'};
1659 1660 1661
    }
}

1662 1663 1664 1665
sub _valid_values {
    my ($input, $valid, $extra_value) = @_;
    my @result;
    foreach my $item (@$input) {
1666
        $item = trim($item);
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
        if (defined $extra_value and $item eq $extra_value) {
            push(@result, $item);
        }
        elsif (grep { $_->name eq $item } @$valid) {
            push(@result, $item);
        }
    }
    return @result;
}

1677 1678 1679 1680 1681 1682 1683
######################################
# Internal Accessors: Boolean Charts #
######################################

sub _charts_to_conditions {
    my ($self) = @_;
    
1684 1685 1686
    my $clause = $self->_charts;
    my @joins;
    $clause->walk_conditions(sub {
1687
        my ($clause, $condition) = @_;
1688 1689 1690 1691 1692
        return if !$condition->translated;
        push(@joins, @{ $condition->translated->{joins} });
    });
    return (\@joins, $clause);
}
1693

1694 1695 1696 1697 1698 1699 1700
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;
1701 1702
}

1703
sub _params_to_data_structure {
1704
    my ($self) = @_;
1705 1706
    
    # First we get the "special" charts, representing all the normal
1707
    # fields on the search page. This may modify _params, so it needs to
1708 1709 1710
    # happen first.
    my $clause = $self->_special_charts;

1711 1712 1713 1714 1715
    # 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 );
1716
    
1717 1718 1719 1720 1721 1722
    return $clause;
}

sub _boolean_charts {
    my ($self) = @_;
    
1723
    my $params = $self->_params;
1724
    my @param_list = keys %$params;
1725 1726 1727 1728 1729
    
    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;
    
1730
    my $clause = new Bugzilla::Search::Clause();
1731 1732 1733 1734 1735
    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;
        
1736
        my $and_clause = new Bugzilla::Search::Clause();
1737 1738 1739 1740 1741
        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;
            
1742
            my $or_clause = new Bugzilla::Search::Clause('OR');
1743
            foreach my $or_id (@or_ids) {
1744 1745 1746
                my $identifier = "$chart_id-$and_id-$or_id";
                my $field = $params->{"field$identifier"};
                my $operator = $params->{"type$identifier"};
1747
                my $value = $params->{"value$identifier"};
1748 1749
                # no-value operators ignore the value, however a value needs to be set
                $value = ' ' if $operator && grep { $_ eq $operator } NO_VALUE_OPERATORS;
1750
                $or_clause->add($field, $operator, $value);
1751
            }
1752 1753
            $and_clause->add($or_clause);
            $and_clause->negate(1) if $params->{"negate$chart_id"};
1754
        }
1755
        $clause->add($and_clause);
1756
    }
1757 1758

    return @{$clause->children} ? $clause : undef;
1759 1760
}

1761 1762 1763
sub _custom_search {
    my ($self) = @_;
    my $params = $self->_params;
1764

1765 1766 1767
    my @field_ids = $self->_field_ids;
    return unless scalar @field_ids;

1768 1769 1770 1771 1772
    my $joiner = $params->{j_top} || '';
    my $current_clause = $joiner eq 'AND_G'
        ? new Bugzilla::Search::ClauseGroup()
        : new Bugzilla::Search::Clause($joiner);

1773
    my @clause_stack;
1774
    foreach my $id (@field_ids) {
1775 1776
        my $field = $params->{"f$id"};
        if ($field eq 'OP') {
1777 1778 1779 1780
            my $joiner = $params->{"j$id"} || '';
            my $new_clause = $joiner eq 'AND_G'
                ? new Bugzilla::Search::ClauseGroup()
                : new Bugzilla::Search::Clause($joiner);
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
            $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"};
1796 1797
        # no-value operators ignore the value, however a value needs to be set
        $value = ' ' if $operator && grep { $_ eq $operator } NO_VALUE_OPERATORS;
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
        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;
}

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
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;
}

1820
sub _handle_chart {
1821
    my ($self, $chart_id, $clause, $condition) = @_;
1822 1823
    my $dbh = Bugzilla->dbh;
    my $params = $self->_params;
1824
    my ($field, $operator, $value) = $condition->fov;
1825
    return if (!defined $field or !defined $operator or !defined $value);
1826
    $field = FIELD_MAP->{$field} || $field;
1827 1828

    my ($string_value, $orig_value);
1829 1830
    state $is_mysql = $dbh->isa('Bugzilla::DB::Mysql') ? 1 : 0;

1831 1832 1833 1834 1835
    if (ref $value eq 'ARRAY') {
        # Trim input and ignore blank values.
        @$value = map { trim($_) } @$value;
        @$value = grep { defined $_ and $_ ne '' } @$value;
        return if !@$value;
1836
        $orig_value = join(',', @$value);
1837
        if ($field eq 'longdesc' && $is_mysql) {
1838 1839
            @$value = map { _convert_unicode_characters($_) } @$value;
        }
1840 1841 1842 1843
        $string_value = join(',', @$value);
    }
    else {
        return if $value eq '';
1844
        $orig_value = $value;
1845 1846 1847
        if ($field eq 'longdesc' && $is_mysql) {
            $value = _convert_unicode_characters($value);
        }
1848 1849
        $string_value = $value;
    }
1850

1851 1852 1853
    $self->_chart_fields->{$field}
        or ThrowCodeError("invalid_field_name", { field => $field });
    trick_taint($field);
1854
    
1855 1856 1857
    # This is the field as you'd reference it in a SQL statement.
    my $full_field = $field =~ /\./ ? $field : "bugs.$field";

1858 1859 1860 1861 1862
    # "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.
    #
1863
    # all_values is for search functions that do operate
1864
    # on multiple values, like anyexact.
1865
    
1866
    my %search_args = (
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
        chart_id     => $chart_id,
        sequence     => $chart_id,
        field        => $field,
        full_field   => $full_field,
        operator     => $operator,
        value        => $string_value,
        all_values   => $value,
        joins        => [],
        bugs_table   => 'bugs',
        table_suffix => '',
1877
        condition    => $condition,
1878
    );
1879 1880
    $clause->update_search_args(\%search_args);

1881
    $search_args{quoted} = $self->_quote_unless_numeric(\%search_args);
1882 1883
    # This should add a "term" selement to %search_args.
    $self->do_search_function(\%search_args);
1884 1885 1886 1887 1888

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

1889 1890 1891 1892 1893
    # 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,
1894
        value => $orig_value, term => $search_args{term},
1895
    });
1896 1897 1898 1899 1900 1901

    foreach my $join (@{ $search_args{joins} }) {
        $join->{bugs_table}   = $search_args{bugs_table};
        $join->{table_suffix} = $search_args{table_suffix};
    }

1902
    $condition->translated(\%search_args);
1903
}
1904

1905 1906 1907 1908 1909 1910
# XXX - This is a hack for MySQL which doesn't understand Unicode characters
# above U+FFFF, see Bugzilla::Comment::_check_thetext(). This hack can go away
# once we require MySQL 5.5.3 and use utf8mb4.
sub _convert_unicode_characters {
    my $string = shift;

1911 1912 1913
    # Perl 5.13.8 and older complain about non-characters.
    no warnings 'utf8';
    $string =~ s/([\x{10000}-\x{10FFFF}])/"\x{FDD0}[" . uc(sprintf('U+%04x', ord($1))) . "]\x{FDD1}"/eg;
1914 1915 1916
    return $string;
}

1917
##################################
1918
# do_search_function And Helpers #
1919 1920
##################################

1921 1922 1923 1924
# 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) = @_;
1925
    my ($field, $operator) = @$args{qw(field operator)};
1926
    
1927
    if (my $parse_func = SPECIAL_PARSING->{$field}) {
1928
        $self->$parse_func($args);
1929 1930 1931
        # Some parsing functions set $term, though most do not.
        # For the ones that set $term, we don't need to do any further
        # parsing.
1932
        return if $args->{term};
1933 1934
    }
    
1935
    my $operator_field_override = $self->_get_operator_field_override();
1936
    my $override = $operator_field_override->{$field};
1937 1938
    # Attachment fields get special handling, if they don't have a specific
    # individual override.
1939
    if (!$override and $field =~ /^attachments\./) {
1940 1941 1942
        $override = $operator_field_override->{attachments};
    }
    # If there's still no override, check for an override on the field's type.
1943
    if (!$override) {
1944
        my $field_obj = $self->_chart_fields->{$field};
1945
        $override = $operator_field_override->{$field_obj->type};
1946 1947 1948
    }
    
    if ($override) {
1949 1950
        my $search_func = $self->_pick_override_function($override, $operator);
        $self->$search_func($args) if $search_func;
1951 1952 1953 1954 1955
    }

    # 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.
1956
    if (!defined $args->{term}) {
1957 1958
        $self->_do_operator_function($args);
    }
1959 1960 1961 1962 1963 1964 1965 1966
    
    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 });
    }
1967 1968 1969 1970 1971 1972
}

# A helper for various search functions that need to run operator
# functions directly.
sub _do_operator_function {
    my ($self, $func_args) = @_;
1973
    my $operator = $func_args->{operator};
1974 1975 1976
    my $operator_func = OPERATORS->{$operator}
      || ThrowCodeError("search_field_operator_unsupported",
                        { operator => $operator });
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
    $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";
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
}

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

2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
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};
}

2027 2028 2029 2030 2031 2032
sub _get_column_joins {
    my $self = shift;
    my $cache = Bugzilla->request_cache;

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

2033
    my %column_joins = %{ $self->COLUMN_JOINS() };
2034 2035 2036 2037 2038 2039 2040
    Bugzilla::Hook::process('buglist_column_joins',
                            { column_joins => \%column_joins });

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

2041 2042 2043
###########################
# Search Function Helpers #
###########################
2044

2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
# 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;
2060 2061

    # These operators are really numeric operators with numeric fields.
2062
    $numeric_operator = grep { $_ eq $operator } keys %{ SIMPLE_OPERATORS() };
2063

2064 2065 2066 2067 2068
    if ($is_numeric) {
        my $quoted = $value;
        trick_taint($quoted);
        return $quoted;
    }
2069 2070 2071
    elsif ($numeric_field && !$numeric_value && $numeric_operator) {
        ThrowUserError('number_not_numeric', { field => $field, num => $value });
    }
2072 2073 2074
    return Bugzilla->dbh->quote($value);
}

2075
sub build_subselect {
2076
    my ($outer, $inner, $table, $cond, $negate) = @_;
2077 2078 2079 2080 2081 2082 2083
    if ($table =~ /\battach_data\b/) {
        # It takes a long time to scan the whole attach_data table
        # unconditionally, so we return the subselect and let the DB optimizer
        # restrict the search based on other search criteria.
        my $not = $negate ? "NOT" : "";
        return "$outer $not IN (SELECT DISTINCT $inner FROM $table WHERE $cond)";
    }
2084 2085 2086 2087 2088 2089 2090
    # Execute subselects immediately to avoid dependent subqueries, which are
    # large performance hits on MySql
    my $q = "SELECT DISTINCT $inner FROM $table WHERE $cond";
    my $dbh = Bugzilla->dbh;
    my $list = $dbh->selectcol_arrayref($q);
    return $negate ? "1=1" : "1=2" unless @$list;
    return $dbh->sql_in($outer, $list, $negate);
2091 2092
}

2093 2094 2095 2096
# 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).
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
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;
}

2120 2121 2122 2123 2124 2125 2126 2127 2128
# 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;
2129
    my @terms = map { $dbh->sql_ilike($_, $args->{full_field}) } @words;
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
    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;
}

2162 2163 2164
#####################################
# "Special Parsing" Functions: Date #
#####################################
2165

2166
sub _timestamp_translate {
2167
    my ($self, $ignore_time, $args) = @_;
2168 2169
    my $value = $args->{value};
    my $dbh = Bugzilla->dbh;
2170

2171 2172 2173
    return if $value !~ /^(?:[\+\-]?\d+[hdwmy]s?|now)$/i;

    $value = SqlifyDate($value);
2174 2175
    # By default, the time is appended to the date, which we don't always want.
    if ($ignore_time) {
2176 2177 2178 2179
        ($value) = split(/\s/, $value);
    }
    $args->{value} = $value;
    $args->{quoted} = $dbh->quote($value);
2180 2181
}

2182 2183 2184 2185
sub _datetime_translate {
    return shift->_timestamp_translate(0, @_);
}

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
sub _last_visit_datetime {
    my ($self, $args) = @_;
    my $value = $args->{value};

    $self->_datetime_translate($args);
    if ($value eq $args->{value}) {
        # Failed to translate a datetime. let's try the pronoun expando.
        if ($value eq '%last_changed%') {
            $self->_add_extra_column('changeddate');
            $args->{value} = $args->{quoted} = 'bugs.delta_ts';
        }
    }
}


2201 2202 2203 2204
sub _date_translate {
    return shift->_timestamp_translate(1, @_);
}

2205 2206
sub SqlifyDate {
    my ($str) = @_;
2207
    my $fmt = "%Y-%m-%d %H:%M:%S";
2208
    $str = "" if (!defined $str || lc($str) eq 'now');
2209 2210 2211
    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);
2212
    }
2213

2214 2215
    if ($str =~ /^(-|\+)?(\d+)([hdwmy])(s?)$/i) {   # relative date
        my ($sign, $amount, $unit, $startof, $date) = ($1, $2, lc $3, lc $4, time);
2216 2217
        my ($sec, $min, $hour, $mday, $month, $year, $wday)  = localtime($date);
        if ($sign && $sign eq '+') { $amount = -$amount; }
2218
        $startof = 1 if $amount == 0;
2219
        if ($unit eq 'w') {                  # convert weeks to days
2220 2221
            $amount = 7*$amount;
            $amount += $wday if $startof;
2222 2223 2224
            $unit = 'd';
        }
        if ($unit eq 'd') {
2225 2226 2227 2228 2229 2230
            if ($startof) {
              $fmt = "%Y-%m-%d 00:00:00";
              $date -= $sec + 60*$min + 3600*$hour;
            }
            $date -= 24*3600*$amount;
            return time2str($fmt, $date);
2231 2232
        }
        elsif ($unit eq 'y') {
2233 2234 2235 2236 2237 2238 2239
            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);
            }
2240 2241 2242
        }
        elsif ($unit eq 'm') {
            $month -= $amount;
2243 2244
            $year += floor($month/12);
            $month %= 12;
2245 2246 2247 2248 2249 2250 2251
            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);
            }
2252 2253
        }
        elsif ($unit eq 'h') {
2254 2255 2256 2257 2258 2259
            # Special case for 'beginning of an hour'
            if ($startof) {
                $fmt = "%Y-%m-%d %H:00:00";
            } 
            $date -= 3600*$amount;
            return time2str($fmt, $date);
2260 2261
        }
        return undef;                      # should not happen due to regexp at top
2262
    }
2263 2264 2265
    my $date = str2time($str);
    if (!defined($date)) {
        ThrowUserError("illegal_date", { date => $str });
2266
    }
2267
    return time2str($fmt, $date);
2268 2269
}

2270 2271 2272
######################################
# "Special Parsing" Functions: Users #
######################################
2273

2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
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%") {
2290
        return "COALESCE(bugs.qa_contact,0)";
2291
    }
2292 2293

    ThrowUserError('illegal_pronoun', { pronoun => $noun });
2294 2295
}

2296
sub _contact_pronoun {
2297
    my ($self, $args) = @_;
2298
    my $value = $args->{value};
2299
    my $user = $self->_user;
2300 2301

    if ($value =~ /^\%group\.[^%]+%$/) {
2302
        $self->_contact_exact_group($args);
2303
    }
2304 2305 2306
    elsif ($value =~ /^(%\w+%)$/) {
        $args->{value} = pronoun($1, $user);
        $args->{quoted} = $args->{value};
2307
        $args->{value_is_id} = 1;
2308 2309 2310
    }
}

2311
sub _contact_exact_group {
2312
    my ($self, $args) = @_;
2313 2314
    my ($value, $operator, $field, $chart_id, $joins, $sequence) =
        @$args{qw(value operator field chart_id joins sequence)};
2315
    my $dbh = Bugzilla->dbh;
2316
    my $user = $self->_user;
2317

2318
    # We already know $value will match this regexp, else we wouldn't be here.
2319
    $value =~ /\%group\.([^%]+)%/;
2320 2321 2322 2323
    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.
2324
    $user->in_group($group)
2325 2326 2327 2328
      || 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();
2329

2330
    my $group_ids = Bugzilla::Group->flatten_group_membership($group->id);
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347

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

2348
    my $table = "user_group_map_$chart_id";
2349 2350 2351
    my $join = {
        table => 'user_group_map',
        as    => $table,
2352
        from  => $from,
2353 2354 2355 2356 2357
        to    => 'user_id',
        extra => [$dbh->sql_in("$table.group_id", $group_ids),
                  "$table.isbless = 0"],
    };
    push(@$joins, $join);
2358 2359 2360 2361 2362
    if ($operator =~ /^not/) {
        $args->{term} = "$table.group_id IS NULL";
    }
    else {
        $args->{term} = "$table.group_id IS NOT NULL";
2363 2364 2365
    }
}

2366 2367 2368 2369 2370 2371 2372 2373 2374
sub _get_user_id {
    my ($self, $value) = @_;

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

2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
#####################################################################
# Search Functions
#####################################################################

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

2386 2387 2388
# For all the "user" fields--assigned_to, reporter, qa_contact,
# cc, commenter, requestee, etc.
sub _user_nonchanged {
2389
    my ($self, $args) = @_;
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    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;
2420
    }
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
    elsif (substr($field, -9) eq '_realname') {
        my $as = "name_${field}_$chart_id";
        # For fields with periods in their name.
        $as =~ s/\./_/;
        my $join = {
            table => 'profiles',
            as    => $as,
            from  => substr($args->{full_field}, 0, -9),
            to    => 'userid',
            join  => (!$is_in_other_table and !$is_nullable) ? 'INNER' : undef,
        };
        push(@$joins, $join);
        $args->{full_field} = "$as.realname";
    }
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
    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";
2448
    }
2449

2450 2451 2452 2453 2454 2455 2456
    # 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)";
    }
2457
    
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
    # 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.
2469
        my $is_negative = $operator =~ /^(?:no|isempty)/ ? 1 : 0;
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
        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} };
2489
            my $new_table = "SELECT DISTINCT $columns FROM $table AS $as $join_sql";
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
            $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";
        }
    }
2510 2511
}

2512
# XXX This duplicates having Commenter as a search field.
2513
sub _long_desc_changedby {
2514 2515
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value) = @$args{qw(chart_id joins value)};
2516

2517
    my $table = "longdescs_$chart_id";
2518
    push(@$joins, { table => 'longdescs', as => $table });
2519
    my $user_id = $self->_get_user_id($value);
2520
    $args->{term} = "$table.who = $user_id";
2521 2522 2523 2524 2525 2526

    # 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";
    }
2527 2528
}

2529
sub _long_desc_changedbefore_after {
2530 2531 2532
    my ($self, $args) = @_;
    my ($chart_id, $operator, $value, $joins) =
        @$args{qw(chart_id operator value joins)};
2533
    my $dbh = Bugzilla->dbh;
2534

2535
    my $sql_operator = ($operator =~ /before/) ? '<=' : '>=';
2536 2537
    my $table = "longdescs_$chart_id";
    my $sql_date = $dbh->quote(SqlifyDate($value));
2538 2539 2540 2541 2542 2543
    my $join = {
        table => 'longdescs',
        as    => $table,
        extra => ["$table.bug_when $sql_operator $sql_date"],
    };
    push(@$joins, $join);
2544
    $args->{term} = "$table.bug_when IS NOT NULL";
2545 2546 2547 2548 2549 2550

    # 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";
    }
2551 2552
}

2553 2554 2555 2556
sub _long_desc_nonchanged {
    my ($self, $args) = @_;
    my ($chart_id, $operator, $value, $joins, $bugs_table) =
        @$args{qw(chart_id operator value joins bugs_table)};
2557 2558 2559 2560 2561

    if ($operator =~ /^is(not)?empty$/) {
        $args->{term} = $self->_multiselect_isempty($args, $operator eq 'isnotempty');
        return;
    }
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    my $dbh = Bugzilla->dbh;

    my $table = "longdescs_$chart_id";
    my $join_args = {
        chart_id   => $chart_id,
        sequence   => $chart_id,
        field      => 'longdesc',
        full_field => "$table.thetext",
        operator   => $operator,
        value      => $value,
        all_values => $value,
        quoted     => $dbh->quote($value),
        joins      => [],
        bugs_table => $bugs_table,
    };
    $self->_do_operator_function($join_args);

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

    my $join = {
        table => 'longdescs',
        as    => $table,
        extra => [ $join_args->{term} ],
    };
    push(@$joins, $join);

    $args->{term} =  "$table.comment_id IS NOT NULL";
}

2595
sub _content_matches {
2596
    my ($self, $args) = @_;
2597 2598
    my ($chart_id, $joins, $fields, $operator, $value) =
        @$args{qw(chart_id joins fields operator value)};
2599
    my $dbh = Bugzilla->dbh;
2600

2601
    # "content" is an alias for columns containing text for which we
2602
    # can search a full-text index and retrieve results by relevance,
2603 2604 2605 2606 2607
    # 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.

2608
    # Add the fulltext table to the query so we can search on it.
2609
    my $table = "bugs_fulltext_$chart_id";
2610
    my $comments_col = "comments";
2611
    $comments_col = "comments_noprivate" unless $self->_user->is_insider;
2612
    push(@$joins, { table => 'bugs_fulltext', as => $table });
2613
    
2614
    # Create search terms to add to the SELECT and WHERE clauses.
2615
    my ($term1, $rterm1) =
2616
        $dbh->sql_fulltext_search("$table.$comments_col", $value);
2617
    my ($term2, $rterm2) =
2618
        $dbh->sql_fulltext_search("$table.short_desc", $value);
2619 2620 2621
    $rterm1 = $term1 if !$rterm1;
    $rterm2 = $term2 if !$rterm2;

2622
    # The term to use in the WHERE clause.
2623
    my $term = "$term1 OR $term2";
2624 2625
    if ($operator =~ /not/i) {
        $term = "NOT($term)";
2626
    }
2627
    $args->{term} = $term;
2628
    
2629
    # In order to sort by relevance (in case the user requests it),
2630 2631
    # 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 
2632
    # terms to the relevance sql.
2633 2634 2635
    #
    # We build the relevance SQL by modifying the COLUMNS list directly,
    # which is kind of a hack but works.
2636
    my $current = $self->COLUMNS->{'relevance'}->{name};
2637
    $current = $current ? "$current + " : '';
2638
    # For NOT searches, we just add 0 to the relevance.
2639
    my $select_term = $operator =~ /not/ ? 0 : "($current$rterm1 + $rterm2)";
2640
    $self->COLUMNS->{'relevance'}->{name} = $select_term;
2641 2642
}

2643
sub _long_descs_count {
2644 2645
    my ($self, $args) = @_;
    my ($chart_id, $joins) = @$args{qw(chart_id joins)};
2646 2647
    my $table = "longdescs_count_$chart_id";
    my $extra =  $self->_user->is_insider ? "" : "WHERE isprivate = 0";
2648
    my $join = {
2649 2650
        table => "(SELECT bug_id, COUNT(*) AS num"
                 . " FROM longdescs $extra GROUP BY bug_id)",
2651 2652 2653
        as    => $table,
    };
    push(@$joins, $join);
2654 2655 2656
    $args->{full_field} = "${table}.num";
}

2657
sub _work_time_changedby {
2658 2659
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value) = @$args{qw(chart_id joins value)};
2660
    
2661
    my $table = "longdescs_$chart_id";
2662
    push(@$joins, { table => 'longdescs', as => $table });
2663
    my $user_id = $self->_get_user_id($value);
2664
    $args->{term} = "$table.who = $user_id AND $table.work_time != 0";
2665 2666
}

2667
sub _work_time_changedbefore_after {
2668 2669 2670
    my ($self, $args) = @_;
    my ($chart_id, $operator, $value, $joins) =
        @$args{qw(chart_id operator value joins)};
2671 2672
    my $dbh = Bugzilla->dbh;
    
2673
    my $table = "longdescs_$chart_id";
2674
    my $sql_operator = ($operator =~ /before/) ? '<=' : '>=';
2675
    my $sql_date = $dbh->quote(SqlifyDate($value));
2676 2677 2678 2679 2680 2681 2682
    my $join = {
        table => 'longdescs',
        as    => $table,
        extra => ["$table.work_time != 0",
                  "$table.bug_when $sql_operator $sql_date"],
    };
    push(@$joins, $join);
2683 2684
    
    $args->{term} = "$table.bug_when IS NOT NULL";
2685 2686 2687
}

sub _work_time {
2688
    my ($self, $args) = @_;
2689
    $self->_add_extra_column('actual_time');
2690
    $args->{full_field} = $self->COLUMNS->{actual_time}->{name};
2691 2692 2693
}

sub _percentage_complete {
2694
    my ($self, $args) = @_;
2695
    
2696
    $args->{full_field} = $self->COLUMNS->{percentage_complete}->{name};
2697

2698 2699 2700
    # 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');
2701 2702
}

2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
sub _last_visit_ts {
    my ($self, $args) = @_;

    $args->{full_field} = $self->COLUMNS->{last_visit_ts}->{name};
    $self->_add_extra_column('last_visit_ts');
}

sub _last_visit_ts_invalid_operator {
    my ($self, $args) = @_;

    ThrowUserError('search_field_operator_invalid',
        { field    => $args->{field},
          operator => $args->{operator} });
}

2718
sub _days_elapsed {
2719
    my ($self, $args) = @_;
2720 2721
    my $dbh = Bugzilla->dbh;
    
2722 2723
    $args->{full_field} = "(" . $dbh->sql_to_days('NOW()') . " - " .
                                $dbh->sql_to_days('bugs.delta_ts') . ")";
2724 2725 2726
}

sub _component_nonchanged {
2727
    my ($self, $args) = @_;
2728
    
2729 2730 2731 2732 2733
    $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});
2734
}
2735

2736
sub _product_nonchanged {
2737
    my ($self, $args) = @_;
2738 2739
    
    # Generate the restriction condition
2740 2741 2742 2743 2744
    $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);
2745 2746
}

2747 2748 2749 2750 2751 2752 2753 2754 2755
sub _alias_nonchanged {
    my ($self, $args) = @_;

    $args->{full_field} = "bugs_aliases.alias";
    $self->_do_operator_function($args);
    $args->{term} = build_subselect("bugs.bug_id",
        "bugs_aliases.bug_id", "bugs_aliases", $args->{term});
}

2756
sub _classification_nonchanged {
2757 2758
    my ($self, $args) = @_;
    my $joins = $args->{joins};
2759
    
2760 2761 2762 2763
    # This joins the right tables for us.
    $self->_add_extra_column('product');
    
    # Generate the restriction condition    
2764 2765 2766
    $args->{full_field} = "classifications.name";
    $self->_do_operator_function($args);
    my $term = $args->{term};
2767
    $args->{term} = build_subselect("map_product.classification_id",
2768
        "classifications.id", "classifications", $term);
2769 2770
}

2771
sub _nullable {
2772
    my ($self, $args) = @_;
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
    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)";
}

2790 2791 2792 2793 2794 2795 2796
sub _nullable_date {
    my ($self, $args) = @_;
    my $field = $args->{full_field};
    my $empty = Bugzilla->dbh->quote(EMPTY_DATE);
    $args->{full_field} = "COALESCE($field, $empty)";
}

2797 2798 2799 2800 2801 2802 2803
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);
2804 2805 2806
}

sub _owner_idle_time_greater_less {
2807 2808 2809
    my ($self, $args) = @_;
    my ($chart_id, $joins, $value, $operator) =
        @$args{qw(chart_id joins value operator)};
2810 2811
    my $dbh = Bugzilla->dbh;
    
2812 2813 2814 2815
    my $table = "idle_$chart_id";
    my $quoted = $dbh->quote(SqlifyDate($value));
    
    my $ld_table = "comment_$table";
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832
    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);
2833 2834 2835
    
    if ($operator =~ /greater/) {
        $args->{term} =
2836
            "$ld_table.who IS NULL AND $act_table.who IS NULL";
2837
    } else {
2838
         $args->{term} =
2839
            "($ld_table.who IS NOT NULL OR $act_table.who IS NOT NULL)";
2840 2841 2842
    }
}

2843
sub _multiselect_negative {
2844 2845
    my ($self, $args) = @_;
    my ($field, $operator) = @$args{qw(field operator)};
2846

2847
    $args->{operator} = $self->_reverse_operator($operator);
2848
    $args->{term} = $self->_multiselect_term($args, 1);
2849 2850 2851
}

sub _multiselect_multiple {
2852
    my ($self, $args) = @_;
2853 2854
    my ($chart_id, $field, $operator, $value)
        = @$args{qw(chart_id field operator value)};
2855
    my $dbh = Bugzilla->dbh;
2856
    
2857 2858 2859 2860 2861 2862
    # 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);
2863
    
2864
    my @terms;
2865
    foreach my $word (@words) {
2866
        next if $word eq '';
2867
        $args->{value} = $word;
2868 2869
        $args->{quoted} = $dbh->quote($word);
        push(@terms, $self->_multiselect_term($args));
2870 2871
    }
    
2872
    # The spacing in the joins helps make the resulting SQL more readable.
2873
    if ($operator =~ /^any/) {
2874
        $args->{term} = join("\n        OR ", @terms);
2875 2876
    }
    else {
2877
        $args->{term} = join("\n        AND ", @terms);
2878 2879 2880
    }
}

2881 2882
sub _flagtypes_nonchanged {
    my ($self, $args) = @_;
2883 2884
    my ($chart_id, $operator, $value, $joins, $bugs_table, $condition) =
        @$args{qw(chart_id operator value joins bugs_table condition)};
2885 2886 2887 2888 2889 2890

    if ($operator =~ /^is(not)?empty$/) {
        $args->{term} = $self->_multiselect_isempty($args, $operator eq 'isnotempty');
        return;
    }

2891 2892
    my $dbh = Bugzilla->dbh;

2893 2894 2895 2896 2897 2898 2899 2900 2901
    # For 'not' operators, we need to negate the whole term.
    # If you search for "Flags" (does not contain) "approval+" we actually want
    # to return *bugs* that don't contain an approval+ flag.  Without rewriting
    # the negation we'll search for *flags* which don't contain approval+.
    if ($operator =~ s/^not//) {
        $args->{operator} = $operator;
        $condition->operator($operator);
        $condition->negate(1);
    }
2902

2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
    my $subselect_args = {
        chart_id   => $chart_id,
        sequence   => $chart_id,
        field      => 'flagtypes.name',
        full_field =>  $dbh->sql_string_concat("flagtypes_$chart_id.name", "flags_$chart_id.status"),
        operator   => $operator,
        value      => $value,
        all_values => $value,
        quoted     => $dbh->quote($value),
        joins      => [],
        bugs_table => "bugs_$chart_id",
2914
    };
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
    $self->_do_operator_function($subselect_args);
    my $subselect_term = $subselect_args->{term};

    # don't call build_subselect as this must run as a true sub-select
    $args->{term} = "EXISTS (
        SELECT 1
          FROM $bugs_table bugs_$chart_id
          LEFT JOIN attachments AS attachments_$chart_id
                    ON bugs_$chart_id.bug_id = attachments_$chart_id.bug_id
          LEFT JOIN flags AS flags_$chart_id
                    ON bugs_$chart_id.bug_id = flags_$chart_id.bug_id
                       AND (flags_$chart_id.attach_id = attachments_$chart_id.attach_id
                            OR flags_$chart_id.attach_id IS NULL)
          LEFT JOIN flagtypes AS flagtypes_$chart_id
                    ON flags_$chart_id.type_id = flagtypes_$chart_id.id
     WHERE bugs_$chart_id.bug_id = $bugs_table.bug_id
           AND $subselect_term
    )";
2933 2934
}

2935 2936 2937 2938 2939 2940 2941
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)
}

2942 2943 2944
sub _multiselect_table {
    my ($self, $args) = @_;
    my ($field, $chart_id) = @$args{qw(field chart_id)};
2945 2946
    my $dbh = Bugzilla->dbh;
    
2947 2948 2949 2950 2951
    if ($field eq 'keywords') {
        $args->{full_field} = 'keyworddefs.name';
        return "keywords INNER JOIN keyworddefs".
                               " ON keywords.keywordid = keyworddefs.id";
    }
2952
    elsif ($field eq 'tag') {
2953
        $args->{full_field} = 'tag.name';
2954 2955
        return "bug_tag INNER JOIN tag ON bug_tag.tag_id = tag.id AND user_id = "
               . ($self->_sharer_id || $self->_user->id);
2956
    }
2957 2958 2959 2960 2961
    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";
    }
2962 2963 2964
    elsif ($field eq 'blocked' or $field eq 'dependson') {
        my $select = $field eq 'blocked' ? 'dependson' : 'blocked';
        $args->{_select_field} = $select;
2965
        $args->{full_field} = $field;
2966 2967
        return "dependencies";
    }
2968 2969 2970 2971 2972 2973
    elsif ($field eq 'longdesc') {
        $args->{_extra_where} = " AND isprivate = 0"
            if !$self->_user->is_insider;
        $args->{full_field} = 'thetext';
        return "longdescs";
    }
2974 2975 2976 2977 2978 2979 2980 2981
    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";
    }
2982 2983 2984 2985 2986 2987 2988
    elsif ($field =~ /^attachments/) {
        $args->{_extra_where} = " AND isprivate = 0"
            if !$self->_user->is_insider;
        $field =~ /^attachments\.(.+)$/;
        $args->{full_field} = $1;
        return "attachments";
    }
2989 2990 2991 2992 2993 2994
    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"
    }
2995 2996 2997 2998 2999 3000 3001
    elsif ($field eq 'comment_tag') {
        $args->{_extra_where} = " AND longdescs.isprivate = 0"
            if !$self->_user->is_insider;
        $args->{full_field} = 'longdescs_tags.tag';
        return "longdescs INNER JOIN longdescs_tags".
               " ON longdescs.comment_id = longdescs_tags.comment_id";
    }
3002 3003 3004 3005 3006 3007
    my $table = "bug_$field";
    $args->{full_field} = "bug_$field.value";
    return $table;
}

sub _multiselect_term {
3008
    my ($self, $args, $not) = @_;
3009
    my ($operator) = $args->{operator};
3010
    my $value = $args->{value} || '';
3011 3012
    # 'empty' operators require special handling
    return $self->_multiselect_isempty($args, $not)
3013
        if ($operator =~ /^is(not)?empty$/ || $value eq '---');
3014 3015 3016
    my $table = $self->_multiselect_table($args);
    $self->_do_operator_function($args);
    my $term = $args->{term};
3017
    $term .= $args->{_extra_where} || '';
3018
    my $select = $args->{_select_field} || 'bug_id';
3019
    return build_subselect("$args->{bugs_table}.bug_id", $select, $table, $term, $not);
3020 3021
}

3022 3023 3024 3025 3026 3027
# We can't use the normal operator_functions to build isempty queries which
# join to different tables.
sub _multiselect_isempty {
    my ($self, $args, $not) = @_;
    my ($field, $operator, $joins, $chart_id) = @$args{qw(field operator joins chart_id)};
    my $dbh = Bugzilla->dbh;
3028
    $operator = $self->_reverse_operator($operator) if $not;
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
    $not = $operator eq 'isnotempty' ? 'NOT' : '';

    if ($field eq 'keywords') {
        push @$joins, {
            table => 'keywords',
            as    => "keywords_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
        };
        return "keywords_$chart_id.bug_id IS $not NULL";
    }
    elsif ($field eq 'bug_group') {
        push @$joins, {
            table => 'bug_group_map',
            as    => "bug_group_map_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
        };
        return "bug_group_map_$chart_id.bug_id IS $not NULL";
    }
    elsif ($field eq 'flagtypes.name') {
        push @$joins, {
            table => 'flags',
            as    => "flags_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
        };
        return "flags_$chart_id.bug_id IS $not NULL";
    }
    elsif ($field eq 'blocked' or $field eq 'dependson') {
        my $to = $field eq 'blocked' ? 'dependson' : 'blocked';
        push @$joins, {
            table => 'dependencies',
            as    => "dependencies_$chart_id",
            from  => 'bug_id',
            to    => $to,
        };
        return "dependencies_$chart_id.$to IS $not NULL";
    }
    elsif ($field eq 'longdesc') {
        my @extra = ( "longdescs_$chart_id.type != " . CMT_HAS_DUPE );
        push @extra, "longdescs_$chart_id.isprivate = 0"
            unless $self->_user->is_insider;
        push @$joins, {
            table => 'longdescs',
            as    => "longdescs_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
            extra => \@extra,
        };
        return $not
            ? "longdescs_$chart_id.thetext != ''"
            : "longdescs_$chart_id.thetext = ''";
    }
    elsif ($field eq 'longdescs.isprivate') {
        ThrowUserError('search_field_operator_invalid', { field  => $field,
                                                          operator => $operator });
    }
    elsif ($field =~ /^attachments\.(.+)/) {
        my $sub_field = $1;
        if ($sub_field eq 'description' || $sub_field eq 'filename' || $sub_field eq 'mimetype') {
            # can't be null/empty
            return $not ? '1=1' : '1=2';
        } else {
            # all other fields which get here are boolean
            ThrowUserError('search_field_operator_invalid', { field => $field,
                                                              operator => $operator });
        }
    }
    elsif ($field eq 'attach_data.thedata') {
        push @$joins, {
            table => 'attachments',
            as    => "attachments_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
            extra => [ $self->_user->is_insider ? '' : "attachments_$chart_id.isprivate = 0" ],
        };
        push @$joins, {
            table => 'attach_data',
            as    => "attach_data_$chart_id",
            from  => "attachments_$chart_id.attach_id",
            to    => 'id',
        };
        return "attach_data_$chart_id.thedata IS $not NULL";
    }
    elsif ($field eq 'tag') {
        push @$joins, {
            table => 'bug_tag',
            as    => "bug_tag_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
        };
        push @$joins, {
            table => 'tag',
            as    => "tag_$chart_id",
            from  => "bug_tag_$chart_id.tag_id",
            to    => 'id',
            extra => [ "tag_$chart_id.user_id = " . ($self->_sharer_id || $self->_user->id) ],
        };
        return "tag_$chart_id.id IS $not NULL";
    }
3130 3131 3132 3133 3134 3135 3136 3137 3138
    elsif ($self->_multi_select_fields->{$field}) {
        push @$joins, {
            table => "bug_$field",
            as => "bug_${field}_$chart_id",
            from  => 'bug_id',
            to    => 'bug_id',
        };
        return "bug_${field}_$chart_id.bug_id IS $not NULL";
    }
3139 3140
}

3141 3142 3143 3144
###############################
# Standard Operator Functions #
###############################

3145 3146 3147 3148 3149 3150
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";
3151 3152 3153
}

sub _casesubstring {
3154
    my ($self, $args) = @_;
3155
    my ($full_field, $value) = @$args{qw(full_field value)};
3156
    my $dbh = Bugzilla->dbh;
3157 3158

    $args->{term} = $dbh->sql_like($value, $full_field);
3159 3160 3161
}

sub _substring {
3162
    my ($self, $args) = @_;
3163
    my ($full_field, $value) = @$args{qw(full_field value)};
3164
    my $dbh = Bugzilla->dbh;
3165 3166

    $args->{term} = $dbh->sql_ilike($value, $full_field);
3167 3168 3169
}

sub _notsubstring {
3170
    my ($self, $args) = @_;
3171
    my ($full_field, $value) = @$args{qw(full_field value)};
3172
    my $dbh = Bugzilla->dbh;
3173 3174

    $args->{term} = $dbh->sql_not_ilike($value, $full_field);
3175 3176 3177
}

sub _regexp {
3178 3179
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
3180 3181
    my $dbh = Bugzilla->dbh;
    
3182
    $args->{term} = $dbh->sql_regexp($full_field, $quoted);
3183 3184 3185
}

sub _notregexp {
3186 3187
    my ($self, $args) = @_;
    my ($full_field, $quoted) = @$args{qw(full_field quoted)};
3188 3189
    my $dbh = Bugzilla->dbh;
    
3190
    $args->{term} = $dbh->sql_not_regexp($full_field, $quoted);
3191 3192
}

3193
sub _anyexact {
3194
    my ($self, $args) = @_;
3195
    my ($field, $full_field) = @$args{qw(field full_field)};
3196 3197
    my $dbh = Bugzilla->dbh;
    
3198
    my @list = $self->_all_values($args, ',');
3199
    @list = map { $self->_quote_unless_numeric($args, $_) } @list;
3200
    
3201
    if (@list) {
3202 3203 3204
        $args->{term} = $dbh->sql_in($full_field, \@list);
    }
    else {
3205
        $args->{term} = '';
3206 3207 3208 3209
    }
}

sub _anywordsubstr {
3210
    my ($self, $args) = @_;
3211

3212
    my @terms = $self->_substring_terms($args);
3213
    $args->{term} = @terms ? '(' . join("\n\tOR ", @terms) . ')' : '';
3214 3215 3216
}

sub _allwordssubstr {
3217
    my ($self, $args) = @_;
3218

3219
    my @terms = $self->_substring_terms($args);
3220
    $args->{term} = @terms ? '(' . join("\n\tAND ", @terms) . ')' : '';
3221 3222 3223
}

sub _nowordssubstr {
3224 3225 3226 3227
    my ($self, $args) = @_;
    $self->_anywordsubstr($args);
    my $term = $args->{term};
    $args->{term} = "NOT($term)";
3228 3229 3230
}

sub _anywords {
3231
    my ($self, $args) = @_;
3232

3233 3234 3235 3236
    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;
3237
    $args->{term} = @terms ? '(' . join("\n\tOR ", @terms) . ')' : '';
3238 3239 3240
}

sub _allwords {
3241
    my ($self, $args) = @_;
3242

3243
    my @terms = $self->_word_terms($args);
3244
    $args->{term} = @terms ? '(' . join("\n\tAND ", @terms) . ')' : '';
3245 3246 3247
}

sub _nowords {
3248 3249 3250 3251
    my ($self, $args) = @_;
    $self->_anywords($args);
    my $term = $args->{term};
    $args->{term} = "NOT($term)";
3252 3253 3254
}

sub _changedbefore_changedafter {
3255
    my ($self, $args) = @_;
3256 3257
    my ($chart_id, $joins, $field, $operator, $value) =
        @$args{qw(chart_id joins field operator value)};
3258
    my $dbh = Bugzilla->dbh;
3259

3260
    my $field_object = $self->_chart_fields->{$field}
3261
        || ThrowCodeError("invalid_field_name", { field => $field });
3262 3263 3264 3265 3266 3267 3268 3269 3270
    
    # 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/) ? '<=' : '>=';
3271
    my $field_id = $field_object->id;
3272 3273 3274 3275
    # 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";

3276
    my $sql_date = $dbh->quote(SqlifyDate($value));
3277 3278 3279 3280 3281 3282
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.bug_when $sql_operator $sql_date"],
    };
3283

3284
    $args->{term} = "$table.bug_when IS NOT NULL";
3285 3286
    $self->_changed_security_check($args, $join);
    push(@$joins, $join);
3287 3288 3289
}

sub _changedfrom_changedto {
3290
    my ($self, $args) = @_;
3291 3292
    my ($chart_id, $joins, $field, $operator, $quoted) =
        @$args{qw(chart_id joins field operator quoted)};
3293
    
3294
    my $column = ($operator =~ /from/) ? 'removed' : 'added';
3295
    my $field_object = $self->_chart_fields->{$field}
3296 3297
        || ThrowCodeError("invalid_field_name", { field => $field });
    my $field_id = $field_object->id;
3298
    my $table = "act_${field_id}_$chart_id";
3299 3300 3301 3302 3303 3304 3305
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.$column = $quoted"],
    };

3306
    $args->{term} = "$table.bug_when IS NOT NULL";
3307 3308
    $self->_changed_security_check($args, $join);
    push(@$joins, $join);
3309 3310 3311
}

sub _changedby {
3312
    my ($self, $args) = @_;
3313 3314
    my ($chart_id, $joins, $field, $operator, $value) =
        @$args{qw(chart_id joins field operator value)};
3315
    
3316
    my $field_object = $self->_chart_fields->{$field}
3317 3318
        || ThrowCodeError("invalid_field_name", { field => $field });
    my $field_id = $field_object->id;
3319
    my $table = "act_${field_id}_$chart_id";
3320
    my $user_id  = $self->_get_user_id($value);
3321 3322 3323 3324 3325 3326
    my $join = {
        table => 'bugs_activity',
        as    => $table,
        extra => ["$table.fieldid = $field_id",
                  "$table.who = $user_id"],
    };
3327

3328
    $args->{term} = "$table.bug_when IS NOT NULL";
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
    $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";
    }
3353 3354
}

3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
sub _isempty {
    my ($self, $args) = @_;
    my $full_field = $args->{full_field};
    $args->{term} = "$full_field IS NULL OR $full_field = " . $self->_empty_value($args->{field});
}

sub _isnotempty {
    my ($self, $args) = @_;
    my $full_field = $args->{full_field};
    $args->{term} = "$full_field IS NOT NULL AND $full_field != " . $self->_empty_value($args->{field});
}

sub _empty_value {
    my ($self, $field) = @_;
    my $field_obj = $self->_chart_fields->{$field};
    return "0" if $field_obj->type == FIELD_TYPE_BUG_ID;
    return Bugzilla->dbh->quote(EMPTY_DATETIME) if $field_obj->type == FIELD_TYPE_DATETIME;
    return Bugzilla->dbh->quote(EMPTY_DATE) if $field_obj->type == FIELD_TYPE_DATE;
    return "''";
}

3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
######################
# 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.
3400 3401
sub _translate_old_column {
    my ($self, $column) = @_;
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
    # 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
3415 3416 3417
    foreach my $key (%{ $self->COLUMNS }) {
        next unless exists $self->COLUMNS->{$key}->{name};
        return $key if $self->COLUMNS->{$key}->{name} eq $column;
3418 3419 3420 3421 3422
    }

    return $column;
}

3423
1;
3424

3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
__END__

=head1 NAME

Bugzilla::Search - Provides methods to run queries against bugs.

=head1 SYNOPSIS

    use Bugzilla::Search;

    my $search = new Bugzilla::Search({'fields' => \@fields,
                                       'params' => \%search_criteria,
                                       'sharer' => $sharer_id,
                                       'user'   => $user_obj,
                                       'allow_unlimited' => 1});

    my $data = $search->data;
    my ($data, $extra_data) = $search->data;

=head1 DESCRIPTION

Search.pm represents a search object. It's the single way to collect
data about bugs in a secure way. The list of bugs matching criteria
defined by the caller are filtered based on the user privileges.

=head1 METHODS

=head2 new

=over

=item B<Description>

Create a Bugzilla::Search object.

=item B<Params>

=over

=item C<fields>

An arrayref representing the bug attributes for which data is desired.
Legal attributes are listed in the fielddefs DB table. At least one field
must be defined, typically the 'bug_id' field.

=item C<params>

A hashref representing search criteria. Each key => value pair represents
a search criteria, where the key is the search field and the value is the
value for this field. At least one search criteria must be defined if the
'search_allow_no_criteria' parameter is turned off, else an error is thrown.

=item C<sharer>

3479
When a saved search is shared by a user, this is their user ID.
3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530

=item C<user>

A L<Bugzilla::User> object representing the user to whom the data is addressed.
All security checks are done based on this user object, so it's not safe
to share results of the query with other users as not all users have the
same privileges or have the same role for all bugs in the list. If this
parameter is not defined, then the currently logged in user is taken into
account. If no user is logged in, then only public bugs will be returned.

=item C<allow_unlimited>

If set to a true value, the number of bugs retrieved by the query is not
limited.

=back

=item B<Returns>

A L<Bugzilla::Search> object.

=back

=head2 data

=over

=item B<Description>

Returns bugs matching search criteria passed to C<new()>.

=item B<Params>

None

=item B<Returns>

In scalar context, this method returns a reference to a list of bugs.
Each item of the list represents a bug, which is itself a reference to
a list where each item represents a bug attribute, in the same order as
specified in the C<fields> parameter of C<new()>.

In list context, this methods also returns a reference to a list containing
references to hashes. For each hash, two keys are defined: C<sql> contains
the SQL query which has been executed, and C<time> contains the time spent
to execute the SQL query, in seconds. There can be either a single hash, or
two hashes if two SQL queries have been executed sequentially to get all the
required data.

=back

3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
=head1 B<Methods in need of POD>

=over

=item invalid_order_columns

=item COLUMN_JOINS

=item split_order_term

=item SqlifyDate

=item REPORT_COLUMNS

=item pronoun

=item COLUMNS

=item order

=item search_description

=item IsValidQueryType

=item build_subselect

=item do_search_function

=item boolean_charts_to_custom_search

=back