buglist.cgi 49.9 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::User;
44
use Bugzilla::Bug;
45
use Bugzilla::Product;
46
use Bugzilla::Keyword;
47
use Bugzilla::Field;
48

49 50
use Date::Parse;

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

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

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

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

76 77 78
################################################################################
# Data and Security Validation
################################################################################
79

80
# Whether or not the user wants to change multiple bugs.
81
my $dotweak = $cgi->param('tweak') ? 1 : 0;
82 83 84

# Log the user in
if ($dotweak) {
85
    Bugzilla->login(LOGIN_REQUIRED);
86
    Bugzilla->user->in_group("editbugs")
87 88 89
      || ThrowUserError("auth_failure", {group  => "editbugs",
                                         action => "modify",
                                         object => "multiple_bugs"});
90 91
}

92
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
93 94 95 96
if (defined $cgi->param('format') && $cgi->param('format') eq "rdf"
    && !defined $cgi->param('ctype')) {
    $cgi->param('ctype', "rdf");
    $cgi->delete('format');
97
}
98

99 100 101 102 103
# Treat requests for ctype=rss as requests for ctype=atom
if (defined $cgi->param('ctype') && $cgi->param('ctype') eq "rss") {
    $cgi->param('ctype', "atom");
}

104 105 106 107 108 109
# 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.
110
if ((defined $cgi->param('ctype')) && ($cgi->param('ctype') eq "js")) {
111
    Bugzilla->logout_request();
112
}
113

114 115 116 117 118 119 120
# 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/);

121 122 123
# 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.
124 125
my $format = $template->get_format("list/list", scalar $cgi->param('format'),
                                   scalar $cgi->param('ctype'));
126

127 128 129 130 131 132 133 134
# 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.
135 136
# 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)
137 138
#
my $serverpush =
139 140 141
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
142
        && (($ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/) || ($ENV{'HTTP_USER_AGENT'} =~ /MSIE 5.*Mac_PowerPC/))
143
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
144 145 146
            && !$agent
              && !defined($cgi->param('serverpush'))
                || $cgi->param('serverpush');
147

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

151 152 153
# The params object to use for the actual query itself
my $params;

154 155
# 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.
156
if (defined $cgi->param('regetlastlist')) {
157
    $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
158

159
    $order = "reuse last sort" unless $order;
160 161
    my $bug_id = $cgi->cookie('BUGLIST');
    $bug_id =~ s/:/,/g;
162 163
    # set up the params for this new query
    $params = new Bugzilla::CGI({
164
                                 bug_id => $bug_id,
165 166
                                 order => $order,
                                });
167 168
}

169 170
if ($buffer =~ /&cmd-/) {
    my $url = "query.cgi?$buffer#chart";
171
    print $cgi->redirect(-location => $url);
172
    # Generate and return the UI (HTML page) from the appropriate template.
173
    $vars->{'message'} = "buglist_adding_field";
174 175
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
176
      || ThrowTemplateError($template->error());
177 178
    exit;
}
179

180 181 182 183
# 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;
184
if ($cgi->param('content')) { $fulltext = 1 }
185
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
186
foreach my $chart (@charts) {
187
    if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
188 189 190 191 192
        $fulltext = 1;
        last;
    }
}

193 194 195 196
################################################################################
# Utilities
################################################################################

197
local our @weekday= qw( Sun Mon Tue Wed Thu Fri Sat );
198 199 200 201 202 203 204 205 206 207 208 209 210 211
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;
}
212

213
sub LookupNamedQuery {
214
    my ($name, $sharer_id) = @_;
215
    my $user = Bugzilla->login(LOGIN_REQUIRED);
216
    my $dbh = Bugzilla->dbh;
217 218 219 220
    my $owner_id;

    # $name and $sharer_id are safe -- we only use them below in SELECT
    # placeholders and then in error messages (which are always HTML-filtered).
221
    $name || ThrowUserError("query_name_missing");
222
    trick_taint($name);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    if ($sharer_id) {
        trick_taint($sharer_id);
        $owner_id = $sharer_id;
    }
    else {
        $owner_id = $user->id;
    }

    my ($id, $result) = $dbh->selectrow_array('SELECT id, query
                                                 FROM namedqueries
                                                WHERE userid = ? AND name = ?',
                                              undef, ($owner_id, $name));
    defined($result)
        || ThrowUserError("missing_query", {'queryname' => $name,
                                            'sharer_id' => $sharer_id});

    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});
        }
    }
249 250 251 252
    
    $result
       || ThrowUserError("buglist_parameters_required", {'queryname' => $name});

253 254 255
    return $result;
}

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

    # Validate the query name.
    $query_name || ThrowUserError("query_name_missing");
    $query_name !~ /[<>&]/ || ThrowUserError("illegal_query_name");
288
    (length($query_name) <= 64) || ThrowUserError("query_name_too_long");
289 290 291 292 293 294 295 296 297 298 299
    trick_taint($query_name);

    detaint_natural($userid);
    detaint_natural($link_in_footer);

    $query || ThrowUserError("buglist_parameters_required",
                             {'queryname' => $query});
    # $query is safe, because we always urlencode or html_quote
    # it when we display it to the user.
    trick_taint($query);

300 301
    $dbh->bz_lock_tables('namedqueries WRITE',
                         'namedqueries_link_in_footer WRITE');
302 303 304 305 306 307 308

    my $result = $dbh->selectrow_array("SELECT userid FROM namedqueries"
        . " WHERE userid = ? AND name = ?"
        , undef, ($userid, $query_name));
    if ($result) {
        $query_existed_before = 1;
        $dbh->do("UPDATE namedqueries"
309
            . " SET query = ?, query_type = ?"
310
            . " WHERE userid = ? AND name = ?"
311
            , undef, ($query, $query_type, $userid, $query_name));
312 313 314
    } else {
        $query_existed_before = 0;
        $dbh->do("INSERT INTO namedqueries"
315 316 317 318 319 320 321 322 323 324
            . " (userid, name, query, query_type)"
            . " VALUES (?, ?, ?, ?)"
            , undef, ($userid, $query_name, $query, $query_type));
        if ($link_in_footer) {
            $dbh->do('INSERT INTO namedqueries_link_in_footer
                                 (namedquery_id, user_id)
                          VALUES (?, ?)',
                     undef,
                     ($dbh->bz_last_key('namedqueries', 'id'), $userid));
        }
325 326
    }

327
    $dbh->bz_unlock_tables();
328 329 330
    return $query_existed_before;
}

331 332 333 334 335 336
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 " .
337 338
                                       "WHERE series_id = ?"
                                       , undef, ($series_id));
339 340 341 342 343
    $result
           || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
    return $result;
}

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

357
sub GetGroups {
358
    my $dbh = Bugzilla->dbh;
359
    my $user = Bugzilla->user;
360

361 362 363
    # 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.
364
    my $grouplist = $user->groups_as_string;
365
    my $groups = $dbh->selectall_arrayref(
366
                "SELECT  id, name, description, isactive
367
                   FROM  groups
368
                  WHERE  id IN ($grouplist)
369
                    AND  isbuggroup = 1
370
               ORDER BY  description "
371
               , {Slice => {}});
372

373
    return $groups;
374
}
375

376

377 378 379
################################################################################
# Command Execution
################################################################################
380

381 382
$cgi->param('cmdtype', "") if !defined $cgi->param('cmdtype');
$cgi->param('remaction', "") if !defined $cgi->param('remaction');
383

384 385
# Backwards-compatibility - the old interface had cmdtype="runnamed" to run
# a named command, and we can't break this because it's in bookmarks.
386 387 388
if ($cgi->param('cmdtype') eq "runnamed") {  
    $cgi->param('cmdtype', "dorem");
    $cgi->param('remaction', "run");
389 390
}

391 392 393 394 395 396
# 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);
397

398 399 400 401 402 403 404 405
# 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}";
406 407
if ($cgi->param('cmdtype') eq "dorem" && $cgi->param('remaction') =~ /^run/) {
    $filename = $cgi->param('namedcmd') . "-$date.$format->{extension}";
408 409 410 411 412
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}

413
# Take appropriate action based on user's request.
414 415
if ($cgi->param('cmdtype') eq "dorem") {  
    if ($cgi->param('remaction') eq "run") {
416 417 418 419 420 421 422 423 424
        $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.
        if (!$cgi->param('sharer_id') ||
            $cgi->param('sharer_id') == Bugzilla->user->id) {
            $vars->{'searchname'} = $cgi->param('namedcmd');
            $vars->{'searchtype'} = "saved";
        }
425
        $params = new Bugzilla::CGI($buffer);
426
        $order = $params->param('order') || $order;
427

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

        # 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
                                                      = ?
455
                                      ', undef, $user->id, $qname);
456 457 458 459 460 461 462 463
        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
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        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);
        }
482 483

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

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

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

522 523 524 525
            my %bug_ids;
            unless ($query_name) {
                # No new query name has been given. We retrieve bug IDs
                # currently set in the selected saved search.
526 527 528 529 530 531
                $query_name = $cgi->param('oldqueryname');
                my $old_query = LookupNamedQuery($query_name);
                foreach my $bug_id (split(/[\s,=]+/, $old_query)) {
                    $bug_ids{$bug_id} = 1 if detaint_natural($bug_id);
                }
            }
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549

            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);
550 551
            $query_type = LIST_OF_BUGS;
        }
552
        my $tofooter = 1;
553
        my $existed_before = InsertNamedQuery($user->id, $query_name, $new_query,
554
                                              $tofooter, $query_type);
555
        if ($existed_before) {
556 557
            $vars->{'message'} = "buglist_updated_named_query";
        }
558
        else {
559
            $vars->{'message'} = "buglist_new_named_query";
560
        }
561 562 563

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

566
        $vars->{'queryname'} = $query_name;
567
        
568
        print $cgi->header();
569 570 571
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
572
    }
terry%netscape.com's avatar
terry%netscape.com committed
573 574
}

575 576 577 578 579
# 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');
580
    $buffer = $params->query_string;
581
}
terry%netscape.com's avatar
terry%netscape.com committed
582

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
################################################################################
# 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, 
600
#       and the redundant short_desc column is removed when the client
601
#       requests "all" columns.
602 603
# 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.
604

605
local our $columns = {};
606 607 608
sub DefineColumn {
    my ($id, $name, $title) = @_;
    $columns->{$id} = { 'name' => $name , 'title' => $title };
609
}
610

611
# Column:     ID                    Name                           Title
612
DefineColumn("bug_id"            , "bugs.bug_id"                , "ID"               );
613
DefineColumn("alias"             , "bugs.alias"                 , "Alias"            );
614 615
DefineColumn("opendate"          , "bugs.creation_ts"           , "Opened"           );
DefineColumn("changeddate"       , "bugs.delta_ts"              , "Changed"          );
616
DefineColumn("bug_severity"      , "bugs.bug_severity"          , "Severity"         );
617
DefineColumn("priority"          , "bugs.priority"              , "Priority"         );
618 619
DefineColumn("rep_platform"      , "bugs.rep_platform"          , "Hardware"         );
DefineColumn("assigned_to"       , "map_assigned_to.login_name" , "Assignee"         );
620 621
DefineColumn("reporter"          , "map_reporter.login_name"    , "Reporter"         );
DefineColumn("qa_contact"        , "map_qa_contact.login_name"  , "QA Contact"       );
622
if ($format->{'extension'} eq 'html') {
623 624 625
    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");
626
} else {
627 628 629
    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");
630
}
631
DefineColumn("bug_status"        , "bugs.bug_status"            , "Status"           );
632
DefineColumn("resolution"        , "bugs.resolution"            , "Resolution"       );
633 634
DefineColumn("short_short_desc"  , "bugs.short_desc"            , "Summary"          );
DefineColumn("short_desc"        , "bugs.short_desc"            , "Summary"          );
635
DefineColumn("status_whiteboard" , "bugs.status_whiteboard"     , "Whiteboard"       );
636 637
DefineColumn("component"         , "map_components.name"        , "Component"        );
DefineColumn("product"           , "map_products.name"          , "Product"          );
638
DefineColumn("classification"    , "map_classifications.name"   , "Classification"   );
639
DefineColumn("version"           , "bugs.version"               , "Version"          );
640
DefineColumn("op_sys"            , "bugs.op_sys"                , "OS"               );
641 642 643
DefineColumn("target_milestone"  , "bugs.target_milestone"      , "Target Milestone" );
DefineColumn("votes"             , "bugs.votes"                 , "Votes"            );
DefineColumn("keywords"          , "bugs.keywords"              , "Keywords"         );
644 645 646
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");
647 648 649 650 651 652 653
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"); 
654
DefineColumn("relevance"         , "relevance"                  , "Relevance"        );
655
DefineColumn("deadline"          , $dbh->sql_date_format('bugs.deadline', '%Y-%m-%d') . " AS deadline", "Deadline");
656

657 658 659 660
foreach my $field (Bugzilla->get_fields({ custom => 1, obsolete => 0})) {
    DefineColumn($field->name, 'bugs.' . $field->name, $field->description);
}

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

689
    # Use the columns listed in the user's preferences.
690
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
691
}
692 693
else {
    # Use the default list of columns.
694
    @displaycolumns = DEFAULT_COLUMN_LIST;
695 696
}

697 698 699 700
# 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);
701

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

706 707 708
# 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.
709 710

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

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

728 729 730 731 732 733
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


734 735 736
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
737

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

740
# The bug ID is always selected because bug IDs are always displayed.
741 742 743 744
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
                     "resolution");
745

746
# if using classification, we also need to look in product.classification_id
747
if (Bugzilla->params->{"useclassification"}) {
748 749 750
    push (@selectcolumns,"product");
}

751
# remaining and actual_time are required for percentage_complete calculation:
752
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
753 754 755 756
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

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

760 761 762 763 764
# 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);
765
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
766 767
}

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

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

776 777
    # This is the list of fields that are needed by the Atom filter.
    my @required_atom_columns = (
778 779 780 781 782 783 784 785 786 787
      'short_desc',
      'opendate',
      'changeddate',
      'reporter_realname',
      'priority',
      'bug_severity',
      'assigned_to_realname',
      'bug_status'
    );

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

793 794 795
################################################################################
# Query Generation
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
796

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

800 801 802 803
# Remove columns with no names, such as percentage_complete
#  (or a removed *_time column due to permissions)
@selectnames = grep($_ ne '', @selectnames);

804 805 806
################################################################################
# Sort Order Determination
################################################################################
807

808
# Add to the query some instructions for sorting the bug list.
809 810 811 812 813 814

# 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');
815 816 817 818 819
       
        # Cookies from early versions of Specific Search included this text,
        # which is now invalid.
        $order =~ s/ LIMIT 200//;
        
820 821 822 823 824
        $order_from_cookie = 1;
    }
    else {
        $order = '';  # Remove possible "reuse" identifier as unnecessary
    }
825
}
826

827
my $db_order = "";  # Modified version of $order for use with SQL query
828 829 830 831
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
        /^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;
850
            my @columnnames = map($columns->{lc($_)}->{'name'}, keys(%$columns));
851
            # A custom list of columns.  Make sure each column is valid.
852 853 854 855
            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)
856
                if (grep($fragment =~ /^\Q$_\E(\s+(asc|desc))?$/, @columnnames, keys(%$columns))) {
857 858 859 860
                    next if $fragment =~ /\brelevance\b/ && !$fulltext;
                    push(@order, $fragment);
                }
                else {
861
                    my $vars = { fragment => $fragment };
862
                    if ($order_from_cookie) {
863
                        $cgi->remove_cookie('LASTORDER');
864
                        ThrowCodeError("invalid_column_name_cookie", $vars);
865 866
                    }
                    else {
867
                        ThrowCodeError("invalid_column_name_form", $vars);
868
                    }
869 870
                }
            }
871
            $order = join(",", @order);
872 873 874
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
            trick_taint($order);
875
        };
terry%netscape.com's avatar
terry%netscape.com committed
876
    }
877 878 879 880 881
}
else {
    # DEFAULT
    $order = "bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
}
882

883
# Make sure ORDER BY columns are included in the field list.
884 885 886 887 888 889
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)$//;
890 891 892 893

        # While newer fragments contain IDs for aliased columns, older
        # LASTORDER cookies (or bookmarks) may contain full names.
        # Convert them to an ID here.
894
        if ($fragment =~ / AS (\w+)/) {
895
            $fragment = $1;
896
        }
897 898 899 900 901 902 903

        $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'};
904
        }
905

906 907 908
        push @selectnames, $fragment;
    }
}
909

910
$db_order = $order;  # Copy $order into $db_order for use with SQL query
911

912 913 914 915 916 917 918 919
# 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;
920

921 922 923
# 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;
924

925 926 927 928 929
# 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);

930 931
# Generate the basic SQL query that will be used to generate the bug list.
my $search = new Bugzilla::Search('fields' => \@selectnames, 
932 933
                                  'params' => $params,
                                  'order' => \@orderstrings);
934 935
my $query = $search->getSQL();

936 937 938 939 940
if (defined $cgi->param('limit')) {
    my $limit = $cgi->param('limit');
    if (detaint_natural($limit)) {
        $query .= " " . $dbh->sql_limit($limit);
    }
941 942
}
elsif ($fulltext) {
943
    $query .= " " . $dbh->sql_limit(FULLTEXT_BUGLIST_LIMIT);
944
    $vars->{'sorted_by_relevance'} = 1;
945 946
}

947

948 949 950
################################################################################
# Query Execution
################################################################################
951

952
if ($cgi->param('debug')) {
953 954
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
955
    $vars->{'debugdata'} = $search->getDebugData();
956 957
}

958 959
# Time to use server push to display an interim message to the user until
# the query completes and we can display the bug list.
960
my $disposition = '';
961
if ($serverpush) {
962 963 964
    $filename =~ s/\\/\\\\/g; # escape backslashes
    $filename =~ s/"/\\"/g; # escape quotes
    $disposition = qq#inline; filename="$filename"#;
965

966
    print $cgi->multipart_init(-content_disposition => $disposition);
967
    print $cgi->multipart_start();
968

969
    # Generate and return the UI (HTML page) from the appropriate template.
970 971
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
972

973 974 975 976 977 978
    # Under mod_perl, flush stdout so that the page actually shows up.
    if ($ENV{MOD_PERL}) {
        require Apache2::RequestUtil;
        Apache2::RequestUtil->request->rflush();
    }

979 980 981
    # 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
982 983
}

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

988
# Normally, we ignore SIGTERM and SIGPIPE, but we need to
989 990 991 992 993
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

994
# Execute the query.
995 996
my $buglist_sth = $dbh->prepare($query);
$buglist_sth->execute();
997

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

999 1000 1001
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
1002

1003 1004
# 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
1005

1006 1007 1008
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
1009
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
1010

1011
my @bugs; # the list of records
1012

1013
while (my @row = $buglist_sth->fetchrow_array()) {
1014
    my $bug = {}; # a record
1015

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

1023 1024 1025
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
1026
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
1027 1028

        # Put in the change date as a time, so that the template date plugin
1029
        # can format the date in any way needed by the template. ICS and Atom
1030 1031 1032
        # have specific, and different, date and time formatting.
        $bug->{'changedtime'} = str2time($bug->{'changeddate'});
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});        
1033 1034 1035
    }

    if ($bug->{'opendate'}) {
1036 1037 1038
        # Put in the open date as a time for the template date plugin.
        $bug->{'opentime'} = str2time($bug->{'opendate'});
        $bug->{'opendate'} = DiffDate($bug->{'opendate'});
1039
    }
terry%netscape.com's avatar
terry%netscape.com committed
1040

1041
    # Record the assignee, product, and status in the big hashes of those things.
1042
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
1043
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
1044
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
1045

1046
    $bug->{'secure_mode'} = undef;
1047

1048 1049
    # Add the record to the list.
    push(@bugs, $bug);
1050 1051

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

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

1085 1086 1087
################################################################################
# Template Variable Definition
################################################################################
1088

1089
# Define the variables and functions that will be passed to the UI template.
1090

1091
$vars->{'bugs'} = \@bugs;
1092
$vars->{'buglist'} = \@bugidlist;
1093
$vars->{'buglist_joined'} = join(',', @bugidlist);
1094 1095
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
1096

1097
my @openstates = BUG_STATE_OPEN;
1098 1099
$vars->{'openstates'} = \@openstates;
$vars->{'closedstates'} = ['CLOSED', 'VERIFIED', 'RESOLVED'];
1100

1101 1102 1103
# 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
1104 1105 1106 1107 1108
# 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');
1109
$vars->{'order'} = $order;
1110
$vars->{'caneditbugs'} = Bugzilla->user->in_group('editbugs');
terry%netscape.com's avatar
terry%netscape.com committed
1111

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

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

1124
$vars->{'quip'} = GetQuip();
1125
$vars->{'currenttime'} = time();
1126 1127

# The following variables are used when the user is making changes to multiple bugs.
1128
if ($dotweak) {
1129
    $vars->{'dotweak'} = 1;
1130
    $vars->{'use_keywords'} = 1 if Bugzilla::Keyword::keyword_count();
1131

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

1139
    $vars->{'unconfirmedstate'} = 'UNCONFIRMED';
1140 1141 1142 1143

    $vars->{'bugstatuses'} = [ keys %$bugstatuses ];

    # The groups to which the user belongs.
1144
    $vars->{'groups'} = GetGroups();
1145 1146 1147 1148 1149 1150 1151

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

1161 1162 1163 1164
# 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');

1165

1166 1167 1168
################################################################################
# HTTP Header Generation
################################################################################
1169

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

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

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

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

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

1208
if ($serverpush) {
1209 1210
    # close the "please wait" page, then open the buglist page
    print $cgi->multipart_end();
1211
    my @extra;
1212
    push @extra, (-charset => "utf8") if Bugzilla->params->{"utf8"};
1213 1214 1215
    print $cgi->multipart_start(-type => $contenttype, 
                                -content_disposition => $disposition, 
                                @extra);
1216 1217 1218 1219 1220
} else {
    # Suggest a name for the bug list if the user wants to save it as a file.
    # If we are doing server push, then we did this already in the HTTP headers
    # that started the server push, so we don't have to do it again here.
    print $cgi->header(-type => $contenttype,
1221
                       -content_disposition => "$disp; filename=$filename");
1222
}
terry%netscape.com's avatar
terry%netscape.com committed
1223

1224

1225 1226 1227
################################################################################
# Content Generation
################################################################################
1228

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

1233

1234 1235 1236 1237
################################################################################
# Script Conclusion
################################################################################

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