bf8ae3cb7030743fc2e3dc8a4e31511f7e3a29f1
[freeside.git] / rt / lib / RT / CustomFields.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2018 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::CustomFields - a collection of RT CustomField objects
52
53 =head1 SYNOPSIS
54
55   use RT::CustomFields;
56
57 =head1 DESCRIPTION
58
59 =head1 METHODS
60
61
62
63 =cut
64
65
66 package RT::CustomFields;
67
68 use strict;
69 use warnings;
70
71 use base 'RT::SearchBuilder';
72
73 use RT::CustomField;
74
75 sub Table { 'CustomFields'}
76
77 sub _Init {
78     my $self = shift;
79
80   # By default, order by SortOrder
81   $self->OrderByCols(
82          { ALIAS => 'main',
83            FIELD => 'SortOrder',
84            ORDER => 'ASC' },
85          { ALIAS => 'main',
86            FIELD => 'Name',
87            ORDER => 'ASC' },
88          { ALIAS => 'main',
89            FIELD => 'id',
90            ORDER => 'ASC' },
91      );
92     $self->{'with_disabled_column'} = 1;
93
94     return ( $self->SUPER::_Init(@_) );
95 }
96
97 =head2 LimitToGrouping
98
99 Limits this collection object to custom fields which appear under a
100 specified grouping by calling L</Limit> for each CF name as appropriate.
101
102 Requires an L<RT::Record> object or class name as the first argument and
103 accepts a grouping name as the second.  If the grouping name is false
104 (usually via the empty string), limits to custom fields which appear in no
105 grouping.
106
107 I<Caveat:> While the record object or class name is used to find the
108 available groupings, no automatic limit is placed on the lookup type of
109 the custom fields.  It's highly suggested you limit the collection by
110 queue or another lookup type first.  This is already done for you if
111 you're creating the collection via the L</CustomFields> method on an
112 L<RT::Record> object.
113
114 =cut
115
116 sub LimitToGrouping {
117     my $self = shift;
118     my $obj = shift;
119     my $grouping = shift;
120
121     my $grouping_class = $self->NewItem->_GroupingClass($obj);
122
123     my $config = RT->Config->Get('CustomFieldGroupings');
124        $config = {} unless ref($config) eq 'HASH';
125        $config = $config->{$grouping_class} || [];
126     my %h = ref $config eq "ARRAY" ? @{$config} : %{$config};
127
128     if ( $grouping ) {
129         my $list = $h{$grouping};
130         unless ( $list and ref($list) eq 'ARRAY' and @$list ) {
131             return $self->Limit( FIELD => 'id', VALUE => 0, ENTRYAGGREGATOR => 'AND' );
132         }
133         $self->Limit(
134             FIELD         => 'Name',
135             FUNCTION      => 'LOWER(?)',
136             OPERATOR      => 'IN',
137             VALUE         => [map {lc $_} @{$list}],
138             CASESENSITIVE => 1,
139         );
140     } else {
141         my @list = map {@$_} grep defined && ref($_) eq 'ARRAY',
142             values %h;
143
144         return unless @list;
145
146         $self->Limit(
147             FIELD         => 'Name',
148             FUNCTION      => 'LOWER(?)',
149             OPERATOR      => 'NOT IN',
150             VALUE         => [ map {lc $_} @list ],
151             CASESENSITIVE => 1,
152         );
153     }
154     return;
155 }
156
157
158 =head2 LimitToLookupType
159
160 Takes LookupType and limits collection.
161
162 =cut
163
164 sub LimitToLookupType  {
165     my $self = shift;
166     my $lookup = shift;
167
168     $self->Limit( FIELD => 'LookupType', VALUE => "$lookup" );
169 }
170
171 =head2 LimitToChildType
172
173 Takes partial LookupType and limits collection to records
174 where LookupType is equal or ends with the value.
175
176 =cut
177
178 sub LimitToChildType  {
179     my $self = shift;
180     my $lookup = shift;
181
182     $self->Limit( FIELD => 'LookupType', VALUE => "$lookup", OPERATOR => "ENDSWITH" );
183 }
184
185
186 =head2 LimitToParentType
187
188 Takes partial LookupType and limits collection to records
189 where LookupType is equal or starts with the value.
190
191 =cut
192
193 sub LimitToParentType  {
194     my $self = shift;
195     my $lookup = shift;
196
197     $self->Limit( FIELD => 'LookupType', VALUE => "$lookup", OPERATOR => "STARTSWITH" );
198 }
199
200 =head2 LimitToObjectId
201
202 Takes an ObjectId and limits the collection to CFs applied to said object.
203
204 When called multiple times the ObjectId limits are joined with OR.
205
206 =cut
207
208 sub LimitToObjectId {
209     my $self = shift;
210     my $id = shift;
211     $self->Limit(
212         ALIAS           => $self->_OCFAlias,
213         FIELD           => 'ObjectId',
214         OPERATOR        => '=',
215         VALUE           => $id || 0,
216         ENTRYAGGREGATOR => 'OR'
217     );
218 }
219
220 =head2 LimitToGlobalOrObjectId
221
222 Takes list of object IDs and limits collection to custom
223 fields that are added to these objects or globally.
224
225 =cut
226
227 sub LimitToGlobalOrObjectId {
228     my $self = shift;
229     my $global_only = 1;
230
231
232     foreach my $id (@_) {
233         $self->LimitToObjectId($id);
234         $global_only = 0 if $id;
235     }
236
237     $self->LimitToObjectId(0) unless $global_only;
238 }
239
240 =head2 LimitToNotAdded
241
242 Takes either list of object ids or nothing. Limits collection
243 to custom fields to listed objects or any corespondingly. Use
244 zero to mean global.
245
246 =cut
247
248 sub LimitToNotAdded {
249     my $self = shift;
250     return RT::ObjectCustomFields->new( $self->CurrentUser )
251         ->LimitTargetToNotAdded( $self => @_ );
252 }
253
254 =head2 LimitToAdded
255
256 Limits collection to custom fields to listed objects or any corespondingly. Use
257 zero to mean global.
258
259 =cut
260
261 sub LimitToAdded {
262     my $self = shift;
263     return RT::ObjectCustomFields->new( $self->CurrentUser )
264         ->LimitTargetToAdded( $self => @_ );
265 }
266
267 =head2 LimitToGlobalOrQueue QUEUEID
268
269 Limits the set of custom fields found to global custom fields or those
270 tied to the queue C<QUEUEID>, similar to L</LimitToGlobalOrObjectId>.
271
272 Note that this will cause the collection to only return ticket CFs.
273
274 =cut
275
276 sub LimitToGlobalOrQueue {
277     my $self = shift;
278     my $queue = shift;
279     $self->LimitToGlobalOrObjectId( $queue );
280     $self->LimitToLookupType( 'RT::Queue-RT::Ticket' );
281 }
282
283
284 =head2 LimitToQueue QUEUEID
285
286 Takes a numeric C<QUEUEID>, and limits the Custom Field collection to
287 those only applied directly to it; this limit is OR'd with other
288 L</LimitToQueue> and L</LimitToGlobal> limits.
289
290 Note that this will cause the collection to only return ticket CFs.
291
292 =cut
293
294 sub LimitToQueue  {
295    my $self = shift;
296    my $queue = shift;
297
298    $self->Limit (ALIAS => $self->_OCFAlias,
299                  ENTRYAGGREGATOR => 'OR',
300                  FIELD => 'ObjectId',
301                  VALUE => "$queue")
302        if defined $queue;
303    $self->LimitToLookupType( 'RT::Queue-RT::Ticket' );
304 }
305
306
307 =head2 LimitToGlobal
308
309 Limits the Custom Field collection to global ticket CFs; this limit is
310 OR'd with L</LimitToQueue> limits.
311
312 Note that this will cause the collection to only return ticket CFs.
313
314 =cut
315
316 sub LimitToGlobal  {
317    my $self = shift;
318
319   $self->Limit (ALIAS => $self->_OCFAlias,
320                 ENTRYAGGREGATOR => 'OR',
321                 FIELD => 'ObjectId',
322                 VALUE => 0);
323   $self->LimitToLookupType( 'RT::Queue-RT::Ticket' );
324 }
325
326
327 =head2 ApplySortOrder
328
329 Sort custom fields according to thier order application to objects. It's
330 expected that collection contains only records of one
331 L<RT::CustomField/LookupType> and applied to one object or globally
332 (L</LimitToGlobalOrObjectId>), otherwise sorting makes no sense.
333
334 =cut
335
336 sub ApplySortOrder {
337     my $self = shift;
338     my $order = shift || 'ASC';
339     $self->OrderByCols( {
340         ALIAS => $self->_OCFAlias,
341         FIELD => 'SortOrder',
342         ORDER => $order,
343     } );
344 }
345
346
347 =head2 ContextObject
348
349 Returns context object for this collection of custom fields,
350 but only if it's defined.
351
352 =cut
353
354 sub ContextObject {
355     my $self = shift;
356     return $self->{'context_object'};
357 }
358
359
360 =head2 SetContextObject
361
362 Sets context object for this collection of custom fields.
363
364 =cut
365
366 sub SetContextObject {
367     my $self = shift;
368     return $self->{'context_object'} = shift;
369 }
370
371
372 sub _OCFAlias {
373     my $self = shift;
374     return RT::ObjectCustomFields->new( $self->CurrentUser )
375         ->JoinTargetToThis( $self => @_ );
376 }
377
378
379 =head2 AddRecord
380
381 Overrides the collection to ensure that only custom fields the user can
382 see are returned; also propagates down the L</ContextObject>.
383
384 =cut
385
386 sub AddRecord {
387     my $self = shift;
388     my ($record) = @_;
389
390     $record->SetContextObject( $self->ContextObject );
391     return unless $record->CurrentUserHasRight('SeeCustomField');
392     return $self->SUPER::AddRecord( $record );
393 }
394
395 =head2 NewItem
396
397 Returns an empty new RT::CustomField item
398 Overrides <RT::SearchBuilder/NewItem> to make sure </ContextObject>
399 is inherited.
400
401 =cut
402
403 sub NewItem {
404     my $self = shift;
405     my $res = RT::CustomField->new($self->CurrentUser);
406     $res->SetContextObject($self->ContextObject);
407     return $res;
408 }
409
410 RT::Base->_ImportOverlays();
411
412 1;