Quicksearch.pm 19.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# Contributor(s): C. Begle
#                 Jesse Ruderman
#                 Andreas Franke <afranke@mathweb.org>
#                 Stephen Lee <slee@uk.bnsmc.com>
#                 Marc Schumann <wurblzap@gmail.com>

package Bugzilla::Search::Quicksearch;

# Make it harder for us to do dangerous things in Perl.
use strict;

use Bugzilla::Error;
27
use Bugzilla::Constants;
28
use Bugzilla::Keyword;
29
use Bugzilla::Status;
30
use Bugzilla::Field;
31
use Bugzilla::Util;
32

33 34 35
use List::Util qw(min max);
use List::MoreUtils qw(firstidx);

36 37 38
use base qw(Exporter);
@Bugzilla::Search::Quicksearch::EXPORT = qw(quicksearch);

39
# Custom mappings for some fields.
40
use constant MAPPINGS => {
41 42 43 44 45 46 47 48
    # Status, Resolution, Platform, OS, Priority, Severity
    "status"   => "bug_status",
    "platform" => "rep_platform",
    "os"       => "op_sys",
    "severity" => "bug_severity",

    # People: AssignedTo, Reporter, QA Contact, CC, etc.
    "assignee" => "assigned_to",
49
    "owner"    => "assigned_to",
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

    # Product, Version, Component, Target Milestone
    "milestone" => "target_milestone",

    # Summary, Description, URL, Status whiteboard, Keywords
    "summary"     => "short_desc",
    "description" => "longdesc",
    "comment"     => "longdesc",
    "url"         => "bug_file_loc",
    "whiteboard"  => "status_whiteboard",
    "sw"          => "status_whiteboard",
    "kw"          => "keywords",
    "group"       => "bug_group",

    # Flags
    "flag"        => "flagtypes.name",
    "requestee"   => "requestees.login_name",
    "setter"      => "setters.login_name",

    # Attachments
    "attachment"     => "attachments.description",
    "attachmentdesc" => "attachments.description",
    "attachdesc"     => "attachments.description",
    "attachmentdata" => "attach_data.thedata",
    "attachdata"     => "attach_data.thedata",
    "attachmentmimetype" => "attachments.mimetype",
    "attachmimetype" => "attachments.mimetype"
};

sub FIELD_MAP {
    my $cache = Bugzilla->request_cache;
    return $cache->{quicksearch_fields} if $cache->{quicksearch_fields};

    # Get all the fields whose names don't contain periods. (Fields that
    # contain periods are always handled in MAPPINGS.) 
    my @db_fields = grep { $_->name !~ /\./ } 
86
                         @{ Bugzilla->fields({ obsolete => 0 }) };
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    my %full_map = (%{ MAPPINGS() }, map { $_->name => $_->name } @db_fields);

    # Eliminate the fields that start with bug_ or rep_, because those are
    # handled by the MAPPINGS instead, and we don't want too many names
    # for them. (Also, otherwise "rep" doesn't match "reporter".)
    #
    # Remove "status_whiteboard" because we have "whiteboard" for it in
    # the mappings, and otherwise "stat" can't match "status".
    #
    # Also, don't allow searching the _accessible stuff via quicksearch
    # (both because it's unnecessary and because otherwise 
    # "reporter_accessible" and "reporter" both match "rep".
    delete @full_map{qw(rep_platform bug_status bug_file_loc bug_group
                        bug_severity bug_status
                        status_whiteboard
                        cclist_accessible reporter_accessible)};

104 105
    Bugzilla::Hook::process('quicksearch_map', {'map' => \%full_map} );

106 107 108 109 110 111 112 113 114 115
    $cache->{quicksearch_fields} = \%full_map;

    return $cache->{quicksearch_fields};
}

# Certain fields, when specified like "field:value" get an operator other
# than "substring"
use constant FIELD_OPERATOR => {
    content         => 'matches',
    owner_idle_time => 'greaterthan',
116
};
117 118

# We might want to put this into localconfig or somewhere
119 120 121 122 123 124 125 126 127 128
use constant PRODUCT_EXCEPTIONS => (
    'row',   # [Browser]
             #   ^^^
    'new',   # [MailNews]
             #      ^^^
);
use constant COMPONENT_EXCEPTIONS => (
    'hang'   # [Bugzilla: Component/Keyword Changes]
             #                               ^^^^
);
129 130

# Quicksearch-wide globals for boolean charts.
131
our ($chart, $and, $or, $fulltext);
132 133 134

sub quicksearch {
    my ($searchstring) = (@_);
135
    my $cgi = Bugzilla->cgi;
136

137 138 139 140
    $chart = 0;
    $and   = 0;
    $or    = 0;

141 142 143 144
    # Remove leading and trailing commas and whitespace.
    $searchstring =~ s/(^[\s,]+|[\s,]+$)//g;
    ThrowUserError('buglist_parameters_required') unless ($searchstring);

145 146
    $fulltext = Bugzilla->user->settings->{'quicksearch_fulltext'}->{'value'} eq 'on' ? 1 : 0;

147
    if ($searchstring =~ m/^[0-9,\s]*$/) {
148
        _bug_numbers_only($searchstring);
149 150
    }
    else {
151
        _handle_alias($searchstring);
152 153 154 155 156 157

        # Globally translate " AND ", " OR ", " NOT " to space, pipe, dash.
        $searchstring =~ s/\s+AND\s+/ /g;
        $searchstring =~ s/\s+OR\s+/|/g;
        $searchstring =~ s/\s+NOT\s+/ -/g;

158
        my @words = splitString($searchstring);
159
        _handle_status_and_resolution(\@words);
160

161
        my (@unknownFields, %ambiguous_fields);
162 163 164 165 166 167 168 169

        # Loop over all main-level QuickSearch words.
        foreach my $qsword (@words) {
            my $negate = substr($qsword, 0, 1) eq '-';
            if ($negate) {
                $qsword = substr($qsword, 1);
            }

170 171
            # No special first char
            if (!_handle_special_first_chars($qsword, $negate)) {
172 173
                # Split by '|' to get all operands for a boolean OR.
                foreach my $or_operand (split(/\|/, $qsword)) {
174
                    if (!_handle_field_names($or_operand, $negate,
175 176
                                             \@unknownFields, 
                                             \%ambiguous_fields))
177
                    {
178 179 180
                        # Having ruled out the special cases, we may now split
                        # by comma, which is another legal boolean OR indicator.
                        foreach my $word (split(/,/, $or_operand)) {
181 182
                            if (!_special_field_syntax($word, $negate)) {
                                _default_quicksearch_word($word, $negate);
183
                            }
184 185 186 187 188
                            _handle_urls($word, $negate);
                        }
                    }
                }
            }
189 190 191 192 193
            $chart++;
            $and = 0;
            $or = 0;
        } # foreach (@words)

194
        # Inform user about any unknown fields
195
        if (scalar(@unknownFields) || scalar(keys %ambiguous_fields)) {
196
            ThrowUserError("quicksearch_unknown_field",
197 198
                           { unknown   => \@unknownFields,
                             ambiguous => \%ambiguous_fields });
199 200 201
        }

        # Make sure we have some query terms left
202 203 204 205 206 207 208 209
        scalar($cgi->param())>0 || ThrowUserError("buglist_parameters_required");
    }

    # List of quicksearch-specific CGI parameters to get rid of.
    my @params_to_strip = ('quicksearch', 'load', 'run');
    my $modified_query_string = $cgi->canonicalise_query(@params_to_strip);

    if ($cgi->param('load')) {
210
        my $urlbase = correct_urlbase();
211
        # Param 'load' asks us to display the query in the advanced search form.
212
        print $cgi->redirect(-uri => "${urlbase}query.cgi?format=advanced&amp;"
213
                             . $modified_query_string);
214 215 216 217 218 219 220 221 222
    }

    # Otherwise, pass the modified query string to the caller.
    # We modified $cgi->params, so the caller can choose to look at that, too,
    # and disregard the return value.
    $cgi->delete(@params_to_strip);
    return $modified_query_string;
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
##########################
# Parts of quicksearch() #
##########################

sub _bug_numbers_only {
    my $searchstring = shift;
    my $cgi = Bugzilla->cgi;
    # Allow separation by comma or whitespace.
    $searchstring =~ s/[,\s]+/,/g;

    if ($searchstring !~ /,/) {
        # Single bug number; shortcut to show_bug.cgi.
        print $cgi->redirect(
            -uri => correct_urlbase() . "show_bug.cgi?id=$searchstring");
        exit;
    }
    else {
        # List of bug numbers.
        $cgi->param('bug_id', $searchstring);
        $cgi->param('order', 'bugs.bug_id');
243
        $cgi->param('bug_id_type', 'anyexact');
244 245 246 247 248 249 250 251 252 253 254
    }
}

sub _handle_alias {
    my $searchstring = shift;
    if ($searchstring =~ /^([^,\s]+)$/) {
        my $alias = $1;
        # We use this direct SQL because we want quicksearch to be VERY fast.
        my $is_alias = Bugzilla->dbh->selectrow_array(
            q{SELECT 1 FROM bugs WHERE alias = ?}, undef, $alias);
        if ($is_alias) {
255
            $alias = url_quote($alias);
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            print Bugzilla->cgi->redirect(
                -uri => correct_urlbase() . "show_bug.cgi?id=$alias");
            exit;
        }
    }
}

sub _handle_status_and_resolution {
    my ($words) = @_;
    my $legal_statuses = get_legal_field_values('bug_status');
    my $legal_resolutions = get_legal_field_values('resolution');

    my @openStates = BUG_STATE_OPEN;
    my @closedStates;
    my (%states, %resolutions);

    foreach (@$legal_statuses) {
        push(@closedStates, $_) unless is_open_state($_);
    }
    foreach (@openStates) { $states{$_} = 1 }
    if ($words->[0] eq 'ALL') {
        foreach (@$legal_statuses) { $states{$_} = 1 }
        shift @$words;
    }
    elsif ($words->[0] eq 'OPEN') {
        shift @$words;
    }
283 284
    elsif ($words->[0] =~ /^[A-Z_]+(,[_A-Z]+)*$/) {
        # e.g. CON,IN_PR,FIX
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        undef %states;
        if (matchPrefixes(\%states,
                          \%resolutions,
                          [split(/,/, $words->[0])],
                          $legal_statuses,
                          $legal_resolutions)) {
            shift @$words;
        }
        else {
            # Carry on if no match found
            foreach (@openStates) { $states{$_} = 1 }
        }
    }
    else {
        # Default: search for unresolved bugs only.
        # Put custom code here if you would like to change this behaviour.
    }

    # If we have wanted resolutions, allow closed states
    if (keys(%resolutions)) {
        foreach (@closedStates) { $states{$_} = 1 }
    }

    Bugzilla->cgi->param('bug_status', keys(%states));
    Bugzilla->cgi->param('resolution', keys(%resolutions));
}


sub _handle_special_first_chars {
    my ($qsword, $negate) = @_;

    my $firstChar = substr($qsword, 0, 1);
    my $baseWord = substr($qsword, 1);
    my @subWords = split(/[\|,]/, $baseWord);

    if ($firstChar eq '#') {
        addChart('short_desc', 'substring', $baseWord, $negate);
322
        addChart('content', 'matches', _matches_phrase($baseWord), $negate) if $fulltext;
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        return 1;
    }
    if ($firstChar eq ':') {
        foreach (@subWords) {
            addChart('product', 'substring', $_, $negate);
            addChart('component', 'substring', $_, $negate);
        }
        return 1;
    }
    if ($firstChar eq '@') {
        addChart('assigned_to', 'substring', $_, $negate) foreach (@subWords);
        return 1;
    }
    if ($firstChar eq '[') {
        addChart('short_desc', 'substring', $baseWord, $negate);
        addChart('status_whiteboard', 'substring', $baseWord, $negate);
        return 1;
    }
    if ($firstChar eq '!') {
        addChart('keywords', 'anywords', $baseWord, $negate);
        return 1;
    }
    return 0;
}

sub _handle_field_names {
349
    my ($or_operand, $negate, $unknownFields, $ambiguous_fields) = @_;
350 351 352 353 354 355 356 357 358 359 360 361 362 363
    
    # Flag and requestee shortcut
    if ($or_operand =~ /^(?:flag:)?([^\?]+\?)([^\?]*)$/) {
        addChart('flagtypes.name', 'substring', $1, $negate);
        $chart++; $and = $or = 0; # Next chart for boolean AND
        addChart('requestees.login_name', 'substring', $2, $negate);
        return 1;
    }
    
    # generic field1,field2,field3:value1,value2 notation
    if ($or_operand =~ /^([^:]+):([^:]+)$/) {
        my @fields = split(/,/, $1);
        my @values = split(/,/, $2);
        foreach my $field (@fields) {
364
            my $translated = _translate_field_name($field);
365
            # Skip and record any unknown fields
366
            if (!defined $translated) {
367 368 369
                push(@$unknownFields, $field);
                next;
            }
370 371 372 373 374 375 376 377 378
            # If we got back an array, that means the substring is
            # ambiguous and could match more than field name
            elsif (ref $translated) {
                $ambiguous_fields->{$field} = $translated;
                next;
            }
            foreach my $value (@values) {
                my $operator = FIELD_OPERATOR->{$translated} || 'substring';
                addChart($translated, $operator, $value, $negate);
379 380 381 382 383 384 385 386
            }
        }
        return 1;
    }
    
    return 0;
}

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
sub _translate_field_name {
    my $field = shift;
    $field = lc($field);
    my $field_map = FIELD_MAP;

    # If the field exactly matches a mapping, just return right now.
    return $field_map->{$field} if exists $field_map->{$field};

    # Check if we match, as a starting substring, exactly one field.
    my @field_names = keys %$field_map;
    my @matches = grep { $_ =~ /^\Q$field\E/ } @field_names;
    # Eliminate duplicates that are actually the same field
    # (otherwise "assi" matches both "assignee" and "assigned_to", and
    # the lines below fail when they shouldn't.)
    my %match_unique = map { $field_map->{$_} => $_ } @matches;
    @matches = values %match_unique;

    if (scalar(@matches) == 1) {
        return $field_map->{$matches[0]};
    }
    elsif (scalar(@matches) > 1) {
        return \@matches;
    }

    # Check if we match exactly one custom field, ignoring the cf_ on the
    # custom fields (to allow people to type things like "build" for 
    # "cf_build").
    my %cfless;
    foreach my $name (@field_names) {
        my $no_cf = $name;
        if ($no_cf =~ s/^cf_//) {
            if ($field eq $no_cf) {
                return $field_map->{$name};
            }
            $cfless{$no_cf} = $name;
        }
    }

    # See if we match exactly one substring of any of the cf_-less fields.
    my @cfless_matches = grep { $_ =~ /^\Q$field\E/ } (keys %cfless);

    if (scalar(@cfless_matches) == 1) {
        my $match = $cfless_matches[0];
        my $actual_field = $cfless{$match};
        return $field_map->{$actual_field};
    }
    elsif (scalar(@matches) > 1) {
        return \@matches;
    }

    return undef;
}

440 441 442 443 444
sub _special_field_syntax {
    my ($word, $negate) = @_;
    
    # P1-5 Syntax
    if ($word =~ m/^P(\d+)(?:-(\d+))?$/i) {
445
        my ($p_start, $p_end) = ($1, $2);
446
        my $legal_priorities = get_legal_field_values('priority');
447 448 449 450 451 452 453 454 455 456

        # If Pn exists explicitly, use it.
        my $start = firstidx { $_ eq "P$p_start" } @$legal_priorities;
        my $end;
        $end = firstidx { $_ eq "P$p_end" } @$legal_priorities if defined $p_end;

        # If Pn doesn't exist explicitly, then we mean the nth priority.
        if ($start == -1) {
            $start = max(0, $p_start - 1);
        }
457
        my $prios = $legal_priorities->[$start];
458 459 460 461 462 463 464 465

        if (defined $end) {
            # If Pn doesn't exist explicitly, then we mean the nth priority.
            if ($end == -1) {
                $end = min(scalar(@$legal_priorities), $p_end) - 1;
                $end = max(0, $end); # Just in case the user typed P0.
            }
            ($start, $end) = ($end, $start) if $end < $start;
466 467
            $prios = join(',', @$legal_priorities[$start..$end])
        }
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        addChart('priority', 'anyexact', $prios, $negate);
        return 1;
    }
    return 0;    
}

sub _default_quicksearch_word {
    my ($word, $negate) = @_;
    
    if (!grep { lc($word) eq $_ } PRODUCT_EXCEPTIONS and length($word) > 2) {
        addChart('product', 'substring', $word, $negate);
    }
    
    if (!grep { lc($word) eq $_ } COMPONENT_EXCEPTIONS and length($word) > 2) {
        addChart('component', 'substring', $word, $negate);
    }
    
    my @legal_keywords = map($_->name, Bugzilla::Keyword->get_all);
    if (grep { lc($word) eq lc($_) } @legal_keywords) {
        addChart('keywords', 'substring', $word, $negate);
    }
    
491
    addChart('alias', 'substring', $word, $negate);
492 493
    addChart('short_desc', 'substring', $word, $negate);
    addChart('status_whiteboard', 'substring', $word, $negate);
494
    addChart('content', 'matches', _matches_phrase($word), $negate) if $fulltext;
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
}

sub _handle_urls {
    my ($word, $negate) = @_;
    # URL field (for IP addrs, host.names,
    # scheme://urls)
    if ($word =~ m/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/
        || $word =~ /^[A-Za-z]+(\.[A-Za-z]+)+/
        || $word =~ /:[\\\/][\\\/]/
        || $word =~ /localhost/
        || $word =~ /mailto[:]?/)
        # || $word =~ /[A-Za-z]+[:][0-9]+/ #host:port
    {
        addChart('bug_file_loc', 'substring', $word, $negate);
    }
}

512 513 514 515
###########################################################################
# Helpers
###########################################################################

516 517 518 519 520 521 522 523 524 525 526
# Split string on whitespace, retaining quoted strings as one
sub splitString {
    my $string = shift;
    my @quoteparts;
    my @parts;
    my $i = 0;

    # Now split on quote sign; be tolerant about unclosed quotes
    @quoteparts = split(/"/, $string);
    foreach my $part (@quoteparts) {
        # After every odd quote, quote special chars
527 528 529 530 531 532
        if ($i++ %2) {
            $part = url_quote($part);
            # Protect the minus sign from being considered
            # as negation, in quotes.
            $part =~ s/(?<=^)\-/%2D/;
        }
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    }
    # Join again
    $string = join('"', @quoteparts);

    # Now split on unescaped whitespace
    @parts = split(/\s+/, $string);
    foreach (@parts) {
        # Protect plus signs from becoming a blank.
        # If "+" appears as the first character, leave it alone
        # as it has a special meaning. Strings which start with
        # "+" must be quoted.
        s/(?<!^)\+/%2B/g;
        # Remove quotes
        s/"//g;
    }
    return @parts;
}

551 552 553 554 555 556 557
# Quote and escape a phrase appropriately for a "content matches" search.
sub _matches_phrase {
    my ($phrase) = @_;
    $phrase =~ s/"/\\"/g;
    return "\"$phrase\"";
}

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
# Expand found prefixes to states or resolutions
sub matchPrefixes {
    my $hr_states = shift;
    my $hr_resolutions = shift;
    my $ar_prefixes = shift;
    my $ar_check_states = shift;
    my $ar_check_resolutions = shift;
    my $foundMatch = 0;

    foreach my $prefix (@$ar_prefixes) {
        foreach (@$ar_check_states) {
            if (/^$prefix/) {
                $$hr_states{$_} = 1;
                $foundMatch = 1;
            }
        }
        foreach (@$ar_check_resolutions) {
            if (/^$prefix/) {
                $$hr_resolutions{$_} = 1;
                $foundMatch = 1;
            }
        }
    }
    return $foundMatch;
}

# Negate comparison type
sub negateComparisonType {
    my $comparisonType = shift;

588
    if ($comparisonType eq 'anywords') {
589 590
        return 'nowords';
    }
591
    return "not$comparisonType";
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
}

# Add a boolean chart
sub addChart {
    my ($field, $comparisonType, $value, $negate) = @_;

    $negate && ($comparisonType = negateComparisonType($comparisonType));
    makeChart("$chart-$and-$or", $field, $comparisonType, $value);
    if ($negate) {
        $and++;
        $or = 0;
    }
    else {
        $or++;
    }
}

# Create the CGI parameters for a boolean chart
sub makeChart {
    my ($expr, $field, $type, $value) = @_;

613
    my $cgi = Bugzilla->cgi;
614 615
    $cgi->param("field$expr", $field);
    $cgi->param("type$expr",  $type);
616
    $cgi->param("value$expr", url_decode($value));
617 618 619
}

1;