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 qw(. 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::Util qw(vers_cmp);
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_start_transaction();
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_commit_transaction();
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
    my ($buf) = (@_);
114
    my $cgi = Bugzilla->cgi;
115
    $buf = new Bugzilla::CGI($buf);
116
    my $foundone = 0;
117 118

    # Nothing must be undef, otherwise the template complains.
119 120
    foreach my $name ("bug_status", "resolution", "assigned_to",
                      "rep_platform", "priority", "bug_severity",
121
                      "classification", "product", "reporter", "op_sys",
122
                      "component", "version", "chfield", "chfieldfrom",
123
                      "chfieldto", "chfieldvalue", "target_milestone",
124 125
                      "email", "emailtype", "emailreporter",
                      "emailassigned_to", "emailcc", "emailqa_contact",
126
                      "emaillongdesc", "content",
127 128 129
                      "changedin", "votes", "short_desc", "short_desc_type",
                      "long_desc", "long_desc_type", "bug_file_loc",
                      "bug_file_loc_type", "status_whiteboard",
130
                      "status_whiteboard_type", "bug_id",
131
                      "bugidtype", "keywords", "keywords_type",
132
                      "deadlinefrom", "deadlineto",
133
                      "x_axis_field", "y_axis_field", "z_axis_field",
134 135 136
                      "chart_format", "cumulate", "x_labels_vertical",
                      "category", "subcategory", "name", "newcategory",
                      "newsubcategory", "public", "frequency") 
137
    {
138
        $default{$name} = [];
139
    }
140
 
141 142 143
    # we won't prefill the boolean chart data from this query if
    # there are any being submitted via params
    my $prefillcharts = (grep(/^field-/, $cgi->param)) ? 0 : 1;
144 145
 
    # Iterate over the URL parameters
146 147 148
    foreach my $name ($buf->param()) {
        my @values = $buf->param($name);

149 150 151 152 153 154 155 156
        # If the name begins with the string 'field', 'type', 'value', or
        # 'negate', then it is part of the boolean charts. Because
        # these are built different than the rest of the form, we need
        # to store these as parameters. We also 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|negate)/) {
            $cgi->param(-name => $name, -value => $values[0]) if ($prefillcharts);
157 158
            $foundone = 1;
        }
159 160 161
        # 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.
162
        elsif ($name =~ m/^(.+)(\d)$/ && defined($default{$1})) {
163
            $foundone = 1;
164
            $default{$1}->[$2] = $values[0];
terry%netscape.com's avatar
terry%netscape.com committed
165
        }
166
        elsif (exists $default{$name}) {
167
            $foundone = 1;
168 169 170
            push (@{$default{$name}}, @values);
        }
    }
171
    return $foundone;
terry%netscape.com's avatar
terry%netscape.com committed
172
}
173

174
if (!PrefillForm($buffer)) {
175 176 177
    # Ah-hah, there was no form stuff specified.  Do it again with the
    # default query.
    if ($userdefaultquery) {
178
        PrefillForm($userdefaultquery);
179
    } else {
180
        PrefillForm(Bugzilla->params->{"defaultquery"});
181 182
    }
}
183

184
if (!scalar(@{$default{'chfieldto'}}) || $default{'chfieldto'}->[0] eq "") {
185
    $default{'chfieldto'} = ["Now"];
terry%netscape.com's avatar
terry%netscape.com committed
186 187
}

188 189
# 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.
190 191
my @selectable_products = sort {lc($a->name) cmp lc($b->name)} 
                               @{$user->get_selectable_products};
192
Bugzilla::Product::preload(\@selectable_products);
193

194
# Create the component, version and milestone lists.
195 196 197 198 199 200 201 202
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});
203 204
}

205
my @components = sort(keys %components);
206
my @versions = sort { vers_cmp (lc($a), lc($b)) } keys %versions;
207 208
my @milestones = sort(keys %milestones);

209
$vars->{'product'} = \@selectable_products;
210

211
# Create data structures representing each classification
212
if (Bugzilla->params->{'useclassification'}) {
213
    $vars->{'classification'} = $user->get_selectable_classifications;
214 215
}

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

219
$vars->{'version'} = \@versions;
220

221
if (Bugzilla->params->{'usetargetmilestone'}) {
222
    $vars->{'target_milestone'} = \@milestones;
223 224
}

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

227 228 229 230
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)];
231

232 233
my @chfields;

234
push @chfields, "[Bug creation]";
235 236 237

# This is what happens when you have variables whose definition depends
# on the DB schema, and then the underlying schema changes...
238
foreach my $val (editable_bug_fields()) {
239 240 241
    if ($val eq 'classification_id') {
        $val = 'classification';
    } elsif ($val eq 'product_id') {
242 243 244 245 246 247 248
        $val = 'product';
    } elsif ($val eq 'component_id') {
        $val = 'component';
    }
    push @chfields, $val;
}

249
if (Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'})) {
250 251 252 253 254 255 256
    push @chfields, "work_time";
} else {
    @chfields = grep($_ ne "estimated_time", @chfields);
    @chfields = grep($_ ne "remaining_time", @chfields);
}
@chfields = (sort(@chfields));
$vars->{'chfield'} = \@chfields;
257 258 259 260 261
$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');
262 263

# Boolean charts
264 265 266 267 268 269 270 271 272 273 274 275 276
my @fields = Bugzilla->get_fields({ obsolete => 0 });

# If we're not in the time-tracking group, exclude time-tracking fields.
if (!Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'})) {
    foreach my $tt_field (qw(estimated_time remaining_time work_time
                             percentage_complete deadline))
    {
        @fields = grep($_->name ne $tt_field, @fields);
    }
}

@fields = sort {lc($a->description) cmp lc($b->description)} @fields;
unshift(@fields, { name => "noop", description => "---" });
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
$vars->{'userdefaultquery'} = $userdefaultquery;
$vars->{'orders'} = \@orders;
338
$default{'order'} = [$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());