summaryrefslogtreecommitdiff
path: root/rt/lib/RT/Users.pm
blob: 72c03dfe8525de83d8d8469280bdbca9596269e7 (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
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2018 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 }}}

=head1 NAME

  RT::Users - Collection of RT::User objects

=head1 SYNOPSIS

  use RT::Users;


=head1 DESCRIPTION


=head1 METHODS


=cut


package RT::Users;

use strict;
use warnings;

use base 'RT::SearchBuilder';

use RT::User;

sub Table { 'Users'}


sub _Init {
    my $self = shift;
    $self->{'with_disabled_column'} = 1;

    my @result = $self->SUPER::_Init(@_);
    # By default, order by name
    $self->OrderBy( ALIAS => 'main',
                    FIELD => 'Name',
                    ORDER => 'ASC' );

    # XXX: should be generalized
    $self->{'princalias'} = $self->Join(
                 ALIAS1 => 'main',
                 FIELD1 => 'id',
                 TABLE2 => 'Principals',
                 FIELD2 => 'id' );
    $self->Limit( ALIAS => $self->{'princalias'},
                  FIELD => 'PrincipalType',
                  VALUE => 'User',
                );

    return (@result);
}


=head2 PrincipalsAlias

Returns the string that represents this Users object's primary "Principals" alias.

=cut

# XXX: should be generalized
sub PrincipalsAlias {
    my $self = shift;
    return($self->{'princalias'});

}


=head2 LimitToEnabled

Only find items that haven't been disabled

=cut

# XXX: should be generalized
sub LimitToEnabled {
    my $self = shift;

    $self->{'handled_disabled_column'} = 1;
    $self->Limit(
        ALIAS    => $self->PrincipalsAlias,
        FIELD    => 'Disabled',
        VALUE    => '0',
    );
}

=head2 LimitToDeleted

Only find items that have been deleted.

=cut

sub LimitToDeleted {
    my $self = shift;
    
    $self->{'handled_disabled_column'} = $self->{'find_disabled_rows'} = 1;
    $self->Limit(
        ALIAS => $self->PrincipalsAlias,
        FIELD => 'Disabled',
        VALUE => 1,
    );
}



=head2 LimitToEmail

Takes one argument. an email address. limits the returned set to
that email address

=cut

sub LimitToEmail {
    my $self = shift;
    my $addr = shift;
    $self->Limit( FIELD => 'EmailAddress', VALUE => $addr, CASESENSITIVE => 0 );
}



=head2 MemberOfGroup PRINCIPAL_ID

takes one argument, a group's principal id. Limits the returned set
to members of a given group

=cut

sub MemberOfGroup {
    my $self  = shift;
    my $group = shift;

    return $self->loc("No group specified") if ( !defined $group );

    my $groupalias = $self->NewAlias('CachedGroupMembers');

    # Join the principal to the groups table
    $self->Join( ALIAS1 => $self->PrincipalsAlias,
                 FIELD1 => 'id',
                 ALIAS2 => $groupalias,
                 FIELD2 => 'MemberId' );
    $self->Limit( ALIAS => $groupalias,
                  FIELD => 'Disabled',
                  VALUE => 0 );

    $self->Limit( ALIAS    => "$groupalias",
                  FIELD    => 'GroupId',
                  VALUE    => "$group",
                  OPERATOR => "=" );
}



=head2 LimitToPrivileged

Limits to users who can be made members of ACLs and groups

=cut

sub LimitToPrivileged {
    my $self = shift;
    $self->MemberOfGroup( RT->PrivilegedUsers->id );
}

=head2 LimitToUnprivileged

Limits to unprivileged users only

=cut

sub LimitToUnprivileged {
    my $self = shift;
    $self->MemberOfGroup( RT->UnprivilegedUsers->id);
}


sub Limit {
    my $self = shift;
    my %args = @_;
    $args{'CASESENSITIVE'} = 0 unless exists $args{'CASESENSITIVE'} or $args{'ALIAS'};
    return $self->SUPER::Limit( %args );
}

=head2 WhoHaveRight { Right => 'name', Object => $rt_object , IncludeSuperusers => undef, IncludeSubgroupMembers => undef, IncludeSystemRights => undef, EquivObjects => [ ] }


find all users who the right Right for this group, either individually
or as members of groups

If passed a queue object, with no id, it will find users who have that right for _any_ queue

=cut

# XXX: should be generalized
sub _JoinGroupMembers
{
    my $self = shift;
    my %args = (
        IncludeSubgroupMembers => 1,
        @_
    );

    my $principals = $self->PrincipalsAlias;

    # The cachedgroupmembers table is used for unrolling group memberships
    # to allow fast lookups. if we bind to CachedGroupMembers, we'll find
    # all members of groups recursively. if we don't we'll find only 'direct'
    # members of the group in question
    my $group_members;
    if ( $args{'IncludeSubgroupMembers'} ) {
        $group_members = $self->NewAlias('CachedGroupMembers');
    }
    else {
        $group_members = $self->NewAlias('GroupMembers');
    }

    $self->Join(
        ALIAS1 => $group_members,
        FIELD1 => 'MemberId',
        ALIAS2 => $principals,
        FIELD2 => 'id'
    );
    $self->Limit(
        ALIAS => $group_members,
        FIELD => 'Disabled',
        VALUE => 0,
    ) if $args{'IncludeSubgroupMembers'};

    return $group_members;
}

# XXX: should be generalized
sub _JoinGroups
{
    my $self = shift;
    my %args = (@_);

    my $group_members = $self->_JoinGroupMembers( %args );
    my $groups = $self->NewAlias('Groups');
    $self->Join(
        ALIAS1 => $groups,
        FIELD1 => 'id',
        ALIAS2 => $group_members,
        FIELD2 => 'GroupId'
    );

    return $groups;
}

# XXX: should be generalized
sub _JoinACL
{
    my $self = shift;
    my %args = (
        Right                  => undef,
        IncludeSuperusers      => undef,
        @_,
    );

    if ( $args{'Right'} ) {
        my $canonic = RT::ACE->CanonicalizeRightName( $args{'Right'} );
        unless ( $canonic ) {
            $RT::Logger->error("Invalid right. Couldn't canonicalize right '$args{'Right'}'");
        }
        else {
            $args{'Right'} = $canonic;
        }
    }

    my $acl = $self->NewAlias('ACL');
    $self->Limit(
        ALIAS    => $acl,
        FIELD    => 'RightName',
        OPERATOR => ( $args{Right} ? '=' : 'IS NOT' ),
        VALUE => $args{Right} || 'NULL',
        ENTRYAGGREGATOR => 'OR'
    );
    if ( $args{'IncludeSuperusers'} and $args{'Right'} ) {
        $self->Limit(
            ALIAS           => $acl,
            FIELD           => 'RightName',
            OPERATOR        => '=',
            VALUE           => 'SuperUser',
            ENTRYAGGREGATOR => 'OR'
        );
    }
    return $acl;
}

# XXX: should be generalized
sub _GetEquivObjects
{
    my $self = shift;
    my %args = (
        Object                 => undef,
        IncludeSystemRights    => undef,
        EquivObjects           => [ ],
        @_
    );
    return () unless $args{'Object'};

    my @objects = ($args{'Object'});
    if ( UNIVERSAL::isa( $args{'Object'}, 'RT::Ticket' ) ) {
        # If we're looking at ticket rights, we also want to look at the associated queue rights.
        # this is a little bit hacky, but basically, now that we've done the ticket roles magic,
        # we load the queue object and ask all the rest of our questions about the queue.

        # XXX: This should be abstracted into object itself
        if( $args{'Object'}->id ) {
            push @objects, $args{'Object'}->ACLEquivalenceObjects;
        } else {
            push @objects, 'RT::Queue';
        }
    }

    if( $args{'IncludeSystemRights'} ) {
        push @objects, $RT::System;
    }
    push @objects, @{ $args{'EquivObjects'} };
    return grep $_, @objects;
}

# XXX: should be generalized
sub WhoHaveRight {
    my $self = shift;
    my %args = (
        Right                  => undef,
        Object                 => undef,
        IncludeSystemRights    => undef,
        IncludeSuperusers      => undef,
        IncludeSubgroupMembers => 1,
        EquivObjects           => [ ],
        @_
    );

    if ( defined $args{'ObjectType'} || defined $args{'ObjectId'} ) {
        $RT::Logger->crit( "WhoHaveRight called with the Obsolete ObjectId/ObjectType API");
        return (undef);
    }

    my $from_role = $self->Clone;
    $from_role->WhoHaveRoleRight( %args );

    my $from_group = $self->Clone;
    $from_group->WhoHaveGroupRight( %args );

    #XXX: DIRTY HACK
    use DBIx::SearchBuilder 1.50; #no version on ::Union :(
    use DBIx::SearchBuilder::Union;
    my $union = DBIx::SearchBuilder::Union->new();
    $union->add( $from_group );
    $union->add( $from_role );
    %$self = %$union;
    bless $self, ref($union);

    return;
}

# XXX: should be generalized
sub WhoHaveRoleRight
{
    my $self = shift;
    my %args = (
        Right                  => undef,
        Object                 => undef,
        IncludeSystemRights    => undef,
        IncludeSuperusers      => undef,
        IncludeSubgroupMembers => 1,
        EquivObjects           => [ ],
        @_
    );

    my @objects = $self->_GetEquivObjects( %args );

    # RT::Principal->RolesWithRight only expects EquivObjects, so we need to
    # fill it.  At the very least it needs $args{Object}, which
    # _GetEquivObjects above does for us.
    unshift @{$args{'EquivObjects'}}, @objects;

    my @roles = RT::Principal->RolesWithRight( %args );
    unless ( @roles ) {
        $self->_AddSubClause( "WhichRole", "(main.id = 0)" );
        return;
    }

    my $groups = $self->_JoinGroups( %args );

    # no system user
    $self->Limit( ALIAS => $self->PrincipalsAlias,
                  FIELD => 'id',
                  OPERATOR => '!=',
                  VALUE => RT->SystemUser->id
                );

    $self->_AddSubClause( "WhichRole", "(". join( ' OR ',
        map $RT::Handle->__MakeClauseCaseInsensitive("$groups.Name", '=', "'$_'"), @roles
    ) .")" );

    my @groups_clauses = $self->_RoleClauses( $groups, @objects );
    $self->_AddSubClause( "WhichObject", "(". join( ' OR ', @groups_clauses ) .")" )
        if @groups_clauses;

    return;
}

sub _RoleClauses {
    my $self = shift;
    my $groups = shift;
    my @objects = @_;

    my @groups_clauses;
    foreach my $obj ( @objects ) {
        my $type = ref($obj)? ref($obj): $obj;

        my $role_clause = $RT::Handle->__MakeClauseCaseInsensitive("$groups.Domain", '=', "'$type-Role'");

        if ( my $id = eval { $obj->id } ) {
            $role_clause .= " AND $groups.Instance = $id";
        }
        push @groups_clauses, "($role_clause)";
    }
    return @groups_clauses;
}

# XXX: should be generalized
sub _JoinGroupMembersForGroupRights
{
    my $self = shift;
    my %args = (@_);
    my $group_members = $self->_JoinGroupMembers( %args );
    $self->Limit( ALIAS => $args{'ACLAlias'},
                  FIELD => 'PrincipalId',
                  VALUE => "$group_members.GroupId",
                  QUOTEVALUE => 0,
                );
    return $group_members;
}

# XXX: should be generalized
sub WhoHaveGroupRight
{
    my $self = shift;
    my %args = (
        Right                  => undef,
        Object                 => undef,
        IncludeSystemRights    => undef,
        IncludeSuperusers      => undef,
        IncludeSubgroupMembers => 1,
        EquivObjects           => [ ],
        @_
    );

    # Find only rows where the right granted is
    # the one we're looking up or _possibly_ superuser
    my $acl = $self->_JoinACL( %args );

    my ($check_objects) = ('');
    my @objects = $self->_GetEquivObjects( %args );

    my %seen;
    if ( @objects ) {
        my @object_clauses;
        foreach my $obj ( @objects ) {
            my $type = ref($obj)? ref($obj): $obj;
            my $id = 0;
            $id = $obj->id if ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id;
            next if $seen{"$type-$id"}++;

            my $object_clause = "$acl.ObjectType = '$type'";
            $object_clause   .= " AND $acl.ObjectId   = $id" if $id;
            push @object_clauses, "($object_clause)";
        }

        $check_objects = join ' OR ', @object_clauses;
    } else {
        if( !$args{'IncludeSystemRights'} ) {
            $check_objects = "($acl.ObjectType != 'RT::System')";
        }
    }
    $self->_AddSubClause( "WhichObject", "($check_objects)" );
    
    my $group_members = $self->_JoinGroupMembersForGroupRights( %args, ACLAlias => $acl );
    # Find only members of groups that have the right.
    $self->Limit( ALIAS => $acl,
                  FIELD => 'PrincipalType',
                  VALUE => 'Group',
                );
    
    # no system user
    $self->Limit( ALIAS => $self->PrincipalsAlias,
                  FIELD => 'id',
                  OPERATOR => '!=',
                  VALUE => RT->SystemUser->id
                );
    return $group_members;
}


=head2 WhoBelongToGroups { Groups => ARRAYREF, IncludeSubgroupMembers => 1, IncludeUnprivileged => 0 }

Return members who belong to any of the groups passed in the groups whose IDs
are included in the Groups arrayref.

If IncludeSubgroupMembers is true (default) then members of any group that's a
member of one of the passed groups are returned. If it's cleared then only
direct member users are returned.

If IncludeUnprivileged is false (default) then only privileged members are
returned; otherwise either privileged or unprivileged group members may be
returned.

=cut

sub WhoBelongToGroups {
    my $self = shift;
    my %args = ( Groups                 => undef,
                 IncludeSubgroupMembers => 1,
                 IncludeUnprivileged    => 0,
                 @_ );

    if (!$args{'IncludeUnprivileged'}) {
        $self->LimitToPrivileged();
    }
    my $group_members = $self->_JoinGroupMembers( %args );

    $self->Limit(
        ALIAS      => $group_members,
        FIELD      => 'GroupId',
        OPERATOR   => 'IN',
        VALUE      => [ 0, @{$args{'Groups'}} ],
    );
}

=head2 SimpleSearch

Does a 'simple' search of Users against a specified Term.

This Term is compared to a number of fields using various types of SQL
comparison operators.

Ensures that the returned collection of Users will have a value for Return.

This method is passed the following.  You must specify a Term and a Return.

    Privileged - Whether or not to limit to Privileged Users (0 or 1)
    Fields     - Hashref of data - defaults to C<$UserSearchFields> emulate that if you want to override
    Term       - String that is in the fields specified by Fields
    Return     - What field on the User you want to be sure isn't empty
    Exclude    - Array reference of ids to exclude
    Max        - What to limit this collection to

=cut

sub SimpleSearch {
    my $self = shift;
    my %args = (
        Privileged  => 0,
        Fields      => RT->Config->Get('UserSearchFields'),
        Term        => undef,
        Exclude     => [],
        Return      => undef,
        Max         => 10,
        @_
    );

    return $self unless defined $args{Return}
                        and defined $args{Term}
                        and length $args{Term};

    $self->RowsPerPage( $args{Max} );

    $self->LimitToPrivileged() if $args{Privileged};

    while (my ($name, $op) = each %{$args{Fields}}) {
        $op = 'STARTSWITH'
        unless $op =~ /^(?:LIKE|(?:START|END)SWITH|=|!=)$/i;

        if ($name =~ /^CF\.(?:\{(.*)}|(.*))$/) {
            my $cfname = $1 || $2;
            my $cf = RT::CustomField->new(RT->SystemUser);
            my ($ok, $msg) = $cf->LoadByName( Name => $cfname, LookupType => 'RT::User');
            if ( $ok ) {
                $self->LimitCustomField(
                    CUSTOMFIELD     => $cf->Id,
                    OPERATOR        => $op,
                    VALUE           => $args{Term},
                    ENTRYAGGREGATOR => 'OR',
                    SUBCLAUSE       => 'autocomplete',
                );
            } else {
                RT->Logger->warning("Asked to search custom field $name but unable to load a User CF with the name $cfname: $msg");
            }
        } else {
            $self->Limit(
                FIELD           => $name,
                OPERATOR        => $op,
                VALUE           => $args{Term},
                ENTRYAGGREGATOR => 'OR',
                SUBCLAUSE       => 'autocomplete',
            );
        }
    }

    # Exclude users we don't want
    $self->Limit(FIELD => 'id', OPERATOR => 'NOT IN', VALUE => $args{Exclude} )
        if @{$args{Exclude}};

    if ( RT->Config->Get('DatabaseType') eq 'Oracle' ) {
        $self->Limit(
            FIELD    => $args{Return},
            OPERATOR => 'IS NOT',
            VALUE    => 'NULL',
        );
    }
    else {
        $self->Limit( FIELD => $args{Return}, OPERATOR => '!=', VALUE => '' );
        $self->Limit(
            FIELD           => $args{Return},
            OPERATOR        => 'IS NOT',
            VALUE           => 'NULL',
            ENTRYAGGREGATOR => 'AND'
        );
    }

    return $self;
}

RT::Base->_ImportOverlays();

1;