buglist.cgi 36.6 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
use Bugzilla::Constants;
41 42

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

45 46 47 48 49 50 51 52 53 54 55 56 57 58
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
59

60 61
my $cgi = Bugzilla->cgi;

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

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

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

# Log the user in
if ($dotweak) {
76
    Bugzilla->login(LOGIN_REQUIRED);
77
    UserInGroup("editbugs") || ThrowUserError("insufficient_privs_for_multi");
78 79 80
    GetVersionTable();
}
else {
81
    Bugzilla->login();
82 83
}

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

# 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.
96
if ((exists $::FORM{'ctype'}) && ($::FORM{'ctype'} eq "js")) {
97
    Bugzilla->logout_request();
98
}
99

100 101 102
# 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.
103
my $format = GetFormat("list/list", $::FORM{'format'}, $::FORM{'ctype'});
104

105 106 107 108 109 110 111 112 113 114
# 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 =
115 116 117 118 119 120 121
  $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'};
122 123

my $order = $::FORM{'order'} || "";
124
my $order_from_cookie = 0;  # True if $order set using the LASTORDER cookie
125

126 127 128
# The params object to use for the actual query itself
my $params;

129 130 131
# 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'}) {
132
    $cgi->cookie('BUGLIST') || ThrowUserError("missing_cookie");
133

134
    $order = "reuse last sort" unless $order;
135 136 137

    # set up the params for this new query
    $params = new Bugzilla::CGI({
138
                                 bug_id => [split(/:/, $cgi->cookie('BUGLIST'))],
139 140
                                 order => $order,
                                });
141 142
}

143 144
if ($::buffer =~ /&cmd-/) {
    my $url = "query.cgi?$::buffer#chart";
145
    print $cgi->redirect(-location => $url);
146
    # Generate and return the UI (HTML page) from the appropriate template.
147
    $vars->{'message'} = "buglist_adding_field";
148 149
    $vars->{'url'} = $url;
    $template->process("global/message.html.tmpl", $vars)
150
      || ThrowTemplateError($template->error());
151 152
    exit;
}
153

154 155 156 157 158 159 160 161 162 163 164 165 166
# 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;
if ($::FORM{'content'}) { $fulltext = 1 }
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), keys %::FORM);
foreach my $chart (@charts) {
    if ($::FORM{"field$chart"} eq 'content' && $::FORM{"value$chart"}) {
        $fulltext = 1;
        last;
    }
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
################################################################################
# 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;
}
186

187 188 189 190 191 192 193 194
sub iCalendarDateTime {
    my ($datestr) = @_;
    my $date = str2time($datestr);
    my ($s,$m,$h,$d,$mo,$y,$wd)= gmtime $date;
    $date = sprintf "%04d%02d%02dT%02d%02d%02dZ", 1900+$y,$mo+1,$d,$h,$m,$s;
    return $date;
}

195 196
sub LookupNamedQuery {
    my ($name) = @_;
197
    Bugzilla->login(LOGIN_REQUIRED);
198
    my $userid = DBNameToIdAndCheck(Bugzilla->user->login);
199 200 201
    my $qname = SqlQuote($name);
    SendSQL("SELECT query FROM namedqueries WHERE userid = $userid AND name = $qname");
    my $result = FetchOneColumn();
202 203 204 205 206
    
    defined($result) || ThrowUserError("missing_query", {'queryname' => $name});
    $result
       || ThrowUserError("buglist_parameters_required", {'queryname' => $name});

207 208 209
    return $result;
}

210 211 212 213 214 215 216 217 218 219 220 221
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;
}

222
sub GetQuip {
223

224 225
    my $quip;

226 227 228 229 230 231 232
    # COUNT is quick because it is cached for MySQL. We may want to revisit
    # this when we support other databases.

    SendSQL("SELECT COUNT(quip) FROM quips WHERE approved = 1");
    my $count = FetchOneColumn();
    my $random = int(rand($count));
    SendSQL("SELECT quip FROM quips WHERE approved = 1 LIMIT $random,1");
233 234 235

    if (MoreSQLData()) {
        ($quip) = FetchSQLData();
236
    }
237 238

    return $quip;
239
}
240

241 242
sub GetGroupsByUserId {
    my ($userid) = @_;
243

244
    return if !$userid;
245 246

    SendSQL("
247 248
        SELECT DISTINCT  groups.id, name, description, isactive
                   FROM  groups, user_group_map
249
                  WHERE  user_id = $userid AND isbless = 0
250
                    AND  user_group_map.group_id = groups.id
251
                    AND  isbuggroup = 1
252
               ORDER BY  description ");
253 254 255 256 257

    my @groups;

    while (MoreSQLData()) {
        my $group = {};
258
        ($group->{'id'}, $group->{'name'},
259 260 261 262 263 264
         $group->{'description'}, $group->{'isactive'}) = FetchSQLData();
        push(@groups, $group);
    }

    return \@groups;
}
265

266

267 268 269
################################################################################
# Command Execution
################################################################################
270

271 272 273
$::FORM{'cmdtype'} ||= "";
$::FORM{'remaction'} ||= "";

274 275 276 277 278 279 280
# 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";
}

281 282 283 284 285 286
# 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);
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
# 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;
}

303 304 305
# Take appropriate action based on user's request.
if ($::FORM{'cmdtype'} eq "dorem") {  
    if ($::FORM{'remaction'} eq "run") {
306
        $::buffer = LookupNamedQuery($::FORM{"namedcmd"});
307
        $vars->{'searchname'} = $::FORM{'namedcmd'};
308
        $vars->{'searchtype'} = "saved";
309
        $params = new Bugzilla::CGI($::buffer);
310
        $order = $params->param('order') || $order;
311
    }
312 313
    elsif ($::FORM{'remaction'} eq "runseries") {
        $::buffer = LookupSeries($::FORM{"series_id"});
314
        $vars->{'searchname'} = $::FORM{'namedcmd'};
315
        $vars->{'searchtype'} = "series";
316 317 318
        $params = new Bugzilla::CGI($::buffer);
        $order = $params->param('order') || $order;
    }
319
    elsif ($::FORM{'remaction'} eq "forget") {
320
        Bugzilla->login(LOGIN_REQUIRED);
321
        my $userid = DBNameToIdAndCheck(Bugzilla->user->login);
322 323
        my $qname = SqlQuote($::FORM{'namedcmd'});
        SendSQL("DELETE FROM namedqueries WHERE userid = $userid AND name = $qname");
324 325 326

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

328
        print $cgi->header();
329
        # Generate and return the UI (HTML page) from the appropriate template.
330 331
        $vars->{'message'} = "buglist_query_gone";
        $vars->{'namedcmd'} = $::FORM{'namedcmd'};
332 333
        $vars->{'url'} = "query.cgi";
        $template->process("global/message.html.tmpl", $vars)
334
          || ThrowTemplateError($template->error());
335
        exit;
336 337
    }
}
338
elsif (($::FORM{'cmdtype'} eq "doit") && $::FORM{'remtype'}) {
339
    if ($::FORM{'remtype'} eq "asdefault") {
340
        Bugzilla->login(LOGIN_REQUIRED);
341
        my $userid = DBNameToIdAndCheck(Bugzilla->user->login);
342 343
        my $qname = SqlQuote($::defaultqueryname);
        my $qbuffer = SqlQuote($::buffer);
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

        SendSQL("LOCK TABLES namedqueries WRITE");

        SendSQL("SELECT userid FROM namedqueries WHERE userid = $userid " .
        "AND name = $qname");
        my $result = FetchOneColumn();
        if ($result) {
            SendSQL("UPDATE namedqueries SET query = $qbuffer " .
                    "WHERE userid = $userid AND name = $qname");
        } else {
            SendSQL("INSERT INTO namedqueries (userid, name, query, linkinfooter) VALUES " .
                    "($userid, $qname, $qbuffer, 0)");
        }

        SendSQL("UNLOCK TABLES");

360
        $vars->{'message'} = "buglist_new_default_query";
361
    }
362
    elsif ($::FORM{'remtype'} eq "asnamed") {
363
        Bugzilla->login(LOGIN_REQUIRED);
364
        my $userid = DBNameToIdAndCheck(Bugzilla->user->login);
365

366
        my $name = trim($::FORM{'newqueryname'});
367 368
        $name || ThrowUserError("query_name_missing");
        $name !~ /[<>&]/ || ThrowUserError("illegal_query_name");
369
        my $qname = SqlQuote($name);
370

371 372
        $::FORM{'newquery'} || ThrowUserError("buglist_parameters_required", 
                                              {'queryname' => $name});
373
        my $qbuffer = SqlQuote($::FORM{'newquery'});
374
        
375
        my $tofooter = 1;
376

377 378 379 380 381 382 383 384
        $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";
        }

385 386
        SendSQL("LOCK TABLES namedqueries WRITE");

387 388 389 390 391
        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");
392
        }
393
        else {
394
            SendSQL("INSERT INTO namedqueries (userid, name, query, linkinfooter)
395 396
                     VALUES ($userid, $qname, $qbuffer, $tofooter)");
        }
397

398 399
        SendSQL("UNLOCK TABLES");

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

404
        $vars->{'queryname'} = $name;
405
        
406
        print $cgi->header();
407 408 409
        $template->process("global/message.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
410
    }
terry%netscape.com's avatar
terry%netscape.com committed
411 412 413
}


414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
################################################################################
# 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, 
431
#       and the redundant short_desc column is removed when the client
432 433 434 435 436 437
#       requests "all" columns.

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

440
# Column:     ID                    Name                           Title
441
DefineColumn("bug_id"            , "bugs.bug_id"                , "ID"               );
442
DefineColumn("alias"             , "bugs.alias"                 , "Alias"           );
443 444
DefineColumn("opendate"          , "bugs.creation_ts"           , "Opened"           );
DefineColumn("changeddate"       , "bugs.delta_ts"              , "Changed"          );
445
DefineColumn("bug_severity"      , "bugs.bug_severity"          , "Severity"         );
446
DefineColumn("priority"          , "bugs.priority"              , "Priority"         );
447 448 449
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"         );
450
DefineColumn("reporter"          , "map_reporter.login_name"    , "Reporter"         );
451
DefineColumn("reporter_realname" , "map_reporter.realname"      , "Reporter"         );
452
DefineColumn("qa_contact"        , "map_qa_contact.login_name"  , "QA Contact"       );
453
DefineColumn("qa_contact_realname", "map_qa_contact.realname"   , "QA Contact"       );
454
DefineColumn("bug_status"        , "bugs.bug_status"            , "Status"           );
455
DefineColumn("resolution"        , "bugs.resolution"            , "Result"           );
456 457
DefineColumn("short_short_desc"  , "bugs.short_desc"            , "Summary"          );
DefineColumn("short_desc"        , "bugs.short_desc"            , "Summary"          );
458
DefineColumn("status_whiteboard" , "bugs.status_whiteboard"     , "Status Summary"   );
459 460
DefineColumn("component"         , "map_components.name"        , "Component"        );
DefineColumn("product"           , "map_products.name"          , "Product"          );
461
DefineColumn("version"           , "bugs.version"               , "Version"          );
462
DefineColumn("op_sys"            , "bugs.op_sys"                , "OS"               );
463 464 465
DefineColumn("target_milestone"  , "bugs.target_milestone"      , "Target Milestone" );
DefineColumn("votes"             , "bugs.votes"                 , "Votes"            );
DefineColumn("keywords"          , "bugs.keywords"              , "Keywords"         );
466 467 468
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");
469
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"); 
470 471 472
DefineColumn("relevance"         , "relevance"                  , "Relevance"        );


473 474 475 476 477 478 479
################################################################################
# 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 = ();
480 481
if (defined $params->param('columnlist')) {
    if ($params->param('columnlist') eq "all") {
482
        # If the value of the CGI parameter is "all", display all columns,
483 484
        # but remove the redundant "short_desc" column.
        @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
terry%netscape.com's avatar
terry%netscape.com committed
485
    }
486
    else {
487
        @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
488
    }
terry%netscape.com's avatar
terry%netscape.com committed
489
}
490
elsif (defined $cgi->cookie('COLUMNLIST')) {
491
    # 2002-10-31 Rename column names (see bug 176461)
492
    my $columnlist = $cgi->cookie('COLUMNLIST');
493 494 495 496 497 498 499
    $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/;
500

501
    # Use the columns listed in the user's preferences.
502
    @displaycolumns = split(/ /, $columnlist);
terry%netscape.com's avatar
terry%netscape.com committed
503
}
504 505 506
else {
    # Use the default list of columns.
    @displaycolumns = @::default_column_list;
507 508
}

509 510 511 512
# 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);
513

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

518 519 520
# 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.
521 522

# Some versions of perl will taint 'votes' if this is done as a single
523 524 525 526
# statement, because the votes param is tainted at this point
my $votes = $params->param('votes');
$votes ||= "";
if (trim($votes) && !grep($_ eq 'votes', @displaycolumns)) {
527 528
    push(@displaycolumns, 'votes');
}
terry%netscape.com's avatar
terry%netscape.com committed
529

530 531 532 533 534 535 536 537
# 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
538

539 540 541 542 543 544
# Remove the relevance column if the user is not doing a fulltext search.
if (grep('relevance', @displaycolumns) && !$fulltext) {
    @displaycolumns = grep($_ ne 'relevance', @displaycolumns);
}


545 546 547
################################################################################
# Select Column Determination
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
548

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

551
# The bug ID is always selected because bug IDs are always displayed.
552 553 554 555
# Severity, priority, resolution and status are required for buglist
# CSS classes.
my @selectcolumns = ("bug_id", "bug_severity", "priority", "bug_status",
                     "resolution");
556

557
# remaining and actual_time are required for precentage_complete calculation:
558
if (lsearch(\@displaycolumns, "percentage_complete") >= 0) {
559 560 561 562
    push (@selectcolumns, "remaining_time");
    push (@selectcolumns, "actual_time");
}

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

566 567 568 569 570
# 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);
571
    push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
572 573
}

574 575 576
if ($format->{'extension'} eq 'ics') {
    push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
}
577

578 579 580
################################################################################
# Query Generation
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
581

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

585 586 587 588
# Remove columns with no names, such as percentage_complete
#  (or a removed *_time column due to permissions)
@selectnames = grep($_ ne '', @selectnames);

589 590 591
################################################################################
# Sort Order Determination
################################################################################
592

593
# Add to the query some instructions for sorting the bug list.
594 595
if ($cgi->cookie('LASTORDER') && (!$order || $order =~ /^reuse/i)) {
    $order = $cgi->cookie('LASTORDER');
596
    $order_from_cookie = 1;
597
}
598

599
my $db_order = "";  # Modified version of $order for use with SQL query
600 601 602 603
if ($order) {
    # Convert the value of the "order" form field into a list of columns
    # by which to sort the results.
    ORDER: for ($order) {
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        /^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;
622
            my @columnnames = map($columns->{lc($_)}->{'name'}, keys(%$columns));
623
            # A custom list of columns.  Make sure each column is valid.
624 625 626 627
            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)
628 629 630 631 632
                if (grep($fragment =~ /^\Q$_\E(\s+(asc|desc))?$/, @columnnames)) {
                    next if $fragment =~ /\brelevance\b/ && !$fulltext;
                    push(@order, $fragment);
                }
                else {
633
                    my $vars = { fragment => $fragment };
634
                    if ($order_from_cookie) {
635 636
                        $cgi->send_cookie(-name => 'LASTORDER',
                                          -expires => 'Tue, 15-Sep-1998 21:49:00 GMT');
637
                        ThrowCodeError("invalid_column_name_cookie", $vars);
638 639
                    }
                    else {
640
                        ThrowCodeError("invalid_column_name_form", $vars);
641
                    }
642 643
                }
            }
644
            $order = join(",", @order);
645 646 647
            # Now that we have checked that all columns in the order are valid,
            # detaint the order string.
            trick_taint($order);
648
        };
terry%netscape.com's avatar
terry%netscape.com committed
649
    }
650 651 652 653 654
}
else {
    # DEFAULT
    $order = "bugs.bug_status, bugs.priority, map_assigned_to.login_name, bugs.bug_id";
}
655

656 657 658 659 660 661 662 663 664 665
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;
    }
}
666

667
$db_order = $order;  # Copy $order into $db_order for use with SQL query
668

669 670 671 672 673 674 675 676
# 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;
677

678 679 680
# 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;
681

682 683 684 685 686 687 688 689 690 691 692 693 694 695
# 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 /;
}

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

696 697 698 699
if ($::FORM{'limit'} && detaint_natural($::FORM{'limit'})) {
    $query .= " LIMIT $::FORM{'limit'}";
}
elsif ($fulltext) {
700 701 702
    $query .= " LIMIT 200";
}

703

704 705 706
################################################################################
# Query Execution
################################################################################
707

708 709 710 711 712
if ($::FORM{'debug'}) {
    $vars->{'debug'} = 1;
    $vars->{'query'} = $query;
}

713 714 715
# 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) {
716 717 718
    print $cgi->multipart_init(-content_disposition => "inline; filename=$filename");

    print $cgi->multipart_start();
719

720
    # Generate and return the UI (HTML page) from the appropriate template.
721 722
    $template->process("list/server-push.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
723 724

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

727 728
# Connect to the shadow database if this installation is using one to improve
# query performance.
729
Bugzilla->switch_to_shadow_db();
terry%netscape.com's avatar
terry%netscape.com committed
730

731 732 733 734 735 736
# 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';

737 738
# Execute the query.
SendSQL($query);
739

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

741 742 743
################################################################################
# Results Retrieval
################################################################################
terry%netscape.com's avatar
terry%netscape.com committed
744

745 746
# 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
747

748 749 750
my $bugowners = {};
my $bugproducts = {};
my $bugstatuses = {};
751
my @bugidlist;
terry%netscape.com's avatar
terry%netscape.com committed
752

753
my @bugs; # the list of records
754

755 756
while (my @row = FetchSQLData()) {
    my $bug = {}; # a record
757

758
    # Slurp the row of data into the record.
759 760
    # The second from last column in the record is the number of groups
    # to which the bug is restricted.
761
    foreach my $column (@selectcolumns) {
762
        $bug->{$column} = shift @row;
763
    }
terry%netscape.com's avatar
terry%netscape.com committed
764

765 766 767
    # Process certain values further (i.e. date format conversion).
    if ($bug->{'changeddate'}) {
        $bug->{'changeddate'} =~ 
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
            s/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/$1-$2-$3 $4:$5:$6/;
        if ($format->{'extension'} eq 'ics') {
            $bug->{'changeddate'} = iCalendarDateTime($bug->{'changeddate'});
        }
        else {
            $bug->{'changeddate'} = DiffDate($bug->{'changeddate'});
        }
    }

    if ($bug->{'opendate'}) {
        if ($format->{'extension'} eq 'ics') {
            $bug->{'opendate'} = iCalendarDateTime($bug->{'opendate'});
        }
        else {
            $bug->{'opendate'} = DiffDate($bug->{'opendate'});
        }
784
    }
terry%netscape.com's avatar
terry%netscape.com committed
785

786
    # Record the owner, product, and status in the big hashes of those things.
787
    $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
788
    $bugproducts->{$bug->{'product'}} = 1 if $bug->{'product'};
789
    $bugstatuses->{$bug->{'bug_status'}} = 1 if $bug->{'bug_status'};
terry%netscape.com's avatar
terry%netscape.com committed
790

791 792
    $bug->{isingroups} = 0;

793 794
    # Add the record to the list.
    push(@bugs, $bug);
795 796

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

800 801 802 803 804 805 806 807
# 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()) {
808 809
        my ($bug_id) = FetchSQLData();
        $privatebugs{$bug_id} = 1;
810 811
    }
    foreach my $bug (@bugs) {
812
        if ($privatebugs{$bug->{'bug_id'}}) {
813 814 815 816
            $bug->{isingroups} = 1;
        }
    }
}
817

818 819 820
################################################################################
# Template Variable Definition
################################################################################
821

822
# Define the variables and functions that will be passed to the UI template.
823

824
$vars->{'bugs'} = \@bugs;
825
$vars->{'buglist'} = join(',', @bugidlist);
826 827
$vars->{'columns'} = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;
828

829 830 831
my @openstates = OpenStates();
$vars->{'openstates'} = \@openstates;
$vars->{'closedstates'} = ['CLOSED', 'VERIFIED', 'RESOLVED'];
832

833 834 835 836 837 838 839 840
# 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;
841
$vars->{'urlquerypart'} =~ s/(order|cmdtype)=[^&]*&?//g;
842
$vars->{'order'} = $order;
terry%netscape.com's avatar
terry%netscape.com committed
843

844
# The user's login account name (i.e. email address).
845
my $login = Bugzilla->user ? Bugzilla->user->login : "";
846

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

849 850 851
# Whether or not this user is authorized to move bugs to another installation.
$vars->{'ismover'} = 1
  if Param('move-enabled')
852 853
    && defined($login)
      && Param('movers') =~ /^(\Q$login\E[,\s])|([,\s]\Q$login\E[,\s]+)/;
854

855 856 857 858 859 860
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
861 862
}

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

867
$vars->{'quip'} = GetQuip();
868
$vars->{'currenttime'} = time();
869 870 871
if ($format->{'extension'} eq 'ics') {
    $vars->{'currenttime'} = iCalendarDateTime(scalar gmtime $vars->{'currenttime'});
}
872 873

# The following variables are used when the user is making changes to multiple bugs.
874
if ($dotweak) {
875 876 877
    $vars->{'dotweak'} = 1;
    $vars->{'use_keywords'} = 1 if @::legal_keywords;

878 879
    my @enterable_products = GetEnterableProducts();
    $vars->{'products'} = \@enterable_products;
880 881 882 883 884 885 886 887 888 889
    $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.
890
    $vars->{'groups'} = GetGroupsByUserId($::userid);
891 892 893 894 895 896 897 898 899 900 901

    # 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
902 903
    }
}
904

905

906 907 908
################################################################################
# HTTP Header Generation
################################################################################
909

910
# Generate HTTP headers
terry%netscape.com's avatar
terry%netscape.com committed
911

912
my $contenttype;
913
my $disp = "inline";
terry%netscape.com's avatar
terry%netscape.com committed
914

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

918
    if ($order) {
919
        $cgi->send_cookie(-name => 'LASTORDER',
920
                          -value => $order,
921
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
922
    }
923
    my $bugids = join(":", @bugidlist);
924
    # See also Bug 111999
925
    if (length($bugids) < 4000) {
926 927 928
        $cgi->send_cookie(-name => 'BUGLIST',
                          -value => $bugids,
                          -expires => 'Fri, 01-Jan-2038 00:00:00 GMT');
929
    }
930
    else {
931 932
        $cgi->send_cookie(-name => 'BUGLIST',
                          -expires => 'Tue, 15-Sep-1998 21:49:00 GMT');
933
        $vars->{'toolong'} = 1;
terry%netscape.com's avatar
terry%netscape.com committed
934
    }
935 936

    $contenttype = "text/html";
937 938
}
else {
939
    $contenttype = $format->{'ctype'};
terry%netscape.com's avatar
terry%netscape.com committed
940 941
}

942 943 944 945 946 947
if ($format->{'extension'} eq "csv") {
    # We set CSV files to be downloaded, as they are designed for importing
    # into other programs.
    $disp = "attachment";
}

948 949 950 951 952 953 954
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,
955
                       -content_disposition => "$disp; filename=$filename");
956
}
terry%netscape.com's avatar
terry%netscape.com committed
957

958

959 960 961
################################################################################
# Content Generation
################################################################################
962

963
# Generate and return the UI (HTML page) from the appropriate template.
964
$template->process($format->{'template'}, $vars)
965
  || ThrowTemplateError($template->error());
966

967

968 969 970 971
################################################################################
# Script Conclusion
################################################################################

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