buglist.cgi 47.4 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::Recent;
44
use Bugzilla::Search::Saved;
45
use Bugzilla::User;
46
use Bugzilla::Bug;
47
use Bugzilla::Product;
48
use Bugzilla::Keyword;
49
use Bugzilla::Field;
50
use Bugzilla::Status;
51
use Bugzilla::Token;
52

53 54
use Date::Parse;

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

61 62 63
# 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'.
64
my $user = Bugzilla->login();
65

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

71 72 73 74 75 76 77 78 79 80 81 82 83
# 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;
}

84 85 86 87 88
# 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();
89
    my $uri_length = length($cgi->self_url());
90 91 92 93 94 95 96 97 98 99 100 101

    if (!$cgi->param('regetlastlist') and !$cgi->param('list_id')
        and $user->id) 
    {
        # Insert a placeholder Bugzilla::Search::Recent, so that we know what
        # the id of the resulting search will be. This is then pulled out
        # of the Referer header when viewing show_bug.cgi to know what
        # bug list we came from.
        my $recent_search = Bugzilla::Search::Recent->create_placeholder;
        $cgi->param('list_id', $recent_search->id);
    }

102 103 104 105
    if ($uri_length < CGI_URI_LIMIT) {
        print $cgi->redirect(-url => $cgi->self_url());
        exit;
    }
106 107
}

108 109 110 111 112 113 114 115 116
# 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.
}

117
# If configured to not allow empty words, reject empty searches from the
118 119 120
# Find a Specific Bug search form, including words being a single or 
# several consecutive whitespaces only.
if (!Bugzilla->params->{'specific_search_allow_empty_words'}
121 122
    && defined($cgi->param('content')) && $cgi->param('content') =~ /^\s*$/)
{
123 124 125
    ThrowUserError("buglist_parameters_required");
}

126 127 128
################################################################################
# Data and Security Validation
################################################################################
129

130
# Whether or not the user wants to change multiple bugs.
131
my $dotweak = $cgi->param('tweak') ? 1 : 0;
132 133 134

# Log the user in
if ($dotweak) {
135
    Bugzilla->login(LOGIN_REQUIRED);
136 137
}

138
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
139 140 141 142
if (defined $cgi->param('format') && $cgi->param('format') eq "rdf"
    && !defined $cgi->param('ctype')) {
    $cgi->param('ctype', "rdf");
    $cgi->delete('format');
143
}
144

145 146 147 148 149
# Treat requests for ctype=rss as requests for ctype=atom
if (defined $cgi->param('ctype') && $cgi->param('ctype') eq "rss") {
    $cgi->param('ctype', "atom");
}

150 151 152 153 154 155
# 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.
156
if ((defined $cgi->param('ctype')) && ($cgi->param('ctype') eq "js")) {
157
    Bugzilla->logout_request();
158
}
159

160 161 162 163 164 165 166
# 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/);

167 168 169
# 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.
170 171
my $format = $template->get_format("list/list", scalar $cgi->param('format'),
                                   scalar $cgi->param('ctype'));
172

173 174 175 176 177 178
# 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. 
179 180 181
# 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)
182
# MSIE 5+ supports it on Mac (but not on Windows) (bug 190370)
183 184
#
my $serverpush =
185 186 187
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
188
        && (($ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/) || ($ENV{'HTTP_USER_AGENT'} =~ /MSIE 5.*Mac_PowerPC/))
189
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
190 191 192
            && !$agent
              && !defined($cgi->param('serverpush'))
                || $cgi->param('serverpush');
193

194
my $order = $cgi->param('order') || "";
195

196 197 198
# The params object to use for the actual query itself
my $params;

199 200
# 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.
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
if (my $last_list = $cgi->param('regetlastlist')) {
    my ($bug_ids, $order);

    # Logged-out users use the old cookie method for storing the last search.
    if (!$user->id or $last_list eq 'cookie') {
        $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
        $order = "reuse last sort" unless $order;
        $bug_ids = $cgi->cookie('BUGLIST');
        $bug_ids =~ s/:/,/g;
    }
    # But logged in users store the last X searches in the DB so they can
    # have multiple bug lists available.
    else {
        my $last_search = Bugzilla::Search::Recent->check(
            { id => $last_list });
        $bug_ids = join(',', @{ $last_search->bug_list });
        $order   = $last_search->list_order if !$order;
    }
219
    # set up the params for this new query
220
    $params = new Bugzilla::CGI({ bug_id => $bug_ids, order => $order });
221 222
}

223 224 225 226
# 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;
227
if ($cgi->param('content')) { $fulltext = 1 }
228
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
229
foreach my $chart (@charts) {
230
    if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
231 232 233 234 235
        $fulltext = 1;
        last;
    }
}

236 237 238 239 240 241 242 243
################################################################################
# Utilities
################################################################################

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

245
    if( $age < 18*60*60 ) {
246
        $date = format_time($datestr, '%H:%M:%S');
247
    } elsif( $age < 6*24*60*60 ) {
248
        $date = format_time($datestr, '%a %H:%M');
249
    } else {
250
        $date = format_time($datestr, '%Y-%m-%d');
251 252 253
    }
    return $date;
}
254

255
sub LookupNamedQuery {
256 257
    my ($name, $sharer_id, $query_type, $throw_error) = @_;
    $throw_error = 1 unless defined $throw_error;
258

259
    Bugzilla->login(LOGIN_REQUIRED);
260

261 262 263 264 265
    my $constructor = $throw_error ? 'check' : 'new';
    my $query = Bugzilla::Search::Saved->$constructor(
        { user => $sharer_id, name => $name });

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

267 268 269
    if (defined $query_type and $query->type != $query_type) {
        ThrowUserError("missing_query", { queryname => $name,
                                          sharer_id => $sharer_id });
270
    }
271

272 273 274 275
    $query->url
       || ThrowUserError("buglist_parameters_required", { queryname  => $name });

    return wantarray ? ($query->url, $query->id) : $query->url;
276 277
}

278 279 280 281 282 283 284 285 286 287 288 289 290
# 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.
291 292
# query_type (optional) - 1 if the Named Query contains a list of
# bug IDs only, 0 otherwise (default).
293 294 295 296 297
#
# 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.
298
sub InsertNamedQuery {
299
    my ($query_name, $query, $link_in_footer, $query_type) = @_;
300
    my $dbh = Bugzilla->dbh;
301 302

    $query_name = trim($query_name);
303
    my ($query_obj) = grep {lc($_->name) eq lc($query_name)} @{Bugzilla->user->queries};
304 305

    if ($query_obj) {
306
        $query_obj->set_name($query_name);
307 308 309
        $query_obj->set_url($query);
        $query_obj->set_query_type($query_type);
        $query_obj->update();
310
    } else {
311 312 313 314 315 316
        Bugzilla::Search::Saved->create({
            name           => $query_name,
            query          => $query,
            query_type     => $query_type,
            link_in_footer => $link_in_footer
        });
317 318
    }

319
    return $query_obj ? 1 : 0;
320 321
}

322 323 324 325 326 327
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 " .
328 329
                                       "WHERE series_id = ?"
                                       , undef, ($series_id));
330 331 332 333 334
    $result
           || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
    return $result;
}

335
sub GetQuip {
336
    my $dbh = Bugzilla->dbh;
337 338
    # COUNT is quick because it is cached for MySQL. We may want to revisit
    # this when we support other databases.
339 340
    my $count = $dbh->selectrow_array("SELECT COUNT(quip)"
                                    . " FROM quips WHERE approved = 1");
341
    my $random = int(rand($count));
342
    my $quip = 
343 344
        $dbh->selectrow_array("SELECT quip FROM quips WHERE approved = 1 " . 
                              $dbh->sql_limit(1, $random));
345
    return $quip;
346
}
347

348
# Return groups available for at least one product of the buglist.
349
sub GetGroups {
350
    my $product_names = shift;
351
    my $user = Bugzilla->user;
352 353 354 355 356 357 358 359 360 361 362 363 364
    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);
365

366 367 368 369 370 371 372
            # 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];
373
}
374

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
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);
    }
}

391

392 393 394
################################################################################
# Command Execution
################################################################################
395

396 397
my $cmdtype   = $cgi->param('cmdtype')   || '';
my $remaction = $cgi->param('remaction') || '';
398

399 400
# Backwards-compatibility - the old interface had cmdtype="runnamed" to run
# a named command, and we can't break this because it's in bookmarks.
401 402 403
if ($cmdtype eq "runnamed") {  
    $cmdtype = "dorem";
    $remaction = "run";
404 405
}

406 407 408 409 410 411
# 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);
412

413 414 415 416 417 418 419 420
# 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}";
421
if ($cmdtype eq "dorem" && $remaction =~ /^run/) {
422
    $filename = $cgi->param('namedcmd') . "-$date.$format->{extension}";
423 424 425 426
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}
427 428
$filename =~ s/\\/\\\\/g; # escape backslashes
$filename =~ s/"/\\"/g; # escape quotes
429

430
# Take appropriate action based on user's request.
431 432
if ($cmdtype eq "dorem") {  
    if ($remaction eq "run") {
433 434 435
        my $query_id;
        ($buffer, $query_id) = LookupNamedQuery(scalar $cgi->param("namedcmd"),
                                                scalar $cgi->param('sharer_id'));
436 437
        # If this is the user's own query, remember information about it
        # so that it can be modified easily.
438
        $vars->{'searchname'} = $cgi->param('namedcmd');
439 440 441
        if (!$cgi->param('sharer_id') ||
            $cgi->param('sharer_id') == Bugzilla->user->id) {
            $vars->{'searchtype'} = "saved";
442
            $vars->{'search_id'} = $query_id;
443
        }
444
        $params = new Bugzilla::CGI($buffer);
445
        $order = $params->param('order') || $order;
446

447
    }
448
    elsif ($remaction eq "runseries") {
449
        $buffer = LookupSeries(scalar $cgi->param("series_id"));
450
        $vars->{'searchname'} = $cgi->param('namedcmd');
451
        $vars->{'searchtype'} = "series";
452
        $params = new Bugzilla::CGI($buffer);
453 454
        $order = $params->param('order') || $order;
    }
455
    elsif ($remaction eq "forget") {
456
        $user = Bugzilla->login(LOGIN_REQUIRED);
457 458 459
        # 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.
460
        my $qname = $cgi->param('namedcmd');
461
        trick_taint($qname);
462 463 464 465 466 467 468 469 470 471 472 473

        # 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
                                                      = ?
474
                                      ', undef, $user->id, $qname);
475 476 477 478 479 480 481 482
        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
483 484 485
        my $query_id;
        ($buffer, $query_id) = LookupNamedQuery(scalar $cgi->param("namedcmd"),
                                                $user->id);
486 487 488 489
        if (!$query_id) {
            # The user has no query of this name. Play along.
        }
        else {
490 491 492 493
            # Make sure the user really wants to delete his saved search.
            my $token = $cgi->param('token');
            check_hash_token($token, [$query_id, $qname]);

494 495 496 497 498 499 500 501 502 503
            $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);
        }
504 505

        # Now reset the cached queries
506
        $user->flush_queries_cache();
507

508
        print $cgi->header();
509
        # Generate and return the UI (HTML page) from the appropriate template.
510
        $vars->{'message'} = "buglist_query_gone";
511
        $vars->{'namedcmd'} = $qname;
512
        $vars->{'url'} = "buglist.cgi?newquery=" . url_quote($buffer) . "&cmdtype=doit&remtype=asnamed&newqueryname=" . url_quote($qname);
513
        $template->process("global/message.html.tmpl", $vars)
514
          || ThrowTemplateError($template->error());
515
        exit;
516 517
    }
}
518
elsif (($cmdtype eq "doit") && defined $cgi->param('remtype')) {
519
    if ($cgi->param('remtype') eq "asdefault") {
520
        $user = Bugzilla->login(LOGIN_REQUIRED);
521
        InsertNamedQuery(DEFAULT_QUERY_NAME, $buffer);
522
        $vars->{'message'} = "buglist_new_default_query";
523
    }
524
    elsif ($cgi->param('remtype') eq "asnamed") {
525
        $user = Bugzilla->login(LOGIN_REQUIRED);
526
        my $query_name = $cgi->param('newqueryname');
527 528
        my $new_query = $cgi->param('newquery');
        my $query_type = QUERY_LIST;
529 530 531 532 533 534 535
        # 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)$/
536
              || ThrowUserError('unknown_action', {action => $action});
537 538 539 540 541

            # 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');
542 543
            }

544
            my %bug_ids;
545
            my $is_new_name = 0;
546
            if ($query_name) {
547 548
                my ($query, $query_id) =
                  LookupNamedQuery($query_name, undef, QUERY_LIST, !THROW_ERROR);
549
                # Make sure this name is not already in use by a normal saved search.
550 551 552
                if ($query) {
                    ThrowUserError('query_name_exists', {name     => $query_name,
                                                         query_id => $query_id});
553
                }
554
                $is_new_name = 1;
555
            }
556 557 558 559 560 561 562
            # 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).
563 564 565 566
            my ($old_query, $query_id) =
              LookupNamedQuery($query_name, undef, LIST_OF_BUGS, !$is_new_name);

            if ($old_query) {
567 568 569
                # 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')) {
570 571 572
                    $bug_ids{$bug_id} = 1 if detaint_natural($bug_id);
                }
            }
573 574 575 576 577

            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;
578 579
                my $bug = Bugzilla::Bug->check($bug_id);
                $bug_ids{$bug->id} = $keep_bug;
580 581
                $changes = 1;
            }
582 583 584 585
            ThrowUserError('no_bug_ids',
                           {'action' => $action,
                            'tag' => $query_name})
              unless $changes;
586 587 588 589

            # 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.
590 591 592 593
            if (!scalar @bug_ids) {
                ThrowUserError('no_bugs_in_list', {name     => $query_name,
                                                   query_id => $query_id});
            }
594
            $new_query = "bug_id=" . join(',', sort {$a <=> $b} @bug_ids);
595 596
            $query_type = LIST_OF_BUGS;
        }
597
        my $tofooter = 1;
598
        my $existed_before = InsertNamedQuery($query_name, $new_query,
599
                                              $tofooter, $query_type);
600
        if ($existed_before) {
601 602
            $vars->{'message'} = "buglist_updated_named_query";
        }
603
        else {
604
            $vars->{'message'} = "buglist_new_named_query";
605
        }
606 607 608

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

611
        $vars->{'queryname'} = $query_name;
612
        
613
        print $cgi->header();
614 615 616
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
617
    }
terry%netscape.com's avatar
terry%netscape.com committed
618 619
}

620 621 622 623 624
# 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');
625
    $buffer = $params->query_string;
626
}
terry%netscape.com's avatar
terry%netscape.com committed
627

628 629 630 631
################################################################################
# Column Definition
################################################################################

632
my $columns = Bugzilla::Search::COLUMNS;
633

634 635 636 637 638 639 640
################################################################################
# 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 = ();
641 642
if (defined $params->param('columnlist')) {
    if ($params->param('columnlist') eq "all") {
643
        # If the value of the CGI parameter is "all", display all columns,
644 645
        # but remove the redundant "short_desc" column.
        @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
terry%netscape.com's avatar
terry%netscape.com committed
646
    }
647
    else {
648
        @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
649
    }
terry%netscape.com's avatar
terry%netscape.com committed
650
}
651
elsif (defined $cgi->cookie('COLUMNLIST')) {
652
    # 2002-10-31 Rename column names (see bug 176461)
653
    my $columnlist = $cgi->cookie('COLUMNLIST');
654 655 656 657 658 659 660
    $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/;
661

662
    # Use the columns listed in the user's preferences.
663
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
664
}
665 666
else {
    # Use the default list of columns.
667
    @displaycolumns = DEFAULT_COLUMN_LIST;
668 669
}

670 671 672 673
# 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);
674

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

679 680
# 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)
681
if (!Bugzilla->user->is_timetracker) {
682 683 684 685
   @displaycolumns = grep($_ ne 'estimated_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'remaining_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'actual_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'percentage_complete', @displaycolumns);
686
   @displaycolumns = grep($_ ne 'deadline', @displaycolumns);
687
}
terry%netscape.com's avatar
terry%netscape.com committed
688

689 690 691 692 693 694
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


695 696 697
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
698

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

701
# The bug ID is always selected because bug IDs are always displayed.
702 703 704
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
705
                     "resolution", "product");
706

707
# remaining and actual_time are required for percentage_complete calculation:
708
if (grep { $_ eq "percentage_complete" } @displaycolumns) {
709 710 711 712
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

713 714 715 716 717 718 719 720 721 722 723 724
# 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);
    }
}

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

730 731
# 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
732 733
# has for modifying the bugs.
if ($dotweak) {
734
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
735 736
}

737 738 739
if ($format->{'extension'} eq 'ics') {
    push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
}
740

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

745 746
    # This is the list of fields that are needed by the Atom filter.
    my @required_atom_columns = (
747 748 749
      'short_desc',
      'opendate',
      'changeddate',
750
      'reporter',
751 752 753
      'reporter_realname',
      'priority',
      'bug_severity',
754
      'assigned_to',
755
      'assigned_to_realname',
756 757 758 759
      'bug_status',
      'product',
      'component',
      'resolution'
760
    );
761
    push(@required_atom_columns, 'target_milestone') if Bugzilla->params->{'usetargetmilestone'};
762

763
    foreach my $required (@required_atom_columns) {
764 765 766 767
        push(@selectcolumns, $required) if !grep($_ eq $required,@selectcolumns);
    }
}

768 769 770
################################################################################
# Sort Order Determination
################################################################################
771

772
# Add to the query some instructions for sorting the bug list.
773 774 775 776 777 778

# 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');
779 780 781 782
       
        # Cookies from early versions of Specific Search included this text,
        # which is now invalid.
        $order =~ s/ LIMIT 200//;
783 784 785 786
    }
    else {
        $order = '';  # Remove possible "reuse" identifier as unnecessary
    }
787
}
788

789 790 791 792
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
793
        /^Bug Number$/ && do {
794
            $order = "bug_id";
795 796 797
            last ORDER;
        };
        /^Importance$/ && do {
798
            $order = "priority,bug_severity";
799 800 801
            last ORDER;
        };
        /^Assignee$/ && do {
802
            $order = "assigned_to,bug_status,priority,bug_id";
803 804 805
            last ORDER;
        };
        /^Last Changed$/ && do {
806
            $order = "changeddate,bug_status,priority,assigned_to,bug_id";
807 808 809
            last ORDER;
        };
        do {
810
            my (@order, @invalid_fragments);
811

812
            # A custom list of columns.  Make sure each column is valid.
813 814
            foreach my $fragment (split(/,/, $order)) {
                $fragment = trim($fragment);
815
                next unless $fragment;
816 817 818 819 820 821 822 823 824
                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");
825 826
                }
                else {
827
                    push(@invalid_fragments, $fragment);
828 829
                }
            }
830 831 832 833 834
            if (scalar @invalid_fragments) {
                $vars->{'message'} = 'invalid_column_name';
                $vars->{'invalid_fragments'} = \@invalid_fragments;
            }

835
            $order = join(",", @order);
836 837
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
838
            trick_taint($order) if $order;
839
        };
terry%netscape.com's avatar
terry%netscape.com committed
840
    }
841
}
842 843

if (!$order) {
844
    # DEFAULT
845
    $order = "bug_status,priority,assigned_to,bug_id";
846
}
847

848
my @orderstrings = split(/,\s*/, $order);
849

850
# Generate the basic SQL query that will be used to generate the bug list.
851
my $search = new Bugzilla::Search('fields' => \@selectcolumns, 
852 853
                                  'params' => $params,
                                  'order' => \@orderstrings);
854
my $query = $search->getSQL();
855
$vars->{'search_description'} = $search->search_description;
856

857 858 859 860 861
if (defined $cgi->param('limit')) {
    my $limit = $cgi->param('limit');
    if (detaint_natural($limit)) {
        $query .= " " . $dbh->sql_limit($limit);
    }
862 863
}
elsif ($fulltext) {
864
    $query .= " " . $dbh->sql_limit(FULLTEXT_BUGLIST_LIMIT);
865 866 867
    if ($cgi->param('order') && $cgi->param('order') =~ /^relevance/) {
        $vars->{'message'} = 'buglist_sorted_by_relevance';
    }
868 869
}

870

871 872 873
################################################################################
# Query Execution
################################################################################
874

875
if ($cgi->param('debug')) {
876 877
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
878 879 880 881 882 883 884
    # 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);
    }
885 886
}

887 888 889
# 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) {
890 891
    print $cgi->multipart_init();
    print $cgi->multipart_start(-type => 'text/html');
892

893
    # Generate and return the UI (HTML page) from the appropriate template.
894 895
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
896

897 898 899 900 901 902
    # Under mod_perl, flush stdout so that the page actually shows up.
    if ($ENV{MOD_PERL}) {
        require Apache2::RequestUtil;
        Apache2::RequestUtil->request->rflush();
    }

903 904 905
    # 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
906 907
}

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

912
# Normally, we ignore SIGTERM and SIGPIPE, but we need to
913 914 915 916 917
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

918
# Execute the query.
919 920
my $buglist_sth = $dbh->prepare($query);
$buglist_sth->execute();
921

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

923 924 925
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
926

927 928
# 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
929

930
# If we're doing time tracking, then keep totals for all bugs.
931 932 933 934 935 936
my $percentage_complete = grep($_ eq 'percentage_complete', @displaycolumns);
my $estimated_time      = grep($_ eq 'estimated_time', @displaycolumns);
my $remaining_time      = grep($_ eq 'remaining_time', @displaycolumns)
                            || $percentage_complete;
my $actual_time         = grep($_ eq 'actual_time', @displaycolumns)
                            || $percentage_complete;
937 938 939 940 941 942 943 944 945

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),
                };
    
946 947 948
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
949
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
950

951
my @bugs; # the list of records
952

953
while (my @row = $buglist_sth->fetchrow_array()) {
954
    my $bug = {}; # a record
955

956
    # Slurp the row of data into the record.
957 958
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
959
    foreach my $column (@selectcolumns) {
960
        $bug->{$column} = shift @row;
961
    }
terry%netscape.com's avatar
terry%netscape.com committed
962

963 964 965
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
966
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
967

968 969
        $bug->{'changedtime'} = $bug->{'changeddate'}; # for iCalendar and Atom
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});
970 971 972
    }

    if ($bug->{'opendate'}) {
973
        $bug->{'opentime'} = $bug->{'opendate'}; # for iCalendar
974
        $bug->{'opendate'} = DiffDate($bug->{'opendate'});
975
    }
terry%netscape.com's avatar
terry%netscape.com committed
976

977
    # Record the assignee, product, and status in the big hashes of those things.
978
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
979
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
980
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
981

982
    $bug->{'secure_mode'} = undef;
983

984 985
    # Add the record to the list.
    push(@bugs, $bug);
986 987

    # Add id to list for checking for bug privacy later
988
    push(@bugidlist, $bug->{'bug_id'});
989 990 991 992 993

    # 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);
994 995
}

996 997 998 999
# 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;
1000
if (@bugidlist) {
1001
    my $sth = $dbh->prepare(
1002 1003 1004 1005 1006 1007 1008
        "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 " .
1009
         "WHERE " . $dbh->sql_in('bugs.bug_id', \@bugidlist) . 
1010
            $dbh->sql_group_by('bugs.bug_id'));
1011 1012
    $sth->execute();
    while (my ($bug_id, $min_membercontrol) = $sth->fetchrow_array()) {
1013
        $min_membercontrol{$bug_id} = $min_membercontrol || CONTROLMAPNA;
1014 1015
    }
    foreach my $bug (@bugs) {
1016
        next unless defined($min_membercontrol{$bug->{'bug_id'}});
1017
        if ($min_membercontrol{$bug->{'bug_id'}} == CONTROLMAPMANDATORY) {
1018
            $bug->{'secure_mode'} = 'implied';
1019
        }
1020 1021 1022
        else {
            $bug->{'secure_mode'} = 'manual';
        }
1023 1024
    }
}
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034
# 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
}                             

1035 1036 1037
################################################################################
# Template Variable Definition
################################################################################
1038

1039
# Define the variables and functions that will be passed to the UI template.
1040

1041
$vars->{'bugs'} = \@bugs;
1042
$vars->{'buglist'} = \@bugidlist;
1043
$vars->{'buglist_joined'} = join(',', @bugidlist);
1044 1045
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
1046

1047
$vars->{'openstates'} = [BUG_STATE_OPEN];
1048
$vars->{'closedstates'} = [map {$_->name} closed_bug_statuses()];
1049

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
# 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++;
    }
}

1061 1062 1063
# 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
1064 1065 1066 1067 1068
# 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');
1069
$vars->{'order'} = $order;
1070
$vars->{'caneditbugs'} = 1;
1071
$vars->{'time_info'} = $time_info;
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

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
1082

1083
my @bugowners = keys %$bugowners;
1084
if (scalar(@bugowners) > 1 && Bugzilla->user->in_group('editbugs')) {
1085
    my $suffix = Bugzilla->params->{'emailsuffix'};
1086 1087 1088
    map(s/$/$suffix/, @bugowners) if $suffix;
    my $bugowners = join(",", @bugowners);
    $vars->{'bugowners'} = $bugowners;
terry%netscape.com's avatar
terry%netscape.com committed
1089 1090
}

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

1095
$vars->{'quip'} = GetQuip();
1096
$vars->{'currenttime'} = localtime(time());
1097

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
# 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.
1113
if ($one_product && Bugzilla->user->can_enter_product($one_product)) {
1114 1115 1116
    $vars->{'one_product'} = $one_product;
}

1117
# The following variables are used when the user is making changes to multiple bugs.
1118
if ($dotweak && scalar @bugs) {
1119 1120 1121 1122 1123 1124
    if (!$vars->{'caneditbugs'}) {
        _close_standby_message('text/html', 'inline', $serverpush);
        ThrowUserError('auth_failure', {group  => 'editbugs',
                                        action => 'modify',
                                        object => 'multiple_bugs'});
    }
1125
    $vars->{'dotweak'} = 1;
1126 1127 1128
  
    # issue_session_token needs to write to the master DB.
    Bugzilla->switch_to_main_db();
1129
    $vars->{'token'} = issue_session_token('buglist_mass_change');
1130
    Bugzilla->switch_to_shadow_db();
1131

1132
    $vars->{'products'} = Bugzilla->user->get_enterable_products;
1133 1134 1135 1136
    $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');
1137
    $vars->{'resolutions'} = get_legal_field_values('resolution');
1138

1139 1140 1141 1142
    # 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
1143
                               WHERE ' . $dbh->sql_in('value', \@bug_statuses));
1144 1145 1146 1147

    # 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 =
1148
      $dbh->selectcol_arrayref(
1149
            'SELECT DISTINCT sw1.new_status
1150
               FROM status_workflow sw1
1151 1152 1153 1154
         INNER JOIN bug_status
                 ON bug_status.id = sw1.new_status
              WHERE bug_status.isactive = 1
                AND NOT EXISTS 
1155 1156 1157 1158 1159 1160 1161 1162
                   (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))');
1163 1164 1165

    $vars->{'current_bug_statuses'} = [keys %$bugstatuses];
    $vars->{'new_bug_statuses'} = Bugzilla::Status->new_from_list($bug_status_ids);
1166 1167 1168

    # The groups the user belongs to and which are editable for the given buglist.
    $vars->{'groups'} = GetGroups(\@products);
1169 1170 1171 1172 1173

    # 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.
1174 1175 1176 1177 1178 1179 1180
    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
1181 1182
    }
}
1183

1184 1185 1186 1187
# 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');

1188 1189 1190
# If we did a quick search then redisplay the previously entered search 
# string in the text field.
$vars->{'quicksearch'} = $searchstring;
1191

1192 1193 1194
################################################################################
# HTTP Header Generation
################################################################################
1195

1196
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
1197

1198
my $contenttype;
1199
my $disposition = "inline";
terry%netscape.com's avatar
terry%netscape.com committed
1200

1201
if ($format->{'extension'} eq "html" && !$agent) {
1202 1203 1204 1205
    if (!$cgi->param('regetlastlist')) {
        Bugzilla->user->save_last_search(
            { bugs => \@bugidlist, order => $order, vars => $vars,
              list_id => scalar $cgi->param('list_id') });
1206
    }
1207
    $contenttype = "text/html";
1208 1209
}
else {
1210
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
1211 1212
}

1213 1214 1215
if ($format->{'extension'} eq "csv") {
    # We set CSV files to be downloaded, as they are designed for importing
    # into other programs.
1216
    $disposition = "attachment";
1217 1218
}

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

1222
_close_standby_message($contenttype, $disposition, $serverpush);
1223

1224 1225 1226
################################################################################
# Content Generation
################################################################################
1227

1228
# Generate and return the UI (HTML page) from the appropriate template.
1229
$template->process($format->{'template'}, $vars)
1230
  || ThrowTemplateError($template->error());
1231

1232

1233 1234 1235 1236
################################################################################
# Script Conclusion
################################################################################

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