summaryrefslogtreecommitdiff
blob: 560c97414c256966a23dfa05ff18d66f24faf89c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
#!/usr/bin/perl -T
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.

use 5.10.1;
use strict;
use warnings;

use lib qw(. lib);

use Bugzilla;
use Bugzilla::Constants;
use Bugzilla::Error;
use Bugzilla::Util;
use Bugzilla::Search;
use Bugzilla::Search::Quicksearch;
use Bugzilla::Search::Recent;
use Bugzilla::Search::Saved;
use Bugzilla::Bug;
use Bugzilla::Product;
use Bugzilla::Field;
use Bugzilla::Status;
use Bugzilla::Token;

use Date::Parse;
use List::MoreUtils qw(any uniq);

my $cgi      = Bugzilla->cgi;
my $dbh      = Bugzilla->dbh;
my $template = Bugzilla->template;
my $vars     = {};

## REDHAT EXTENSION BEGIN 706784
# Define the values
my @multiple_fields
  = qw(multiple_components multiple_target_releases multiple_versions);
foreach (@multiple_fields) {
  $vars->{$_} = 0;
}
## REDHAT EXTENSION END 706784

# 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'.
my $user = Bugzilla->login();

$cgi->redirect_search_url();

my $buffer = $cgi->query_string();
if (length($buffer) == 0) {
  ThrowUserError("buglist_parameters_required");
}

# 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.
}

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

################################################################################
# Data and Security Validation
################################################################################

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

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

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

$cgi->delete('the_orders');

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

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

# 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 compatible with Gecko-based browsers and Opera, but not with
# MSIE, Lynx or Safari (bug 441496).

my $serverpush
  = $format->{'extension'} eq "html"
  && exists $ENV{'HTTP_USER_AGENT'}
  && $ENV{'HTTP_USER_AGENT'} =~ /(Mozilla.[3-9]|Opera)/
  && $ENV{'HTTP_USER_AGENT'} !~ /compatible/i
  && $ENV{'HTTP_USER_AGENT'} !~ /(?:WebKit|Trident|KHTML)/
  && !defined($cgi->param('serverpush')) || $cgi->param('serverpush');
## REDHAT EXTENSION START 1539437
$serverpush = 0;
## REDHAT EXTENSION END 1539437

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

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

# 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 (my $last_list = $cgi->param('regetlastlist')) {
  my $bug_ids;

  # Logged-out users use the old cookie method for storing the last search.
  if (!$user->id or $last_list eq 'cookie') {
    $bug_ids = $cgi->cookie('BUGLIST') or ThrowUserError("missing_cookie");
    $bug_ids =~ s/[:-]/,/g;
    $order ||= "reuse last sort";
  }

  # But logged in users store the last X searches in the DB so they can
  # have multiple bug lists available.
  else {
    my $last_search = Bugzilla::Search::Recent->check({id => $last_list});
    $bug_ids = join(',', @{$last_search->bug_list});
    $order ||= $last_search->list_order;
  }

  # set up the params for this new query
  $params = new Bugzilla::CGI({bug_id => $bug_ids, order => $order});
  $params->param('list_id', $last_list);
}

# 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 ($cgi->param('content')) { $fulltext = 1 }
my @charts = map(/^field(\d-\d-\d)$/ ? $1 : (), $cgi->param());
foreach my $chart (@charts) {
  if ($cgi->param("field$chart") eq 'content' && $cgi->param("value$chart")) {
    $fulltext = 1;
    last;
  }
}

## REDHAT EXTENSION START 1503911
# Handle advanced search fields
@charts = map(/^f(\d+)$/ ? $1 : (), $cgi->param());
foreach my $chart (@charts) {
  if ($cgi->param("f$chart") eq 'content' && $cgi->param("v$chart")) {
    $fulltext = 1;
    last;
  }
}
## REDHAT EXTENSION END 1503911

################################################################################
# Utilities
################################################################################

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

  if ($age < 18 * 60 * 60) {
    $date = format_time($datestr, '%H:%M:%S');
  }
  elsif ($age < 6 * 24 * 60 * 60) {
    $date = format_time($datestr, '%a %H:%M');
  }
  else {
    $date = format_time($datestr, '%Y-%m-%d');
  }
  return $date;
}

sub LookupNamedQuery {
  my ($name, $sharer_id) = @_;

  Bugzilla->login(LOGIN_REQUIRED);

  my $query = Bugzilla::Search::Saved->check(
    {user => $sharer_id, name => $name, _error => 'missing_query'});

  $query->url || ThrowUserError("buglist_parameters_required");

  # Detaint $sharer_id.
  $sharer_id = $query->user->id if $sharer_id;
  return wantarray ? ($query->url, $query->id, $sharer_id) : $query->url;
}

# 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.
#
# 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.
sub InsertNamedQuery {
  my ($query_name, $query, $link_in_footer) = @_;
  my $dbh = Bugzilla->dbh;

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

  if ($query_obj) {
    $query_obj->set_name($query_name);
    $query_obj->set_url($query);
    $query_obj->update();
  }
  else {
    Bugzilla::Search::Saved->create({
      name => $query_name, query => $query, link_in_footer => $link_in_footer
    });
  }

  return $query_obj ? 1 : 0;
}

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 = ?",
    undef, ($series_id));
  $result || ThrowCodeError("invalid_series_id", {'series_id' => $series_id});
  return $result;
}

sub GetQuip {
  my $dbh = Bugzilla->dbh;

  # COUNT is quick because it is cached for MySQL. We may want to revisit
  # this when we support other databases.
  my $count = $dbh->selectrow_array(
    "SELECT COUNT(quip)" . " FROM quips WHERE approved = 1");
  my $random = int(rand($count));
  my $quip   = $dbh->selectrow_array(
    "SELECT quip FROM quips WHERE approved = 1 " . $dbh->sql_limit(1, $random));
  return $quip;
}

# Return groups available for at least one product of the buglist.
sub GetGroups {
  my $product_names = shift;
  my $user          = Bugzilla->user;
  my %legal_groups;

  foreach my $product_name (@$product_names) {
    my $product = Bugzilla::Product->new({name => $product_name, cache => 1});

    foreach my $gid (keys %{$product->group_controls}) {

      # The user can only edit groups they belong to.
      next unless $user->in_group_id($gid);

      # The user has no control on groups marked as NA or MANDATORY.
      my $group = $product->group_controls->{$gid};
      next
        if ($group->{membercontrol} == CONTROLMAPMANDATORY
        || $group->{membercontrol} == CONTROLMAPNA);

      # It's fine to include inactive groups. Those will be marked
      # as "remove only" when editing several bugs at once.
      $legal_groups{$gid} ||= $group->{group};
    }
  }

  # Return a list of group objects.
  return [values %legal_groups];
}

sub _get_common_flag_types {
  my $component_ids = shift;
  my $user          = Bugzilla->user;

  # Get all the different components in the bug list
  my $components = Bugzilla::Component->new_from_list($component_ids);
  my %flag_types;
  my @flag_types_ids;
  foreach my $component (@$components) {
    foreach my $flag_type (@{$component->flag_types->{'bug'}}) {
      push @flag_types_ids, $flag_type->id;
      $flag_types{$flag_type->id} = $flag_type;
    }
  }

  # We only want flags that appear in all components
  my %common_flag_types;
  foreach my $id (keys %flag_types) {
    my $flag_type_count = scalar grep { $_ == $id } @flag_types_ids;
    $common_flag_types{$id} = $flag_types{$id}
      if $flag_type_count == scalar @$components;
  }

  # We only show flags that a user can request.
  my @show_flag_types
    = grep { $user->can_request_flag($_) } values %common_flag_types;
  my $any_flags_requesteeble = grep { $_->is_requesteeble } @show_flag_types;

  return (\@show_flag_types, $any_flags_requesteeble);
}

################################################################################
# Command Execution
################################################################################

my $cmdtype   = $cgi->param('cmdtype')   || '';
my $remaction = $cgi->param('remaction') || '';
my $sharer_id;

# 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 ($cmdtype eq "runnamed") {
  $cmdtype   = "dorem";
  $remaction = "run";
}

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

# 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 $disp_prefix = "bugs";
if ($cmdtype eq "dorem" && $remaction =~ /^run/) {
  $disp_prefix = $cgi->param('namedcmd');
}

# Take appropriate action based on user's request.
if ($cmdtype eq "dorem") {
  if ($remaction eq "run") {
    my $query_id;
    ($buffer, $query_id, $sharer_id)
      = 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.
    ## REDHAT EXTENSION BEGIN 523845
    Bugzilla::Search::Saved::update_expiry_timestamp($query_id);
    ## REDHAT EXTENSION END 523845
    $vars->{'searchname'} = $cgi->param('namedcmd');
    if (!$cgi->param('sharer_id') || $cgi->param('sharer_id') == $user->id) {
      $vars->{'searchtype'} = "saved";
      $vars->{'search_id'}  = $query_id;
    }
    $params = new Bugzilla::CGI($buffer);
    $order  = $params->param('order') || $order;

  }
  elsif ($remaction eq "runseries") {
    $buffer               = LookupSeries(scalar $cgi->param("series_id"));
    $vars->{'searchname'} = $cgi->param('namedcmd');
    $vars->{'searchtype'} = "series";
    $params               = new Bugzilla::CGI($buffer);
    $order                = $params->param('order') || $order;
  }
  elsif ($remaction eq "forget") {
    $user = Bugzilla->login(LOGIN_REQUIRED);

    # 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.
    my $qname = $cgi->param('namedcmd');
    trick_taint($qname);

    # 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
                                                      = ?
                                      ', undef, $user->id, $qname
    );
    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
    my $query_id;
    ($buffer, $query_id)
      = LookupNamedQuery(scalar $cgi->param("namedcmd"), $user->id);
    if ($query_id) {

      # Make sure the user really wants to delete their saved search.
      my $token = $cgi->param('token');
      check_hash_token($token, [$query_id, $qname]);

      ## REDHAT EXTENSION BEGIN 1225325
      $dbh->bz_start_transaction();
      ## REDHAT EXTENSION END 1225325

      $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
      );

      ## REDHAT EXTENSION BEGIN 513060
      $dbh->do(
        'DELETE FROM namedqueries_in_front_page
                            WHERE namedquery_id = ?', undef, $query_id
      );
      ## REDHAT EXTENSION END 513060

      ## REDHAT EXTENSION BEGIN 1225325
      $dbh->bz_commit_transaction();
      ## REDHAT EXTENSION END 1225325
    }

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

    print $cgi->header();

    # Generate and return the UI (HTML page) from the appropriate template.
    $vars->{'message'}  = "buglist_query_gone";
    $vars->{'namedcmd'} = $qname;
    $vars->{'url'}
      = "buglist.cgi?newquery="
      . url_quote($buffer)
      . "&cmdtype=doit&remtype=asnamed&newqueryname="
      . url_quote($qname)
      . "&token="
      . url_quote(issue_hash_token(['savedsearch']));
    $template->process("global/message.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
    exit;
  }
}
elsif (($cmdtype eq "doit") && defined $cgi->param('remtype')) {
  if ($cgi->param('remtype') eq "asdefault") {
    $user = Bugzilla->login(LOGIN_REQUIRED);
    my $token = $cgi->param('token');
    check_hash_token($token, ['searchknob']);
    $buffer = $params->canonicalise_query('cmdtype', 'remtype', 'query_based_on',
      'token');
    InsertNamedQuery(DEFAULT_QUERY_NAME, $buffer);
    $vars->{'message'} = "buglist_new_default_query";
  }
  elsif ($cgi->param('remtype') eq "asnamed") {
    $user = Bugzilla->login(LOGIN_REQUIRED);
    my $query_name = $cgi->param('newqueryname');
    my $new_query  = $cgi->param('newquery');
    my $token      = $cgi->param('token');
    check_hash_token($token, ['savedsearch']);
    my $existed_before = InsertNamedQuery($query_name, $new_query, 1);
    if ($existed_before) {
      $vars->{'message'} = "buglist_updated_named_query";
    }
    else {
      $vars->{'message'} = "buglist_new_named_query";
    }
    $vars->{'queryname'} = $query_name;

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

    print $cgi->header();
    $template->process("global/message.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
    exit;
  }
}

# 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');
  $buffer = $params->query_string;
}

## REDHAT EXTENSION START 2124411
$vars->{'row_group1'} = defined $params->param('row_group1');
$vars->{'row_group2'} = defined $params->param('row_group2');
## REDHAT EXTENSION END 2124411

################################################################################
# Column Definition
################################################################################

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

################################################################################
# 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 = ();
if (defined $params->param('columnlist')) {
  if ($params->param('columnlist') eq "all") {

    # If the value of the CGI parameter is "all", display all columns,
    # but remove the redundant "short_desc" column.
    @displaycolumns = grep($_ ne 'short_desc', keys(%$columns));
  }
  else {
    ## REDHAT EXTENSION START 2133587
    if ($params->param('columnlist') =~ m/delta_ts/) {
      my $col_list = $params->param('columnlist');
      $col_list =~ s/delta_ts/changeddate/;
      $params->param('columnlist', $col_list);
    }
    ## REDHAT EXTENSION END 2133587

    @displaycolumns = split(/[ ,]+/, $params->param('columnlist'));
  }
}
elsif (defined $cgi->cookie('COLUMNLIST')) {

  # 2002-10-31 Rename column names (see bug 176461)
  my $columnlist = $cgi->cookie('COLUMNLIST');
  $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/;

  # Use the columns listed in the user's preferences.
  @displaycolumns = split(/ /, $columnlist);
}
else {
  # Use the default list of columns.
  @displaycolumns = DEFAULT_COLUMN_LIST;
}

## REDHAT EXTENSION START 1123712
# In Red Hat Bugzilla <= 3.6 we allowed 'flags' as a column. It was added
# as flagtypes.name in upstream 4.0, but broke our customisation
foreach my $field (@displaycolumns) {
  $field = 'flagtypes.name' if $field eq 'flags';
}
## REDHAT EXTENSION END 1123712

# 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.
## REDHAT EXTENSION START 2133587
my (@real_cols, @unknown);
foreach my $column (@displaycolumns) {
  trick_taint($column);
  if (defined $columns->{$column}) {
    push(@real_cols, $column);
  }
  elsif (defined Bugzilla->EXT2INT_FIELD_MAP->{$column}) {
    push(@real_cols, Bugzilla->EXT2INT_FIELD_MAP->{$column});
  }
  else {
    ## One day we should throw an error or at least complain about these
    push(@unknown, $column);
  }
}

@displaycolumns = @real_cols;
## REDHAT EXTENSION END 2133587

# Remove the "ID" column from the list because bug IDs are always displayed
# and are hard-coded into the display templates.
@displaycolumns = grep($_ ne 'bug_id', @displaycolumns);

# 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 (!$user->is_timetracker) {
  foreach my $tt_field (TIMETRACKING_FIELDS) {
    @displaycolumns = grep($_ ne $tt_field, @displaycolumns);
  }
}

## REDHAT EXTENSION START 1503911
# For now we are going to inject the column whenever an FTS is run
# Remove the relevance column if the user is not doing a fulltext search.
#if (grep('relevance', @displaycolumns) && !$fulltext) {
@displaycolumns = grep($_ ne 'relevance', @displaycolumns);

#}
unshift(@displaycolumns, 'relevance') if ($fulltext);
## REDHAT EXTENSION END 1503911

################################################################################
# Select Column Determination
################################################################################

# Generate the list of columns that will be selected in the SQL query.

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

# remaining and actual_time are required for percentage_complete calculation:
if (grep { $_ eq "percentage_complete" } @displaycolumns) {
  push(@selectcolumns, "remaining_time");
  push(@selectcolumns, "actual_time");
}

# Make sure that the login_name version of a field is always also
# requested if the realname version is requested, so that we can
# display the login name when the realname is empty.
my @realname_fields = grep(/_realname$/, @displaycolumns);
foreach my $item (@realname_fields) {
  my $login_field = $item;
  $login_field =~ s/_realname$//;
  if (!grep($_ eq $login_field, @selectcolumns)) {
    push(@selectcolumns, $login_field);
  }
}

# Display columns are selected because otherwise we could not display them.
foreach my $col (@displaycolumns) {
  push(@selectcolumns, $col) if !grep($_ eq $col, @selectcolumns);
}

# If the user is editing multiple bugs, we also make sure to select the
# status, because the values of that field determines what options the user
# has for modifying the bugs.
if ($dotweak) {
  push(@selectcolumns, "bug_status") if !grep($_ eq 'bug_status', @selectcolumns);
  push(@selectcolumns, "bugs.component_id");
}

if ($format->{'extension'} eq 'ics') {
  push(@selectcolumns, "opendate") if !grep($_ eq 'opendate', @selectcolumns);
  if (Bugzilla->params->{'timetrackinggroup'}) {
    push(@selectcolumns, "deadline") if !grep($_ eq 'deadline', @selectcolumns);
  }
}

if ($format->{'extension'} eq 'atom') {

  # The title of the Atom feed will be the same one as for the bug list.
  $vars->{'title'} = $cgi->param('title');

  # This is the list of fields that are needed by the Atom filter.
  my @required_atom_columns = (
    'short_desc',           'opendate',   'changeddate',  'reporter',
    'reporter_realname',    'priority',   'bug_severity', 'assigned_to',
    'assigned_to_realname', 'bug_status', 'product',      'component',
    'resolution'
  );
  push(@required_atom_columns, 'target_milestone')
    if Bugzilla->params->{'usetargetmilestone'};

  foreach my $required (@required_atom_columns) {
    push(@selectcolumns, $required) if !grep($_ eq $required, @selectcolumns);
  }
}

################################################################################
# Sort Order Determination
################################################################################

# Add to the query some instructions for sorting the bug list.

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

    # Cookies from early versions of Specific Search included this text,
    # which is now invalid.
    $order =~ s/ LIMIT 200//;
  }
  else {
    $order = '';    # Remove possible "reuse" identifier as unnecessary
  }
}

my @order_columns;
if ($order) {

  # Convert the value of the "order" form field into a list of columns
  # by which to sort the results.
ORDER: for ($order) {
    /^Bug Number$/ && do {
      @order_columns = ("bug_id");
      last ORDER;
    };
    /^Importance$/ && do {
      @order_columns = ("priority", "bug_severity");
      last ORDER;
    };
    /^Assignee$/ && do {
      @order_columns = ("assigned_to", "bug_status", "priority", "bug_id");
      last ORDER;
    };
    /^Last Changed$/ && do {
      @order_columns
        = ("changeddate", "bug_status", "priority", "assigned_to", "bug_id");
      last ORDER;
    };
    do {
      # A custom list of columns. Bugzilla::Search will validate items.
      @order_columns = split(/\s*,\s*/, $order);
    };
  }
}

if (!scalar @order_columns) {

  # DEFAULT
  @order_columns = ("bug_status", "priority", "assigned_to", "bug_id");

  unshift(@order_columns, 'relevance DESC') if($fulltext);
}

## REDHAT EXTENSION START 2133587
my (@real_order, @unknown_order_cols);
foreach my $col (@order_columns) {
  trick_taint($col);
  my ($column, $dir) = split (/\s+/, $col);

  if (defined $columns->{$column}) {
    push(@real_order, $col);
  }
  elsif (defined Bugzilla->EXT2INT_FIELD_MAP->{$column}) {
    my $real_col = Bugzilla->EXT2INT_FIELD_MAP->{$column};
    $real_col .= " $dir" if($dir);
    push(@real_order, $real_col);
  }
  else {
    ## One day we should throw an error or at least complain about these
    push(@unknown_order_cols, $col);
  }
}
@order_columns = @real_order;
## REDHAT EXTENSION END 2133587

# In the HTML interface, by default, we limit the returned results,
# which speeds up quite a few searches where people are really only looking
# for the top results.

#  RED HAT EXTENSION START 1347097
#if ($format->{'extension'} eq 'html' && !defined $params->param('limit')) {
#  $params->param('limit', Bugzilla->params->{'default_search_limit'});
#  $vars->{'default_limited'} = 1;
#}
#  RED HAT EXTENSION END 1347097

## REDHAT EXTENSION BEGIN 1315421

my $search_terms = scalar $params->Vars;

Bugzilla::Hook::process('buglist_filter_params', {params => $search_terms});

my $old_user = Bugzilla->user;
if ($cgi->should_restrict_searches) {
  ThrowUserError('bad_referer', {no_back => 1});
}

#  RED HAT EXTENSION START 1347097
# BUGBUG this doesn't get copied when set in the URI
if (!defined $params->param('limit') && defined $cgi->param('limit')) {
  $params->param('limit', $cgi->param('limit'));
}

if (!defined $params->param('offset') && defined $cgi->param('offset')) {
  $params->param('offset', $cgi->param('offset'));
}

if (!Bugzilla->user->id) {
  $params->param('limit',
    Bugzilla->user->settings->{'def_buglist_size'}->{'value'});
}
else {
  unless (defined $params->param('limit')
    && $params->param('limit') >= 0
    && $params->param('limit') <= Bugzilla->params->{max_search_results})
  {
    $params->param('limit',
      Bugzilla->user->settings->{'def_buglist_size'}->{'value'});
    $vars->{'default_limited'} = 1;
  }
}
#  RED HAT EXTENSION END 1347097

# Generate the basic SQL query that will be used to generate the bug list.
my $search = new Bugzilla::Search(
  'fields' => \@selectcolumns,
  'params' => $search_terms,
  'order'  => \@order_columns,
  'sharer' => $sharer_id
);
## REDHAT EXTENSION END 1315421

$order = join(',', $search->order);

## REDHAT EXTENSION BEGIN 1039815
# We need to determine if any columns need to be filtered. Best to do this
# once rather than once per row :)
my %filtered_columns = ();
foreach my $column (@selectcolumns) {

  # Not all columns are fields
  my $field = Bugzilla::Field->new({name => $column});
  if (
    $field
## REDHAT EXTENSION START 1323078
    && (
      (
           $field->type == Bugzilla::Constants::FIELD_TYPE_MULTI_SELECT
        || $field->type == Bugzilla::Constants::FIELD_TYPE_ONE_SELECT
      )
      || ($field->name =~ /agile_pool/)
    )
## REDHAT EXTENSION END 1323078
    )
  {
    # Some fields (like partner, are restricted on what you can see)
    my $values = Bugzilla->user->see_field_values($field);

    # not defined = no restrictions, scalar = some values
    if (defined $values) {
      $filtered_columns{$column} = $values;
    }
  }
}
## REDHAT EXTENSION END 1039815

if (scalar @{$search->invalid_order_columns}) {
  $vars->{'message'}           = 'invalid_column_name';
  $vars->{'invalid_fragments'} = $search->invalid_order_columns;
}

if ($fulltext and grep {/^relevance/} $search->order) {
  $vars->{'message'} = 'buglist_sorted_by_relevance';
}

# We don't want saved searches and other buglist things to save
# our default limit.
$params->delete('limit') if $vars->{'default_limited'};

################################################################################
# Query Execution
################################################################################

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

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

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

  # 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.
}

# Connect to the shadow database if this installation is using one to improve
# query performance.
$dbh = Bugzilla->switch_to_shadow_db();

# Normally, we ignore SIGTERM and SIGPIPE, 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';

# Execute the query.
#  RED HAT EXTENSION START 1347097
my ($data, $extra_data);
if (($cgi->param('format') && $cgi->param('format') eq 'tvp')
  || $format->{'extension'} eq 'csv' || $format->{'extension'} eq 'atom')
{
  ($data, $extra_data) = $search->data;
}

$vars->{'search_description'} = $search->search_description;
$vars->{'num_matches'}        = 0 + @{$search->bug_ids};
#  RED HAT EXTENSION END 1347097

Bugzilla->set_user($old_user);

if ( $cgi->param('debug')
  && Bugzilla->params->{debug_group}
  && $user->in_group(Bugzilla->params->{debug_group}))
{
  $vars->{'debug'}   = 1;
  $vars->{'queries'} = $extra_data;
  my $query_time = 0;
  $query_time += $_->{'time'} foreach @$extra_data;
  $vars->{'query_time'} = $query_time;

  # Explains are limited to admins because you could use them to figure
  # out how many hidden bugs are in a particular product (by doing
  # searches and looking at the number of rows the explain says it's
  # examining).
  if ($user->in_group('admin')) {
    foreach my $query (@$extra_data) {
      $query->{explain} = $dbh->bz_explain($query->{sql});
    }
  }
}

################################################################################
# Results Retrieval
################################################################################

# Retrieve the query results one row at a time and write the data into a list
# of Perl records.

# If we're doing time tracking, then keep totals for all bugs.
my $percentage_complete = grep($_ eq 'percentage_complete', @displaycolumns);
my $estimated_time      = grep($_ eq 'estimated_time',      @displaycolumns);
my $remaining_time
  = grep($_ eq 'remaining_time', @displaycolumns) || $percentage_complete;
my $actual_time
  = grep($_ eq 'actual_time', @displaycolumns) || $percentage_complete;

my $time_info = {
  'estimated_time'      => 0,
  'remaining_time'      => 0,
  'actual_time'         => 0,
  'percentage_complete' => 0,
  'time_present' =>
    ($estimated_time || $remaining_time || $actual_time || $percentage_complete),
};

my $bugowners       = {};
my $bugproducts     = {};
my $bugcomponentids = {};
my $bugcomponents   = {};
my $bugstatuses     = {};
#  RED HAT EXTENSION START 1347097
my @bugidlist;
if ((!$cgi->param('format') || $cgi->param('format') ne 'tvp')
  || $format->{'extension'} eq 'csv')
{
  @bugidlist = @{$search->bug_ids};
}
#  RED HAT EXTENSION END 1347097

my @bugs;    # the list of records

foreach my $row (@$data) {
  my $bug = {};    # a record

  # Slurp the row of data into the record.
  # The second from last column in the record is the number of groups
  # to which the bug is restricted.
  foreach my $column (@selectcolumns) {
    ## REDHAT EXTENSION START 479375 1039815
    if (defined($filtered_columns{$column}) && defined($row->[0])) {
## REDHAT EXTENSION START 1323078
      if ($column =~ /agile_pool/i && defined $filtered_columns{$column}) {
        my $val = shift @$row;
        if (any { $_ == $val } @{$filtered_columns{$column}}) {
          $bug->{$column} = $val;
        }
        else {
          $bug->{$column} = '';
        }
      }
      else {
## REDHAT EXTENSION END 1323078
        my $all_partners = shift @$row;
        my @filtered_partners;
        foreach my $partner (split(/[,\s]+/, $all_partners)) {
          if (grep { $_->name eq $partner } @{$filtered_columns{$column}}) {
            push @filtered_partners, $partner;
          }
        }
        $bug->{$column} = join(', ', @filtered_partners);
      }
    }
    else {
## REDHAT EXTENSION START 1323078
# It appears that sometimes row->[0] is not defined ...
      if ($column =~ /agile_pool/i && defined $filtered_columns{$column}) {
        my $val = shift @$row;
        if (any { $_ == $val } @{$filtered_columns{$column}}) {
          $bug->{$column} = $val;
        }
        else {
          $bug->{$column} = '';
        }
      }
      else {
## REDHAT EXTENSION END 1323078
        $bug->{$column} = shift @$row;
      }
    }
    ## REDHAT EXTENSION END 479375 1039815
  }

  # 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->{'changedtime'} = $bug->{'changeddate'};          # for iCalendar and Atom
    $bug->{'changeddate'} = DiffDate($bug->{'changeddate'})
      if ($format->{'extension'} ne 'html');    ## REDHAT EXTENSION 1594830
  }

  if ($bug->{'opendate'}) {
    $bug->{'opentime'} = $bug->{'opendate'};            # for iCalendar
    $bug->{'opendate'} = DiffDate($bug->{'opendate'})
      if ($format->{'extension'} ne 'html');            ## REDHAT EXTENSION 1657894
  }

  # Record the assignee, product, and status in the big hashes of those things.
  $bugowners->{$bug->{'assigned_to'}} = 1 if $bug->{'assigned_to'};
  $bugproducts->{$bug->{'product'}}   = 1 if $bug->{'product'};
  $bugcomponentids->{$bug->{'bugs.component_id'}} = 1
    if $bug->{'bugs.component_id'};
  $bugcomponents->{$bug->{'component'}} = 1 if $bug->{'component'};
  $bugstatuses->{$bug->{'bug_status'}}  = 1 if $bug->{'bug_status'};

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

  ## REDHAT EXTENSION START 818974
  if (grep { $_ eq 'ext_bz_count' or $_ eq 'ext_bz_list' } @displaycolumns) {
    $bug->{external_bugs} = Bugzilla::Bug->new($bug->{bug_id})->external_bugs;
  }
  ## REDHAT EXTENSION END 818974

  ## REDHAT EXTENSION END 536717
  if (grep { $_ eq 'blocks_all' } @displaycolumns) {
    $bug->{blocks_all}
      = Bugzilla::Bug->new($bug->{bug_id})->dependent_bugs('blocked');
  }
  if (grep { $_ eq 'dependson_all' } @displaycolumns) {
    $bug->{dependson_all}
      = Bugzilla::Bug->new($bug->{bug_id})->dependent_bugs('dependson');
  }
  ## REDHAT EXTENSION END 536717

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

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

  # Compute time tracking info.
  $time_info->{'estimated_time'} += $bug->{'estimated_time'} if ($estimated_time);
  $time_info->{'remaining_time'} += $bug->{'remaining_time'} if ($remaining_time);
  $time_info->{'actual_time'}    += $bug->{'actual_time'}    if ($actual_time);
}

# 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;
if (@$data && @bugidlist) { #  RED HAT EXTENSION 1347097
  my $sth
    = $dbh->prepare(
        "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 "
      . $dbh->sql_in('bugs.bug_id', \@bugidlist)
      . $dbh->sql_group_by('bugs.bug_id'));
  $sth->execute();
  while (my ($bug_id, $min_membercontrol) = $sth->fetchrow_array()) {
    $min_membercontrol{$bug_id} = $min_membercontrol || CONTROLMAPNA;
  }
  foreach my $bug (@bugs) {
    next unless defined($min_membercontrol{$bug->{'bug_id'}});
    if ($min_membercontrol{$bug->{'bug_id'}} == CONTROLMAPMANDATORY) {
      $bug->{'secure_mode'} = 'implied';
    }
    else {
      $bug->{'secure_mode'} = 'manual';
    }
  }
}

# Compute percentage complete without rounding.
my $sum = $time_info->{'actual_time'} + $time_info->{'remaining_time'};
if ($sum > 0) {
  $time_info->{'percentage_complete'} = 100 * $time_info->{'actual_time'} / $sum;
}
else {    # remaining_time <= 0
  $time_info->{'percentage_complete'} = 0;
}

################################################################################
# Template Variable Definition
################################################################################

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

## REDHAT EXTENSION BEGIN 587798
Bugzilla::Hook::process("add_extra_values",
  {component => 1, version => 1, bugs => \@bugs, bug_id_field => 'bug_id',});
## REDHAT EXTENSION END 587798

$vars->{'bugs'}           = \@bugs;
$vars->{'buglist'}        = \@bugidlist;
$vars->{'buglist_joined'} = join(',', @bugidlist);
$vars->{'columns'}        = $columns;
$vars->{'displaycolumns'} = \@displaycolumns;

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

# The iCal file needs priorities ordered from 1 to 9 (highest to lowest)
# If there are more than 9 values, just make all the lower ones 9
if ($format->{'extension'} eq 'ics') {
  my $n = 1;
  $vars->{'ics_priorities'} = {};
  my $priorities = get_legal_field_values('priority');
  foreach my $p (@$priorities) {
    $vars->{'ics_priorities'}->{$p} = ($n > 9) ? 9 : $n++;
  }
}

#After the search has run, so relevance is correctly set
$order = join(',', $search->order);

$vars->{'order'}       = $order;
$vars->{'caneditbugs'} = 1;
$vars->{'time_info'}   = $time_info;

if (!$user->in_group('editbugs')) {
  foreach my $product (keys %$bugproducts) {
    my $prod = Bugzilla::Product->new({name => $product, cache => 1});
    if (!$user->in_group('editbugs', $prod->id)) {
      $vars->{'caneditbugs'} = 0;
      last;
    }
  }
}

my @bugowners = keys %$bugowners;
if (scalar(@bugowners) > 1 && $user->in_group('editbugs')) {
  my $suffix = Bugzilla->params->{'emailsuffix'};
  map(s/$/$suffix/, @bugowners) if $suffix;
  my $bugowners = join(",", @bugowners);
  $vars->{'bugowners'} = $bugowners;
}

# Whether or not to split the column titles across two rows to make
# the list more compact.
## RED HAT EXTENSION 1406282
$vars->{'splitheader'} = 0;


if ($user->settings->{'display_quips'}->{'value'} eq 'on') {
  $vars->{'quip'} = GetQuip();
}

$vars->{'currenttime'} = localtime(time());

# See if there's only one product in all the results (or only one product
# that we searched for), which allows us to provide more helpful links.
my @products = keys %$bugproducts;
my $one_product;
if (scalar(@products) == 1) {
  $one_product = Bugzilla::Product->new({name => $products[0], cache => 1});
}

# This is used in the "Zarroo Boogs" case.
elsif (my @product_input = $cgi->param('product')) {
  if (scalar(@product_input) == 1 and $product_input[0] ne '') {
    $one_product = Bugzilla::Product->new({name => $product_input[0], cache => 1});
  }
}

# We only want the template to use it if the user can actually
# enter bugs against it.
if ($one_product && $user->can_enter_product($one_product)) {
  $vars->{'one_product'} = $one_product;
}

# See if there's only one component in all the results (or only one component
# that we searched for), which allows us to provide more helpful links.
# But only if it's active
my @components = keys %$bugcomponents;
my $one_component;
if (scalar(@components) == 1) {
  if ($one_product) {
    $one_component
      = Bugzilla::Component->new({product => $one_product, name => $components[0]});
    $vars->{one_component} = $components[0]
      if ($one_component && $one_component->is_active);
  }
}

# This is used in the "Zarroo Boogs" case.
elsif (my @component_input = $cgi->param('component')) {
  if (scalar(@component_input) == 1 and $component_input[0] ne '') {
    $vars->{one_component} = $cgi->param('component');
  }
}


## RED HAT EXTENSION START 1657824
%{$vars->{'statuses'}}
  = map { $_->name => $_->sortkey } Bugzilla::Status->get_all;
## RED HAT EXTENSION END 1657824

# The following variables are used when the user is making changes to multiple bugs.
if ($dotweak && scalar @bugs) {
  if (!$vars->{'caneditbugs'}) {
    ThrowUserError('auth_failure',
      {group => 'editbugs', action => 'modify', object => 'multiple_bugs'});
  }
  $vars->{'dotweak'} = 1;

  # issue_session_token needs to write to the master DB.
  Bugzilla->switch_to_main_db();
  $vars->{'token'} = issue_session_token('buglist_mass_change');
  Bugzilla->switch_to_shadow_db();

  $vars->{'products'}    = $user->get_enterable_products;
  $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'} = get_legal_field_values('resolution');

  ($vars->{'flag_types'}, $vars->{any_flags_requesteeble})
    = _get_common_flag_types([keys %$bugcomponentids]);

  # Convert bug statuses to their ID.
  my @bug_statuses   = map { $dbh->quote($_) } keys %$bugstatuses;
  my $bug_status_ids = $dbh->selectcol_arrayref(
    'SELECT id FROM bug_status
                               WHERE ' . $dbh->sql_in('value', \@bug_statuses)
  );

  # This query collects new statuses which are common to all current bug statuses.
  # It also accepts transitions where the bug status doesn't change.
  $bug_status_ids = $dbh->selectcol_arrayref(
    'SELECT DISTINCT sw1.new_status
               FROM status_workflow sw1
         INNER JOIN bug_status
                 ON bug_status.id = sw1.new_status
              WHERE bug_status.isactive = 1
                AND NOT EXISTS 
                   (SELECT * FROM status_workflow sw2
                     WHERE sw2.old_status != sw1.new_status 
                           AND '
      . $dbh->sql_in('sw2.old_status', $bug_status_ids) . ' AND NOT EXISTS 
                           (SELECT * FROM status_workflow sw3
                             WHERE sw3.new_status = sw1.new_status
                                   AND sw3.old_status = sw2.old_status))'
  );

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

  # The groups the user belongs to and which are editable for the given buglist.
  $vars->{'groups'} = GetGroups(\@products);

  # 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.
  if ($one_product) {
    $vars->{'versions'}
      = [map($_->name, grep($_->is_active, @{$one_product->versions}))];
    $vars->{'components'}
      = [map($_->name, grep($_->is_active, @{$one_product->components}))];
    if (Bugzilla->params->{'usetargetmilestone'}) {
      $vars->{'milestones'}
        = [map($_->name, grep($_->is_active, @{$one_product->milestones}))];
    }
    if (Bugzilla->params->{'usetargetrelease'}) {
      $vars->{'releases'}
        = [map($_->name, grep($_->is_active, @{$one_product->releases}))];
    }

    ## REDHAT EXTENSION BEGIN 706784
    foreach my $multiple_field (@multiple_fields) {
      $vars->{$multiple_field} = $one_product->$multiple_field;
    }
    ## REDHAT EXTENSION END 706784
    ## REDHAT EXTENSION START 653316
    # We need this as a object, to get the sub components
    if ($vars->{one_component}) {
      $vars->{one_component_obj}
        = Bugzilla::Component->new({
        product => $one_product, name => $vars->{one_component}
        });
    }
    ## REDHAT EXTENSION END 653316
  }
  else {
    # We will only show the values at are active in all products.
    my %values = ();
    my @fields = ('components', 'versions');
    if (Bugzilla->params->{'usetargetmilestone'}) {
      push @fields, 'milestones';
    }
    if (Bugzilla->params->{'usetargetrelease'}) {
      push @fields, 'releases';
    }

    # Go through each product and count the number of times each field
    # is used
    foreach my $product_name (@products) {
      my $product = Bugzilla::Product->new({name => $product_name, cache => 1});
      foreach my $field (@fields) {
        my $list = $product->$field;
        foreach my $item (@$list) {
          ++$values{$field}{$item->name} if $item->is_active;
        }
      }
    }

    # Now we get the list of each field and see which values have
    # $product_count (i.e. appears in every product)
    my $product_count = scalar(@products);
    foreach my $field (@fields) {
      my @values
        = grep { $values{$field}{$_} == $product_count } keys %{$values{$field}};
      if (scalar @values) {
        @{$vars->{$field}}
          = $field eq 'version'
          ? sort { vers_cmp(lc($a), lc($b)) } @values
          : sort { lc($a) cmp lc($b) } @values;
      }

      # Do we need to show a warning about limited visiblity?
      if (@values != scalar keys %{$values{$field}}) {
        $vars->{excluded_values} = 1;
      }
    }
  }
}

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

# If we did a quick search then redisplay the previously entered search
# string in the text field.
$vars->{'quicksearch'} = $searchstring;

################################################################################
# HTTP Header Generation
################################################################################

# Generate HTTP headers

my $contenttype;
my $disposition = "inline";

if ($format->{'extension'} eq "html") {
  my $list_id = $cgi->param('list_id') || $cgi->param('regetlastlist');
  my $search  = $user->save_last_search(
    {bugs => \@bugidlist, order => $order, vars => $vars, list_id => $list_id});
  $cgi->param('list_id', $search->id) if $search;
  $contenttype = "text/html";
}
else {
  $contenttype = $format->{'ctype'};
}

# Set 'urlquerypart' once the buglist ID is known.
$vars->{'urlquerypart'}
  = $params->canonicalise_query('order', 'cmdtype', 'query_based_on', 'token');

#  RED HAT EXTENSION START 1347097
$vars->{'real_cols'}
  = "    '" . join("',\n    '", ('bug_id', @displaycolumns)) . "'";
$vars->{'search_cols'} = Bugzilla->internal_to_api(['id', @displaycolumns]);
$vars->{'search_json'} = Bugzilla->search_as({
  format     => 'json',
  search     => $vars->{'urlquerypart'},
  columnlist => $vars->{'search_cols'},
});
chomp($vars->{'search_json'});
#  RED HAT EXTENSION END 1347097

if ($format->{'extension'} eq "csv") {

  # We set CSV files to be downloaded, as they are designed for importing
  # into other programs.
  $disposition = "attachment";

  # If the user clicked the CSV link in the search results,
  # They should get the Field Description, not the column name in the db
  $vars->{'human'} = $cgi->param('human');
}

$cgi->close_standby_message($contenttype, $disposition, $disp_prefix,
  $format->{'extension'});

################################################################################
# Content Generation
################################################################################

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

@displaycolumns = uniq @displaycolumns;

################################################################################
# Script Conclusion
################################################################################

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