Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / rt / lib / RT / SearchBuilder.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2012 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 =head1 NAME
50
51   RT::SearchBuilder - a baseclass for RT collection objects
52
53 =head1 SYNOPSIS
54
55 =head1 DESCRIPTION
56
57
58 =head1 METHODS
59
60
61
62
63 =cut
64
65 package RT::SearchBuilder;
66
67 use RT::Base;
68 use DBIx::SearchBuilder "1.50";
69
70 use strict;
71 use warnings;
72
73
74 use base qw(DBIx::SearchBuilder RT::Base);
75
76 sub _Init  {
77     my $self = shift;
78     
79     $self->{'user'} = shift;
80     unless(defined($self->CurrentUser)) {
81         use Carp;
82         Carp::confess("$self was created without a CurrentUser");
83         $RT::Logger->err("$self was created without a CurrentUser");
84         return(0);
85     }
86     $self->SUPER::_Init( 'Handle' => $RT::Handle);
87 }
88
89 sub CleanSlate {
90     my $self = shift;
91     $self->{'_sql_aliases'} = {};
92     return $self->SUPER::CleanSlate(@_);
93 }
94
95 sub JoinTransactions {
96     my $self = shift;
97     my %args = ( New => 0, @_ );
98
99     return $self->{'_sql_aliases'}{'transactions'}
100         if !$args{'New'} && $self->{'_sql_aliases'}{'transactions'};
101
102     my $alias = $self->Join(
103         ALIAS1 => 'main',
104         FIELD1 => 'id',
105         TABLE2 => 'Transactions',
106         FIELD2 => 'ObjectId',
107     );
108
109     my $item = $self->NewItem;
110     my $object_type = $item->can('ObjectType') ? $item->ObjectType : ref $item;
111
112     $self->RT::SearchBuilder::Limit(
113         LEFTJOIN => $alias,
114         FIELD    => 'ObjectType',
115         VALUE    => $object_type,
116     );
117     $self->{'_sql_aliases'}{'transactions'} = $alias
118         unless $args{'New'};
119
120     return $alias;
121 }
122
123 sub OrderByCols {
124     my $self = shift;
125     my @sort;
126     for my $s (@_) {
127         next if defined $s->{FIELD} and $s->{FIELD} =~ /\W/;
128         $s->{FIELD} = $s->{FUNCTION} if $s->{FUNCTION};
129         push @sort, $s;
130     }
131     return $self->SUPER::OrderByCols( @sort );
132 }
133
134 # If we're setting RowsPerPage or FirstRow, ensure we get a natural number or undef.
135 sub RowsPerPage {
136     my $self = shift;
137     return if @_ and defined $_[0] and $_[0] =~ /\D/;
138     return $self->SUPER::RowsPerPage(@_);
139 }
140
141 sub FirstRow {
142     my $self = shift;
143     return if @_ and defined $_[0] and $_[0] =~ /\D/;
144     return $self->SUPER::FirstRow(@_);
145 }
146
147 =head2 LimitToEnabled
148
149 Only find items that haven't been disabled
150
151 =cut
152
153 sub LimitToEnabled {
154     my $self = shift;
155
156     $self->{'handled_disabled_column'} = 1;
157     $self->Limit( FIELD => 'Disabled', VALUE => '0' );
158 }
159
160 =head2 LimitToDeleted
161
162 Only find items that have been deleted.
163
164 =cut
165
166 sub LimitToDeleted {
167     my $self = shift;
168
169     $self->{'handled_disabled_column'} = $self->{'find_disabled_rows'} = 1;
170     $self->Limit( FIELD => 'Disabled', VALUE => '1' );
171 }
172
173 =head2 FindAllRows
174
175 Find all matching rows, regardless of whether they are disabled or not
176
177 =cut
178
179 sub FindAllRows {
180     shift->{'find_disabled_rows'} = 1;
181 }
182
183 =head2 LimitCustomField
184
185 Takes a paramhash of key/value pairs with the following keys:
186
187 =over 4
188
189 =item CUSTOMFIELD - CustomField id. Optional
190
191 =item OPERATOR - The usual Limit operators
192
193 =item VALUE - The value to compare against
194
195 =back
196
197 =cut
198
199 sub _SingularClass {
200     my $self = shift;
201     my $class = ref($self);
202     $class =~ s/s$// or die "Cannot deduce SingularClass for $class";
203     return $class;
204 }
205
206 sub LimitCustomField {
207     my $self = shift;
208     my %args = ( VALUE        => undef,
209                  CUSTOMFIELD  => undef,
210                  OPERATOR     => '=',
211                  @_ );
212
213     my $alias = $self->Join(
214         TYPE       => 'left',
215         ALIAS1     => 'main',
216         FIELD1     => 'id',
217         TABLE2     => 'ObjectCustomFieldValues',
218         FIELD2     => 'ObjectId'
219     );
220     $self->Limit(
221         ALIAS      => $alias,
222         FIELD      => 'CustomField',
223         OPERATOR   => '=',
224         VALUE      => $args{'CUSTOMFIELD'},
225     ) if ($args{'CUSTOMFIELD'});
226     $self->Limit(
227         ALIAS      => $alias,
228         FIELD      => 'ObjectType',
229         OPERATOR   => '=',
230         VALUE      => $self->_SingularClass,
231     );
232     $self->Limit(
233         ALIAS      => $alias,
234         FIELD      => 'Content',
235         OPERATOR   => $args{'OPERATOR'},
236         VALUE      => $args{'VALUE'},
237     );
238 }
239
240 =head2 Limit PARAMHASH
241
242 This Limit sub calls SUPER::Limit, but defaults "CASESENSITIVE" to 1, thus
243 making sure that by default lots of things don't do extra work trying to 
244 match lower(colname) agaist lc($val);
245
246 We also force VALUE to C<NULL> when the OPERATOR is C<IS> or C<IS NOT>.
247 This ensures that we don't pass invalid SQL to the database or allow SQL
248 injection attacks when we pass through user specified values.
249
250 =cut
251
252 sub Limit {
253     my $self = shift;
254     my %ARGS = (
255         CASESENSITIVE => 1,
256         OPERATOR => '=',
257         @_,
258     );
259
260     # We use the same regex here that DBIx::SearchBuilder uses to exclude
261     # values from quoting
262     if ( $ARGS{'OPERATOR'} =~ /IS/i ) {
263         # Don't pass anything but NULL for IS and IS NOT
264         $ARGS{'VALUE'} = 'NULL';
265     }
266
267     if ($ARGS{FUNCTION}) {
268         ($ARGS{ALIAS}, $ARGS{FIELD}) = split /\./, delete $ARGS{FUNCTION}, 2;
269         $self->SUPER::Limit(%ARGS);
270     } elsif ($ARGS{FIELD} =~ /\W/
271           or $ARGS{OPERATOR} !~ /^(=|<|>|!=|<>|<=|>=
272                                   |(NOT\s*)?LIKE
273                                   |(NOT\s*)?(STARTS|ENDS)WITH
274                                   |(NOT\s*)?MATCHES
275                                   |IS(\s*NOT)?
276                                   |IN
277                                   |\@\@)$/ix) {
278         $RT::Logger->crit("Possible SQL injection attack: $ARGS{FIELD} $ARGS{OPERATOR}");
279         $self->SUPER::Limit(
280             %ARGS,
281             FIELD    => 'id',
282             OPERATOR => '<',
283             VALUE    => '0',
284         );
285     } else {
286         $self->SUPER::Limit(%ARGS);
287     }
288 }
289
290 =head2 ItemsOrderBy
291
292 If it has a SortOrder attribute, sort the array by SortOrder.
293 Otherwise, if it has a "Name" attribute, sort alphabetically by Name
294 Otherwise, just give up and return it in the order it came from the
295 db.
296
297 =cut
298
299 sub ItemsOrderBy {
300     my $self = shift;
301     my $items = shift;
302   
303     if ($self->NewItem()->_Accessible('SortOrder','read')) {
304         $items = [ sort { $a->SortOrder <=> $b->SortOrder } @{$items} ];
305     }
306     elsif ($self->NewItem()->_Accessible('Name','read')) {
307         $items = [ sort { lc($a->Name) cmp lc($b->Name) } @{$items} ];
308     }
309
310     return $items;
311 }
312
313 =head2 ItemsArrayRef
314
315 Return this object's ItemsArray, in the order that ItemsOrderBy sorts
316 it.
317
318 =cut
319
320 sub ItemsArrayRef {
321     my $self = shift;
322     return $self->ItemsOrderBy($self->SUPER::ItemsArrayRef());
323 }
324
325 # make sure that Disabled rows never get seen unless
326 # we're explicitly trying to see them.
327
328 sub _DoSearch {
329     my $self = shift;
330
331     if ( $self->{'with_disabled_column'}
332         && !$self->{'handled_disabled_column'}
333         && !$self->{'find_disabled_rows'}
334     ) {
335         $self->LimitToEnabled;
336     }
337     return $self->SUPER::_DoSearch(@_);
338 }
339 sub _DoCount {
340     my $self = shift;
341
342     if ( $self->{'with_disabled_column'}
343         && !$self->{'handled_disabled_column'}
344         && !$self->{'find_disabled_rows'}
345     ) {
346         $self->LimitToEnabled;
347     }
348     return $self->SUPER::_DoCount(@_);
349 }
350
351 =head2 ColumnMapClassName
352
353 ColumnMap needs a Collection name to load the correct list display.
354 Depluralization is hard, so provide an easy way to correct the naive
355 algorithm that this code uses.
356
357 =cut
358
359 sub ColumnMapClassName {
360     my $self = shift;
361     my $Class = ref $self;
362     $Class =~ s/s$//;
363     $Class =~ s/:/_/g;
364     return $Class;
365 }
366
367 RT::Base->_ImportOverlays();
368
369 1;