buglist.cgi 51.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 36
use lib qw(.);

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

50 51
use Date::Parse;

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

58 59 60 61 62
# 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();

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

68 69 70 71 72 73 74 75 76
# 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.
}

77
# If configured to not allow empty words, reject empty searches from the
78 79 80
# Find a Specific Bug search form, including words being a single or 
# several consecutive whitespaces only.
if (!Bugzilla->params->{'specific_search_allow_empty_words'}
81 82
    && defined($cgi->param('content')) && $cgi->param('content') =~ /^\s*$/)
{
83 84 85
    ThrowUserError("buglist_parameters_required");
}

86 87 88
################################################################################
# Data and Security Validation
################################################################################
89

90
# Whether or not the user wants to change multiple bugs.
91
my $dotweak = $cgi->param('tweak') ? 1 : 0;
92 93 94

# Log the user in
if ($dotweak) {
95
    Bugzilla->login(LOGIN_REQUIRED);
96
    Bugzilla->user->in_group("editbugs")
97 98 99
      || ThrowUserError("auth_failure", {group  => "editbugs",
                                         action => "modify",
                                         object => "multiple_bugs"});
100 101
}

102
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
103 104 105 106
if (defined $cgi->param('format') && $cgi->param('format') eq "rdf"
    && !defined $cgi->param('ctype')) {
    $cgi->param('ctype', "rdf");
    $cgi->delete('format');
107
}
108

109 110 111 112 113
# Treat requests for ctype=rss as requests for ctype=atom
if (defined $cgi->param('ctype') && $cgi->param('ctype') eq "rss") {
    $cgi->param('ctype', "atom");
}

114 115 116 117 118 119
# 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.
120
if ((defined $cgi->param('ctype')) && ($cgi->param('ctype') eq "js")) {
121
    Bugzilla->logout_request();
122
}
123

124 125 126 127 128 129 130
# 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/);

131 132 133
# 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.
134 135
my $format = $template->get_format("list/list", scalar $cgi->param('format'),
                                   scalar $cgi->param('ctype'));
136

137 138 139 140 141 142 143 144
# 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. 
# Even Communicator 4.51 has bugs with it, especially during page reload.
# http://www.browsercaps.org used as source of compatible browsers.
145 146
# Safari (WebKit) does not support it, despite a UA that says otherwise (bug 188712)
# MSIE 5+ supports it on Mac (but not on Windows) (bug 190370)
147 148
#
my $serverpush =
149 150 151
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
152
        && (($ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/) || ($ENV{'HTTP_USER_AGENT'} =~ /MSIE 5.*Mac_PowerPC/))
153
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
154 155 156
            && !$agent
              && !defined($cgi->param('serverpush'))
                || $cgi->param('serverpush');
157

158
my $order = $cgi->param('order') || "";
159
my $order_from_cookie = 0;  # True if $order set using the LASTORDER cookie
160

161 162 163
# The params object to use for the actual query itself
my $params;

164 165
# 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.
166
if (defined $cgi->param('regetlastlist')) {
167
    $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
168

169
    $order = "reuse last sort" unless $order;
170 171
    my $bug_id = $cgi->cookie('BUGLIST');
    $bug_id =~ s/:/,/g;
172 173
    # set up the params for this new query
    $params = new Bugzilla::CGI({
174
                                 bug_id => $bug_id,
175 176
                                 order => $order,
                                });
177 178
}

179 180
if ($buffer =~ /&cmd-/) {
    my $url = "query.cgi?$buffer#chart";
181
    print $cgi->redirect(-location => $url);
182
    # Generate and return the UI (HTML page) from the appropriate template.
183
    $vars->{'message'} = "buglist_adding_field";
184 185
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
186
      || ThrowTemplateError($template->error());
187 188
    exit;
}
189

190 191 192 193
# 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;
194
if ($cgi->param('content')) { $fulltext = 1 }
195
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
196
foreach my $chart (@charts) {
197
    if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
198 199 200 201 202
        $fulltext = 1;
        last;
    }
}

203 204 205 206
################################################################################
# Utilities
################################################################################

207
local our @weekday= qw( Sun Mon Tue Wed Thu Fri Sat );
208 209 210 211 212 213 214 215 216 217 218 219 220 221
sub DiffDate {
    my ($datestr) = @_;
    my $date = str2time($datestr);
    my $age = time() - $date;
    my ($s,$m,$h,$d,$mo,$y,$wd)= localtime $date;
    if( $age < 18*60*60 ) {
        $date = sprintf "%02d:%02d:%02d", $h,$m,$s;
    } elsif( $age < 6*24*60*60 ) {
        $date = sprintf "%s %02d:%02d", $weekday[$wd],$h,$m;
    } else {
        $date = sprintf "%04d-%02d-%02d", 1900+$y,$mo+1,$d;
    }
    return $date;
}
222

223
sub LookupNamedQuery {
224
    my ($name, $sharer_id, $query_type, $throw_error) = @_;
225
    my $user = Bugzilla->login(LOGIN_REQUIRED);
226
    my $dbh = Bugzilla->dbh;
227
    my $owner_id;
228
    $throw_error = 1 unless defined $throw_error;
229 230 231

    # $name and $sharer_id are safe -- we only use them below in SELECT
    # placeholders and then in error messages (which are always HTML-filtered).
232
    $name || ThrowUserError("query_name_missing");
233
    trick_taint($name);
234 235
    if ($sharer_id) {
        $owner_id = $sharer_id;
236 237
        detaint_natural($owner_id);
        $owner_id || ThrowUserError('illegal_user_id', {'userid' => $sharer_id});
238 239 240 241 242
    }
    else {
        $owner_id = $user->id;
    }

243 244 245 246 247 248 249 250 251
    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
252
                                                 FROM namedqueries
253 254 255
                                                WHERE userid = ? AND name = ?
                                                      $extra",
                                               undef, @args);
256 257 258 259 260
    if (!defined($result)) {
        return 0 unless $throw_error;
        ThrowUserError("missing_query", {'queryname' => $name,
                                         'sharer_id' => $sharer_id});
    }
261 262 263 264 265 266 267 268 269 270 271

    if ($sharer_id) {
        my $group = $dbh->selectrow_array('SELECT group_id
                                             FROM namedquery_group_map
                                            WHERE namedquery_id = ?',
                                          undef, $id);
        if (!grep {$_ == $group} values(%{$user->groups()})) {
            ThrowUserError("missing_query", {'queryname' => $name,
                                             'sharer_id' => $sharer_id});
        }
    }
272 273 274 275
    
    $result
       || ThrowUserError("buglist_parameters_required", {'queryname' => $name});

276 277 278
    return $result;
}

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

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

    if ($query_obj) {
        $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
sub GetGroups {
349
    my $dbh = Bugzilla->dbh;
350
    my $user = Bugzilla->user;
351

352 353 354
    # Create an array where each item is a hash. The hash contains 
    # as keys the name of the columns, which point to the value of 
    # the columns for that row.
355
    my $grouplist = $user->groups_as_string;
356
    my $groups = $dbh->selectall_arrayref(
357
                "SELECT  id, name, description, isactive
358
                   FROM  groups
359
                  WHERE  id IN ($grouplist)
360
                    AND  isbuggroup = 1
361
               ORDER BY  description "
362
               , {Slice => {}});
363

364
    return $groups;
365
}
366

367

368 369 370
################################################################################
# Command Execution
################################################################################
371

372 373
$cgi->param('cmdtype', "") if !defined $cgi->param('cmdtype');
$cgi->param('remaction', "") if !defined $cgi->param('remaction');
374

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

382 383 384 385 386 387
# 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);
388

389 390 391 392 393 394 395 396
# 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}";
397 398
if ($cgi->param('cmdtype') eq "dorem" && $cgi->param('remaction') =~ /^run/) {
    $filename = $cgi->param('namedcmd') . "-$date.$format->{extension}";
399 400 401 402
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}
403 404
$filename =~ s/\\/\\\\/g; # escape backslashes
$filename =~ s/"/\\"/g; # escape quotes
405

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

421
    }
422
    elsif ($cgi->param('remaction') eq "runseries") {
423
        $buffer = LookupSeries(scalar $cgi->param("series_id"));
424
        $vars->{'searchname'} = $cgi->param('namedcmd');
425
        $vars->{'searchtype'} = "series";
426
        $params = new Bugzilla::CGI($buffer);
427 428
        $order = $params->param('order') || $order;
    }
429
    elsif ($cgi->param('remaction') eq "forget") {
430
        my $user = Bugzilla->login(LOGIN_REQUIRED);
431 432 433
        # 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.
434
        my $qname = $cgi->param('namedcmd');
435
        trick_taint($qname);
436 437 438 439 440 441 442 443 444 445 446 447

        # 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
                                                      = ?
448
                                      ', undef, $user->id, $qname);
449 450 451 452 453 454 455 456
        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
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        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 {
            $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);
        }
475 476

        # Now reset the cached queries
477
        $user->flush_queries_cache();
478

479
        print $cgi->header();
480
        # Generate and return the UI (HTML page) from the appropriate template.
481
        $vars->{'message'} = "buglist_query_gone";
482
        $vars->{'namedcmd'} = $qname;
483 484
        $vars->{'url'} = "query.cgi";
        $template->process("global/message.html.tmpl", $vars)
485
          || ThrowTemplateError($template->error());
486
        exit;
487 488
    }
}
489 490
elsif (($cgi->param('cmdtype') eq "doit") && defined $cgi->param('remtype')) {
    if ($cgi->param('remtype') eq "asdefault") {
491
        my $user = Bugzilla->login(LOGIN_REQUIRED);
492
        InsertNamedQuery(DEFAULT_QUERY_NAME, $buffer);
493
        $vars->{'message'} = "buglist_new_default_query";
494
    }
495
    elsif ($cgi->param('remtype') eq "asnamed") {
496
        my $user = Bugzilla->login(LOGIN_REQUIRED);
497
        my $query_name = $cgi->param('newqueryname');
498 499
        my $new_query = $cgi->param('newquery');
        my $query_type = QUERY_LIST;
500 501 502 503 504 505 506 507 508 509 510 511 512
        # 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');
513 514
            }

515
            my %bug_ids;
516
            my $is_new_name = 0;
517 518 519 520 521
            if ($query_name) {
                # Make sure this name is not already in use by a normal saved search.
                if (LookupNamedQuery($query_name, undef, QUERY_LIST, !THROW_ERROR)) {
                    ThrowUserError('query_name_exists', {'name' => $query_name});
                }
522
                $is_new_name = 1;
523
            }
524 525 526 527 528 529 530 531
            # 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)) {
532 533 534
                # 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')) {
535 536 537
                    $bug_ids{$bug_id} = 1 if detaint_natural($bug_id);
                }
            }
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

            my $keep_bug = ($action eq 'add') ? 1 : 0;
            my $changes = 0;
            foreach my $bug_id (split(/[\s,]+/, $cgi->param('bug_ids'))) {
                next unless $bug_id;
                ValidateBugID($bug_id);
                $bug_ids{$bug_id} = $keep_bug;
                $changes = 1;
            }
            ThrowUserError('no_bug_ids', {'action' => $action}) unless $changes;

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

            $new_query = "bug_id=" . join(',', sort {$a <=> $b} @bug_ids);
556 557
            $query_type = LIST_OF_BUGS;
        }
558
        my $tofooter = 1;
559
        my $existed_before = InsertNamedQuery($query_name, $new_query,
560
                                              $tofooter, $query_type);
561
        if ($existed_before) {
562 563
            $vars->{'message'} = "buglist_updated_named_query";
        }
564
        else {
565
            $vars->{'message'} = "buglist_new_named_query";
566
        }
567 568 569

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

572
        $vars->{'queryname'} = $query_name;
573
        
574
        print $cgi->header();
575 576 577
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
578
    }
terry%netscape.com's avatar
terry%netscape.com committed
579 580
}

581 582 583 584 585
# 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');
586
    $buffer = $params->query_string;
587
}
terry%netscape.com's avatar
terry%netscape.com committed
588

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
################################################################################
# Column Definition
################################################################################

# Define the columns that can be selected in a query and/or displayed in a bug
# list.  Column records include the following fields:
#
# 1. ID: a unique identifier by which the column is referred in code;
#
# 2. Name: The name of the column in the database (may also be an expression
#          that returns the value of the column);
#
# 3. Title: The title of the column as displayed to users.
# 
# Note: There are a few hacks in the code that deviate from these definitions.
#       In particular, when the list is sorted by the "votes" field the word 
#       "DESC" is added to the end of the field to sort in descending order, 
606
#       and the redundant short_desc column is removed when the client
607
#       requests "all" columns.
608 609
# Note: For column names using aliasing (SQL "<field> AS <alias>"), the column
#       ID needs to be identical to the field ID for list ordering to work.
610

611
local our $columns = {};
612 613 614
sub DefineColumn {
    my ($id, $name, $title) = @_;
    $columns->{$id} = { 'name' => $name , 'title' => $title };
615
}
616

617
# Column:     ID                    Name                           Title
618
DefineColumn("bug_id"            , "bugs.bug_id"                , "ID"               );
619
DefineColumn("alias"             , "bugs.alias"                 , "Alias"            );
620 621
DefineColumn("opendate"          , "bugs.creation_ts"           , "Opened"           );
DefineColumn("changeddate"       , "bugs.delta_ts"              , "Changed"          );
622
DefineColumn("bug_severity"      , "bugs.bug_severity"          , "Severity"         );
623
DefineColumn("priority"          , "bugs.priority"              , "Priority"         );
624 625
DefineColumn("rep_platform"      , "bugs.rep_platform"          , "Hardware"         );
DefineColumn("assigned_to"       , "map_assigned_to.login_name" , "Assignee"         );
626 627
DefineColumn("reporter"          , "map_reporter.login_name"    , "Reporter"         );
DefineColumn("qa_contact"        , "map_qa_contact.login_name"  , "QA Contact"       );
628
if ($format->{'extension'} eq 'html') {
629 630 631
    DefineColumn("assigned_to_realname", "CASE WHEN map_assigned_to.realname = '' THEN map_assigned_to.login_name ELSE map_assigned_to.realname END AS assigned_to_realname", "Assignee"  );
    DefineColumn("reporter_realname"   , "CASE WHEN map_reporter.realname    = '' THEN map_reporter.login_name    ELSE map_reporter.realname    END AS reporter_realname"   , "Reporter"  );
    DefineColumn("qa_contact_realname" , "CASE WHEN map_qa_contact.realname  = '' THEN map_qa_contact.login_name  ELSE map_qa_contact.realname  END AS qa_contact_realname" , "QA Contact");
632
} else {
633 634 635
    DefineColumn("assigned_to_realname", "map_assigned_to.realname AS assigned_to_realname", "Assignee"  );
    DefineColumn("reporter_realname"   , "map_reporter.realname AS reporter_realname"      , "Reporter"  );
    DefineColumn("qa_contact_realname" , "map_qa_contact.realname AS qa_contact_realname"  , "QA Contact");
636
}
637
DefineColumn("bug_status"        , "bugs.bug_status"            , "Status"           );
638
DefineColumn("resolution"        , "bugs.resolution"            , "Resolution"       );
639 640
DefineColumn("short_short_desc"  , "bugs.short_desc"            , "Summary"          );
DefineColumn("short_desc"        , "bugs.short_desc"            , "Summary"          );
641
DefineColumn("status_whiteboard" , "bugs.status_whiteboard"     , "Whiteboard"       );
642 643
DefineColumn("component"         , "map_components.name"        , "Component"        );
DefineColumn("product"           , "map_products.name"          , "Product"          );
644
DefineColumn("classification"    , "map_classifications.name"   , "Classification"   );
645
DefineColumn("version"           , "bugs.version"               , "Version"          );
646
DefineColumn("op_sys"            , "bugs.op_sys"                , "OS"               );
647 648 649
DefineColumn("target_milestone"  , "bugs.target_milestone"      , "Target Milestone" );
DefineColumn("votes"             , "bugs.votes"                 , "Votes"            );
DefineColumn("keywords"          , "bugs.keywords"              , "Keywords"         );
650 651 652
DefineColumn("estimated_time"    , "bugs.estimated_time"        , "Estimated Hours"  );
DefineColumn("remaining_time"    , "bugs.remaining_time"        , "Remaining Hours"  );
DefineColumn("actual_time"       , "(SUM(ldtime.work_time)*COUNT(DISTINCT ldtime.bug_when)/COUNT(bugs.bug_id)) AS actual_time", "Actual Hours");
653 654 655 656 657 658 659
DefineColumn("percentage_complete",
    "(CASE WHEN (SUM(ldtime.work_time)*COUNT(DISTINCT ldtime.bug_when)/COUNT(bugs.bug_id)) " .
    "            + bugs.remaining_time = 0.0 " .
    "THEN 0.0 " .
    "ELSE 100*((SUM(ldtime.work_time)*COUNT(DISTINCT ldtime.bug_when)/COUNT(bugs.bug_id)) " .
    "     /((SUM(ldtime.work_time)*COUNT(DISTINCT ldtime.bug_when)/COUNT(bugs.bug_id)) + bugs.remaining_time)) " .
    "END) AS percentage_complete"                               , "% Complete"); 
660
DefineColumn("relevance"         , "relevance"                  , "Relevance"        );
661
DefineColumn("deadline"          , $dbh->sql_date_format('bugs.deadline', '%Y-%m-%d') . " AS deadline", "Deadline");
662

663 664 665 666
foreach my $field (Bugzilla->get_fields({ custom => 1, obsolete => 0})) {
    DefineColumn($field->name, 'bugs.' . $field->name, $field->description);
}

667 668 669 670 671 672 673
################################################################################
# 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 = ();
674 675
if (defined $params->param('columnlist')) {
    if ($params->param('columnlist') eq "all") {
676
        # If the value of the CGI parameter is "all", display all columns,
677 678
        # but remove the redundant "short_desc" column.
        @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
terry%netscape.com's avatar
terry%netscape.com committed
679
    }
680
    else {
681
        @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
682
    }
terry%netscape.com's avatar
terry%netscape.com committed
683
}
684
elsif (defined $cgi->cookie('COLUMNLIST')) {
685
    # 2002-10-31 Rename column names (see bug 176461)
686
    my $columnlist = $cgi->cookie('COLUMNLIST');
687 688 689 690 691 692 693
    $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/;
694

695
    # Use the columns listed in the user's preferences.
696
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
697
}
698 699
else {
    # Use the default list of columns.
700
    @displaycolumns = DEFAULT_COLUMN_LIST;
701 702
}

703 704 705 706
# 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);
707

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

712 713 714
# 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.
715 716

# Some versions of perl will taint 'votes' if this is done as a single
717 718 719 720
# statement, because the votes param is tainted at this point
my $votes = $params->param('votes');
$votes ||= "";
if (trim($votes) && !grep($_ eq 'votes', @displaycolumns)) {
721 722
    push(@displaycolumns, 'votes');
}
terry%netscape.com's avatar
terry%netscape.com committed
723

724 725
# 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)
726
if (!Bugzilla->user->in_group(Bugzilla->params->{"timetrackinggroup"})) {
727 728 729 730
   @displaycolumns = grep($_ ne 'estimated_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'remaining_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'actual_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'percentage_complete', @displaycolumns);
731
   @displaycolumns = grep($_ ne 'deadline', @displaycolumns);
732
}
terry%netscape.com's avatar
terry%netscape.com committed
733

734 735 736 737 738 739
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


740 741 742
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
743

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

746
# The bug ID is always selected because bug IDs are always displayed.
747 748 749 750
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
                     "resolution");
751

752
# if using classification, we also need to look in product.classification_id
753
if (Bugzilla->params->{"useclassification"}) {
754 755 756
    push (@selectcolumns,"product");
}

757
# remaining and actual_time are required for percentage_complete calculation:
758
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
759 760 761 762
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

763 764
# Display columns are selected because otherwise we could not display them.
push (@selectcolumns, @displaycolumns);
terry%netscape.com's avatar
terry%netscape.com committed
765

766 767 768 769 770
# 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);
771
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
772 773
}

774 775 776
if ($format->{'extension'} eq 'ics') {
    push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
}
777

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

782 783
    # This is the list of fields that are needed by the Atom filter.
    my @required_atom_columns = (
784 785 786 787 788 789 790
      'short_desc',
      'opendate',
      'changeddate',
      'reporter_realname',
      'priority',
      'bug_severity',
      'assigned_to_realname',
791 792 793 794
      'bug_status',
      'product',
      'component',
      'resolution'
795
    );
796
    push(@required_atom_columns, 'target_milestone') if Bugzilla->params->{'usetargetmilestone'};
797

798
    foreach my $required (@required_atom_columns) {
799 800 801 802
        push(@selectcolumns, $required) if !grep($_ eq $required,@selectcolumns);
    }
}

803 804 805
################################################################################
# Query Generation
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
806

807 808
# Convert the list of columns being selected into a list of column names.
my @selectnames = map($columns->{$_}->{'name'}, @selectcolumns);
809

810 811 812 813
# Remove columns with no names, such as percentage_complete
#  (or a removed *_time column due to permissions)
@selectnames = grep($_ ne '', @selectnames);

814 815 816
################################################################################
# Sort Order Determination
################################################################################
817

818
# Add to the query some instructions for sorting the bug list.
819 820 821 822 823 824

# 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');
825 826 827 828 829
       
        # Cookies from early versions of Specific Search included this text,
        # which is now invalid.
        $order =~ s/ LIMIT 200//;
        
830 831 832 833 834
        $order_from_cookie = 1;
    }
    else {
        $order = '';  # Remove possible "reuse" identifier as unnecessary
    }
835
}
836

837
my $db_order = "";  # Modified version of $order for use with SQL query
838 839 840 841
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
        /^Bug Number$/ && do {
            $order = "bugs.bug_id";
            last ORDER;
        };
        /^Importance$/ && do {
            $order = "bugs.priority, bugs.bug_severity";
            last ORDER;
        };
        /^Assignee$/ && do {
            $order = "map_assigned_to.login_name, bugs.bug_status, bugs.priority, bugs.bug_id";
            last ORDER;
        };
        /^Last Changed$/ && do {
            $order = "bugs.delta_ts, bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
            last ORDER;
        };
        do {
            my @order;
860
            my @columnnames = map($columns->{lc($_)}->{'name'}, keys(%$columns));
861
            # A custom list of columns.  Make sure each column is valid.
862 863 864 865
            foreach my $fragment (split(/,/, $order)) {
                $fragment = trim($fragment);
                # Accept an order fragment matching a column name, with
                # asc|desc optionally following (to specify the direction)
866
                if (grep($fragment =~ /^\Q$_\E(\s+(asc|desc))?$/, @columnnames, keys(%$columns))) {
867 868 869 870
                    next if $fragment =~ /\brelevance\b/ && !$fulltext;
                    push(@order, $fragment);
                }
                else {
871
                    my $vars = { fragment => $fragment };
872
                    if ($order_from_cookie) {
873
                        $cgi->remove_cookie('LASTORDER');
874
                        ThrowCodeError("invalid_column_name_cookie", $vars);
875 876
                    }
                    else {
877
                        ThrowCodeError("invalid_column_name_form", $vars);
878
                    }
879 880
                }
            }
881
            $order = join(",", @order);
882 883 884
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
            trick_taint($order);
885
        };
terry%netscape.com's avatar
terry%netscape.com committed
886
    }
887 888 889 890 891
}
else {
    # DEFAULT
    $order = "bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
}
892

893
# Make sure ORDER BY columns are included in the field list.
894 895 896 897 898 899
foreach my $fragment (split(/,/, $order)) {
    $fragment = trim($fragment);
    if (!grep($fragment =~ /^\Q$_\E(\s+(asc|desc))?$/, @selectnames)) {
        # Add order columns to selectnames
        # The fragment has already been validated
        $fragment =~ s/\s+(asc|desc)$//;
900 901 902 903

        # While newer fragments contain IDs for aliased columns, older
        # LASTORDER cookies (or bookmarks) may contain full names.
        # Convert them to an ID here.
904
        if ($fragment =~ / AS (\w+)/) {
905
            $fragment = $1;
906
        }
907 908 909 910 911 912 913

        $fragment =~ tr/a-zA-Z\.0-9\-_//cd;

        # If the order fragment is an ID, we need its corresponding name
        # to be in the field list.
        if (exists($columns->{$fragment})) {
            $fragment = $columns->{$fragment}->{'name'};
914
        }
915

916 917 918
        push @selectnames, $fragment;
    }
}
919

920
$db_order = $order;  # Copy $order into $db_order for use with SQL query
921

922 923 924 925 926 927 928 929
# If we are sorting by votes, sort in descending order if no explicit
# sort order was given
$db_order =~ s/bugs.votes\s*(,|$)/bugs.votes desc$1/i;
                             
# the 'actual_time' field is defined as an aggregate function, but 
# for order we just need the column name 'actual_time'
my $aggregate_search = quotemeta($columns->{'actual_time'}->{'name'});
$db_order =~ s/$aggregate_search/actual_time/g;
930

931 932 933
# the 'percentage_complete' field is defined as an aggregate too
$aggregate_search = quotemeta($columns->{'percentage_complete'}->{'name'});
$db_order =~ s/$aggregate_search/percentage_complete/g;
934

935 936 937 938 939
# Now put $db_order into a format that Bugzilla::Search can use.
# (We create $db_order as a string first because that's the way
# we did it before Bugzilla::Search took an "order" argument.)
my @orderstrings = split(',', $db_order);

940 941
# Generate the basic SQL query that will be used to generate the bug list.
my $search = new Bugzilla::Search('fields' => \@selectnames, 
942 943
                                  'params' => $params,
                                  'order' => \@orderstrings);
944 945
my $query = $search->getSQL();

946 947 948 949 950
if (defined $cgi->param('limit')) {
    my $limit = $cgi->param('limit');
    if (detaint_natural($limit)) {
        $query .= " " . $dbh->sql_limit($limit);
    }
951 952
}
elsif ($fulltext) {
953
    $query .= " " . $dbh->sql_limit(FULLTEXT_BUGLIST_LIMIT);
954
    $vars->{'sorted_by_relevance'} = 1;
955 956
}

957

958 959 960
################################################################################
# Query Execution
################################################################################
961

962
if ($cgi->param('debug')) {
963 964
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
965
    $vars->{'debugdata'} = $search->getDebugData();
966 967
}

968 969 970
# 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) {
971 972
    print $cgi->multipart_init();
    print $cgi->multipart_start(-type => 'text/html');
973

974
    # Generate and return the UI (HTML page) from the appropriate template.
975 976
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
977

978 979 980 981 982 983
    # Under mod_perl, flush stdout so that the page actually shows up.
    if ($ENV{MOD_PERL}) {
        require Apache2::RequestUtil;
        Apache2::RequestUtil->request->rflush();
    }

984 985 986
    # 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
987 988
}

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

993
# Normally, we ignore SIGTERM and SIGPIPE, but we need to
994 995 996 997 998
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

999
# Execute the query.
1000 1001
my $buglist_sth = $dbh->prepare($query);
$buglist_sth->execute();
1002

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

1004 1005 1006
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
1007

1008 1009
# 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
1010

1011 1012 1013
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
1014
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
1015

1016
my @bugs; # the list of records
1017

1018
while (my @row = $buglist_sth->fetchrow_array()) {
1019
    my $bug = {}; # a record
1020

1021
    # Slurp the row of data into the record.
1022 1023
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
1024
    foreach my $column (@selectcolumns) {
1025
        $bug->{$column} = shift @row;
1026
    }
terry%netscape.com's avatar
terry%netscape.com committed
1027

1028 1029 1030
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
1031
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
1032 1033

        # Put in the change date as a time, so that the template date plugin
1034
        # can format the date in any way needed by the template. ICS and Atom
1035
        # have specific, and different, date and time formatting.
1036
        $bug->{'changedtime'} = str2time($bug->{'changeddate'}, Bugzilla->params->{'timezone'});
1037
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});        
1038 1039 1040
    }

    if ($bug->{'opendate'}) {
1041
        # Put in the open date as a time for the template date plugin.
1042
        $bug->{'opentime'} = str2time($bug->{'opendate'}, Bugzilla->params->{'timezone'});
1043
        $bug->{'opendate'} = DiffDate($bug->{'opendate'});
1044
    }
terry%netscape.com's avatar
terry%netscape.com committed
1045

1046
    # Record the assignee, product, and status in the big hashes of those things.
1047
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
1048
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
1049
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
1050

1051
    $bug->{'secure_mode'} = undef;
1052

1053 1054
    # Add the record to the list.
    push(@bugs, $bug);
1055 1056

    # Add id to list for checking for bug privacy later
1057
    push(@bugidlist, $bug->{'bug_id'});
1058 1059
}

1060 1061 1062 1063
# 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;
1064
if (@bugidlist) {
1065
    my $sth = $dbh->prepare(
1066 1067 1068 1069 1070 1071 1072 1073
        "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 " .
         "WHERE bugs.bug_id IN (" . join(',',@bugidlist) . ") " .
1074
            $dbh->sql_group_by('bugs.bug_id'));
1075 1076
    $sth->execute();
    while (my ($bug_id, $min_membercontrol) = $sth->fetchrow_array()) {
1077
        $min_membercontrol{$bug_id} = $min_membercontrol || CONTROLMAPNA;
1078 1079
    }
    foreach my $bug (@bugs) {
1080
        next unless defined($min_membercontrol{$bug->{'bug_id'}});
1081
        if ($min_membercontrol{$bug->{'bug_id'}} == CONTROLMAPMANDATORY) {
1082
            $bug->{'secure_mode'} = 'implied';
1083
        }
1084 1085 1086
        else {
            $bug->{'secure_mode'} = 'manual';
        }
1087 1088
    }
}
1089

1090 1091 1092
################################################################################
# Template Variable Definition
################################################################################
1093

1094
# Define the variables and functions that will be passed to the UI template.
1095

1096
$vars->{'bugs'} = \@bugs;
1097
$vars->{'buglist'} = \@bugidlist;
1098
$vars->{'buglist_joined'} = join(',', @bugidlist);
1099 1100
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
1101

1102
my @openstates = BUG_STATE_OPEN;
1103 1104
$vars->{'openstates'} = \@openstates;
$vars->{'closedstates'} = ['CLOSED', 'VERIFIED', 'RESOLVED'];
1105

1106 1107 1108
# 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
1109 1110 1111 1112 1113
# 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');
1114
$vars->{'order'} = $order;
1115
$vars->{'caneditbugs'} = Bugzilla->user->in_group('editbugs');
terry%netscape.com's avatar
terry%netscape.com committed
1116

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

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

1129
$vars->{'quip'} = GetQuip();
1130
$vars->{'currenttime'} = time();
1131 1132

# The following variables are used when the user is making changes to multiple bugs.
1133
if ($dotweak) {
1134
    $vars->{'dotweak'} = 1;
1135
    $vars->{'valid_keywords'} = [map($_->name, Bugzilla::Keyword->get_all)];
1136
    $vars->{'use_keywords'} = 1 if Bugzilla::Keyword::keyword_count();
1137

1138
    $vars->{'products'} = Bugzilla->user->get_enterable_products;
1139 1140 1141 1142 1143
    $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');
    $vars->{'resolutions'} = Bugzilla::Bug->settable_resolutions;
1144

1145
    $vars->{'unconfirmedstate'} = 'UNCONFIRMED';
1146

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    # 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
                                WHERE value IN (' . join(', ', @bug_statuses) .')');

    # 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 =
      $dbh->selectcol_arrayref('SELECT DISTINCT new_status
                                FROM status_workflow sw1
                                WHERE NOT EXISTS (SELECT * FROM status_workflow sw2
                                                  WHERE sw2.old_status != sw1.new_status
                                                  AND sw2.old_status IN (' . join(', ', @$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))');

    $vars->{'current_bug_statuses'} = [keys %$bugstatuses];
    $vars->{'new_bug_statuses'} = Bugzilla::Status->new_from_list($bug_status_ids);
1167
    # The groups to which the user belongs.
1168
    $vars->{'groups'} = GetGroups();
1169 1170 1171 1172 1173 1174 1175

    # 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.
    $vars->{'bugproducts'} = [ keys %$bugproducts ];
    if (scalar(@{$vars->{'bugproducts'}}) == 1) {
1176 1177 1178 1179 1180
        my $product = new Bugzilla::Product(
            {name => $vars->{'bugproducts'}->[0]});
        $vars->{'versions'} = [map($_->name ,@{$product->versions})];
        $vars->{'components'} = [map($_->name, @{$product->components})];
        $vars->{'targetmilestones'} = [map($_->name, @{$product->milestones})]
1181
            if Bugzilla->params->{'usetargetmilestone'};
terry%netscape.com's avatar
terry%netscape.com committed
1182 1183
    }
}
1184

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

1189

1190 1191 1192
################################################################################
# HTTP Header Generation
################################################################################
1193

1194
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
1195

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

1199
if ($format->{'extension'} eq "html" && !$agent) {
1200
    if ($order) {
1201
        $cgi->send_cookie(-name => 'LASTORDER',
1202
                          -value => $order,
1203
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1204
    }
1205
    my $bugids = join(":", @bugidlist);
1206
    # See also Bug 111999
1207 1208 1209 1210
    if (length($bugids) == 0) {
        $cgi->remove_cookie('BUGLIST');
    }
    elsif (length($bugids) < 4000) {
1211 1212 1213
        $cgi->send_cookie(-name => 'BUGLIST',
                          -value => $bugids,
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
1214
    }
1215
    else {
1216
        $cgi->remove_cookie('BUGLIST');
1217
        $vars->{'toolong'} = 1;
terry%netscape.com's avatar
terry%netscape.com committed
1218
    }
1219 1220

    $contenttype = "text/html";
1221 1222
}
else {
1223
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
1224 1225
}

1226 1227 1228
if ($format->{'extension'} eq "csv") {
    # We set CSV files to be downloaded, as they are designed for importing
    # into other programs.
1229
    $disposition = "attachment";
1230 1231
}

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

1235
if ($serverpush) {
1236
    # Close the "please wait" page, then open the buglist page
1237
    print $cgi->multipart_end();
1238 1239 1240 1241 1242 1243
    print $cgi->multipart_start(-type                => $contenttype,
                                -content_disposition => $disposition);
}
else {
    print $cgi->header(-type                => $contenttype,
                       -content_disposition => $disposition);
1244
}
terry%netscape.com's avatar
terry%netscape.com committed
1245

1246

1247 1248 1249
################################################################################
# Content Generation
################################################################################
1250

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

1255

1256 1257 1258 1259
################################################################################
# Script Conclusion
################################################################################

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