query.cgi 13.5 KB
Newer Older
1
#!/usr/bin/perl -wT
2
# -*- Mode: perl; indent-tabs-mode: nil -*-
terry%netscape.com's avatar
terry%netscape.com committed
3
#
4 5 6 7 8 9 10 11 12 13
# 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.
#
terry%netscape.com's avatar
terry%netscape.com committed
14
# The Original Code is the Bugzilla Bug Tracking System.
15
#
terry%netscape.com's avatar
terry%netscape.com committed
16
# The Initial Developer of the Original Code is Netscape Communications
17 18 19 20
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
terry%netscape.com's avatar
terry%netscape.com committed
21
# Contributor(s): Terry Weissman <terry@mozilla.org>
22
#                 David Gardiner <david.gardiner@unisa.edu.au>
23
#                 Matthias Radestock <matthias@sorted.org>
24
#                 Gervase Markham <gerv@gerv.net>
25
#                 Byron Jones <bugzilla@glob.com.au>
26
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
terry%netscape.com's avatar
terry%netscape.com committed
27

28
use strict;
29
use lib ".";
terry%netscape.com's avatar
terry%netscape.com committed
30

31
use Bugzilla;
32
use Bugzilla::Bug;
33
use Bugzilla::Constants;
34
use Bugzilla::Search;
35
use Bugzilla::User;
36
use Bugzilla::Util;
37
use Bugzilla::Error;
38
use Bugzilla::Product;
39
use Bugzilla::Keyword;
40
use Bugzilla::Field;
41
use Bugzilla::Install::Requirements;
42

43
my $cgi = Bugzilla->cgi;
44
my $dbh = Bugzilla->dbh;
45 46
my $template = Bugzilla->template;
my $vars = {};
47
my $buffer = $cgi->query_string();
48

49
my $user = Bugzilla->login();
50
my $userid = $user->id;
51

52
# Backwards compatibility hack -- if there are any of the old QUERY_*
53
# cookies around, and we are logged in, then move them into the database
54
# and nuke the cookie. This is required for Bugzilla 2.8 and earlier.
55
if ($userid) {
56
    my @oldquerycookies;
57
    foreach my $i ($cgi->cookie()) {
58
        if ($i =~ /^QUERY_(.*)$/) {
59
            push(@oldquerycookies, [$1, $i, $cgi->cookie($i)]);
60 61
        }
    }
62
    if (defined $cgi->cookie('DEFAULTQUERY')) {
63
        push(@oldquerycookies, [DEFAULT_QUERY_NAME, 'DEFAULTQUERY',
64
                                $cgi->cookie('DEFAULTQUERY')]);
65 66 67 68 69
    }
    if (@oldquerycookies) {
        foreach my $ref (@oldquerycookies) {
            my ($name, $cookiename, $value) = (@$ref);
            if ($value) {
70 71 72
                # If the query name contains invalid characters, don't import.
                $name =~ /[<>&]/ && next;
                trick_taint($name);
73
                $dbh->bz_lock_tables('namedqueries WRITE');
74 75 76 77
                my $query = $dbh->selectrow_array(
                    "SELECT query FROM namedqueries " .
                     "WHERE userid = ? AND name = ?",
                     undef, ($userid, $name));
78
                if (!$query) {
79
                    $dbh->do("INSERT INTO namedqueries " .
80
                            "(userid, name, query) VALUES " .
81
                            "(?, ?, ?)", undef, ($userid, $name, $value));
82
                }
83
                $dbh->bz_unlock_tables();
84
            }
85
            $cgi->remove_cookie($cookiename);
86 87
        }
    }
88
}
terry%netscape.com's avatar
terry%netscape.com committed
89

90
if ($cgi->param('nukedefaultquery')) {
91
    if ($userid) {
92 93 94
        $dbh->do("DELETE FROM namedqueries" .
                 " WHERE userid = ? AND name = ?", 
                 undef, ($userid, DEFAULT_QUERY_NAME));
95
    }
96
    $buffer = "";
terry%netscape.com's avatar
terry%netscape.com committed
97 98
}

99
my $userdefaultquery;
100
if ($userid) {
101 102 103 104
    $userdefaultquery = $dbh->selectrow_array(
        "SELECT query FROM namedqueries " .
         "WHERE userid = ? AND name = ?", 
         undef, ($userid, DEFAULT_QUERY_NAME));
terry%netscape.com's avatar
terry%netscape.com committed
105 106
}

107
local our %default;
108

109 110 111 112
# We pass the defaults as a hash of references to arrays. For those
# Items which are single-valued, the template should only reference [0]
# and ignore any multiple values.
sub PrefillForm {
113 114
    my ($buf) = (@_);
    my $foundone = 0;
115 116

    # Nothing must be undef, otherwise the template complains.
117 118
    foreach my $name ("bug_status", "resolution", "assigned_to",
                      "rep_platform", "priority", "bug_severity",
119
                      "classification", "product", "reporter", "op_sys",
120
                      "component", "version", "chfield", "chfieldfrom",
121
                      "chfieldto", "chfieldvalue", "target_milestone",
122 123
                      "email", "emailtype", "emailreporter",
                      "emailassigned_to", "emailcc", "emailqa_contact",
124
                      "emaillongdesc", "content",
125 126 127
                      "changedin", "votes", "short_desc", "short_desc_type",
                      "long_desc", "long_desc_type", "bug_file_loc",
                      "bug_file_loc_type", "status_whiteboard",
128
                      "status_whiteboard_type", "bug_id",
129
                      "bugidtype", "keywords", "keywords_type",
130
                      "x_axis_field", "y_axis_field", "z_axis_field",
131 132 133
                      "chart_format", "cumulate", "x_labels_vertical",
                      "category", "subcategory", "name", "newcategory",
                      "newsubcategory", "public", "frequency") 
134
    {
135 136 137 138 139 140
        # This is a bit of a hack. The default, empty list has 
        # three entries to accommodate the needs of the email fields -
        # we use each position to denote the relevant field. Array
        # position 0 is unused for email fields because the form 
        # parameters historically started at 1.
        $default{$name} = ["", "", ""];
141
    }
142 143 144
 
 
    # Iterate over the URL parameters
145 146 147 148 149
    foreach my $item (split(/\&/, $buf)) {
        my @el = split(/=/, $item);
        my $name = $el[0];
        my $value;
        if ($#el > 0) {
150
            $value = Bugzilla::Util::url_decode($el[1]);
terry%netscape.com's avatar
terry%netscape.com committed
151
        } else {
152 153
            $value = "";
        }
154
        
155 156 157 158 159 160 161 162
        # If the name begins with field, type, or value, then it is part of
        # the boolean charts. Because these are built different than the rest
        # of the form, we don't need to save a default value. We do, however,
        # need to indicate that we found something so the default query isn't
        # added in if all we have are boolean chart items.
        if ($name =~ m/^(?:field|type|value)/) {
            $foundone = 1;
        }
163 164 165
        # If the name ends in a number (which it does for the fields which
        # are part of the email searching), we use the array
        # positions to show the defaults for that number field.
166
        elsif ($name =~ m/^(.+)(\d)$/ && defined($default{$1})) {
167
            $foundone = 1;
168
            $default{$1}->[$2] = $value;
terry%netscape.com's avatar
terry%netscape.com committed
169
        }
170 171 172 173 174 175 176 177 178 179
        # If there's no default yet, we replace the blank string.
        elsif (defined($default{$name}) && $default{$name}->[0] eq "") {
            $foundone = 1;
            $default{$name} = [$value]; 
        } 
        # If there's already a default, we push on the new value.
        elsif (defined($default{$name})) {
            push (@{$default{$name}}, $value);
        }        
    }        
180
    return $foundone;
terry%netscape.com's avatar
terry%netscape.com committed
181
}
182

183

184
if (!PrefillForm($buffer)) {
185 186 187
    # Ah-hah, there was no form stuff specified.  Do it again with the
    # default query.
    if ($userdefaultquery) {
188
        PrefillForm($userdefaultquery);
189
    } else {
190
        PrefillForm(Bugzilla->params->{"defaultquery"});
191 192
    }
}
193

194 195
if ($default{'chfieldto'}->[0] eq "") {
    $default{'chfieldto'} = ["Now"];
terry%netscape.com's avatar
terry%netscape.com committed
196 197
}

198 199
# if using groups for entry, then we don't want people to see products they 
# don't have access to. Remove them from the list.
200 201
my @selectable_products = sort {lc($a->name) cmp lc($b->name)} 
                               @{$user->get_selectable_products};
202

203
# Create the component, version and milestone lists.
204 205 206 207 208 209 210 211
my %components;
my %versions;
my %milestones;

foreach my $product (@selectable_products) {
    $components{$_->name} = 1 foreach (@{$product->components});
    $versions{$_->name}   = 1 foreach (@{$product->versions});
    $milestones{$_->name} = 1 foreach (@{$product->milestones});
212 213
}

214
my @components = sort(keys %components);
215
my @versions = sort { vers_cmp (lc($a), lc($b)) } keys %versions;
216 217
my @milestones = sort(keys %milestones);

218
$vars->{'product'} = \@selectable_products;
219

220
# Create data structures representing each classification
221
if (Bugzilla->params->{'useclassification'}) {
222
    $vars->{'classification'} = $user->get_selectable_classifications;
223 224
}

225 226
# We use 'component_' because 'component' is a Template Toolkit reserved word.
$vars->{'component_'} = \@components;
terry%netscape.com's avatar
terry%netscape.com committed
227

228
$vars->{'version'} = \@versions;
229

230
if (Bugzilla->params->{'usetargetmilestone'}) {
231
    $vars->{'target_milestone'} = \@milestones;
232 233
}

234
$vars->{'have_keywords'} = Bugzilla::Keyword::keyword_count();
235

236 237 238 239
my $legal_resolutions = get_legal_field_values('resolution');
push(@$legal_resolutions, "---"); # Oy, what a hack.
# Another hack - this array contains "" for some reason. See bug 106589.
$vars->{'resolution'} = [grep ($_, @$legal_resolutions)];
240

241 242
my @chfields;

243
push @chfields, "[Bug creation]";
244 245 246

# This is what happens when you have variables whose definition depends
# on the DB schema, and then the underlying schema changes...
247
foreach my $val (editable_bug_fields()) {
248 249 250
    if ($val eq 'classification_id') {
        $val = 'classification';
    } elsif ($val eq 'product_id') {
251 252 253 254 255 256 257
        $val = 'product';
    } elsif ($val eq 'component_id') {
        $val = 'component';
    }
    push @chfields, $val;
}

258
if (Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'})) {
259 260 261 262 263 264 265
    push @chfields, "work_time";
} else {
    @chfields = grep($_ ne "estimated_time", @chfields);
    @chfields = grep($_ ne "remaining_time", @chfields);
}
@chfields = (sort(@chfields));
$vars->{'chfield'} = \@chfields;
266 267 268 269 270
$vars->{'bug_status'} = get_legal_field_values('bug_status');
$vars->{'rep_platform'} = get_legal_field_values('rep_platform');
$vars->{'op_sys'} = get_legal_field_values('op_sys');
$vars->{'priority'} = get_legal_field_values('priority');
$vars->{'bug_severity'} = get_legal_field_values('bug_severity');
271 272

# Boolean charts
273
my @fields;
274
push(@fields, { name => "noop", description => "---" });
275
push(@fields, $dbh->bz_get_field_defs());
276
@fields = sort {lc($a->{'description'}) cmp lc($b->{'description'})} @fields;
277
$vars->{'fields'} = \@fields;
278

279 280 281
# Creating new charts - if the cmd-add value is there, we define the field
# value so the code sees it and creates the chart. It will attempt to select
# "xyzzy" as the default, and fail. This is the correct behaviour.
282
foreach my $cmd (grep(/^cmd-/, $cgi->param)) {
283
    if ($cmd =~ /^cmd-add(\d+)-(\d+)-(\d+)$/) {
284
        $cgi->param(-name => "field$1-$2-$3", -value => "xyzzy");
285 286
    }
}
287

288 289
if (!$cgi->param('field0-0-0')) {
    $cgi->param(-name => 'field0-0-0', -value => "xyzzy");
290 291
}

292 293 294 295
# Create data structure of boolean chart info. It's an array of arrays of
# arrays - with the inner arrays having three members - field, type and
# value.
my @charts;
296
for (my $chart = 0; $cgi->param("field$chart-0-0"); $chart++) {
297
    my @rows;
298
    for (my $row = 0; $cgi->param("field$chart-$row-0"); $row++) {
299
        my @cols;
300
        for (my $col = 0; $cgi->param("field$chart-$row-$col"); $col++) {
301 302 303 304
            my $value = $cgi->param("value$chart-$row-$col");
            if (!defined($value)) {
                $value = '';
            }
305
            push(@cols, { field => $cgi->param("field$chart-$row-$col"),
306
                          type => $cgi->param("type$chart-$row-$col") || 'noop',
307
                          value => $value });
308
        }
309
        push(@rows, \@cols);
310
    }
311
    push(@charts, {'rows' => \@rows, 'negate' => scalar($cgi->param("negate$chart")) });
312 313
}

314
$default{'charts'} = \@charts;
315

316
# Named queries
317
if ($userid) {
318 319
     $vars->{'namedqueries'} = $dbh->selectcol_arrayref(
           "SELECT name FROM namedqueries " .
320
            "WHERE userid = ? AND name != ? " .
321 322
         "ORDER BY name",
         undef, ($userid, DEFAULT_QUERY_NAME));
323
}
terry%netscape.com's avatar
terry%netscape.com committed
324

325 326 327
# Sort order
my $deforder;
my @orders = ('Bug Number', 'Importance', 'Assignee', 'Last Changed');
328

329
if ($cgi->cookie('LASTORDER')) {
330 331 332
    $deforder = "Reuse same sort as last time";
    unshift(@orders, $deforder);
}
333

334
if ($cgi->param('order')) { $deforder = $cgi->param('order') }
335

336 337 338
$vars->{'userdefaultquery'} = $userdefaultquery;
$vars->{'orders'} = \@orders;
$default{'querytype'} = $deforder || 'Importance';
terry%netscape.com's avatar
terry%netscape.com committed
339

340 341
if (($cgi->param('query_format') || $cgi->param('format') || "")
    eq "create-series") {
342 343 344 345
    require Bugzilla::Chart;
    $vars->{'category'} = Bugzilla::Chart::getVisibleSeries();
}

346 347 348
$vars->{'known_name'} = $cgi->param('known_name');


349 350
# Add in the defaults.
$vars->{'default'} = \%default;
351

352 353 354
$vars->{'format'} = $cgi->param('format');
$vars->{'query_format'} = $cgi->param('query_format');

355
# Set default page to "specific" if none provided
356 357 358 359 360 361 362 363
if (!($cgi->param('query_format') || $cgi->param('format'))) {
    if (defined $cgi->cookie('DEFAULTFORMAT')) {
        $vars->{'format'} = $cgi->cookie('DEFAULTFORMAT');
    } else {
        $vars->{'format'} = 'specific';
    }
}

364 365
# Set cookie to current format as default, but only if the format
# one that we should remember.
366
if (defined($vars->{'format'}) && IsValidQueryType($vars->{'format'})) {
367 368 369 370
    $cgi->send_cookie(-name => 'DEFAULTFORMAT',
                      -value => $vars->{'format'},
                      -expires => "Fri, 01-Jan-2038 00:00:00 GMT");
}
371

372
# Generate and return the UI (HTML page) from the appropriate template.
373 374 375
# If we submit back to ourselves (for e.g. boolean charts), we need to
# preserve format information; hence query_format taking priority over
# format.
376 377 378
my $format = $template->get_format("search/search", 
                                   $vars->{'query_format'} || $vars->{'format'}, 
                                   scalar $cgi->param('ctype'));
379 380 381

print $cgi->header($format->{'ctype'});

382
$template->process($format->{'template'}, $vars)
383
  || ThrowTemplateError($template->error());