Quicksearch.pm 20.3 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 36

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

# Word renamings
37 38
use constant MAPPINGS => {
                # Status, Resolution, Platform, OS, Priority, Severity
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
                "status" => "bug_status",
                "resolution" => "resolution",  # no change
                "platform" => "rep_platform",
                "os" => "op_sys",
                "opsys" => "op_sys",
                "priority" => "priority",    # no change
                "pri" => "priority",
                "severity" => "bug_severity",
                "sev" => "bug_severity",
                # People: AssignedTo, Reporter, QA Contact, CC, Added comment (?)
                "owner" => "assigned_to",    # deprecated since bug 76507
                "assignee" => "assigned_to",
                "assignedto" => "assigned_to",
                "reporter" => "reporter",    # no change
                "rep" => "reporter",
                "qa" => "qa_contact",
                "qacontact" => "qa_contact",
                "cc" => "cc",          # no change
                # Product, Version, Component, Target Milestone
                "product" => "product",     # no change
                "prod" => "product",
                "version" => "version",     # no change
                "ver" => "version",
                "component" => "component",   # no change
                "comp" => "component",
                "milestone" => "target_milestone",
                "target" => "target_milestone",
                "targetmilestone" => "target_milestone",
                # Summary, Description, URL, Status whiteboard, Keywords
                "summary" => "short_desc",
                "shortdesc" => "short_desc",
                "desc" => "longdesc",
                "description" => "longdesc",
                #"comment" => "longdesc",    # ???
                          # reserve "comment" for "added comment" email search?
                "longdesc" => "longdesc",
                "url" => "bug_file_loc",
                "whiteboard" => "status_whiteboard",
                "statuswhiteboard" => "status_whiteboard",
                "sw" => "status_whiteboard",
                "keywords" => "keywords",    # no change
                "kw" => "keywords",
81
                "group" => "bug_group",
82 83 84 85 86
                "flag" => "flagtypes.name",
                "requestee" => "requestees.login_name",
                "req" => "requestees.login_name",
                "setter" => "setters.login_name",
                "set" => "setters.login_name",
87 88 89 90
                # Attachments
                "attachment" => "attachments.description",
                "attachmentdesc" => "attachments.description",
                "attachdesc" => "attachments.description",
91 92
                "attachmentdata" => "attach_data.thedata",
                "attachdata" => "attach_data.thedata",
93
                "attachmentmimetype" => "attachments.mimetype",
94 95
                "attachmimetype" => "attachments.mimetype"
};
96 97

# We might want to put this into localconfig or somewhere
98
use constant PLATFORMS => ('pc', 'sun', 'macintosh', 'mac');
99
use constant OPSYSTEMS => ('windows', 'win', 'linux');
100 101 102 103 104 105 106 107 108 109
use constant PRODUCT_EXCEPTIONS => (
    'row',   # [Browser]
             #   ^^^
    'new',   # [MailNews]
             #      ^^^
);
use constant COMPONENT_EXCEPTIONS => (
    'hang'   # [Bugzilla: Component/Keyword Changes]
             #                               ^^^^
);
110 111

# Quicksearch-wide globals for boolean charts.
112
our ($chart, $and, $or);
113 114 115

sub quicksearch {
    my ($searchstring) = (@_);
116
    my $cgi = Bugzilla->cgi;
117
    my $urlbase = correct_urlbase();
118

119 120 121 122
    $chart = 0;
    $and   = 0;
    $or    = 0;

123 124 125 126 127 128 129 130 131 132 133 134
    # Remove leading and trailing commas and whitespace.
    $searchstring =~ s/(^[\s,]+|[\s,]+$)//g;
    ThrowUserError('buglist_parameters_required') unless ($searchstring);

    if ($searchstring =~ m/^[0-9,\s]*$/) {
        # Bug number(s) only.

        # Allow separation by comma or whitespace.
        $searchstring =~ s/[,\s]+/,/g;

        if (index($searchstring, ',') < $[) {
            # Single bug number; shortcut to show_bug.cgi.
135
            print $cgi->redirect(-uri => "${urlbase}show_bug.cgi?id=$searchstring");
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
            exit;
        }
        else {
            # List of bug numbers.
            $cgi->param('bug_id', $searchstring);
            $cgi->param('order', 'bugs.bug_id');
            $cgi->param('bugidtype', 'include');
        }
    }
    else {
        # It's not just a bug number or a list of bug numbers.
        # Maybe it's an alias?
        if ($searchstring =~ /^([^,\s]+)$/) {
            if (Bugzilla->dbh->selectrow_array(q{SELECT COUNT(*)
                                                   FROM bugs
                                                  WHERE alias = ?},
                                               undef,
                                               $1)) {
154
                print $cgi->redirect(-uri => "${urlbase}show_bug.cgi?id=$1");
155 156 157 158 159
                exit;
            }
        }

        # It's no alias either, so it's a more complex query.
160 161
        my $legal_statuses = get_legal_field_values('bug_status');
        my $legal_resolutions = get_legal_field_values('resolution');
162 163 164 165 166 167 168

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

        my @words = splitString($searchstring);
169 170
        my $searchComments = 
            $#words < Bugzilla->params->{'quicksearch_comment_cutoff'};
171
        my @openStates = BUG_STATE_OPEN;
172
        my @closedStates;
173
        my @unknownFields;
174 175
        my (%states, %resolutions);

176
        foreach (@$legal_statuses) {
177
            push(@closedStates, $_) unless is_open_state($_);
178 179 180
        }
        foreach (@openStates) { $states{$_} = 1 }
        if ($words[0] eq 'ALL') {
181
            foreach (@$legal_statuses) { $states{$_} = 1 }
182 183 184 185 186 187 188 189 190 191 192
            shift @words;
        }
        elsif ($words[0] eq 'OPEN') {
            shift @words;
        }
        elsif ($words[0] =~ /^\+[A-Z]+(,[A-Z]+)*$/) {
            # e.g. +DUP,FIX
            if (matchPrefixes(\%states,
                              \%resolutions,
                              [split(/,/, substr($words[0], 1))],
                              \@closedStates,
193
                              $legal_resolutions)) {
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
                shift @words;
                # Allowing additional resolutions means we need to keep
                # the "no resolution" resolution.
                $resolutions{'---'} = 1;
            }
            else {
                # Carry on if no match found.
            }
        }
        elsif ($words[0] =~ /^[A-Z]+(,[A-Z]+)*$/) {
            # e.g. NEW,ASSI,REOP,FIX
            undef %states;
            if (matchPrefixes(\%states,
                              \%resolutions,
                              [split(/,/, $words[0])],
209 210
                              $legal_statuses,
                              $legal_resolutions)) {
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                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 }
        }

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

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

            my $firstChar = substr($qsword, 0, 1);
            my $baseWord = substr($qsword, 1);
            my @subWords = split(/[\|,]/, $baseWord);
            if ($firstChar eq '+') {
                foreach (@subWords) {
                    addChart('short_desc', 'substring', $qsword, $negate);
                }
            }
            elsif ($firstChar eq '#') {
                addChart('short_desc', 'anywords', $baseWord, $negate);
                if ($searchComments) {
                    addChart('longdesc', 'anywords', $baseWord, $negate);
                }
            }
            elsif ($firstChar eq ':') {
                foreach (@subWords) {
                    addChart('product', 'substring', $_, $negate);
                    addChart('component', 'substring', $_, $negate);
                }
            }
            elsif ($firstChar eq '@') {
                foreach (@subWords) {
                    addChart('assigned_to', 'substring', $_, $negate);
                }
            }
            elsif ($firstChar eq '[') {
                addChart('short_desc', 'substring', $baseWord, $negate);
                addChart('status_whiteboard', 'substring', $baseWord, $negate);
            }
            elsif ($firstChar eq '!') {
                addChart('keywords', 'anywords', $baseWord, $negate);

            }
            else { # No special first char

                # Split by '|' to get all operands for a boolean OR.
                foreach my $or_operand (split(/\|/, $qsword)) {
                    if ($or_operand =~ /^votes:([0-9]+)$/) {
                        # votes:xx ("at least xx votes")
277
                        addChart('votes', 'greaterthan', $1 - 1, $negate);
278
                    }
279
                    elsif ($or_operand =~ /^(?:flag:)?([^\?]+\?)([^\?]*)$/) {
280 281 282 283 284
                        # Flag and requestee shortcut
                        addChart('flagtypes.name', 'substring', $1, $negate);
                        $chart++; $and = $or = 0; # Next chart for boolean AND
                        addChart('requestees.login_name', 'substring', $2, $negate);
                    }
285 286 287 288 289
                    elsif ($or_operand =~ /^([^:]+):([^:]+)$/) {
                        # generic field1,field2,field3:value1,value2 notation
                        my @fields = split(/,/, $1);
                        my @values = split(/,/, $2);
                        foreach my $field (@fields) {
290 291 292 293 294
                            # Skip and record any unknown fields
                            if (!defined(MAPPINGS->{$field})) {
                                push(@unknownFields, $field);
                                next;
                            }
295
                            $field = MAPPINGS->{$field};
296 297 298 299 300 301 302 303 304 305 306
                            foreach (@values) {
                                addChart($field, 'substring', $_, $negate);
                            }
                        }

                    }
                    else {

                        # 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)) {
307 308 309
                            # Platform and operating system
                            if (grep({lc($word) eq $_} PLATFORMS)
                                || grep({lc($word) eq $_} OPSYSTEMS)) {
310 311
                                addChart('rep_platform', 'substring',
                                         $word, $negate);
312 313
                                addChart('op_sys', 'substring',
                                         $word, $negate);
314 315 316 317 318 319 320 321
                            }
                            # Priority
                            elsif ($word =~ m/^[pP]([1-5](-[1-5])?)$/) {
                                addChart('priority', 'regexp',
                                         "[$1]", $negate);
                            }
                            # Severity
                            elsif (grep({lc($word) eq substr($_, 0, 3)}
322
                                        @{get_legal_field_values('bug_severity')})) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                                addChart('bug_severity', 'substring',
                                         $word, $negate);
                            }
                            # Votes (votes>xx)
                            elsif ($word =~ m/^votes>([0-9]+)$/) {
                                addChart('votes', 'greaterthan',
                                         $1, $negate);
                            }
                            # Votes (votes>=xx, votes=>xx)
                            elsif ($word =~ m/^votes(>=|=>)([0-9]+)$/) {
                                addChart('votes', 'greaterthan',
                                         $2-1, $negate);

                            }
                            else { # Default QuickSearch word

                                if (!grep({lc($word) eq $_}
340
                                          PRODUCT_EXCEPTIONS) &&
341 342 343 344 345 346
                                    length($word)>2
                                   ) {
                                    addChart('product', 'substring',
                                             $word, $negate);
                                }
                                if (!grep({lc($word) eq $_}
347
                                          COMPONENT_EXCEPTIONS) &&
348 349 350 351 352 353
                                    length($word)>2
                                   ) {
                                    addChart('component', 'substring',
                                             $word, $negate);
                                }
                                if (grep({lc($word) eq $_}
354
                                         map($_->name, Bugzilla::Keyword->get_all))) {
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
                                    addChart('keywords', 'substring',
                                             $word, $negate);
                                    if (length($word)>2) {
                                        addChart('short_desc', 'substring',
                                                 $word, $negate);
                                        addChart('status_whiteboard',
                                                 'substring',
                                                 $word, $negate);
                                    }

                                }
                                else {

                                    addChart('short_desc', 'substring',
                                             $word, $negate);
                                    addChart('status_whiteboard', 'substring',
                                             $word, $negate);
                                }
                                if ($searchComments) {
                                    addChart('longdesc', 'substring',
                                             $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);
                            }
                        } # foreach my $word (split(/,/, $qsword))
                    } # votes and generic field detection
                } # foreach (split(/\|/, $_))
            } # "switch" $firstChar
            $chart++;
            $and = 0;
            $or = 0;
        } # foreach (@words)

399 400 401 402 403 404 405
        # Inform user about any unknown fields
        if (scalar(@unknownFields)) {
            ThrowUserError("quicksearch_unknown_field",
                           { fields => \@unknownFields });
        }

        # Make sure we have some query terms left
406 407 408 409 410 411 412 413 414
        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')) {
        # Param 'load' asks us to display the query in the advanced search form.
415
        print $cgi->redirect(-uri => "${urlbase}query.cgi?format=advanced&amp;"
416
                             . $modified_query_string);
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    }

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

###########################################################################
# Helpers
###########################################################################

# 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);
439 440 441
    foreach my $part (@quoteparts) {
        # After every odd quote, quote special chars
        $part = url_quote($part) if $i++ % 2;
442 443 444 445 446
    }
    # Join again
    $string = join('"', @quoteparts);

    # Now split on unescaped whitespace
447
    @parts = split(/\s+/, $string);
448
    foreach (@parts) {
449 450 451 452 453
        # 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;
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        # Remove quotes
        s/"//g;
    }
    return @parts;
}

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

    if ($comparisonType eq 'substring') {
        return 'notsubstring';
    }
    elsif ($comparisonType eq 'anywords') {
        return 'nowords';
    }
    elsif ($comparisonType eq 'regexp') {
        return 'notregexp';
    }
    else {
        # Don't know how to negate that
        ThrowCodeError('unknown_comparison_type');
    }
}

# 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) = @_;

524
    my $cgi = Bugzilla->cgi;
525 526
    $cgi->param("field$expr", $field);
    $cgi->param("type$expr",  $type);
527
    $cgi->param("value$expr", url_decode($value));
528 529 530
}

1;