-
-
Notifications
You must be signed in to change notification settings - Fork 276
/
Search.pm
3561 lines (3027 loc) · 108 KB
/
Search.pm
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
# 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.
package Bugzilla::Search;
use 5.14.0;
use strict;
use warnings;
use base qw(Exporter);
@Bugzilla::Search::EXPORT = qw(
IsValidQueryType
split_order_term
);
use Bugzilla::Error;
use Bugzilla::Util;
use Bugzilla::Constants;
use Bugzilla::Group;
use Bugzilla::User;
use Bugzilla::Field;
use Bugzilla::Search::Clause;
use Bugzilla::Search::ClauseGroup;
use Bugzilla::Search::Condition qw(condition);
use Bugzilla::Status;
use Bugzilla::Keyword;
use Data::Dumper;
use Date::Format;
use Date::Parse;
use Scalar::Util qw(blessed);
use List::MoreUtils qw(all firstidx part uniq);
use POSIX qw(INT_MAX floor);
use Storable qw(dclone);
use Time::HiRes qw(gettimeofday tv_interval);
# Description Of Boolean Charts
# -----------------------------
#
# A boolean chart is a way of representing the terms in a logical
# expression. Bugzilla builds SQL queries depending on how you enter
# terms into the boolean chart. Boolean charts are represented in
# urls as three-tuples of (chart id, row, column). The query form
# (query.cgi) may contain an arbitrary number of boolean charts where
# each chart represents a clause in a SQL query.
#
# The query form starts out with one boolean chart containing one
# row and one column. Extra rows can be created by pressing the
# AND button at the bottom of the chart. Extra columns are created
# by pressing the OR button at the right end of the chart. Extra
# charts are created by pressing "Add another boolean chart".
#
# Each chart consists of an arbitrary number of rows and columns.
# The terms within a row are ORed together. The expressions represented
# by each row are ANDed together. The expressions represented by each
# chart are ANDed together.
#
# ----------------------
# | col2 | col2 | col3 |
# --------------|------|------|
# | row1 | a1 | a2 | |
# |------|------|------|------| => ((a1 OR a2) AND (b1 OR b2 OR b3) AND (c1))
# | row2 | b1 | b2 | b3 |
# |------|------|------|------|
# | row3 | c1 | | |
# -----------------------------
#
# --------
# | col2 |
# --------------|
# | row1 | d1 | => (d1)
# ---------------
#
# Together, these two charts represent a SQL expression like this
# SELECT blah FROM blah WHERE ( (a1 OR a2)AND(b1 OR b2 OR b3)AND(c1)) AND (d1)
#
# The terms within a single row of a boolean chart are all constraints
# on a single piece of data. If you're looking for a bug that has two
# different people cc'd on it, then you need to use two boolean charts.
# This will find bugs with one CC matching 'foo@blah.org' and and another
# CC matching 'bar@blah.org'.
#
# --------------------------------------------------------------
# CC | equal to
# foo@blah.org
# --------------------------------------------------------------
# CC | equal to
# bar@blah.org
#
# If you try to do this query by pressing the AND button in the
# original boolean chart then what you'll get is an expression that
# looks for a single CC where the login name is both "foo@blah.org",
# and "bar@blah.org". This is impossible.
#
# --------------------------------------------------------------
# CC | equal to
# foo@blah.org
# AND
# CC | equal to
# bar@blah.org
# --------------------------------------------------------------
#############
# Constants #
#############
# When doing searches, NULL datetimes are treated as this date.
use constant EMPTY_DATETIME => '1970-01-01 00:00:00';
use constant EMPTY_DATE => '1970-01-01';
# This is the regex for real numbers from Regexp::Common, modified to be
# more readable.
use constant NUMBER_REGEX => qr/
^[+-]? # A sign, optionally.
(?=\d|\.) # Then either a digit or "."
\d* # Followed by many other digits
(?:
\. # Followed possibly by some decimal places
(?:\d*)
)?
(?: # Followed possibly by an exponent.
[Ee]
[+-]?
\d+
)?
$
/x;
# If you specify a search type in the boolean charts, this describes
# which operator maps to which internal function here.
use constant OPERATORS => {
equals => \&_simple_operator,
notequals => \&_simple_operator,
casesubstring => \&_casesubstring,
substring => \&_substring,
substr => \&_substring,
notsubstring => \&_notsubstring,
regexp => \&_regexp,
notregexp => \&_notregexp,
lessthan => \&_simple_operator,
lessthaneq => \&_simple_operator,
matches => sub { ThrowUserError("search_content_without_matches"); },
notmatches => sub { ThrowUserError("search_content_without_matches"); },
greaterthan => \&_simple_operator,
greaterthaneq => \&_simple_operator,
anyexact => \&_anyexact,
anywordssubstr => \&_anywordsubstr,
allwordssubstr => \&_allwordssubstr,
nowordssubstr => \&_nowordssubstr,
anywords => \&_anywords,
allwords => \&_allwords,
nowords => \&_nowords,
changedbefore => \&_changedbefore_changedafter,
changedafter => \&_changedbefore_changedafter,
changedfrom => \&_changedfrom_changedto,
changedto => \&_changedfrom_changedto,
changedby => \&_changedby,
isempty => \&_isempty,
isnotempty => \&_isnotempty,
};
# Some operators are really just standard SQL operators, and are
# all implemented by the _simple_operator function, which uses this
# constant.
use constant SIMPLE_OPERATORS => {
equals => '=',
notequals => '!=',
greaterthan => '>',
greaterthaneq => '>=',
lessthan => '<',
lessthaneq => "<=",
};
# Most operators just reverse by removing or adding "not" from/to them.
# However, some operators reverse in a different way, so those are listed
# here.
use constant OPERATOR_REVERSE => {
nowords => 'anywords',
nowordssubstr => 'anywordssubstr',
anywords => 'nowords',
anywordssubstr => 'nowordssubstr',
lessthan => 'greaterthaneq',
lessthaneq => 'greaterthan',
greaterthan => 'lessthaneq',
greaterthaneq => 'lessthan',
isempty => 'isnotempty',
isnotempty => 'isempty',
# The following don't currently have reversals:
# casesubstring, anyexact, allwords, allwordssubstr
};
# For these operators, even if a field is numeric (is_numeric returns true),
# we won't treat the input like a number.
use constant NON_NUMERIC_OPERATORS => qw(
changedafter
changedbefore
changedfrom
changedto
regexp
notregexp
);
# These operators ignore the entered value
use constant NO_VALUE_OPERATORS => qw(
isempty
isnotempty
);
use constant MULTI_SELECT_OVERRIDE => {
notequals => \&_multiselect_negative,
notregexp => \&_multiselect_negative,
notsubstring => \&_multiselect_negative,
nowords => \&_multiselect_negative,
nowordssubstr => \&_multiselect_negative,
allwords => \&_multiselect_multiple,
allwordssubstr => \&_multiselect_multiple,
anyexact => \&_multiselect_multiple,
anywords => \&_multiselect_multiple,
anywordssubstr => \&_multiselect_multiple,
_non_changed => \&_multiselect_nonchanged,
};
use constant OPERATOR_FIELD_OVERRIDE => {
# User fields
'attachments.submitter' => {_non_changed => \&_user_nonchanged,},
assigned_to => {_non_changed => \&_user_nonchanged,},
assigned_to_realname => {_non_changed => \&_user_nonchanged,},
cc => {_non_changed => \&_user_nonchanged,},
commenter => {_non_changed => \&_user_nonchanged,},
reporter => {_non_changed => \&_user_nonchanged,},
reporter_realname => {_non_changed => \&_user_nonchanged,},
'requestees.login_name' => {_non_changed => \&_user_nonchanged,},
'setters.login_name' => {_non_changed => \&_user_nonchanged,},
qa_contact => {_non_changed => \&_user_nonchanged,},
qa_contact_realname => {_non_changed => \&_user_nonchanged,},
# General Bug Fields
alias => {_non_changed => \&_alias_nonchanged},
'attach_data.thedata' => MULTI_SELECT_OVERRIDE,
# We check all attachment fields against this.
attachments => MULTI_SELECT_OVERRIDE,
blocked => MULTI_SELECT_OVERRIDE,
bug_file_loc => {_non_changed => \&_nullable},
bug_group => MULTI_SELECT_OVERRIDE,
classification => {_non_changed => \&_classification_nonchanged,},
component => {_non_changed => \&_component_nonchanged,},
content => {
matches => \&_content_matches,
notmatches => \&_content_matches,
_default => sub { ThrowUserError("search_content_without_matches"); },
},
days_elapsed => {_default => \&_days_elapsed,},
dependson => MULTI_SELECT_OVERRIDE,
keywords => MULTI_SELECT_OVERRIDE,
'flagtypes.name' => {_non_changed => \&_flagtypes_nonchanged,},
longdesc => {
changedby => \&_long_desc_changedby,
changedbefore => \&_long_desc_changedbefore_after,
changedafter => \&_long_desc_changedbefore_after,
_non_changed => \&_long_desc_nonchanged,
},
'longdescs.count' => {
changedby => \&_long_desc_changedby,
changedbefore => \&_long_desc_changedbefore_after,
changedafter => \&_long_desc_changedbefore_after,
changedfrom => \&_invalid_combination,
changedto => \&_invalid_combination,
_default => \&_long_descs_count,
},
'longdescs.isprivate' => MULTI_SELECT_OVERRIDE,
owner_idle_time => {
greaterthan => \&_owner_idle_time_greater_less,
greaterthaneq => \&_owner_idle_time_greater_less,
lessthan => \&_owner_idle_time_greater_less,
lessthaneq => \&_owner_idle_time_greater_less,
_default => \&_invalid_combination,
},
product => {_non_changed => \&_product_nonchanged,},
tag => MULTI_SELECT_OVERRIDE,
comment_tag => MULTI_SELECT_OVERRIDE,
# Timetracking Fields
deadline => {_non_changed => \&_deadline},
percentage_complete => {_non_changed => \&_percentage_complete,},
work_time => {
changedby => \&_work_time_changedby,
changedbefore => \&_work_time_changedbefore_after,
changedafter => \&_work_time_changedbefore_after,
_default => \&_work_time,
},
last_visit_ts => {
_non_changed => \&_last_visit_ts,
_default => \&_last_visit_ts_invalid_operator,
},
# Custom Fields
FIELD_TYPE_FREETEXT,
{_non_changed => \&_nullable},
FIELD_TYPE_BUG_ID,
{_non_changed => \&_nullable_int},
FIELD_TYPE_DATETIME,
{_non_changed => \&_nullable_datetime},
FIELD_TYPE_DATE,
{_non_changed => \&_nullable_date},
FIELD_TYPE_TEXTAREA,
{_non_changed => \&_nullable},
FIELD_TYPE_MULTI_SELECT,
MULTI_SELECT_OVERRIDE,
FIELD_TYPE_BUG_URLS,
MULTI_SELECT_OVERRIDE,
};
# These are fields where special action is taken depending on the
# *value* passed in to the chart, sometimes.
# This is a sub because custom fields are dynamic
sub SPECIAL_PARSING {
my $map = {
# Pronoun Fields (Ones that can accept %user%, etc.)
assigned_to => \&_contact_pronoun,
cc => \&_contact_pronoun,
commenter => \&_contact_pronoun,
qa_contact => \&_contact_pronoun,
reporter => \&_contact_pronoun,
'setters.login_name' => \&_contact_pronoun,
'requestees.login_name' => \&_contact_pronoun,
# Date Fields that accept the 1d, 1w, 1m, 1y, etc. format.
creation_ts => \&_datetime_translate,
deadline => \&_date_translate,
delta_ts => \&_datetime_translate,
# last_visit field that accept both a 1d, 1w, 1m, 1y format and the
# %last_changed% pronoun.
last_visit_ts => \&_last_visit_datetime,
};
foreach my $field (Bugzilla->active_custom_fields) {
if ($field->type == FIELD_TYPE_DATETIME) {
$map->{$field->name} = \&_datetime_translate;
}
elsif ($field->type == FIELD_TYPE_DATE) {
$map->{$field->name} = \&_date_translate;
}
}
return $map;
}
# Information about fields that represent "users", used by _user_nonchanged.
# There are other user fields than the ones listed here, but those use
# defaults in _user_nonchanged.
use constant USER_FIELDS => {
'attachments.submitter' =>
{field => 'submitter_id', join => {table => 'attachments'}, isprivate => 1,},
cc => {field => 'who', join => {table => 'cc'},},
commenter => {
field => 'who',
join => {table => 'longdescs', join => 'INNER'},
isprivate => 1,
},
qa_contact => {nullable => 1,},
'requestees.login_name' =>
{nullable => 1, field => 'requestee_id', join => {table => 'flags'},},
'setters.login_name' => {field => 'setter_id', join => {table => 'flags'},},
};
# Backwards compatibility for times that we changed the names of fields
# or URL parameters.
use constant FIELD_MAP => {
'attachments.thedata' => 'attach_data.thedata',
bugidtype => 'bug_id_type',
changedin => 'days_elapsed',
long_desc => 'longdesc',
tags => 'tag',
};
# Some fields are not sorted on themselves, but on other fields.
# We need to have a list of these fields and what they map to.
use constant SPECIAL_ORDER => {
'target_milestone' => {
order => ['map_target_milestone.sortkey', 'map_target_milestone.value'],
join => {
table => 'milestones',
from => 'target_milestone',
to => 'value',
extra => ['bugs.product_id = map_target_milestone.product_id'],
join => 'INNER',
}
},
};
# Certain columns require other columns to come before them
# in _select_columns, and should be put there if they're not there.
use constant COLUMN_DEPENDS => {
classification => ['product'],
percentage_complete => ['actual_time', 'remaining_time'],
};
# This describes tables that must be joined when you want to display
# certain columns in the buglist. For the most part, Search.pm uses
# DB::Schema to figure out what needs to be joined, but for some
# fields it needs a little help.
sub COLUMN_JOINS {
my $invocant = shift;
my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;
my $joins = {
actual_time => {
table => '(SELECT bug_id, SUM(work_time) AS total'
. ' FROM longdescs GROUP BY bug_id)',
join => 'INNER',
},
alias => {table => 'bugs_aliases', as => 'map_alias',},
assigned_to => {
from => 'assigned_to',
to => 'userid',
table => 'profiles',
join => 'INNER',
},
reporter =>
{from => 'reporter', to => 'userid', table => 'profiles', join => 'INNER',},
qa_contact => {from => 'qa_contact', to => 'userid', table => 'profiles',},
component =>
{from => 'component_id', to => 'id', table => 'components', join => 'INNER',},
product =>
{from => 'product_id', to => 'id', table => 'products', join => 'INNER',},
classification => {
table => 'classifications',
from => 'map_product.classification_id',
to => 'id',
join => 'INNER',
},
'flagtypes.name' => {
as => 'map_flags',
table => 'flags',
extra => ['map_flags.attach_id IS NULL'],
then_to => {
as => 'map_flagtypes',
table => 'flagtypes',
from => 'map_flags.type_id',
to => 'id',
},
},
keywords => {
table => 'keywords',
then_to => {
as => 'map_keyworddefs',
table => 'keyworddefs',
from => 'map_keywords.keywordid',
to => 'id',
},
},
blocked => {table => 'dependencies', to => 'dependson',},
dependson => {table => 'dependencies', to => 'blocked',},
'longdescs.count' => {table => 'longdescs', join => 'INNER',},
tag => {
as => 'map_bug_tag',
table => 'bug_tag',
then_to => {
as => 'map_tag',
table => 'tag',
extra => ['map_tag.user_id = ' . $user->id],
from => 'map_bug_tag.tag_id',
to => 'id',
},
},
last_visit_ts => {
as => 'bug_user_last_visit',
table => 'bug_user_last_visit',
extra => ['bug_user_last_visit.user_id = ' . $user->id],
from => 'bug_id',
to => 'bug_id',
},
};
return $joins;
}
# This constant defines 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, the redundant short_desc column is removed when the
# client requests "all" columns.
#
# This is really a constant--that is, once it's been called once, the value
# will always be the same unless somebody adds a new custom field. But
# we have to do a lot of work inside the subroutine to get the data,
# and we don't want it to happen at compile time, so we have it as a
# subroutine.
sub COLUMNS {
my $invocant = shift;
my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;
my $dbh = Bugzilla->dbh;
my $cache = Bugzilla->request_cache;
if (defined $cache->{search_columns}->{$user->id}) {
return $cache->{search_columns}->{$user->id};
}
# These are columns that don't exist in fielddefs, but are valid buglist
# columns. (Also see near the bottom of this function for the definition
# of short_short_desc.)
my %columns = (relevance => {title => 'Relevance'},);
# Next we define columns that have special SQL instead of just something
# like "bugs.bug_id".
my $total_time = "(map_actual_time.total + bugs.remaining_time)";
my %special_sql = (
alias => $dbh->sql_group_concat('DISTINCT map_alias.alias'),
deadline => $dbh->sql_date_format('bugs.deadline', '%Y-%m-%d'),
actual_time => 'map_actual_time.total',
# "FLOOR" is in there to turn this into an integer, making searches
# totally predictable. Otherwise you get floating-point numbers that
# are rather hard to search reliably if you're asking for exact
# numbers.
percentage_complete => "(CASE WHEN $total_time = 0"
. " THEN 0"
. " ELSE FLOOR(100 * (map_actual_time.total / $total_time))" . " END)",
'flagtypes.name' => $dbh->sql_group_concat(
'DISTINCT ' . $dbh->sql_string_concat('map_flagtypes.name', 'map_flags.status'),
undef,
undef,
'map_flagtypes.sortkey, map_flagtypes.name'
),
'keywords' => $dbh->sql_group_concat('DISTINCT map_keyworddefs.name'),
blocked => $dbh->sql_group_concat('DISTINCT map_blocked.blocked'),
dependson => $dbh->sql_group_concat('DISTINCT map_dependson.dependson'),
'longdescs.count' => 'COUNT(DISTINCT map_longdescs_count.comment_id)',
tag => $dbh->sql_group_concat('DISTINCT map_tag.name'),
last_visit_ts => 'bug_user_last_visit.last_visit_ts',
);
# Backward-compatibility for old field names. Goes new_name => old_name.
# These are here and not in _translate_old_column because the rest of the
# code actually still uses the old names, while the fielddefs table uses
# the new names (which is not the case for the fields handled by
# _translate_old_column).
my %old_names = (
creation_ts => 'opendate',
delta_ts => 'changeddate',
work_time => 'actual_time',
);
# Fields that are email addresses
my @email_fields = qw(assigned_to reporter qa_contact);
# Other fields that are stored in the bugs table as an id, but
# should be displayed using their name.
my @id_fields = qw(product component classification);
foreach my $col (@email_fields) {
my $sql = "map_${col}.login_name";
if (!$user->id) {
$sql = $dbh->sql_string_until($sql, $dbh->quote('@'));
}
$special_sql{$col} = $sql;
$special_sql{"${col}_realname"} = "map_${col}.realname";
}
foreach my $col (@id_fields) {
$special_sql{$col} = "map_${col}.name";
}
# Do the actual column-getting from fielddefs, now.
my @fields = @{Bugzilla->fields({obsolete => 0, buglist => 1})};
foreach my $field (@fields) {
my $id = $field->name;
$id = $old_names{$id} if exists $old_names{$id};
my $sql;
if (exists $special_sql{$id}) {
$sql = $special_sql{$id};
}
elsif ($field->type == FIELD_TYPE_MULTI_SELECT) {
$sql = $dbh->sql_group_concat('DISTINCT map_' . $field->name . '.value');
}
else {
$sql = 'bugs.' . $field->name;
}
$columns{$id} = {name => $sql, title => $field->description};
}
# The short_short_desc column is identical to short_desc
$columns{'short_short_desc'} = $columns{'short_desc'};
Bugzilla::Hook::process('buglist_columns', {columns => \%columns});
$cache->{search_columns}->{$user->id} = \%columns;
return $cache->{search_columns}->{$user->id};
}
sub REPORT_COLUMNS {
my $invocant = shift;
my $user = blessed($invocant) ? $invocant->_user : Bugzilla->user;
my $columns = dclone(blessed($invocant) ? $invocant->COLUMNS : COLUMNS);
# There's no reason to support reporting on unique fields.
# Also, some other fields don't make very good reporting axises,
# or simply don't work with the current reporting system.
my @no_report_columns = qw(bug_id alias short_short_desc opendate changeddate
flagtypes.name relevance);
# If you're not a time-tracker, you can't use time-tracking
# columns.
if (!$user->is_timetracker) {
push(@no_report_columns, TIMETRACKING_FIELDS);
}
foreach my $name (@no_report_columns) {
delete $columns->{$name};
}
return $columns;
}
# These are fields that never go into the GROUP BY on any DB. bug_id
# is here because it *always* goes into the GROUP BY as the first item,
# so it should be skipped when determining extra GROUP BY columns.
use constant GROUP_BY_SKIP => qw(
alias
blocked
bug_id
dependson
flagtypes.name
keywords
longdescs.count
percentage_complete
tag
);
###############
# Constructor #
###############
# Note that the params argument may be modified by Bugzilla::Search
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {@_};
bless($self, $class);
$self->{'user'} ||= Bugzilla->user;
# There are certain behaviors of the CGI "Vars" hash that we don't want.
# In particular, if you put a single-value arrayref into it, later you
# get back out a string, which breaks anyexact charts (because they
# need arrays even for individual items, or we will re-trigger bug 67036).
#
# We can't just untie the hash--that would give us a hash with no values.
# We have to manually copy the hash into a new one, and we have to always
# do it, because there's no way to know if we were passed a tied hash
# or not.
my $params_in = $self->_params;
my %params = map { $_ => $params_in->{$_} } keys %$params_in;
$self->{params} = \%params;
return $self;
}
####################
# Public Accessors #
####################
sub data {
my $self = shift;
return $self->{data} if $self->{data};
my $dbh = Bugzilla->dbh;
# If all fields belong to the 'bugs' table, there is no need to split
# the original query into two pieces. Else we override the 'fields'
# argument to first get bug IDs based on the search criteria defined
# by the caller, and the desired fields are collected in the 2nd query.
my @orig_fields = $self->_input_columns;
my $all_in_bugs_table = 1;
foreach my $field (@orig_fields) {
next if ($self->COLUMNS->{$field}->{name} // $field) =~ /^bugs\.\w+$/;
$self->{fields} = ['bug_id'];
$all_in_bugs_table = 0;
last;
}
my $start_time = [gettimeofday()];
my $sql = $self->_sql;
# Do we just want bug IDs to pass to the 2nd query or all the data immediately?
my $func = $all_in_bugs_table ? 'selectall_arrayref' : 'selectcol_arrayref';
my $bug_ids = $dbh->$func($sql);
my @extra_data = ({sql => $sql, time => tv_interval($start_time)});
# Restore the original 'fields' argument, just in case.
$self->{fields} = \@orig_fields unless $all_in_bugs_table;
# If there are no bugs found, or all fields are in the 'bugs' table,
# there is no need for another query.
if (!scalar @$bug_ids || $all_in_bugs_table) {
$self->{data} = $bug_ids;
return wantarray ? ($self->{data}, \@extra_data) : $self->{data};
}
# Make sure the bug_id will be returned. If not, append it to the list.
my $pos = firstidx { $_ eq 'bug_id' } @orig_fields;
if ($pos < 0) {
push(@orig_fields, 'bug_id');
$pos = $#orig_fields;
}
# Now create a query with the buglist above as the single criteria
# and the fields that the caller wants. No need to redo security checks;
# the list has already been validated above.
my $search = $self->new(
'fields' => \@orig_fields,
'params' => {bug_id => $bug_ids, bug_id_type => 'anyexact'},
'sharer' => $self->_sharer_id,
'user' => $self->_user,
'allow_unlimited' => 1,
'_no_security_check' => 1
);
$start_time = [gettimeofday()];
$sql = $search->_sql;
my $unsorted_data = $dbh->selectall_arrayref($sql);
push(@extra_data, {sql => $sql, time => tv_interval($start_time)});
# Let's sort the data. We didn't do it in the query itself because
# we already know in which order to sort bugs thanks to the first query,
# and this avoids additional table joins in the SQL query.
my %data = map { $_->[$pos] => $_ } @$unsorted_data;
$self->{data} = [map { $data{$_} } @$bug_ids];
return wantarray ? ($self->{data}, \@extra_data) : $self->{data};
}
sub _sql {
my ($self) = @_;
return $self->{sql} if $self->{sql};
my $dbh = Bugzilla->dbh;
my ($joins, $clause) = $self->_charts_to_conditions();
if ( !$clause->as_string
&& !Bugzilla->params->{'search_allow_no_criteria'}
&& !$self->{allow_unlimited})
{
ThrowUserError('buglist_parameters_required');
}
my $select = join(', ', $self->_sql_select);
my $from = $self->_sql_from($joins);
my $where = $self->_sql_where($clause);
my $group_by = $dbh->sql_group_by($self->_sql_group_by);
my $order_by
= $self->_sql_order_by
? "\nORDER BY " . join(', ', $self->_sql_order_by)
: '';
my $limit = $self->_sql_limit;
$limit = "\n$limit" if $limit;
my $query = <<END;
SELECT $select
FROM $from
WHERE $where
$group_by$order_by$limit
END
$self->{sql} = $query;
return $self->{sql};
}
sub search_description {
my ($self, $params) = @_;
my $desc = $self->{'search_description'} ||= [];
if ($params) {
push(@$desc, $params);
}
# Make sure that the description has actually been generated if
# people are asking for the whole thing.
else {
$self->_sql;
}
return $self->{'search_description'};
}
sub boolean_charts_to_custom_search {
my ($self, $cgi_buffer) = @_;
my $boolean_charts = $self->_boolean_charts;
my @as_params = $boolean_charts ? $boolean_charts->as_params : ();
# We need to start our new ids after the last custom search "f" id.
# We can just pick the last id in the array because they are sorted
# numerically.
my $last_id = ($self->_field_ids)[-1];
my $count = defined($last_id) ? $last_id + 1 : 0;
foreach my $param_set (@as_params) {
foreach my $name (keys %$param_set) {
my $value = $param_set->{$name};
next if !defined $value;
$cgi_buffer->param($name . $count, $value);
}
$count++;
}
}
sub invalid_order_columns {
my ($self) = @_;
my @invalid_columns;
foreach my $order ($self->_input_order) {
next if defined $self->_validate_order_column($order);
push(@invalid_columns, $order);
}
return \@invalid_columns;
}
sub order {
my ($self) = @_;
return $self->_valid_order;
}
######################
# Internal Accessors #
######################
# Fields that are legal for boolean charts of any kind.
sub _chart_fields {
my ($self) = @_;
if (!$self->{chart_fields}) {
my $chart_fields = Bugzilla->fields({by_name => 1});
if (!$self->_user->is_timetracker) {
foreach my $tt_field (TIMETRACKING_FIELDS) {
delete $chart_fields->{$tt_field};
}
}
$self->{chart_fields} = $chart_fields;
}
return $self->{chart_fields};
}
# There are various places in Search.pm that we need to know the list of
# valid multi-select fields--or really, fields that are stored like
# multi-selects, which includes BUG_URLS fields.
sub _multi_select_fields {
my ($self) = @_;
$self->{multi_select_fields}
||= Bugzilla->fields({
by_name => 1, type => [FIELD_TYPE_MULTI_SELECT, FIELD_TYPE_BUG_URLS]
});
return $self->{multi_select_fields};
}
# $self->{params} contains values that could be undef, could be a string,
# or could be an arrayref. Sometimes we want that value as an array,
# always.
sub _param_array {
my ($self, $name) = @_;
my $value = $self->_params->{$name};
if (!defined $value) {
return ();
}
if (ref($value) eq 'ARRAY') {
return @$value;
}
return ($value);
}
sub _params { $_[0]->{params} }
sub _user { return $_[0]->{user} }
sub _sharer_id { $_[0]->{sharer} }
##############################
# Internal Accessors: SELECT #
##############################
# These are the fields the user has chosen to display on the buglist,
# exactly as they were passed to new().
sub _input_columns { @{$_[0]->{'fields'} || []} }
# These are columns that are also going to be in the SELECT for one reason
# or another, but weren't actually requested by the caller.
sub _extra_columns {
my ($self) = @_;
# Everything that's going to be in the ORDER BY must also be
# in the SELECT.
push(@{$self->{extra_columns}}, $self->_valid_order_columns);
return @{$self->{extra_columns}};
}
# For search functions to modify extra_columns. It doesn't matter if
# people push the same column onto this array multiple times, because
# _select_columns will call "uniq" on its final result.
sub _add_extra_column {
my ($self, $column) = @_;
push(@{$self->{extra_columns}}, $column);
}
# These are the columns that we're going to be actually SELECTing.
sub _display_columns {
my ($self) = @_;
return @{$self->{display_columns}} if $self->{display_columns};
# Do not alter the list from _input_columns at all, even if there are
# duplicated columns. Those are passed by the caller, and the caller
# expects to get them back in the exact same order.
my @columns = $self->_input_columns;
# Only add columns which are not already listed.
my %list = map { $_ => 1 } @columns;
foreach my $column ($self->_extra_columns) {
push(@columns, $column) unless $list{$column}++;
}
$self->{display_columns} = \@columns;
return @{$self->{display_columns}};
}
# These are the columns that are involved in the query.
sub _select_columns {
my ($self) = @_;
return @{$self->{select_columns}} if $self->{select_columns};
my @select_columns;
foreach my $column ($self->_display_columns) {
if (my $add_first = COLUMN_DEPENDS->{$column}) {
push(@select_columns, @$add_first);
}
push(@select_columns, $column);
}
# Remove duplicated columns.
$self->{select_columns} = [uniq @select_columns];
return @{$self->{select_columns}};
}
# This takes _display_columns and translates it into the actual SQL that
# will go into the SELECT clause.
sub _sql_select {
my ($self) = @_;
my @sql_fields;
foreach my $column ($self->_display_columns) {
my $sql = $self->COLUMNS->{$column}->{name} // '';
if ($sql) {
my $alias = $column;
# Aliases cannot contain dots in them. We convert them to underscores.
$alias =~ tr/./_/;
$sql .= " AS $alias";
}
else {
$sql = $column;
}
push(@sql_fields, $sql);
}
return @sql_fields;
}
################################
# Internal Accessors: ORDER BY #
################################
# The "order" that was requested by the consumer, exactly as it was
# requested.
sub _input_order { @{$_[0]->{'order'} || []} }
# Requested order with invalid values removed and old names translated
sub _valid_order {
my ($self) = @_;
return map { ($self->_validate_order_column($_)) } $self->_input_order;
}
# The valid order with just the column names, and no ASC or DESC.
sub _valid_order_columns {
my ($self) = @_;
return map { (split_order_term($_))[0] } $self->_valid_order;
}
sub _validate_order_column {
my ($self, $order_item) = @_;