buglist.cgi 33.7 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>
terry%netscape.com's avatar
terry%netscape.com committed
26

27 28 29 30 31
################################################################################
# Script Initialization
################################################################################

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

34 35
use lib qw(.);

36
use vars qw($template $vars);
37

38
use Bugzilla;
39
use Bugzilla::Search;
40 41

# Include the Bugzilla CGI and general utility library.
42
require "CGI.pl";
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57
use vars qw($db_name
            @components
            @default_column_list
            $defaultqueryname
            @legal_keywords
            @legal_platform
            @legal_priority
            @legal_product
            @legal_severity
            @settable_resolution
            @target_milestone
            $unconfirmedstate
            $userid
            @versions);
terry%netscape.com's avatar
terry%netscape.com committed
58

59 60
my $cgi = Bugzilla->cgi;

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

66
ConnectToDatabase();
67

68 69 70
################################################################################
# Data and Security Validation
################################################################################
71

72 73 74 75 76 77
# Whether or not the user wants to change multiple bugs.
my $dotweak = $::FORM{'tweak'} ? 1 : 0;

# Log the user in
if ($dotweak) {
    confirm_login();
78
    UserInGroup("editbugs") || ThrowUserError("insufficient_privs_for_multi");
79 80 81 82 83 84
    GetVersionTable();
}
else {
    quietly_check_login();
}

85
# Hack to support legacy applications that think the RDF ctype is at format=rdf.
86
if ($::FORM{'format'} && $::FORM{'format'} eq "rdf" && !$::FORM{'ctype'}) { 
87 88 89 90
    $::FORM{'ctype'} = "rdf";
    delete($::FORM{'format'});
}

91 92 93
# 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.
94
my $format = GetFormat("list/list", $::FORM{'format'}, $::FORM{'ctype'});
95

96 97 98 99 100 101 102 103 104 105
# 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.
#
my $serverpush =
106 107 108 109 110 111 112
  $format->{'extension'} eq "html"
    && exists $ENV{'HTTP_USER_AGENT'} 
      && $ENV{'HTTP_USER_AGENT'} =~ /Mozilla.[3-9]/ 
        && $ENV{'HTTP_USER_AGENT'} !~ /[Cc]ompatible/
          && $ENV{'HTTP_USER_AGENT'} !~ /WebKit/
            && !defined($::FORM{'serverpush'})
              || $::FORM{'serverpush'};
113 114

my $order = $::FORM{'order'} || "";
115
my $order_from_cookie = 0;  # True if $order set using $::COOKIE{'LASTORDER'}
116

117 118 119
# The params object to use for the actual query itself
my $params;

120 121 122
# 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.
if ($::FORM{'regetlastlist'}) {
123 124
    $::COOKIE{'BUGLIST'} || ThrowUserError("missing_cookie");

125
    $order = "reuse last sort" unless $order;
126 127 128 129 130 131

    # set up the params for this new query
    $params = new Bugzilla::CGI({
                                 bug_id => [split(/:/, $::COOKIE{'BUGLIST'})],
                                 order => $order,
                                });
132 133
}

134 135
if ($::buffer =~ /&cmd-/) {
    my $url = "query.cgi?$::buffer#chart";
136
    print $cgi->redirect(-location => $url);
137
    # Generate and return the UI (HTML page) from the appropriate template.
138
    $vars->{'message'} = "buglist_adding_field";
139 140
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
141
      || ThrowTemplateError($template->error());
142 143
    exit;
}
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
################################################################################
# Utilities
################################################################################

my @weekday= qw( Sun Mon Tue Wed Thu Fri Sat );
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;
}
164

165 166 167 168 169 170 171
sub LookupNamedQuery {
    my ($name) = @_;
    confirm_login();
    my $userid = DBNameToIdAndCheck($::COOKIE{"Bugzilla_login"});
    my $qname = SqlQuote($name);
    SendSQL("SELECT query FROM namedqueries WHERE userid = $userid AND name = $qname");
    my $result = FetchOneColumn();
172
    $result || ThrowUserError("missing_query", {'queryname' => $name});
173 174 175
    return $result;
}

176 177 178 179 180 181 182 183 184 185 186 187
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 " .
                                       "WHERE series_id = $series_id");
    $result
           || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
    return $result;
}

188
sub GetQuip {
189

190 191
    my $quip;

192
    SendSQL("SELECT quip FROM quips WHERE approved = 1 ORDER BY RAND() LIMIT 1");
193 194 195

    if (MoreSQLData()) {
        ($quip) = FetchSQLData();
196
    }
197 198

    return $quip;
199
}
200

201 202
sub GetGroupsByUserId {
    my ($userid) = @_;
203

204
    return if !$userid;
205 206

    SendSQL("
207 208 209 210 211 212
        SELECT DISTINCT  groups.id, name, description, isactive
                   FROM  groups, user_group_map
                  WHERE  user_id = $userid AND NOT isbless
                    AND  user_group_map.group_id = groups.id
                    AND  isbuggroup
               ORDER BY  description ");
213 214 215 216 217

    my @groups;

    while (MoreSQLData()) {
        my $group = {};
218
        ($group->{'id'}, $group->{'name'},
219 220 221 222 223 224
         $group->{'description'}, $group->{'isactive'}) = FetchSQLData();
        push(@groups, $group);
    }

    return \@groups;
}
225

226

227 228 229
################################################################################
# Command Execution
################################################################################
230

231 232 233
$::FORM{'cmdtype'} ||= "";
$::FORM{'remaction'} ||= "";

234 235 236 237 238 239 240
# Backwards-compatibility - the old interface had cmdtype="runnamed" to run
# a named command, and we can't break this because it's in bookmarks.
if ($::FORM{'cmdtype'} eq "runnamed") {  
    $::FORM{'cmdtype'} = "dorem"; 
    $::FORM{'remaction'} = "run";
}

241 242 243 244 245 246
# 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);
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
# 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}";
if ($::FORM{'cmdtype'} eq "dorem" && $::FORM{'remaction'} =~ /^run/) {
    $filename = "$::FORM{'namedcmd'}-$date.$format->{extension}";
    # Remove white-space from the filename so the user cannot tamper
    # with the HTTP headers.
    $filename =~ s/\s/_/g;
}

263 264 265
# Take appropriate action based on user's request.
if ($::FORM{'cmdtype'} eq "dorem") {  
    if ($::FORM{'remaction'} eq "run") {
266
        $::buffer = LookupNamedQuery($::FORM{"namedcmd"});
267
        $vars->{'title'} = "Bug List: $::FORM{'namedcmd'}";
268
        $params = new Bugzilla::CGI($::buffer);
269
        $order = $params->param('order') || $order;
270
    }
271 272 273 274 275 276
    elsif ($::FORM{'remaction'} eq "runseries") {
        $::buffer = LookupSeries($::FORM{"series_id"});
        $vars->{'title'} = "Bug List: $::FORM{'namedcmd'}";
        $params = new Bugzilla::CGI($::buffer);
        $order = $params->param('order') || $order;
    }
277
    elsif ($::FORM{'remaction'} eq "load") {
278
        my $url = "query.cgi?" . LookupNamedQuery($::FORM{"namedcmd"});
279
        print $cgi->redirect(-location=>$url);
280
        # Generate and return the UI (HTML page) from the appropriate template.
281 282
        $vars->{'message'} = "buglist_load_named_query";
        $vars->{'namedcmd'} = $::FORM{'namedcmd'};
283 284
        $vars->{'url'} = $url;
        $template->process("global/message.html.tmpl", $vars)
285
          || ThrowTemplateError($template->error());
286
        exit;
287 288
    }
    elsif ($::FORM{'remaction'} eq "forget") {
289 290
        confirm_login();
        my $userid = DBNameToIdAndCheck($::COOKIE{"Bugzilla_login"});
291 292
        my $qname = SqlQuote($::FORM{'namedcmd'});
        SendSQL("DELETE FROM namedqueries WHERE userid = $userid AND name = $qname");
293 294 295

        # Now reset the cached queries
        Bugzilla->user->flush_queries_cache();
296

297
        print $cgi->header();
298
        # Generate and return the UI (HTML page) from the appropriate template.
299 300
        $vars->{'message'} = "buglist_query_gone";
        $vars->{'namedcmd'} = $::FORM{'namedcmd'};
301 302
        $vars->{'url'} = "query.cgi";
        $template->process("global/message.html.tmpl", $vars)
303
          || ThrowTemplateError($template->error());
304
        exit;
305 306
    }
}
307
elsif ($::FORM{'cmdtype'} eq "doit" && $::FORM{'remember'}) {
308
    if ($::FORM{'remember'} == 1 && $::FORM{'remtype'} eq "asdefault") {
309 310
        confirm_login();
        my $userid = DBNameToIdAndCheck($::COOKIE{"Bugzilla_login"});
311 312 313 314 315
        my $qname = SqlQuote($::defaultqueryname);
        my $qbuffer = SqlQuote($::buffer);
        SendSQL("REPLACE INTO namedqueries (userid, name, query)
                 VALUES ($userid, $qname, $qbuffer)");
        # Generate and return the UI (HTML page) from the appropriate template.
316
        $vars->{'message'} = "buglist_new_default_query";
317 318
    }
    elsif ($::FORM{'remember'} == 1 && $::FORM{'remtype'} eq "asnamed") {
319 320
        confirm_login();
        my $userid = DBNameToIdAndCheck($::COOKIE{"Bugzilla_login"});
321

322
        my $name = trim($::FORM{'newqueryname'});
323 324
        $name || ThrowUserError("query_name_missing");
        $name !~ /[<>&]/ || ThrowUserError("illegal_query_name");
325
        my $qname = SqlQuote($name);
326 327 328 329

        $::buffer =~ s/[\&\?]cmdtype=[a-z]+//;
        my $qbuffer = SqlQuote($::buffer);

330
        my $tofooter = $::FORM{'tofooter'} ? 1 : 0;
331

332 333 334 335 336 337 338 339
        $vars->{'message'} = "buglist_new_named_query";

        # We want to display the correct message. Check if it existed before
        # we insert, because ->queries may fetch from the db anyway
        if (grep { $_->{name} eq $name } @{Bugzilla->user->queries()}) {
            $vars->{'message'} = "buglist_updated_named_query";
        }

340 341 342 343 344
        SendSQL("SELECT query FROM namedqueries WHERE userid = $userid AND name = $qname");
        if (FetchOneColumn()) {
            SendSQL("UPDATE  namedqueries
                        SET  query = $qbuffer , linkinfooter = $tofooter
                      WHERE  userid = $userid AND name = $qname");
345
        }
346 347 348 349
        else {
            SendSQL("REPLACE INTO namedqueries (userid, name, query, linkinfooter)
                     VALUES ($userid, $qname, $qbuffer, $tofooter)");
        }
350 351 352 353 354

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

355
        $vars->{'queryname'} = $name;
356
    }
terry%netscape.com's avatar
terry%netscape.com committed
357 358 359
}


360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
################################################################################
# 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, 
377
#       and the redundant short_desc column is removed when the client
378 379 380 381 382 383
#       requests "all" columns.

my $columns = {};
sub DefineColumn {
    my ($id, $name, $title) = @_;
    $columns->{$id} = { 'name' => $name , 'title' => $title };
384
}
385

386
# Column:     ID                    Name                           Title
387
DefineColumn("bug_id"            , "bugs.bug_id"                , "ID"               );
388
DefineColumn("alias"             , "bugs.alias"                 , "Alias"           );
389 390
DefineColumn("opendate"          , "bugs.creation_ts"           , "Opened"           );
DefineColumn("changeddate"       , "bugs.delta_ts"              , "Changed"          );
391
DefineColumn("bug_severity"      , "bugs.bug_severity"          , "Severity"         );
392
DefineColumn("priority"          , "bugs.priority"              , "Priority"         );
393 394 395
DefineColumn("rep_platform"      , "bugs.rep_platform"          , "Hardware"         );
DefineColumn("assigned_to"       , "map_assigned_to.login_name" , "Assignee"         );
DefineColumn("assigned_to_realname", "map_assigned_to.realname" , "Assignee"         );
396
DefineColumn("reporter"          , "map_reporter.login_name"    , "Reporter"         );
397
DefineColumn("reporter_realname" , "map_reporter.realname"      , "Reporter"         );
398
DefineColumn("qa_contact"        , "map_qa_contact.login_name"  , "QA Contact"       );
399
DefineColumn("qa_contact_realname", "map_qa_contact.realname"   , "QA Contact"       );
400
DefineColumn("bug_status"        , "bugs.bug_status"            , "Status"           );
401
DefineColumn("resolution"        , "bugs.resolution"            , "Result"           );
402 403
DefineColumn("short_short_desc"  , "bugs.short_desc"            , "Summary"          );
DefineColumn("short_desc"        , "bugs.short_desc"            , "Summary"          );
404
DefineColumn("status_whiteboard" , "bugs.status_whiteboard"     , "Status Summary"   );
405 406
DefineColumn("component"         , "map_components.name"        , "Component"        );
DefineColumn("product"           , "map_products.name"          , "Product"          );
407
DefineColumn("version"           , "bugs.version"               , "Version"          );
408
DefineColumn("op_sys"            , "bugs.op_sys"                , "OS"               );
409 410 411
DefineColumn("target_milestone"  , "bugs.target_milestone"      , "Target Milestone" );
DefineColumn("votes"             , "bugs.votes"                 , "Votes"            );
DefineColumn("keywords"          , "bugs.keywords"              , "Keywords"         );
412 413 414
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");
415
DefineColumn("percentage_complete","(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))) AS percentage_complete", "% Complete"); 
416 417 418 419 420 421 422
################################################################################
# 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 = ();
423 424
if (defined $params->param('columnlist')) {
    if ($params->param('columnlist') eq "all") {
425
        # If the value of the CGI parameter is "all", display all columns,
426 427
        # but remove the redundant "short_desc" column.
        @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
terry%netscape.com's avatar
terry%netscape.com committed
428
    }
429
    else {
430
        @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
431
    }
terry%netscape.com's avatar
terry%netscape.com committed
432
}
433
elsif (defined $::COOKIE{'COLUMNLIST'}) {
434 435 436 437 438 439
    # 2002-10-31 Rename column names (see bug 176461)
    my $columnlist = $::COOKIE{'COLUMNLIST'};
    $columnlist =~ s/owner/assigned_to/;
    $columnlist =~ s/owner_realname/assigned_to_realname/;
    $columnlist =~ s/[^_]platform/rep_platform/;
    $columnlist =~ s/[^_]severity/bug_severity/;
440
    $columnlist =~ s/[^_]status\b/bug_status/;
441 442 443
    $columnlist =~ s/summaryfull/short_desc/;
    $columnlist =~ s/summary/short_short_desc/;

444
    # Use the columns listed in the user's preferences.
445
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
446
}
447 448 449
else {
    # Use the default list of columns.
    @displaycolumns = @::default_column_list;
450 451
}

452 453 454 455
# 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);
456

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

461 462 463
# 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.
464 465

# Some versions of perl will taint 'votes' if this is done as a single
466 467 468 469
# statement, because the votes param is tainted at this point
my $votes = $params->param('votes');
$votes ||= "";
if (trim($votes) && !grep($_ eq 'votes', @displaycolumns)) {
470 471
    push(@displaycolumns, 'votes');
}
terry%netscape.com's avatar
terry%netscape.com committed
472

473 474 475 476 477 478 479 480
# 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)
if (!UserInGroup(Param("timetrackinggroup"))) {
   @displaycolumns = grep($_ ne 'estimated_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'remaining_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'actual_time', @displaycolumns);
   @displaycolumns = grep($_ ne 'percentage_complete', @displaycolumns);
}
terry%netscape.com's avatar
terry%netscape.com committed
481

482 483 484
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
485

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

488
# The bug ID is always selected because bug IDs are always displayed.
489 490 491 492
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
                     "resolution");
493

494
# remaining and actual_time are required for precentage_complete calculation:
495
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
496 497 498 499
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

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

503 504 505 506 507
# 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);
508
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
509 510
}

511

512 513 514
################################################################################
# Query Generation
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
515

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

519 520 521 522
# Remove columns with no names, such as percentage_complete
#  (or a removed *_time column due to permissions)
@selectnames = grep($_ ne '', @selectnames);

523 524 525
################################################################################
# Sort Order Determination
################################################################################
526

527
# Add to the query some instructions for sorting the bug list.
528
if ($::COOKIE{'LASTORDER'} && (!$order || $order =~ /^reuse/i)) {
529
    $order = $::COOKIE{'LASTORDER'};
530
    $order_from_cookie = 1;
531
}
532

533
my $db_order = "";  # Modified version of $order for use with SQL query
534
if ($order) {
535

536 537 538
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
539
        /\./ && do {
540
            my @columnnames = map($columns->{lc($_)}->{'name'}, keys(%$columns));
541
            # A custom list of columns.  Make sure each column is valid.
542 543 544 545 546
            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)
                if (!grep($fragment =~ /^\Q$_\E(\s+(asc|desc))?$/, @columnnames)) {
547
                    my $vars = { fragment => $fragment };
548
                    if ($order_from_cookie) {
549 550
                        $cgi->send_cookie(-name => 'LASTORDER',
                                          -expires => 'Tue, 15-Sep-1998 21:49:00 GMT');
551
                        ThrowCodeError("invalid_column_name_cookie", $vars);
552 553
                    }
                    else {
554
                        ThrowCodeError("invalid_column_name_form", $vars);
555
                    }
556 557 558 559 560
                }
            }
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
            trick_taint($order);
561 562 563
            last ORDER;
        };
        /Number/ && do {
564
            $order = "bugs.bug_id";
565 566 567
            last ORDER;
        };
        /Import/ && do {
568
            $order = "bugs.priority, bugs.bug_severity";
569 570 571
            last ORDER;
        };
        /Assign/ && do {
572
            $order = "map_assigned_to.login_name, bugs.bug_status, bugs.priority, bugs.bug_id";
573 574
            last ORDER;
        };
575
        /Changed/ && do {
576
            $order = "bugs.delta_ts, bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
577 578
            last ORDER;
        };
579
        # DEFAULT
580
        $order = "bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
terry%netscape.com's avatar
terry%netscape.com committed
581
    }
582 583 584 585 586 587 588 589 590 591
    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)$//;
            $fragment =~ tr/a-zA-Z\.0-9\-_//cd;
            push @selectnames, $fragment;
        }
    }
592

593 594
    $db_order = $order;  # Copy $order into $db_order for use with SQL query

595 596 597
    # 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;
598

599 600 601 602 603 604 605 606 607
    # 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;

    # 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;

608 609
}

610 611 612 613 614 615 616 617 618 619 620 621
# Generate the basic SQL query that will be used to generate the bug list.
my $search = new Bugzilla::Search('fields' => \@selectnames, 
                                  'params' => $params);
my $query = $search->getSQL();

# Extra special disgusting hack: if we are ordering by target_milestone,
# change it to order by the sortkey of the target_milestone first.
if ($db_order =~ /bugs.target_milestone/) {
    $db_order =~ s/bugs.target_milestone/ms_order.sortkey,ms_order.value/;
    $query =~ s/\sWHERE\s/ LEFT JOIN milestones ms_order ON ms_order.value = bugs.target_milestone AND ms_order.product_id = bugs.product_id WHERE /;
}

622 623 624 625 626 627 628 629 630
# Even more disgusting hack: if we are doing a full text search,
# order by relevance instead of anything else, and limit to 200 results.
if ($search->{'sorted_by_relevance'}) {
    $db_order = $order = "relevance DESC LIMIT 200";
    $vars->{'sorted_by_relevance'} = 1;
}



631 632
$query .= " ORDER BY $db_order " if ($order);

633

634 635 636
################################################################################
# Query Execution
################################################################################
637

638 639 640 641 642
if ($::FORM{'debug'}) {
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
}

643 644 645
# 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) {
646 647 648
    print $cgi->multipart_init(-content_disposition => "inline; filename=$filename");

    print $cgi->multipart_start();
649

650
    # Generate and return the UI (HTML page) from the appropriate template.
651 652
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
653 654

    print $cgi->multipart_end();
terry%netscape.com's avatar
terry%netscape.com committed
655 656
}

657 658
# Connect to the shadow database if this installation is using one to improve
# query performance.
659
Bugzilla->switch_to_shadow_db();
terry%netscape.com's avatar
terry%netscape.com committed
660

661 662 663 664 665 666
# Normally, we ignore SIGTERM and SIGPIPE (see globals.pl) but we need to
# respond to them here to prevent someone DOSing us by reloading a query
# a large number of times.
$::SIG{TERM} = 'DEFAULT';
$::SIG{PIPE} = 'DEFAULT';

667 668
# Execute the query.
SendSQL($query);
669

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

671 672 673
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
674

675 676
# 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
677

678 679 680
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
681
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
682

683
my @bugs; # the list of records
684

685 686
while (my @row = FetchSQLData()) {
    my $bug = {}; # a record
687

688
    # Slurp the row of data into the record.
689 690
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
691
    foreach my $column (@selectcolumns) {
692
        $bug->{$column} = shift @row;
693
    }
terry%netscape.com's avatar
terry%netscape.com committed
694

695 696 697 698 699 700 701
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
          s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
        $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});
    }
    ($bug->{'opendate'} = DiffDate($bug->{'opendate'})) if $bug->{'opendate'};
terry%netscape.com's avatar
terry%netscape.com committed
702

703
    # Record the owner, product, and status in the big hashes of those things.
704
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
705
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
706
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
707

708 709
    $bug->{isingroups} = 0;

710 711
    # Add the record to the list.
    push(@bugs, $bug);
712 713

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

717 718 719 720 721 722 723 724
# Check for bug privacy and set $bug->{isingroups} = 1 if private 
# to 1 or more groups
my %privatebugs;
if (@bugidlist) {
    SendSQL("SELECT DISTINCT bugs.bug_id FROM bugs, bug_group_map " .
            "WHERE bugs.bug_id = bug_group_map.bug_id " .
            "AND bugs.bug_id IN (" . join(',',@bugidlist) . ")");
    while (MoreSQLData()) {
725 726
        my ($bug_id) = FetchSQLData();
        $privatebugs{$bug_id} = 1;
727 728
    }
    foreach my $bug (@bugs) {
729
        if ($privatebugs{$bug->{'bug_id'}}) {
730 731 732 733
            $bug->{isingroups} = 1;
        }
    }
}
734

735 736 737
################################################################################
# Template Variable Definition
################################################################################
738

739
# Define the variables and functions that will be passed to the UI template.
740

741
$vars->{'bugs'} = \@bugs;
742
$vars->{'buglist'} = join(',', @bugidlist);
743 744
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
745

746 747 748
my @openstates = OpenStates();
$vars->{'openstates'} = \@openstates;
$vars->{'closedstates'} = ['CLOSED', 'VERIFIED', 'RESOLVED'];
749

750 751 752 753 754 755 756 757
# 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
# results).  To get this string, we start with the raw URL query string
# buffer that was created when we initially parsed the URL on script startup,
# then we remove all non-query fields from it, f.e. the sort order (order)
# and command type (cmdtype) fields.
$vars->{'urlquerypart'} = $::buffer;
758
$vars->{'urlquerypart'} =~ s/(order|cmdtype)=[^&]*&?//g;
759
$vars->{'order'} = $order;
terry%netscape.com's avatar
terry%netscape.com committed
760

761
# The user's login account name (i.e. email address).
762
my $login = $::COOKIE{'Bugzilla_login'};
763

764
$vars->{'caneditbugs'} = UserInGroup('editbugs');
terry%netscape.com's avatar
terry%netscape.com committed
765

766 767 768
# Whether or not this user is authorized to move bugs to another installation.
$vars->{'ismover'} = 1
  if Param('move-enabled')
769 770
    && defined($login)
      && Param('movers') =~ /^(\Q$login\E[,\s])|([,\s]\Q$login\E[,\s]+)/;
771

772 773 774 775 776 777
my @bugowners = keys %$bugowners;
if (scalar(@bugowners) > 1 && UserInGroup('editbugs')) {
    my $suffix = Param('emailsuffix');
    map(s/$/$suffix/, @bugowners) if $suffix;
    my $bugowners = join(",", @bugowners);
    $vars->{'bugowners'} = $bugowners;
terry%netscape.com's avatar
terry%netscape.com committed
778 779
}

780 781 782
# Whether or not to split the column titles across two rows to make
# the list more compact.
$vars->{'splitheader'} = $::COOKIE{'SPLITHEADER'} ? 1 : 0;
terry%netscape.com's avatar
terry%netscape.com committed
783

784
$vars->{'quip'} = GetQuip();
785
$vars->{'currenttime'} = time();
786 787

# The following variables are used when the user is making changes to multiple bugs.
788
if ($dotweak) {
789 790 791 792 793 794 795 796 797 798 799 800 801 802
    $vars->{'dotweak'} = 1;
    $vars->{'use_keywords'} = 1 if @::legal_keywords;

    $vars->{'products'} = \@::legal_product;
    $vars->{'platforms'} = \@::legal_platform;
    $vars->{'priorities'} = \@::legal_priority;
    $vars->{'severities'} = \@::legal_severity;
    $vars->{'resolutions'} = \@::settable_resolution;

    $vars->{'unconfirmedstate'} = $::unconfirmedstate;

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

    # The groups to which the user belongs.
803
    $vars->{'groups'} = GetGroupsByUserId($::userid);
804 805 806 807 808 809 810 811 812 813 814

    # 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) {
        my $product = $vars->{'bugproducts'}->[0];
        $vars->{'versions'} = $::versions{$product};
        $vars->{'components'} = $::components{$product};
        $vars->{'targetmilestones'} = $::target_milestone{$product} if Param('usetargetmilestone');
terry%netscape.com's avatar
terry%netscape.com committed
815 816
    }
}
817

818

819 820 821
################################################################################
# HTTP Header Generation
################################################################################
822

823
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
824

825
my $contenttype;
terry%netscape.com's avatar
terry%netscape.com committed
826

827
if ($format->{'extension'} eq "html") {
828
    my $cookiepath = Param("cookiepath");
terry%netscape.com's avatar
terry%netscape.com committed
829

830
    if ($order) {
831
        $cgi->send_cookie(-name => 'LASTORDER',
832
                          -value => $order,
833
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
834
    }
835
    my $bugids = join(":", @bugidlist);
836
    # See also Bug 111999
837
    if (length($bugids) < 4000) {
838 839 840
        $cgi->send_cookie(-name => 'BUGLIST',
                          -value => $bugids,
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
841
    }
842
    else {
843 844
        $cgi->send_cookie(-name => 'BUGLIST',
                          -expires => 'Tue, 15-Sep-1998 21:49:00 GMT');
845
        $vars->{'toolong'} = 1;
terry%netscape.com's avatar
terry%netscape.com committed
846
    }
847 848

    $contenttype = "text/html";
849 850
}
else {
851
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
852 853
}

854 855 856 857 858 859 860 861 862
if ($serverpush) {
    print $cgi->multipart_start(-type=>$contenttype);
} 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,
                       -content_disposition => "inline; filename=$filename");
}
terry%netscape.com's avatar
terry%netscape.com committed
863

864

865 866 867
################################################################################
# Content Generation
################################################################################
868

869
# Generate and return the UI (HTML page) from the appropriate template.
870
$template->process($format->{'template'}, $vars)
871
  || ThrowTemplateError($template->error());
872

873

874 875 876 877
################################################################################
# Script Conclusion
################################################################################

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