summaryrefslogtreecommitdiff
path: root/rt/lib/RT/SearchBuilder/Role/Roles.pm
blob: 327cd49ffd8cba2cbf673987ab4765871d685418 (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
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2017 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}

use strict;
use warnings;

package RT::SearchBuilder::Role::Roles;
use Role::Basic;
use Scalar::Util qw(blessed);

=head1 NAME

RT::Record::Role::Roles - Common methods for records which "watchers" or "roles"

=head1 REQUIRES

=head2 L<RT::SearchBuilder::Role>

=cut

with 'RT::SearchBuilder::Role';

require RT::System;
require RT::Principal;
require RT::Group;
require RT::User;

require RT::EmailParser;

=head1 PROVIDES

=head2 _RoleGroupClass

Returns the class name on which role searches should be based.  This relates to
the internal L<RT::Group/Domain> and distinguishes between roles on the objects
being searched and their counterpart roles on containing classes.  For example,
limiting on L<RT::Queue> roles while searching for L<RT::Ticket>s.

The default implementation is:

    $self->RecordClass

which is the class that this collection object searches and instatiates objects
for.  If you're doing something hinky, you may need to override this method.

=cut

sub _RoleGroupClass {
    my $self = shift;
    return $self->RecordClass;
}

sub _RoleGroupsJoin {
    my $self = shift;
    my %args = (New => 0, Class => '', Name => '', @_);

    $args{'Class'} ||= $self->_RoleGroupClass;

    my $name = $args{'Name'};
    if ( exists $args{'Type'} ) {
        RT->Deprecated( Arguments => 'Type', Instead => 'Name', Remove => '4.4' );
        $name = $args{'Type'};
    }

    return $self->{'_sql_role_group_aliases'}{ $args{'Class'} .'-'. $name }
        if $self->{'_sql_role_group_aliases'}{ $args{'Class'} .'-'. $name }
           && !$args{'New'};

    # If we're looking at a role group on a class that "contains" this record
    # (i.e. roles on queues for tickets), then we assume that the current
    # record has a column named after the containing class (i.e.
    # Tickets.Queue).
    my $instance = $self->_RoleGroupClass eq $args{Class} ? "id" : $args{Class};
       $instance =~ s/^RT:://;

    # Watcher groups are always created for each record, so we use INNER join.
    my $groups = $self->Join(
        ALIAS1          => 'main',
        FIELD1          => $instance,
        TABLE2          => 'Groups',
        FIELD2          => 'Instance',
        ENTRYAGGREGATOR => 'AND',
        DISTINCT        => !!$args{'Type'},
    );
    $self->Limit(
        LEFTJOIN        => $groups,
        ALIAS           => $groups,
        FIELD           => 'Domain',
        VALUE           => $args{'Class'} .'-Role',
        CASESENSITIVE   => 0,
    );
    $self->Limit(
        LEFTJOIN        => $groups,
        ALIAS           => $groups,
        FIELD           => 'Name',
        VALUE           => $name,
        CASESENSITIVE   => 0,
    ) if $name;

    $self->{'_sql_role_group_aliases'}{ $args{'Class'} .'-'. $name } = $groups
        unless $args{'New'};

    return $groups;
}

sub _GroupMembersJoin {
    my $self = shift;
    my %args = (New => 1, GroupsAlias => undef, Left => 1, @_);

    return $self->{'_sql_group_members_aliases'}{ $args{'GroupsAlias'} }
        if $self->{'_sql_group_members_aliases'}{ $args{'GroupsAlias'} }
            && !$args{'New'};

    my $alias = $self->Join(
        $args{'Left'} ? (TYPE            => 'LEFT') : (),
        ALIAS1          => $args{'GroupsAlias'},
        FIELD1          => 'id',
        TABLE2          => 'CachedGroupMembers',
        FIELD2          => 'GroupId',
        ENTRYAGGREGATOR => 'AND',
    );
    $self->Limit(
        LEFTJOIN => $alias,
        ALIAS => $alias,
        FIELD => 'Disabled',
        VALUE => 0,
    );

    $self->{'_sql_group_members_aliases'}{ $args{'GroupsAlias'} } = $alias
        unless $args{'New'};

    return $alias;
}

=head2 _WatcherJoin

Helper function which provides joins to a watchers table both for limits
and for ordering.

=cut

sub _WatcherJoin {
    my $self = shift;

    my $groups = $self->_RoleGroupsJoin(@_);
    my $group_members = $self->_GroupMembersJoin( GroupsAlias => $groups );
    # XXX: work around, we must hide groups that
    # are members of the role group we search in,
    # otherwise them result in wrong NULLs in Users
    # table and break ordering. Now, we know that
    # RT doesn't allow to add groups as members of the
    # ticket roles, so we just hide entries in CGM table
    # with MemberId == GroupId from results
    $self->Limit(
        LEFTJOIN   => $group_members,
        FIELD      => 'GroupId',
        OPERATOR   => '!=',
        VALUE      => "$group_members.MemberId",
        QUOTEVALUE => 0,
    );
    my $users = $self->Join(
        TYPE            => 'LEFT',
        ALIAS1          => $group_members,
        FIELD1          => 'MemberId',
        TABLE2          => 'Users',
        FIELD2          => 'id',
    );
    return ($groups, $group_members, $users);
}


sub RoleLimit {
    my $self = shift;
    my %args = (
        TYPE => '',
        CLASS => '',
        FIELD => undef,
        OPERATOR => '=',
        VALUE => undef,
        @_
    );

    my $class = $args{CLASS} || $self->_RoleGroupClass;

    $args{FIELD} ||= 'id' if $args{VALUE} =~ /^\d+$/;

    my $type = delete $args{TYPE};
    if ($type and not $class->HasRole($type)) {
        RT->Logger->warn("RoleLimit called with invalid role $type for $class");
        return;
    }

    my $column = $type ? $class->Role($type)->{Column} : undef;

    # if it's equality op and search by Email or Name then we can preload user
    # we do it to help some DBs better estimate number of rows and get better plans
    if ( $args{OPERATOR} =~ /^!?=$/
             && (!$args{FIELD} || $args{FIELD} eq 'Name' || $args{FIELD} eq 'EmailAddress') ) {
        my $o = RT::User->new( $self->CurrentUser );
        my $method =
            !$args{FIELD}
            ? ($column ? 'Load' : 'LoadByEmail')
            : $args{FIELD} eq 'EmailAddress' ? 'LoadByEmail': 'Load';
        $o->$method( $args{VALUE} );
        $args{FIELD} = 'id';
        $args{VALUE} = $o->id || 0;
    }

    if ( $column and $args{FIELD} and $args{FIELD} eq 'id' ) {
        $self->Limit(
            %args,
            FIELD => $column,
        );
        return;
    }

    $args{FIELD} ||= 'EmailAddress';

    my ($groups, $group_members, $users);
    if ( $args{'BUNDLE'} ) {
        ($groups, $group_members, $users) = @{ $args{'BUNDLE'} };
    } else {
        $groups = $self->_RoleGroupsJoin( Name => $type, Class => $class, New => !$type );
    }

    $self->_OpenParen( $args{SUBCLAUSE} ) if $args{SUBCLAUSE};
    if ( $args{OPERATOR} =~ /^IS(?: NOT)?$/i ) {
        # is [not] empty case

        $group_members ||= $self->_GroupMembersJoin( GroupsAlias => $groups );
        # to avoid joining the table Users into the query, we just join GM
        # and make sure we don't match records where group is member of itself
        $self->Limit(
            LEFTJOIN   => $group_members,
            FIELD      => 'GroupId',
            OPERATOR   => '!=',
            VALUE      => "$group_members.MemberId",
            QUOTEVALUE => 0,
        );
        $self->Limit(
            %args,
            ALIAS         => $group_members,
            FIELD         => 'GroupId',
            OPERATOR      => $args{OPERATOR},
            VALUE         => $args{VALUE},
        );
    }
    elsif ( $args{OPERATOR} =~ /^!=$|^NOT\s+/i ) {
        # negative condition case

        # reverse op
        $args{OPERATOR} =~ s/!|NOT\s+//i;

        # XXX: we have no way to build correct "Watcher.X != 'Y'" when condition
        # "X = 'Y'" matches more then one user so we try to fetch two records and
        # do the right thing when there is only one exist and semi-working solution
        # otherwise.
        my $users_obj = RT::Users->new( $self->CurrentUser );
        $users_obj->Limit(
            FIELD         => $args{FIELD},
            OPERATOR      => $args{OPERATOR},
            VALUE         => $args{VALUE},
        );
        $users_obj->OrderBy;
        $users_obj->RowsPerPage(2);
        my @users = @{ $users_obj->ItemsArrayRef };

        $group_members ||= $self->_GroupMembersJoin( GroupsAlias => $groups );
        if ( @users <= 1 ) {
            my $uid = 0;
            $uid = $users[0]->id if @users;
            $self->Limit(
                LEFTJOIN      => $group_members,
                ALIAS         => $group_members,
                FIELD         => 'MemberId',
                VALUE         => $uid,
            );
            $self->Limit(
                %args,
                ALIAS           => $group_members,
                FIELD           => 'id',
                OPERATOR        => 'IS',
                VALUE           => 'NULL',
            );
        } else {
            $self->Limit(
                LEFTJOIN   => $group_members,
                FIELD      => 'GroupId',
                OPERATOR   => '!=',
                VALUE      => "$group_members.MemberId",
                QUOTEVALUE => 0,
            );
            $users ||= $self->Join(
                TYPE            => 'LEFT',
                ALIAS1          => $group_members,
                FIELD1          => 'MemberId',
                TABLE2          => 'Users',
                FIELD2          => 'id',
            );
            $self->Limit(
                LEFTJOIN      => $users,
                ALIAS         => $users,
                FIELD         => $args{FIELD},
                OPERATOR      => $args{OPERATOR},
                VALUE         => $args{VALUE},
                CASESENSITIVE => 0,
            );
            $self->Limit(
                %args,
                ALIAS         => $users,
                FIELD         => 'id',
                OPERATOR      => 'IS',
                VALUE         => 'NULL',
            );
        }
    } else {
        # positive condition case

        $group_members ||= $self->_GroupMembersJoin(
            GroupsAlias => $groups, New => 1, Left => 0
        );
        if ($args{FIELD} eq "id") {
            # Save a left join to Users, if possible
            $self->Limit(
                %args,
                ALIAS           => $group_members,
                FIELD           => "MemberId",
                OPERATOR        => $args{OPERATOR},
                VALUE           => $args{VALUE},
                CASESENSITIVE   => 0,
            );
        } else {
            $users ||= $self->Join(
                TYPE            => 'LEFT',
                ALIAS1          => $group_members,
                FIELD1          => 'MemberId',
                TABLE2          => 'Users',
                FIELD2          => 'id',
            );
            $self->Limit(
                %args,
                ALIAS           => $users,
                FIELD           => $args{FIELD},
                OPERATOR        => $args{OPERATOR},
                VALUE           => $args{VALUE},
                CASESENSITIVE   => 0,
            );
        }
    }
    $self->_CloseParen( $args{SUBCLAUSE} ) if $args{SUBCLAUSE};
    return ($groups, $group_members, $users);
}

1;