buglist.cgi 46.8 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
#                 Dan Mosedale <dmose@mozilla.org>
23
#                 Stephan Niemz  <st.n@gmx.net>
24
#                 Andreas Franke <afranke@mathweb.org>
25
#                 Myk Melez <myk@mozilla.org>
26
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
terry%netscape.com's avatar
terry%netscape.com committed
27

28 29 30 31 32
################################################################################
# Script Initialization
################################################################################

# Make it harder for us to do dangerous things in Perl.
33
use strict;
terry%netscape.com's avatar
terry%netscape.com committed
34

35
use lib qw(. lib);
36

37
use Bugzilla;
38 39 40
use Bugzilla::Constants;
use Bugzilla::Error;
use Bugzilla::Util;
41
use Bugzilla::Search;
42
use Bugzilla::Search::Quicksearch;
43
use Bugzilla::Search::Saved;
44
use Bugzilla::User;
45
use Bugzilla::Bug;
46
use Bugzilla::Product;
47
use Bugzilla::Keyword;
48
use Bugzilla::Field;
49
use Bugzilla::Status;
50
use Bugzilla::Token;
51

52 53
use Date::Parse;

54
my $cgi = Bugzilla->cgi;
55
my $dbh = Bugzilla->dbh;
56 57
my $template = Bugzilla->template;
my $vars = {};
58
my $buffer = $cgi->query_string();
59

60 61 62 63 64
# We have to check the login here to get the correct footer if an error is
# thrown and to prevent a logged out user to use QuickSearch if 'requirelogin'
# is turned 'on'.
Bugzilla->login();

65
if (length($buffer) == 0) {
66
    print $cgi->header(-refresh=> '10; URL=query.cgi');
67
    ThrowUserError("buglist_parameters_required");
68
}
69

70 71 72 73 74 75 76 77 78 79 80 81 82
# If a parameter starts with cmd-, this means the And or Or button has been
# pressed in the advanced search page with JS turned off.
if (grep { $_ =~ /^cmd\-/ } $cgi->param()) {
    my $url = "query.cgi?$buffer#chart";
    print $cgi->redirect(-location => $url);
    # Generate and return the UI (HTML page) from the appropriate template.
    $vars->{'message'} = "buglist_adding_field";
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
    exit;
}

83 84 85 86 87
# If query was POSTed, clean the URL from empty parameters and redirect back to
# itself. This will make advanced search URLs more tolerable.
#
if ($cgi->request_method() eq 'POST') {
    $cgi->clean_search_url();
88 89 90 91 92
    my $uri_length = length($cgi->self_url());
    if ($uri_length < CGI_URI_LIMIT) {
        print $cgi->redirect(-url => $cgi->self_url());
        exit;
    }
93 94
}

95 96 97 98 99 100 101 102 103
# Determine whether this is a quicksearch query.
my $searchstring = $cgi->param('quicksearch');
if (defined($searchstring)) {
    $buffer = quicksearch($searchstring);
    # Quicksearch may do a redirect, in which case it does not return.
    # If it does return, it has modified $cgi->params so we can use them here
    # as if this had been a normal query from the beginning.
}

104
# If configured to not allow empty words, reject empty searches from the
105 106 107
# Find a Specific Bug search form, including words being a single or 
# several consecutive whitespaces only.
if (!Bugzilla->params->{'specific_search_allow_empty_words'}
108 109
    && defined($cgi->param('content')) && $cgi->param('content') =~ /^\s*$/)
{
110 111 112
    ThrowUserError("buglist_parameters_required");
}

113 114 115
################################################################################
# Data and Security Validation
################################################################################
116

117
# Whether or not the user wants to change multiple bugs.
118
my $dotweak = $cgi->param('tweak') ? 1 : 0;
119 120 121

# Log the user in
if ($dotweak) {
122
    Bugzilla->login(LOGIN_REQUIRED);
123 124
}

125
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
126 127 128 129
if (defined $cgi->param('format') && $cgi->param('format') eq "rdf"
    && !defined $cgi->param('ctype')) {
    $cgi->param('ctype', "rdf");
    $cgi->delete('format');
130
}
131

132 133 134 135 136
# Treat requests for ctype=rss as requests for ctype=atom
if (defined $cgi->param('ctype') && $cgi->param('ctype') eq "rss") {
    $cgi->param('ctype', "atom");
}

137 138 139 140 141 142
# The js ctype presents a security risk; a malicious site could use it  
# to gather information about secure bugs. So, we only allow public bugs to be
# retrieved with this format.
#
# Note that if and when this call clears cookies or has other persistent 
# effects, we'll need to do this another way instead.
143
if ((defined $cgi->param('ctype')) && ($cgi->param('ctype') eq "js")) {
144
    Bugzilla->logout_request();
145
}
146

147 148 149 150 151 152 153
# An agent is a program that automatically downloads and extracts data
# on its user's behalf.  If this request comes from an agent, we turn off
# various aspects of bug list functionality so agent requests succeed
# and coexist nicely with regular user requests.  Currently the only agent
# we know about is Firefox's microsummary feature.
my $agent = ($cgi->http('X-Moz') && $cgi->http('X-Moz') =~ /\bmicrosummary\b/);

154 155 156
# Determine the format in which the user would like to receive the output.
# Uses the default format if the user did not specify an output format;
# otherwise validates the user's choice against the list of available formats.
157 158
my $format = $template->get_format("list/list", scalar $cgi->param('format'),
                                   scalar $cgi->param('ctype'));
159

160 161 162 163 164 165
# Use server push to display a "Please wait..." message for the user while
# executing their query if their browser supports it and they are viewing
# the bug list as HTML and they have not disabled it by adding &serverpush=0
# to the URL.
#
# Server push is a Netscape 3+ hack incompatible with MSIE, Lynx, and others. 
166 167 168
# Even Communicator 4.51 has bugs with it, especially during page reload.
# http://www.browsercaps.org used as source of compatible browsers.
# Safari (WebKit) does not support it, despite a UA that says otherwise (bug 188712)
169
# MSIE 5+ supports it on Mac (but not on Windows) (bug 190370)
170 171
#
my $serverpush =
172 173 174
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
175
        && (($ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/) || ($ENV{'HTTP_USER_AGENT'} =~ /MSIE 5.*Mac_PowerPC/))
176
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
177 178 179
            && !$agent
              && !defined($cgi->param('serverpush'))
                || $cgi->param('serverpush');
180

181
my $order = $cgi->param('order') || "";
182

183 184 185
# The params object to use for the actual query itself
my $params;

186 187
# If the user is retrieving the last bug list they looked at, hack the buffer
# storing the query string so that it looks like a query retrieving those bugs.
188
if (defined $cgi->param('regetlastlist')) {
189
    $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
190

191
    $order = "reuse last sort" unless $order;
192 193
    my $bug_id = $cgi->cookie('BUGLIST');
    $bug_id =~ s/:/,/g;
194 195
    # set up the params for this new query
    $params = new Bugzilla::CGI({
196
                                 bug_id => $bug_id,
197 198
                                 order => $order,
                                });
199 200
}

201 202 203 204
# Figure out whether or not the user is doing a fulltext search.  If not,
# we'll remove the relevance column from the lists of columns to display
# and order by, since relevance only exists when doing a fulltext search.
my $fulltext = 0;
205
if ($cgi->param('content')) { $fulltext = 1 }
206
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
207
foreach my $chart (@charts) {
208
    if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
209 210 211 212 213
        $fulltext = 1;
        last;
    }
}

214 215 216 217 218 219 220 221
################################################################################
# Utilities
################################################################################

sub DiffDate {
    my ($datestr) = @_;
    my $date = str2time($datestr);
    my $age = time() - $date;
222

223
    if( $age < 18*60*60 ) {
224
        $date = format_time($datestr, '%H:%M:%S');
225
    } elsif( $age < 6*24*60*60 ) {
226
        $date = format_time($datestr, '%a %H:%M');
227
    } else {
228
        $date = format_time($datestr, '%Y-%m-%d');
229 230 231
    }
    return $date;
}
232

233
sub LookupNamedQuery {
234 235
    my ($name, $sharer_id, $query_type, $throw_error) = @_;
    $throw_error = 1 unless defined $throw_error;
236

237
    Bugzilla->login(LOGIN_REQUIRED);
238

239 240 241 242 243
    my $constructor = $throw_error ? 'check' : 'new';
    my $query = Bugzilla::Search::Saved->$constructor(
        { user => $sharer_id, name => $name });

    return $query if (!$query and !$throw_error);
244

245 246 247
    if (defined $query_type and $query->type != $query_type) {
        ThrowUserError("missing_query", { queryname => $name,
                                          sharer_id => $sharer_id });
248
    }
249

250 251 252 253
    $query->url
       || ThrowUserError("buglist_parameters_required", { queryname  => $name });

    return wantarray ? ($query->url, $query->id) : $query->url;
254 255
}

256 257 258 259 260 261 262 263 264 265 266 267 268
# Inserts a Named Query (a "Saved Search") into the database, or
# updates a Named Query that already exists..
# Takes four arguments:
# userid - The userid who the Named Query will belong to.
# query_name - A string that names the new Named Query, or the name
#              of an old Named Query to update. If this is blank, we
#              will throw a UserError. Leading and trailing whitespace
#              will be stripped from this value before it is inserted
#              into the DB.
# query - The query part of the buglist.cgi URL, unencoded. Must not be 
#         empty, or we will throw a UserError.
# link_in_footer (optional) - 1 if the Named Query should be 
# displayed in the user's footer, 0 otherwise.
269 270
# query_type (optional) - 1 if the Named Query contains a list of
# bug IDs only, 0 otherwise (default).
271 272 273 274 275
#
# All parameters are validated before passing them into the database.
#
# Returns: A boolean true value if the query existed in the database 
# before, and we updated it. A boolean false value otherwise.
276
sub InsertNamedQuery {
277
    my ($query_name, $query, $link_in_footer, $query_type) = @_;
278
    my $dbh = Bugzilla->dbh;
279 280

    $query_name = trim($query_name);
281
    my ($query_obj) = grep {lc($_->name) eq lc($query_name)} @{Bugzilla->user->queries};
282 283

    if ($query_obj) {
284
        $query_obj->set_name($query_name);
285 286 287
        $query_obj->set_url($query);
        $query_obj->set_query_type($query_type);
        $query_obj->update();
288
    } else {
289 290 291 292 293 294
        Bugzilla::Search::Saved->create({
            name           => $query_name,
            query          => $query,
            query_type     => $query_type,
            link_in_footer => $link_in_footer
        });
295 296
    }

297
    return $query_obj ? 1 : 0;
298 299
}

300 301 302 303 304 305
sub LookupSeries {
    my ($series_id) = @_;
    detaint_natural($series_id) || ThrowCodeError("invalid_series_id");
    
    my $dbh = Bugzilla->dbh;
    my $result = $dbh->selectrow_array("SELECT query FROM series " .
306 307
                                       "WHERE series_id = ?"
                                       , undef, ($series_id));
308 309 310 311 312
    $result
           || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
    return $result;
}

313
sub GetQuip {
314
    my $dbh = Bugzilla->dbh;
315 316
    # COUNT is quick because it is cached for MySQL. We may want to revisit
    # this when we support other databases.
317 318
    my $count = $dbh->selectrow_array("SELECT COUNT(quip)"
                                    . " FROM quips WHERE approved = 1");
319
    my $random = int(rand($count));
320
    my $quip = 
321 322
        $dbh->selectrow_array("SELECT quip FROM quips WHERE approved = 1 " . 
                              $dbh->sql_limit(1, $random));
323
    return $quip;
324
}
325

326
# Return groups available for at least one product of the buglist.
327
sub GetGroups {
328
    my $product_names = shift;
329
    my $user = Bugzilla->user;
330 331 332 333 334 335 336 337 338 339 340 341 342
    my %legal_groups;

    foreach my $product_name (@$product_names) {
        my $product = new Bugzilla::Product({name => $product_name});

        foreach my $gid (keys %{$product->group_controls}) {
            # The user can only edit groups he belongs to.
            next unless $user->in_group_id($gid);

            # The user has no control on groups marked as NA or MANDATORY.
            my $group = $product->group_controls->{$gid};
            next if ($group->{membercontrol} == CONTROLMAPMANDATORY
                     || $group->{membercontrol} == CONTROLMAPNA);
343

344 345 346 347 348 349 350
            # It's fine to include inactive groups. Those will be marked
            # as "remove only" when editing several bugs at once.
            $legal_groups{$gid} ||= $group->{group};
        }
    }
    # Return a list of group objects.
    return [values %legal_groups];
351
}
352

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
sub _close_standby_message {
    my ($contenttype, $disposition, $serverpush) = @_;
    my $cgi = Bugzilla->cgi;

    # Close the "please wait" page, then open the buglist page
    if ($serverpush) {
        print $cgi->multipart_end();
        print $cgi->multipart_start(-type                => $contenttype,
                                    -content_disposition => $disposition);
    }
    else {
        print $cgi->header(-type                => $contenttype,
                           -content_disposition => $disposition);
    }
}

369

370 371 372
################################################################################
# Command Execution
################################################################################
373

374 375
my $cmdtype   = $cgi->param('cmdtype')   || '';
my $remaction = $cgi->param('remaction') || '';
376

377 378
# Backwards-compatibility - the old interface had cmdtype="runnamed" to run
# a named command, and we can't break this because it's in bookmarks.
379 380 381
if ($cmdtype eq "runnamed") {  
    $cmdtype = "dorem";
    $remaction = "run";
382 383
}

384 385 386 387 388 389
# Now we're going to be running, so ensure that the params object is set up,
# using ||= so that we only do so if someone hasn't overridden this 
# earlier, for example by setting up a named query search.

# This will be modified, so make a copy.
$params ||= new Bugzilla::CGI($cgi);
390

391 392 393 394 395 396 397 398
# Generate a reasonable filename for the user agent to suggest to the user
# when the user saves the bug list.  Uses the name of the remembered query
# if available.  We have to do this now, even though we return HTTP headers 
# at the end, because the fact that there is a remembered query gets 
# forgotten in the process of retrieving it.
my @time = localtime(time());
my $date = sprintf "%04d-%02d-%02d", 1900+$time[5],$time[4]+1,$time[3];
my $filename = "bugs-$date.$format->{extension}";
399
if ($cmdtype eq "dorem" && $remaction =~ /^run/) {
400
    $filename = $cgi->param('namedcmd') . "-$date.$format->{extension}";
401 402 403 404
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}
405 406
$filename =~ s/\\/\\\\/g; # escape backslashes
$filename =~ s/"/\\"/g; # escape quotes
407

408
# Take appropriate action based on user's request.
409 410
if ($cmdtype eq "dorem") {  
    if ($remaction eq "run") {
411 412 413
        my $query_id;
        ($buffer, $query_id) = LookupNamedQuery(scalar $cgi->param("namedcmd"),
                                                scalar $cgi->param('sharer_id'));
414 415
        # If this is the user's own query, remember information about it
        # so that it can be modified easily.
416
        $vars->{'searchname'} = $cgi->param('namedcmd');
417 418 419
        if (!$cgi->param('sharer_id') ||
            $cgi->param('sharer_id') == Bugzilla->user->id) {
            $vars->{'searchtype'} = "saved";
420
            $vars->{'search_id'} = $query_id;
421
        }
422
        $params = new Bugzilla::CGI($buffer);
423
        $order = $params->param('order') || $order;
424

425
    }
426
    elsif ($remaction eq "runseries") {
427
        $buffer = LookupSeries(scalar $cgi->param("series_id"));
428
        $vars->{'searchname'} = $cgi->param('namedcmd');
429
        $vars->{'searchtype'} = "series";
430
        $params = new Bugzilla::CGI($buffer);
431 432
        $order = $params->param('order') || $order;
    }
433
    elsif ($remaction eq "forget") {
434
        my $user = Bugzilla->login(LOGIN_REQUIRED);
435 436 437
        # Copy the name into a variable, so that we can trick_taint it for
        # the DB. We know it's safe, because we're using placeholders in 
        # the SQL, and the SQL is only a DELETE.
438
        my $qname = $cgi->param('namedcmd');
439
        trick_taint($qname);
440 441 442 443 444 445 446 447 448 449 450 451

        # Do not forget the saved search if it is being used in a whine
        my $whines_in_use = 
            $dbh->selectcol_arrayref('SELECT DISTINCT whine_events.subject
                                                 FROM whine_events
                                           INNER JOIN whine_queries
                                                   ON whine_queries.eventid
                                                      = whine_events.id
                                                WHERE whine_events.owner_userid
                                                      = ?
                                                  AND whine_queries.query_name
                                                      = ?
452
                                      ', undef, $user->id, $qname);
453 454 455 456 457 458 459 460
        if (scalar(@$whines_in_use)) {
            ThrowUserError('saved_search_used_by_whines', 
                           { subjects    => join(',', @$whines_in_use),
                             search_name => $qname                      }
            );
        }

        # If we are here, then we can safely remove the saved search
461 462 463
        my $query_id;
        ($buffer, $query_id) = LookupNamedQuery(scalar $cgi->param("namedcmd"),
                                                $user->id);
464 465 466 467
        if (!$query_id) {
            # The user has no query of this name. Play along.
        }
        else {
468 469 470 471
            # Make sure the user really wants to delete his saved search.
            my $token = $cgi->param('token');
            check_hash_token($token, [$query_id, $qname]);

472 473 474 475 476 477 478 479 480 481
            $dbh->do('DELETE FROM namedqueries
                            WHERE id = ?',
                     undef, $query_id);
            $dbh->do('DELETE FROM namedqueries_link_in_footer
                            WHERE namedquery_id = ?',
                     undef, $query_id);
            $dbh->do('DELETE FROM namedquery_group_map
                            WHERE namedquery_id = ?',
                     undef, $query_id);
        }
482 483

        # Now reset the cached queries
484
        $user->flush_queries_cache();
485

486
        print $cgi->header();
487
        # Generate and return the UI (HTML page) from the appropriate template.
488
        $vars->{'message'} = "buglist_query_gone";
489
        $vars->{'namedcmd'} = $qname;
490
        $vars->{'url'} = "buglist.cgi?newquery=" . url_quote($buffer) . "&cmdtype=doit&remtype=asnamed&newqueryname=" . url_quote($qname);
491
        $template->process("global/message.html.tmpl", $vars)
492
          || ThrowTemplateError($template->error());
493
        exit;
494 495
    }
}
496
elsif (($cmdtype eq "doit") && defined $cgi->param('remtype')) {
497
    if ($cgi->param('remtype') eq "asdefault") {
498
        my $user = Bugzilla->login(LOGIN_REQUIRED);
499
        InsertNamedQuery(DEFAULT_QUERY_NAME, $buffer);
500
        $vars->{'message'} = "buglist_new_default_query";
501
    }
502
    elsif ($cgi->param('remtype') eq "asnamed") {
503
        my $user = Bugzilla->login(LOGIN_REQUIRED);
504
        my $query_name = $cgi->param('newqueryname');
505 506
        my $new_query = $cgi->param('newquery');
        my $query_type = QUERY_LIST;
507 508 509 510 511 512 513 514 515 516 517 518 519
        # If list_of_bugs is true, we are adding/removing individual bugs
        # to a saved search. We get the existing list of bug IDs (if any)
        # and add/remove the passed ones.
        if ($cgi->param('list_of_bugs')) {
            # We add or remove bugs based on the action choosen.
            my $action = trim($cgi->param('action') || '');
            $action =~ /^(add|remove)$/
              || ThrowCodeError('unknown_action', {'action' => $action});

            # If we are removing bugs, then we must have an existing
            # saved search selected.
            if ($action eq 'remove') {
                $query_name && ThrowUserError('no_bugs_to_remove');
520 521
            }

522
            my %bug_ids;
523
            my $is_new_name = 0;
524
            if ($query_name) {
525 526
                my ($query, $query_id) =
                  LookupNamedQuery($query_name, undef, QUERY_LIST, !THROW_ERROR);
527
                # Make sure this name is not already in use by a normal saved search.
528 529 530
                if ($query) {
                    ThrowUserError('query_name_exists', {name     => $query_name,
                                                         query_id => $query_id});
531
                }
532
                $is_new_name = 1;
533
            }
534 535 536 537 538 539 540
            # If no new tag name has been given, use the selected one.
            $query_name ||= $cgi->param('oldqueryname');

            # Don't throw an error if it's a new tag name: if the tag already
            # exists, add/remove bugs to it, else create it. But if we are
            # considering an existing tag, then it has to exist and we throw
            # an error if it doesn't (hence the usage of !$is_new_name).
541 542 543 544
            my ($old_query, $query_id) =
              LookupNamedQuery($query_name, undef, LIST_OF_BUGS, !$is_new_name);

            if ($old_query) {
545 546 547
                # We get the encoded query. We need to decode it.
                my $old_cgi = new Bugzilla::CGI($old_query);
                foreach my $bug_id (split /[\s,]+/, scalar $old_cgi->param('bug_id')) {
548 549 550
                    $bug_ids{$bug_id} = 1 if detaint_natural($bug_id);
                }
            }
551 552 553 554 555

            my $keep_bug = ($action eq 'add') ? 1 : 0;
            my $changes = 0;
            foreach my $bug_id (split(/[\s,]+/, $cgi->param('bug_ids'))) {
                next unless $bug_id;
556 557
                my $bug = Bugzilla::Bug->check($bug_id);
                $bug_ids{$bug->id} = $keep_bug;
558 559
                $changes = 1;
            }
560 561 562 563
            ThrowUserError('no_bug_ids',
                           {'action' => $action,
                            'tag' => $query_name})
              unless $changes;
564 565 566 567

            # Only keep bug IDs we want to add/keep. Disregard deleted ones.
            my @bug_ids = grep { $bug_ids{$_} == 1 } keys %bug_ids;
            # If the list is now empty, we could as well delete it completely.
568 569 570 571
            if (!scalar @bug_ids) {
                ThrowUserError('no_bugs_in_list', {name     => $query_name,
                                                   query_id => $query_id});
            }
572
            $new_query = "bug_id=" . join(',', sort {$a <=> $b} @bug_ids);
573 574
            $query_type = LIST_OF_BUGS;
        }
575
        my $tofooter = 1;
576
        my $existed_before = InsertNamedQuery($query_name, $new_query,
577
                                              $tofooter, $query_type);
578
        if ($existed_before) {
579 580
            $vars->{'message'} = "buglist_updated_named_query";
        }
581
        else {
582
            $vars->{'message'} = "buglist_new_named_query";
583
        }
584 585 586

        # Make sure to invalidate any cached query data, so that the footer is
        # correctly displayed
587
        $user->flush_queries_cache();
588

589
        $vars->{'queryname'} = $query_name;
590
        
591
        print $cgi->header();
592 593 594
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
595
    }
terry%netscape.com's avatar
terry%netscape.com committed
596 597
}

598 599 600 601 602
# backward compatibility hack: if the saved query doesn't say which
# form was used to create it, assume it was on the advanced query
# form - see bug 252295
if (!$params->param('query_format')) {
    $params->param('query_format', 'advanced');
603
    $buffer = $params->query_string;
604
}
terry%netscape.com's avatar
terry%netscape.com committed
605

606 607 608 609
################################################################################
# Column Definition
################################################################################

610
my $columns = Bugzilla::Search::COLUMNS;
611

612 613 614 615 616 617 618
################################################################################
# Display Column Determination
################################################################################

# Determine the columns that will be displayed in the bug list via the 
# columnlist CGI parameter, the user's preferences, or the default.
my @displaycolumns = ();
619 620
if (defined $params->param('columnlist')) {
    if ($params->param('columnlist') eq "all") {
621
        # If the value of the CGI parameter is "all", display all columns,
622 623
        # but remove the redundant "short_desc" column.
        @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
terry%netscape.com's avatar
terry%netscape.com committed
624
    }
625
    else {
626
        @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
627
    }
terry%netscape.com's avatar
terry%netscape.com committed
628
}
629
elsif (defined $cgi->cookie('COLUMNLIST')) {
630
    # 2002-10-31 Rename column names (see bug 176461)
631
    my $columnlist = $cgi->cookie('COLUMNLIST');
632 633 634 635 636 637 638
    $columnlist =~ s/\bowner\b/assigned_to/;
    $columnlist =~ s/\bowner_realname\b/assigned_to_realname/;
    $columnlist =~ s/\bplatform\b/rep_platform/;
    $columnlist =~ s/\bseverity\b/bug_severity/;
    $columnlist =~ s/\bstatus\b/bug_status/;
    $columnlist =~ s/\bsummaryfull\b/short_desc/;
    $columnlist =~ s/\bsummary\b/short_short_desc/;
639

640
    # Use the columns listed in the user's preferences.
641
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
642
}
643 644
else {
    # Use the default list of columns.
645
    @displaycolumns = DEFAULT_COLUMN_LIST;
646 647
}

648 649 650 651
# Weed out columns that don't actually exist to prevent the user 
# from hacking their column list cookie to grab data to which they 
# should not have access.  Detaint the data along the way.
@displaycolumns = grep($columns->{$_} && trick_taint($_), @displaycolumns);
652

653 654
# Remove the "ID" column from the list because bug IDs are always displayed
# and are hard-coded into the display templates.
655
@displaycolumns = grep($_ ne 'bug_id', @displaycolumns);
terry%netscape.com's avatar
terry%netscape.com committed
656

657 658
# Remove the timetracking columns if they are not a part of the group
# (happens if a user had access to time tracking and it was revoked/disabled)
659
if (!Bugzilla->user->is_timetracker) {
660 661 662 663
   @displaycolumns = grep($_ ne 'estimated_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'remaining_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'actual_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'percentage_complete', @displaycolumns);
664
   @displaycolumns = grep($_ ne 'deadline', @displaycolumns);
665
}
terry%netscape.com's avatar
terry%netscape.com committed
666

667 668 669 670 671 672
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


673 674 675
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
676

677
# Generate the list of columns that will be selected in the SQL query.
terry%netscape.com's avatar
terry%netscape.com committed
678

679
# The bug ID is always selected because bug IDs are always displayed.
680 681 682
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
683
                     "resolution", "product");
684

685
# remaining and actual_time are required for percentage_complete calculation:
686
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
687 688 689 690
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

691 692 693 694 695 696 697 698 699 700 701 702
# Make sure that the login_name version of a field is always also
# requested if the realname version is requested, so that we can
# display the login name when the realname is empty.
my @realname_fields = grep(/_realname$/, @displaycolumns);
foreach my $item (@realname_fields) {
    my $login_field = $item;
    $login_field =~ s/_realname$//;
    if (!grep($_ eq $login_field, @selectcolumns)) {
        push(@selectcolumns, $login_field);
    }
}

703
# Display columns are selected because otherwise we could not display them.
704 705 706
foreach my $col (@displaycolumns) {
    push (@selectcolumns, $col) if !grep($_ eq $col, @selectcolumns);
}
terry%netscape.com's avatar
terry%netscape.com committed
707

708 709
# If the user is editing multiple bugs, we also make sure to select the 
# status, because the values of that field determines what options the user
710 711
# has for modifying the bugs.
if ($dotweak) {
712
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
713 714
}

715 716 717
if ($format->{'extension'} eq 'ics') {
    push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
}
718

719 720
if ($format->{'extension'} eq 'atom') {
    # The title of the Atom feed will be the same one as for the bug list.
721 722
    $vars->{'title'} = $cgi->param('title');

723 724
    # This is the list of fields that are needed by the Atom filter.
    my @required_atom_columns = (
725 726 727
      'short_desc',
      'opendate',
      'changeddate',
728
      'reporter',
729 730 731
      'reporter_realname',
      'priority',
      'bug_severity',
732
      'assigned_to',
733
      'assigned_to_realname',
734 735 736 737
      'bug_status',
      'product',
      'component',
      'resolution'
738
    );
739
    push(@required_atom_columns, 'target_milestone') if Bugzilla->params->{'usetargetmilestone'};
740

741
    foreach my $required (@required_atom_columns) {
742 743 744 745
        push(@selectcolumns, $required) if !grep($_ eq $required,@selectcolumns);
    }
}

746 747 748
################################################################################
# Sort Order Determination
################################################################################
749

750
# Add to the query some instructions for sorting the bug list.
751 752 753 754 755 756

# First check if we'll want to reuse the last sorting order; that happens if
# the order is not defined or its value is "reuse last sort"
if (!$order || $order =~ /^reuse/i) {
    if ($cgi->cookie('LASTORDER')) {
        $order = $cgi->cookie('LASTORDER');
757 758 759 760
       
        # Cookies from early versions of Specific Search included this text,
        # which is now invalid.
        $order =~ s/ LIMIT 200//;
761 762 763 764
    }
    else {
        $order = '';  # Remove possible "reuse" identifier as unnecessary
    }
765
}
766

767 768 769 770
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
771
        /^Bug Number$/ && do {
772
            $order = "bug_id";
773 774 775
            last ORDER;
        };
        /^Importance$/ && do {
776
            $order = "priority,bug_severity";
777 778 779
            last ORDER;
        };
        /^Assignee$/ && do {
780
            $order = "assigned_to,bug_status,priority,bug_id";
781 782 783
            last ORDER;
        };
        /^Last Changed$/ && do {
784
            $order = "changeddate,bug_status,priority,assigned_to,bug_id";
785 786 787
            last ORDER;
        };
        do {
788
            my (@order, @invalid_fragments);
789

790
            # A custom list of columns.  Make sure each column is valid.
791 792
            foreach my $fragment (split(/,/, $order)) {
                $fragment = trim($fragment);
793
                next unless $fragment;
794 795 796 797 798 799 800 801 802
                my ($column_name, $direction) = split_order_term($fragment);
                $column_name = translate_old_column($column_name);

                # Special handlings for certain columns
                next if $column_name eq 'relevance' && !$fulltext;
                                
                if (exists $columns->{$column_name}) {
                    $direction = " $direction" if $direction;
                    push(@order, "$column_name$direction");
803 804
                }
                else {
805
                    push(@invalid_fragments, $fragment);
806 807
                }
            }
808 809 810 811 812
            if (scalar @invalid_fragments) {
                $vars->{'message'} = 'invalid_column_name';
                $vars->{'invalid_fragments'} = \@invalid_fragments;
            }

813
            $order = join(",", @order);
814 815
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
816
            trick_taint($order) if $order;
817
        };
terry%netscape.com's avatar
terry%netscape.com committed
818
    }
819
}
820 821

if (!$order) {
822
    # DEFAULT
823
    $order = "bug_status,priority,assigned_to,bug_id";
824
}
825

826
my @orderstrings = split(/,\s*/, $order);
827

828
# Generate the basic SQL query that will be used to generate the bug list.
829
my $search = new Bugzilla::Search('fields' => \@selectcolumns, 
830 831
                                  'params' => $params,
                                  'order' => \@orderstrings);
832
my $query = $search->getSQL();
833
$vars->{'search_description'} = $search->search_description;
834

835 836 837 838 839
if (defined $cgi->param('limit')) {
    my $limit = $cgi->param('limit');
    if (detaint_natural($limit)) {
        $query .= " " . $dbh->sql_limit($limit);
    }
840 841
}
elsif ($fulltext) {
842
    $query .= " " . $dbh->sql_limit(FULLTEXT_BUGLIST_LIMIT);
843 844 845
    if ($cgi->param('order') && $cgi->param('order') =~ /^relevance/) {
        $vars->{'message'} = 'buglist_sorted_by_relevance';
    }
846 847
}

848

849 850 851
################################################################################
# Query Execution
################################################################################
852

853
if ($cgi->param('debug')) {
854 855
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
856 857 858 859 860 861 862
    # Explains are limited to admins because you could use them to figure
    # out how many hidden bugs are in a particular product (by doing
    # searches and looking at the number of rows the explain says it's
    # examining).
    if (Bugzilla->user->in_group('admin')) {
        $vars->{'query_explain'} = $dbh->bz_explain($query);
    }
863 864
}

865 866 867
# Time to use server push to display an interim message to the user until
# the query completes and we can display the bug list.
if ($serverpush) {
868 869
    print $cgi->multipart_init();
    print $cgi->multipart_start(-type => 'text/html');
870

871
    # Generate and return the UI (HTML page) from the appropriate template.
872 873
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
874

875 876 877 878 879 880
    # Under mod_perl, flush stdout so that the page actually shows up.
    if ($ENV{MOD_PERL}) {
        require Apache2::RequestUtil;
        Apache2::RequestUtil->request->rflush();
    }

881 882 883
    # Don't do multipart_end() until we're ready to display the replacement
    # page, otherwise any errors that happen before then (like SQL errors)
    # will result in a blank page being shown to the user instead of the error.
terry%netscape.com's avatar
terry%netscape.com committed
884 885
}

886 887
# Connect to the shadow database if this installation is using one to improve
# query performance.
888
$dbh = Bugzilla->switch_to_shadow_db();
terry%netscape.com's avatar
terry%netscape.com committed
889

890
# Normally, we ignore SIGTERM and SIGPIPE, but we need to
891 892 893 894 895
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

896
# Execute the query.
897 898
my $buglist_sth = $dbh->prepare($query);
$buglist_sth->execute();
899

terry%netscape.com's avatar
terry%netscape.com committed
900

901 902 903
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
904

905 906
# Retrieve the query results one row at a time and write the data into a list
# of Perl records.
terry%netscape.com's avatar
terry%netscape.com committed
907

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
# If we're doing time tracking, then keep totals for all bugs.
my $percentage_complete = lsearch(\@displaycolumns, 'percentage_complete') >= 0;
my $estimated_time      = lsearch(\@displaycolumns, 'estimated_time') >= 0;
my $remaining_time    = ((lsearch(\@displaycolumns, 'remaining_time') >= 0)
                         || $percentage_complete);
my $actual_time       = ((lsearch(\@displaycolumns, 'actual_time') >= 0)
                         || $percentage_complete);

my $time_info = { 'estimated_time' => 0,
                  'remaining_time' => 0,
                  'actual_time' => 0,
                  'percentage_complete' => 0,
                  'time_present' => ($estimated_time || $remaining_time ||
                                     $actual_time || $percentage_complete),
                };
    
924 925 926
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
927
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
928

929
my @bugs; # the list of records
930

931
while (my @row = $buglist_sth->fetchrow_array()) {
932
    my $bug = {}; # a record
933

934
    # Slurp the row of data into the record.
935 936
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
937
    foreach my $column (@selectcolumns) {
938
        $bug->{$column} = shift @row;
939
    }
terry%netscape.com's avatar
terry%netscape.com committed
940

941 942 943
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
944
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
945

946 947
        $bug->{'changedtime'} = $bug->{'changeddate'}; # for iCalendar and Atom
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});
948 949 950
    }

    if ($bug->{'opendate'}) {
951
        $bug->{'opentime'} = $bug->{'opendate'}; # for iCalendar
952
        $bug->{'opendate'} = DiffDate($bug->{'opendate'});
953
    }
terry%netscape.com's avatar
terry%netscape.com committed
954

955
    # Record the assignee, product, and status in the big hashes of those things.
956
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
957
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
958
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
959

960
    $bug->{'secure_mode'} = undef;
961

962 963
    # Add the record to the list.
    push(@bugs, $bug);
964 965

    # Add id to list for checking for bug privacy later
966
    push(@bugidlist, $bug->{'bug_id'});
967 968 969 970 971

    # Compute time tracking info.
    $time_info->{'estimated_time'} += $bug->{'estimated_time'} if ($estimated_time);
    $time_info->{'remaining_time'} += $bug->{'remaining_time'} if ($remaining_time);
    $time_info->{'actual_time'}    += $bug->{'actual_time'}    if ($actual_time);
972 973
}

974 975 976 977
# Check for bug privacy and set $bug->{'secure_mode'} to 'implied' or 'manual'
# based on whether the privacy is simply product implied (by mandatory groups)
# or because of human choice
my %min_membercontrol;
978
if (@bugidlist) {
979
    my $sth = $dbh->prepare(
980 981 982 983 984 985 986
        "SELECT DISTINCT bugs.bug_id, MIN(group_control_map.membercontrol) " .
          "FROM bugs " .
    "INNER JOIN bug_group_map " .
            "ON bugs.bug_id = bug_group_map.bug_id " .
     "LEFT JOIN group_control_map " .
            "ON group_control_map.product_id = bugs.product_id " .
           "AND group_control_map.group_id = bug_group_map.group_id " .
987
         "WHERE " . $dbh->sql_in('bugs.bug_id', \@bugidlist) . 
988
            $dbh->sql_group_by('bugs.bug_id'));
989 990
    $sth->execute();
    while (my ($bug_id, $min_membercontrol) = $sth->fetchrow_array()) {
991
        $min_membercontrol{$bug_id} = $min_membercontrol || CONTROLMAPNA;
992 993
    }
    foreach my $bug (@bugs) {
994
        next unless defined($min_membercontrol{$bug->{'bug_id'}});
995
        if ($min_membercontrol{$bug->{'bug_id'}} == CONTROLMAPMANDATORY) {
996
            $bug->{'secure_mode'} = 'implied';
997
        }
998 999 1000
        else {
            $bug->{'secure_mode'} = 'manual';
        }
1001 1002
    }
}
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012
# Compute percentage complete without rounding.
my $sum = $time_info->{'actual_time'}+$time_info->{'remaining_time'};
if ($sum > 0) {
    $time_info->{'percentage_complete'} = 100*$time_info->{'actual_time'}/$sum;
}
else { # remaining_time <= 0 
    $time_info->{'percentage_complete'} = 0
}                             

1013 1014 1015
################################################################################
# Template Variable Definition
################################################################################
1016

1017
# Define the variables and functions that will be passed to the UI template.
1018

1019
$vars->{'bugs'} = \@bugs;
1020
$vars->{'buglist'} = \@bugidlist;
1021
$vars->{'buglist_joined'} = join(',', @bugidlist);
1022 1023
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
1024

1025
$vars->{'openstates'} = [BUG_STATE_OPEN];
1026
$vars->{'closedstates'} = [map {$_->name} closed_bug_statuses()];
1027

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
# The iCal file needs priorities ordered from 1 to 9 (highest to lowest)
# If there are more than 9 values, just make all the lower ones 9
if ($format->{'extension'} eq 'ics') {
    my $n = 1;
    $vars->{'ics_priorities'} = {};
    my $priorities = get_legal_field_values('priority');
    foreach my $p (@$priorities) {
        $vars->{'ics_priorities'}->{$p} = ($n > 9) ? 9 : $n++;
    }
}

1039 1040 1041
# The list of query fields in URL query string format, used when creating
# URLs to the same query results page with different parameters (such as
# a different sort order or when taking some action on the set of query
1042 1043 1044 1045 1046
# results).  To get this string, we call the Bugzilla::CGI::canoncalise_query
# function with a list of elements to be removed from the URL.
$vars->{'urlquerypart'} = $params->canonicalise_query('order',
                                                      'cmdtype',
                                                      'query_based_on');
1047
$vars->{'order'} = $order;
1048
$vars->{'caneditbugs'} = 1;
1049
$vars->{'time_info'} = $time_info;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

if (!Bugzilla->user->in_group('editbugs')) {
    foreach my $product (keys %$bugproducts) {
        my $prod = new Bugzilla::Product({name => $product});
        if (!Bugzilla->user->in_group('editbugs', $prod->id)) {
            $vars->{'caneditbugs'} = 0;
            last;
        }
    }
}
terry%netscape.com's avatar
terry%netscape.com committed
1060

1061
my @bugowners = keys %$bugowners;
1062
if (scalar(@bugowners) > 1 && Bugzilla->user->in_group('editbugs')) {
1063
    my $suffix = Bugzilla->params->{'emailsuffix'};
1064 1065 1066
    map(s/$/$suffix/, @bugowners) if $suffix;
    my $bugowners = join(",", @bugowners);
    $vars->{'bugowners'} = $bugowners;
terry%netscape.com's avatar
terry%netscape.com committed
1067 1068
}

1069 1070
# Whether or not to split the column titles across two rows to make
# the list more compact.
1071
$vars->{'splitheader'} = $cgi->cookie('SPLITHEADER') ? 1 : 0;
terry%netscape.com's avatar
terry%netscape.com committed
1072

1073
$vars->{'quip'} = GetQuip();
1074
$vars->{'currenttime'} = localtime(time());
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
# See if there's only one product in all the results (or only one product
# that we searched for), which allows us to provide more helpful links.
my @products = keys %$bugproducts;
my $one_product;
if (scalar(@products) == 1) {
    $one_product = new Bugzilla::Product({ name => $products[0] });
}
# This is used in the "Zarroo Boogs" case.
elsif (my @product_input = $cgi->param('product')) {
    if (scalar(@product_input) == 1 and $product_input[0] ne '') {
        $one_product = new Bugzilla::Product({ name => $cgi->param('product') });
    }
}
# We only want the template to use it if the user can actually 
# enter bugs against it.
1091
if ($one_product && Bugzilla->user->can_enter_product($one_product)) {
1092 1093 1094
    $vars->{'one_product'} = $one_product;
}

1095
# The following variables are used when the user is making changes to multiple bugs.
1096
if ($dotweak && scalar @bugs) {
1097 1098 1099 1100 1101 1102
    if (!$vars->{'caneditbugs'}) {
        _close_standby_message('text/html', 'inline', $serverpush);
        ThrowUserError('auth_failure', {group  => 'editbugs',
                                        action => 'modify',
                                        object => 'multiple_bugs'});
    }
1103
    $vars->{'dotweak'} = 1;
1104 1105 1106
  
    # issue_session_token needs to write to the master DB.
    Bugzilla->switch_to_main_db();
1107
    $vars->{'token'} = issue_session_token('buglist_mass_change');
1108
    Bugzilla->switch_to_shadow_db();
1109

1110
    $vars->{'products'} = Bugzilla->user->get_enterable_products;
1111 1112 1113 1114
    $vars->{'platforms'} = get_legal_field_values('rep_platform');
    $vars->{'op_sys'} = get_legal_field_values('op_sys');
    $vars->{'priorities'} = get_legal_field_values('priority');
    $vars->{'severities'} = get_legal_field_values('bug_severity');
1115
    $vars->{'resolutions'} = get_legal_field_values('resolution');
1116

1117 1118 1119 1120
    # Convert bug statuses to their ID.
    my @bug_statuses = map {$dbh->quote($_)} keys %$bugstatuses;
    my $bug_status_ids =
      $dbh->selectcol_arrayref('SELECT id FROM bug_status
1121
                               WHERE ' . $dbh->sql_in('value', \@bug_statuses));
1122 1123 1124 1125

    # This query collects new statuses which are common to all current bug statuses.
    # It also accepts transitions where the bug status doesn't change.
    $bug_status_ids =
1126
      $dbh->selectcol_arrayref(
1127
            'SELECT DISTINCT sw1.new_status
1128
               FROM status_workflow sw1
1129 1130 1131 1132
         INNER JOIN bug_status
                 ON bug_status.id = sw1.new_status
              WHERE bug_status.isactive = 1
                AND NOT EXISTS 
1133 1134 1135 1136 1137 1138 1139 1140
                   (SELECT * FROM status_workflow sw2
                     WHERE sw2.old_status != sw1.new_status 
                           AND '
                         . $dbh->sql_in('sw2.old_status', $bug_status_ids)
                         . ' AND NOT EXISTS 
                           (SELECT * FROM status_workflow sw3
                             WHERE sw3.new_status = sw1.new_status
                                   AND sw3.old_status = sw2.old_status))');
1141 1142 1143

    $vars->{'current_bug_statuses'} = [keys %$bugstatuses];
    $vars->{'new_bug_statuses'} = Bugzilla::Status->new_from_list($bug_status_ids);
1144 1145 1146

    # The groups the user belongs to and which are editable for the given buglist.
    $vars->{'groups'} = GetGroups(\@products);
1147 1148 1149 1150 1151

    # If all bugs being changed are in the same product, the user can change
    # their version and component, so generate a list of products, a list of
    # versions for the product (if there is only one product on the list of
    # products), and a list of components for the product.
1152 1153 1154 1155 1156 1157 1158
    if ($one_product) {
        $vars->{'versions'} = [map($_->name ,@{ $one_product->versions })];
        $vars->{'components'} = [map($_->name, @{ $one_product->components })];
        if (Bugzilla->params->{'usetargetmilestone'}) {
            $vars->{'targetmilestones'} = [map($_->name, 
                                               @{ $one_product->milestones })];
        }
terry%netscape.com's avatar
terry%netscape.com committed
1159 1160
    }
}
1161

1162 1163 1164 1165
# If we're editing a stored query, use the existing query name as default for
# the "Remember search as" field.
$vars->{'defaultsavename'} = $cgi->param('query_based_on');

1166

1167 1168 1169
################################################################################
# HTTP Header Generation
################################################################################
1170

1171
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
1172

1173
my $contenttype;
1174
my $disposition = "inline";
terry%netscape.com's avatar
terry%netscape.com committed
1175

1176
if ($format->{'extension'} eq "html" && !$agent) {
1177
    if ($order && !$cgi->param('sharer_id')) {
1178
        $cgi->send_cookie(-name => 'LASTORDER',
1179
                          -value => $order,
1180
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1181
    }
1182
    my $bugids = join(":", @bugidlist);
1183
    # See also Bug 111999
1184 1185 1186 1187
    if (length($bugids) == 0) {
        $cgi->remove_cookie('BUGLIST');
    }
    elsif (length($bugids) < 4000) {
1188 1189 1190
        $cgi->send_cookie(-name => 'BUGLIST',
                          -value => $bugids,
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1191
    }
1192
    else {
1193
        $cgi->remove_cookie('BUGLIST');
1194
        $vars->{'toolong'} = 1;
terry%netscape.com's avatar
terry%netscape.com committed
1195
    }
1196 1197

    $contenttype = "text/html";
1198 1199
}
else {
1200
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
1201 1202
}

1203 1204 1205
if ($format->{'extension'} eq "csv") {
    # We set CSV files to be downloaded, as they are designed for importing
    # into other programs.
1206
    $disposition = "attachment";
1207 1208
}

1209 1210 1211
# Suggest a name for the bug list if the user wants to save it as a file.
$disposition .= "; filename=\"$filename\"";

1212
_close_standby_message($contenttype, $disposition, $serverpush);
1213

1214 1215 1216
################################################################################
# Content Generation
################################################################################
1217

1218
# Generate and return the UI (HTML page) from the appropriate template.
1219
$template->process($format->{'template'}, $vars)
1220
  || ThrowTemplateError($template->error());
1221

1222

1223 1224 1225 1226
################################################################################
# Script Conclusion
################################################################################

1227
print $cgi->multipart_final() if $serverpush;