buglist.cgi 48.3 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
#
# 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();

    print $cgi->redirect(-url => $cgi->self_url());
    exit;
}

81 82 83 84 85 86 87 88 89
# 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.
}

90
# If configured to not allow empty words, reject empty searches from the
91 92 93
# Find a Specific Bug search form, including words being a single or 
# several consecutive whitespaces only.
if (!Bugzilla->params->{'specific_search_allow_empty_words'}
94 95
    && defined($cgi->param('content')) && $cgi->param('content') =~ /^\s*$/)
{
96 97 98
    ThrowUserError("buglist_parameters_required");
}

99 100 101
################################################################################
# Data and Security Validation
################################################################################
102

103
# Whether or not the user wants to change multiple bugs.
104
my $dotweak = $cgi->param('tweak') ? 1 : 0;
105 106 107

# Log the user in
if ($dotweak) {
108
    Bugzilla->login(LOGIN_REQUIRED);
109 110
}

111
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
112 113 114 115
if (defined $cgi->param('format') && $cgi->param('format') eq "rdf"
    && !defined $cgi->param('ctype')) {
    $cgi->param('ctype', "rdf");
    $cgi->delete('format');
116
}
117

118 119 120 121 122
# Treat requests for ctype=rss as requests for ctype=atom
if (defined $cgi->param('ctype') && $cgi->param('ctype') eq "rss") {
    $cgi->param('ctype', "atom");
}

123 124 125 126 127 128
# 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.
129
if ((defined $cgi->param('ctype')) && ($cgi->param('ctype') eq "js")) {
130
    Bugzilla->logout_request();
131
}
132

133 134 135 136 137 138 139
# 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/);

140 141 142
# 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.
143 144
my $format = $template->get_format("list/list", scalar $cgi->param('format'),
                                   scalar $cgi->param('ctype'));
145

146 147 148 149 150 151
# 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. 
152 153 154
# 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)
155
# MSIE 5+ supports it on Mac (but not on Windows) (bug 190370)
156 157
#
my $serverpush =
158 159 160
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
161
        && (($ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/) || ($ENV{'HTTP_USER_AGENT'} =~ /MSIE 5.*Mac_PowerPC/))
162
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
163 164 165
            && !$agent
              && !defined($cgi->param('serverpush'))
                || $cgi->param('serverpush');
166

167
my $order = $cgi->param('order') || "";
168

169 170 171
# The params object to use for the actual query itself
my $params;

172 173
# 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.
174
if (defined $cgi->param('regetlastlist')) {
175
    $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
176

177
    $order = "reuse last sort" unless $order;
178 179
    my $bug_id = $cgi->cookie('BUGLIST');
    $bug_id =~ s/:/,/g;
180 181
    # set up the params for this new query
    $params = new Bugzilla::CGI({
182
                                 bug_id => $bug_id,
183 184
                                 order => $order,
                                });
185 186
}

187 188
if ($buffer =~ /&cmd-/) {
    my $url = "query.cgi?$buffer#chart";
189
    print $cgi->redirect(-location => $url);
190
    # Generate and return the UI (HTML page) from the appropriate template.
191
    $vars->{'message'} = "buglist_adding_field";
192 193
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
194
      || ThrowTemplateError($template->error());
195 196
    exit;
}
197

198 199 200 201
# 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;
202
if ($cgi->param('content')) { $fulltext = 1 }
203
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
204
foreach my $chart (@charts) {
205
    if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
206 207 208 209 210
        $fulltext = 1;
        last;
    }
}

211 212 213 214 215 216 217 218
################################################################################
# Utilities
################################################################################

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

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

230
sub LookupNamedQuery {
231
    my ($name, $sharer_id, $query_type, $throw_error) = @_;
232
    my $user = Bugzilla->login(LOGIN_REQUIRED);
233
    my $dbh = Bugzilla->dbh;
234
    my $owner_id;
235
    $throw_error = 1 unless defined $throw_error;
236 237 238

    # $name and $sharer_id are safe -- we only use them below in SELECT
    # placeholders and then in error messages (which are always HTML-filtered).
239
    $name || ThrowUserError("query_name_missing");
240
    trick_taint($name);
241 242
    if ($sharer_id) {
        $owner_id = $sharer_id;
243 244
        detaint_natural($owner_id);
        $owner_id || ThrowUserError('illegal_user_id', {'userid' => $sharer_id});
245 246 247 248 249
    }
    else {
        $owner_id = $user->id;
    }

250 251 252 253 254 255 256 257 258
    my @args = ($owner_id, $name);
    my $extra = '';
    # If $query_type is defined, then we restrict our search.
    if (defined $query_type) {
        $extra = ' AND query_type = ? ';
        detaint_natural($query_type);
        push(@args, $query_type);
    }
    my ($id, $result) = $dbh->selectrow_array("SELECT id, query
259
                                                 FROM namedqueries
260 261 262
                                                WHERE userid = ? AND name = ?
                                                      $extra",
                                               undef, @args);
263 264 265 266 267 268

    # Some DBs (read: Oracle) incorrectly mark this string as UTF-8
    # even though it has no UTF-8 characters in it, which prevents
    # Bugzilla::CGI from later reading it correctly.
    utf8::downgrade($result) if utf8::is_utf8($result);

269 270 271 272 273
    if (!defined($result)) {
        return 0 unless $throw_error;
        ThrowUserError("missing_query", {'queryname' => $name,
                                         'sharer_id' => $sharer_id});
    }
274 275 276 277 278 279

    if ($sharer_id) {
        my $group = $dbh->selectrow_array('SELECT group_id
                                             FROM namedquery_group_map
                                            WHERE namedquery_id = ?',
                                          undef, $id);
280
        if (!grep { $_->id == $group } @{ $user->groups }) {
281 282 283 284
            ThrowUserError("missing_query", {'queryname' => $name,
                                             'sharer_id' => $sharer_id});
        }
    }
285 286 287 288
    
    $result
       || ThrowUserError("buglist_parameters_required", {'queryname' => $name});

289
    return wantarray ? ($result, $id) : $result;
290 291
}

292 293 294 295 296 297 298 299 300 301 302 303 304
# 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.
305 306
# query_type (optional) - 1 if the Named Query contains a list of
# bug IDs only, 0 otherwise (default).
307 308 309 310 311
#
# 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.
312
sub InsertNamedQuery {
313
    my ($query_name, $query, $link_in_footer, $query_type) = @_;
314
    my $dbh = Bugzilla->dbh;
315 316

    $query_name = trim($query_name);
317
    my ($query_obj) = grep {lc($_->name) eq lc($query_name)} @{Bugzilla->user->queries};
318 319

    if ($query_obj) {
320
        $query_obj->set_name($query_name);
321 322 323
        $query_obj->set_url($query);
        $query_obj->set_query_type($query_type);
        $query_obj->update();
324
    } else {
325 326 327 328 329 330
        Bugzilla::Search::Saved->create({
            name           => $query_name,
            query          => $query,
            query_type     => $query_type,
            link_in_footer => $link_in_footer
        });
331 332
    }

333
    return $query_obj ? 1 : 0;
334 335
}

336 337 338 339 340 341
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 " .
342 343
                                       "WHERE series_id = ?"
                                       , undef, ($series_id));
344 345 346 347 348
    $result
           || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
    return $result;
}

349
sub GetQuip {
350
    my $dbh = Bugzilla->dbh;
351 352
    # COUNT is quick because it is cached for MySQL. We may want to revisit
    # this when we support other databases.
353 354
    my $count = $dbh->selectrow_array("SELECT COUNT(quip)"
                                    . " FROM quips WHERE approved = 1");
355
    my $random = int(rand($count));
356
    my $quip = 
357 358
        $dbh->selectrow_array("SELECT quip FROM quips WHERE approved = 1 " . 
                              $dbh->sql_limit(1, $random));
359
    return $quip;
360
}
361

362
# Return groups available for at least one product of the buglist.
363
sub GetGroups {
364
    my $product_names = shift;
365
    my $user = Bugzilla->user;
366 367 368 369 370 371 372 373 374 375 376 377 378
    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);
379

380 381 382 383 384 385 386
            # 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];
387
}
388

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
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);
    }
}

405

406 407 408
################################################################################
# Command Execution
################################################################################
409

410 411
my $cmdtype   = $cgi->param('cmdtype')   || '';
my $remaction = $cgi->param('remaction') || '';
412

413 414
# Backwards-compatibility - the old interface had cmdtype="runnamed" to run
# a named command, and we can't break this because it's in bookmarks.
415 416 417
if ($cmdtype eq "runnamed") {  
    $cmdtype = "dorem";
    $remaction = "run";
418 419
}

420 421 422 423 424 425
# 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);
426

427 428 429 430 431 432 433 434
# 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}";
435
if ($cmdtype eq "dorem" && $remaction =~ /^run/) {
436
    $filename = $cgi->param('namedcmd') . "-$date.$format->{extension}";
437 438 439 440
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}
441 442
$filename =~ s/\\/\\\\/g; # escape backslashes
$filename =~ s/"/\\"/g; # escape quotes
443

444
# Take appropriate action based on user's request.
445 446
if ($cmdtype eq "dorem") {  
    if ($remaction eq "run") {
447 448 449
        my $query_id;
        ($buffer, $query_id) = LookupNamedQuery(scalar $cgi->param("namedcmd"),
                                                scalar $cgi->param('sharer_id'));
450 451
        # If this is the user's own query, remember information about it
        # so that it can be modified easily.
452
        $vars->{'searchname'} = $cgi->param('namedcmd');
453 454 455
        if (!$cgi->param('sharer_id') ||
            $cgi->param('sharer_id') == Bugzilla->user->id) {
            $vars->{'searchtype'} = "saved";
456
            $vars->{'search_id'} = $query_id;
457
        }
458
        $params = new Bugzilla::CGI($buffer);
459
        $order = $params->param('order') || $order;
460

461
    }
462
    elsif ($remaction eq "runseries") {
463
        $buffer = LookupSeries(scalar $cgi->param("series_id"));
464
        $vars->{'searchname'} = $cgi->param('namedcmd');
465
        $vars->{'searchtype'} = "series";
466
        $params = new Bugzilla::CGI($buffer);
467 468
        $order = $params->param('order') || $order;
    }
469
    elsif ($remaction eq "forget") {
470
        my $user = Bugzilla->login(LOGIN_REQUIRED);
471 472 473
        # 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.
474
        my $qname = $cgi->param('namedcmd');
475
        trick_taint($qname);
476 477 478 479 480 481 482 483 484 485 486 487

        # 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
                                                      = ?
488
                                      ', undef, $user->id, $qname);
489 490 491 492 493 494 495 496
        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
497 498 499 500 501 502 503 504
        my ($query_id) = $dbh->selectrow_array('SELECT id FROM namedqueries
                                                    WHERE userid = ?
                                                      AND name   = ?',
                                                  undef, ($user->id, $qname));
        if (!$query_id) {
            # The user has no query of this name. Play along.
        }
        else {
505 506 507 508
            # Make sure the user really wants to delete his saved search.
            my $token = $cgi->param('token');
            check_hash_token($token, [$query_id, $qname]);

509 510 511 512 513 514 515 516 517 518
            $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);
        }
519 520

        # Now reset the cached queries
521
        $user->flush_queries_cache();
522

523
        print $cgi->header();
524
        # Generate and return the UI (HTML page) from the appropriate template.
525
        $vars->{'message'} = "buglist_query_gone";
526
        $vars->{'namedcmd'} = $qname;
527 528
        $vars->{'url'} = "query.cgi";
        $template->process("global/message.html.tmpl", $vars)
529
          || ThrowTemplateError($template->error());
530
        exit;
531 532
    }
}
533
elsif (($cmdtype eq "doit") && defined $cgi->param('remtype')) {
534
    if ($cgi->param('remtype') eq "asdefault") {
535
        my $user = Bugzilla->login(LOGIN_REQUIRED);
536
        InsertNamedQuery(DEFAULT_QUERY_NAME, $buffer);
537
        $vars->{'message'} = "buglist_new_default_query";
538
    }
539
    elsif ($cgi->param('remtype') eq "asnamed") {
540
        my $user = Bugzilla->login(LOGIN_REQUIRED);
541
        my $query_name = $cgi->param('newqueryname');
542 543
        my $new_query = $cgi->param('newquery');
        my $query_type = QUERY_LIST;
544 545 546 547 548 549 550 551 552 553 554 555 556
        # 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');
557 558
            }

559
            my %bug_ids;
560
            my $is_new_name = 0;
561
            if ($query_name) {
562 563
                my ($query, $query_id) =
                  LookupNamedQuery($query_name, undef, QUERY_LIST, !THROW_ERROR);
564
                # Make sure this name is not already in use by a normal saved search.
565 566 567
                if ($query) {
                    ThrowUserError('query_name_exists', {name     => $query_name,
                                                         query_id => $query_id});
568
                }
569
                $is_new_name = 1;
570
            }
571 572 573 574 575 576 577 578
            # 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).
            if (my $old_query = LookupNamedQuery($query_name, undef, LIST_OF_BUGS, !$is_new_name)) {
579 580 581
                # 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')) {
582 583 584
                    $bug_ids{$bug_id} = 1 if detaint_natural($bug_id);
                }
            }
585 586 587 588 589

            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;
590 591
                my $bug = Bugzilla::Bug->check($bug_id);
                $bug_ids{$bug->id} = $keep_bug;
592 593
                $changes = 1;
            }
594 595 596 597
            ThrowUserError('no_bug_ids',
                           {'action' => $action,
                            'tag' => $query_name})
              unless $changes;
598 599 600 601

            # 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.
602
            ThrowUserError('no_bugs_in_list', {'tag' => $query_name})
603 604 605
              unless scalar(@bug_ids);

            $new_query = "bug_id=" . join(',', sort {$a <=> $b} @bug_ids);
606 607
            $query_type = LIST_OF_BUGS;
        }
608
        my $tofooter = 1;
609
        my $existed_before = InsertNamedQuery($query_name, $new_query,
610
                                              $tofooter, $query_type);
611
        if ($existed_before) {
612 613
            $vars->{'message'} = "buglist_updated_named_query";
        }
614
        else {
615
            $vars->{'message'} = "buglist_new_named_query";
616
        }
617 618 619

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

622
        $vars->{'queryname'} = $query_name;
623
        
624
        print $cgi->header();
625 626 627
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
628
    }
terry%netscape.com's avatar
terry%netscape.com committed
629 630
}

631 632 633 634 635
# 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');
636
    $buffer = $params->query_string;
637
}
terry%netscape.com's avatar
terry%netscape.com committed
638

639 640 641 642
################################################################################
# Column Definition
################################################################################

643
my $columns = Bugzilla::Search::COLUMNS;
644

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

673
    # Use the columns listed in the user's preferences.
674
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
675
}
676 677
else {
    # Use the default list of columns.
678
    @displaycolumns = DEFAULT_COLUMN_LIST;
679 680
}

681 682 683 684
# 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);
685

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

690 691 692
# Add the votes column to the list of columns to be displayed
# in the bug list if the user is searching for bugs with a certain
# number of votes and the votes column is not already on the list.
693 694

# Some versions of perl will taint 'votes' if this is done as a single
695 696 697 698
# statement, because the votes param is tainted at this point
my $votes = $params->param('votes');
$votes ||= "";
if (trim($votes) && !grep($_ eq 'votes', @displaycolumns)) {
699 700
    push(@displaycolumns, 'votes');
}
terry%netscape.com's avatar
terry%netscape.com committed
701

702 703
# 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)
704
if (!Bugzilla->user->in_group(Bugzilla->params->{"timetrackinggroup"})) {
705 706 707 708
   @displaycolumns = grep($_ ne 'estimated_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'remaining_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'actual_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'percentage_complete', @displaycolumns);
709
   @displaycolumns = grep($_ ne 'deadline', @displaycolumns);
710
}
terry%netscape.com's avatar
terry%netscape.com committed
711

712 713 714 715 716 717
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


718 719 720
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
721

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

724
# The bug ID is always selected because bug IDs are always displayed.
725 726 727 728
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
                     "resolution");
729

730
# if using classification, we also need to look in product.classification_id
731
if (Bugzilla->params->{"useclassification"}) {
732 733 734
    push (@selectcolumns,"product");
}

735
# remaining and actual_time are required for percentage_complete calculation:
736
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
737 738 739 740
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

741 742 743 744 745 746 747 748 749 750 751 752
# 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);
    }
}

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

758 759 760 761 762
# If the user is editing multiple bugs, we also make sure to select the product
# and status because the values of those fields determine what options the user
# has for modifying the bugs.
if ($dotweak) {
    push(@selectcolumns, "product") if !grep($_ eq 'product', @selectcolumns);
763
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
764 765
}

766 767 768
if ($format->{'extension'} eq 'ics') {
    push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
}
769

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

774 775
    # This is the list of fields that are needed by the Atom filter.
    my @required_atom_columns = (
776 777 778 779 780 781 782
      'short_desc',
      'opendate',
      'changeddate',
      'reporter_realname',
      'priority',
      'bug_severity',
      'assigned_to_realname',
783 784 785 786
      'bug_status',
      'product',
      'component',
      'resolution'
787
    );
788
    push(@required_atom_columns, 'target_milestone') if Bugzilla->params->{'usetargetmilestone'};
789

790
    foreach my $required (@required_atom_columns) {
791 792 793 794
        push(@selectcolumns, $required) if !grep($_ eq $required,@selectcolumns);
    }
}

795 796 797
################################################################################
# Sort Order Determination
################################################################################
798

799
# Add to the query some instructions for sorting the bug list.
800 801 802 803 804 805

# 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');
806 807 808 809
       
        # Cookies from early versions of Specific Search included this text,
        # which is now invalid.
        $order =~ s/ LIMIT 200//;
810 811 812 813
    }
    else {
        $order = '';  # Remove possible "reuse" identifier as unnecessary
    }
814
}
815

816 817 818 819
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
820
        /^Bug Number$/ && do {
821
            $order = "bug_id";
822 823 824
            last ORDER;
        };
        /^Importance$/ && do {
825
            $order = "priority,bug_severity";
826 827 828
            last ORDER;
        };
        /^Assignee$/ && do {
829
            $order = "assigned_to,bug_status,priority,bug_id";
830 831 832
            last ORDER;
        };
        /^Last Changed$/ && do {
833
            $order = "changeddate,bug_status,priority,assigned_to,bug_id";
834 835 836
            last ORDER;
        };
        do {
837
            my (@order, @invalid_fragments);
838

839
            # A custom list of columns.  Make sure each column is valid.
840 841
            foreach my $fragment (split(/,/, $order)) {
                $fragment = trim($fragment);
842
                next unless $fragment;
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
                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 we are sorting by votes, sort in descending order if
                # no explicit sort order was given.
                if ($column_name eq 'votes' && !$direction) {
                    $direction = "DESC";
                }

                if (exists $columns->{$column_name}) {
                    $direction = " $direction" if $direction;
                    push(@order, "$column_name$direction");
858 859
                }
                else {
860
                    push(@invalid_fragments, $fragment);
861 862
                }
            }
863 864 865 866 867
            if (scalar @invalid_fragments) {
                $vars->{'message'} = 'invalid_column_name';
                $vars->{'invalid_fragments'} = \@invalid_fragments;
            }

868
            $order = join(",", @order);
869 870
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
871
            trick_taint($order) if $order;
872
        };
terry%netscape.com's avatar
terry%netscape.com committed
873
    }
874
}
875 876

if (!$order) {
877
    # DEFAULT
878
    $order = "bug_status,priority,assigned_to,bug_id";
879
}
880

881
my @orderstrings = split(/,\s*/, $order);
882

883
# Generate the basic SQL query that will be used to generate the bug list.
884
my $search = new Bugzilla::Search('fields' => \@selectcolumns, 
885 886
                                  'params' => $params,
                                  'order' => \@orderstrings);
887
my $query = $search->getSQL();
888
$vars->{'search_description'} = $search->search_description;
889

890 891 892 893 894
if (defined $cgi->param('limit')) {
    my $limit = $cgi->param('limit');
    if (detaint_natural($limit)) {
        $query .= " " . $dbh->sql_limit($limit);
    }
895 896
}
elsif ($fulltext) {
897
    $query .= " " . $dbh->sql_limit(FULLTEXT_BUGLIST_LIMIT);
898
    $vars->{'message'} = 'buglist_sorted_by_relevance' if ($cgi->param('order') =~ /^relevance/);
899 900
}

901

902 903 904
################################################################################
# Query Execution
################################################################################
905

906
if ($cgi->param('debug')) {
907 908
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
909 910 911 912 913 914 915
    # 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);
    }
916 917
}

918 919 920
# 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) {
921 922
    print $cgi->multipart_init();
    print $cgi->multipart_start(-type => 'text/html');
923

924
    # Generate and return the UI (HTML page) from the appropriate template.
925 926
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
927

928 929 930 931 932 933
    # Under mod_perl, flush stdout so that the page actually shows up.
    if ($ENV{MOD_PERL}) {
        require Apache2::RequestUtil;
        Apache2::RequestUtil->request->rflush();
    }

934 935 936
    # 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
937 938
}

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

943
# Normally, we ignore SIGTERM and SIGPIPE, but we need to
944 945 946 947 948
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

949
# Execute the query.
950 951
my $buglist_sth = $dbh->prepare($query);
$buglist_sth->execute();
952

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

954 955 956
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
957

958 959
# 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
960

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
# 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),
                };
    
977 978 979
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
980
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
981

982
my @bugs; # the list of records
983

984
while (my @row = $buglist_sth->fetchrow_array()) {
985
    my $bug = {}; # a record
986

987
    # Slurp the row of data into the record.
988 989
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
990
    foreach my $column (@selectcolumns) {
991
        $bug->{$column} = shift @row;
992
    }
terry%netscape.com's avatar
terry%netscape.com committed
993

994 995 996
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
997
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
998

999 1000
        $bug->{'changedtime'} = $bug->{'changeddate'}; # for iCalendar and Atom
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});
1001 1002 1003
    }

    if ($bug->{'opendate'}) {
1004
        $bug->{'opentime'} = $bug->{'opendate'}; # for iCalendar
1005
        $bug->{'opendate'} = DiffDate($bug->{'opendate'});
1006
    }
terry%netscape.com's avatar
terry%netscape.com committed
1007

1008
    # Record the assignee, product, and status in the big hashes of those things.
1009
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
1010
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
1011
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
1012

1013
    $bug->{'secure_mode'} = undef;
1014

1015 1016
    # Add the record to the list.
    push(@bugs, $bug);
1017 1018

    # Add id to list for checking for bug privacy later
1019
    push(@bugidlist, $bug->{'bug_id'});
1020 1021 1022 1023 1024

    # 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);
1025 1026
}

1027 1028 1029 1030
# 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;
1031
if (@bugidlist) {
1032
    my $sth = $dbh->prepare(
1033 1034 1035 1036 1037 1038 1039
        "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 " .
1040
         "WHERE " . $dbh->sql_in('bugs.bug_id', \@bugidlist) . 
1041
            $dbh->sql_group_by('bugs.bug_id'));
1042 1043
    $sth->execute();
    while (my ($bug_id, $min_membercontrol) = $sth->fetchrow_array()) {
1044
        $min_membercontrol{$bug_id} = $min_membercontrol || CONTROLMAPNA;
1045 1046
    }
    foreach my $bug (@bugs) {
1047
        next unless defined($min_membercontrol{$bug->{'bug_id'}});
1048
        if ($min_membercontrol{$bug->{'bug_id'}} == CONTROLMAPMANDATORY) {
1049
            $bug->{'secure_mode'} = 'implied';
1050
        }
1051 1052 1053
        else {
            $bug->{'secure_mode'} = 'manual';
        }
1054 1055
    }
}
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065
# 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
}                             

1066 1067 1068
################################################################################
# Template Variable Definition
################################################################################
1069

1070
# Define the variables and functions that will be passed to the UI template.
1071

1072
$vars->{'bugs'} = \@bugs;
1073
$vars->{'buglist'} = \@bugidlist;
1074
$vars->{'buglist_joined'} = join(',', @bugidlist);
1075 1076
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
1077

1078
$vars->{'openstates'} = [BUG_STATE_OPEN];
1079
$vars->{'closedstates'} = [map {$_->name} closed_bug_statuses()];
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
# 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++;
    }
}

1092 1093 1094
# 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
1095 1096 1097 1098 1099
# 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');
1100
$vars->{'order'} = $order;
1101
$vars->{'caneditbugs'} = 1;
1102
$vars->{'time_info'} = $time_info;
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

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
1113

1114
my @bugowners = keys %$bugowners;
1115
if (scalar(@bugowners) > 1 && Bugzilla->user->in_group('editbugs')) {
1116
    my $suffix = Bugzilla->params->{'emailsuffix'};
1117 1118 1119
    map(s/$/$suffix/, @bugowners) if $suffix;
    my $bugowners = join(",", @bugowners);
    $vars->{'bugowners'} = $bugowners;
terry%netscape.com's avatar
terry%netscape.com committed
1120 1121
}

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

1126
$vars->{'quip'} = GetQuip();
1127
$vars->{'currenttime'} = localtime(time());
1128 1129

# The following variables are used when the user is making changes to multiple bugs.
1130
if ($dotweak && scalar @bugs) {
1131 1132 1133 1134 1135 1136
    if (!$vars->{'caneditbugs'}) {
        _close_standby_message('text/html', 'inline', $serverpush);
        ThrowUserError('auth_failure', {group  => 'editbugs',
                                        action => 'modify',
                                        object => 'multiple_bugs'});
    }
1137
    $vars->{'dotweak'} = 1;
1138
    $vars->{'use_keywords'} = 1 if Bugzilla::Keyword::keyword_count();
1139 1140 1141
  
    # issue_session_token needs to write to the master DB.
    Bugzilla->switch_to_main_db();
1142
    $vars->{'token'} = issue_session_token('buglist_mass_change');
1143
    Bugzilla->switch_to_shadow_db();
1144

1145
    $vars->{'products'} = Bugzilla->user->get_enterable_products;
1146 1147 1148 1149
    $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');
1150
    $vars->{'resolutions'} = get_legal_field_values('resolution');
1151

1152 1153 1154 1155
    # 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
1156
                               WHERE ' . $dbh->sql_in('value', \@bug_statuses));
1157 1158 1159 1160

    # 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 =
1161
      $dbh->selectcol_arrayref(
1162
            'SELECT DISTINCT sw1.new_status
1163
               FROM status_workflow sw1
1164 1165 1166 1167
         INNER JOIN bug_status
                 ON bug_status.id = sw1.new_status
              WHERE bug_status.isactive = 1
                AND NOT EXISTS 
1168 1169 1170 1171 1172 1173 1174 1175
                   (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))');
1176 1177 1178

    $vars->{'current_bug_statuses'} = [keys %$bugstatuses];
    $vars->{'new_bug_statuses'} = Bugzilla::Status->new_from_list($bug_status_ids);
1179 1180 1181 1182

    # The groups the user belongs to and which are editable for the given buglist.
    my @products = keys %$bugproducts;
    $vars->{'groups'} = GetGroups(\@products);
1183 1184 1185 1186 1187

    # 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.
1188 1189
    if (scalar(@products) == 1) {
        my $product = new Bugzilla::Product({name => $products[0]});
1190 1191 1192
        $vars->{'versions'} = [map($_->name ,@{$product->versions})];
        $vars->{'components'} = [map($_->name, @{$product->components})];
        $vars->{'targetmilestones'} = [map($_->name, @{$product->milestones})]
1193
            if Bugzilla->params->{'usetargetmilestone'};
terry%netscape.com's avatar
terry%netscape.com committed
1194 1195
    }
}
1196

1197 1198 1199 1200
# 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');

1201

1202 1203 1204
################################################################################
# HTTP Header Generation
################################################################################
1205

1206
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
1207

1208
my $contenttype;
1209
my $disposition = "inline";
terry%netscape.com's avatar
terry%netscape.com committed
1210

1211
if ($format->{'extension'} eq "html" && !$agent) {
1212
    if ($order && !$cgi->param('sharer_id')) {
1213
        $cgi->send_cookie(-name => 'LASTORDER',
1214
                          -value => $order,
1215
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1216
    }
1217
    my $bugids = join(":", @bugidlist);
1218
    # See also Bug 111999
1219 1220 1221 1222
    if (length($bugids) == 0) {
        $cgi->remove_cookie('BUGLIST');
    }
    elsif (length($bugids) < 4000) {
1223 1224 1225
        $cgi->send_cookie(-name => 'BUGLIST',
                          -value => $bugids,
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1226
    }
1227
    else {
1228
        $cgi->remove_cookie('BUGLIST');
1229
        $vars->{'toolong'} = 1;
terry%netscape.com's avatar
terry%netscape.com committed
1230
    }
1231 1232

    $contenttype = "text/html";
1233 1234
}
else {
1235
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
1236 1237
}

1238 1239 1240
if ($format->{'extension'} eq "csv") {
    # We set CSV files to be downloaded, as they are designed for importing
    # into other programs.
1241
    $disposition = "attachment";
1242 1243
}

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

1247
_close_standby_message($contenttype, $disposition, $serverpush);
1248

1249 1250 1251
################################################################################
# Content Generation
################################################################################
1252

1253
# Generate and return the UI (HTML page) from the appropriate template.
1254
$template->process($format->{'template'}, $vars)
1255
  || ThrowTemplateError($template->error());
1256

1257

1258 1259 1260 1261
################################################################################
# Script Conclusion
################################################################################

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