TimeWorked-like custom fields, RT#11168
[freeside.git] / rt / lib / RT / Groups_Overlay.pm
index 4a3231e..fa39e8c 100644 (file)
@@ -1,26 +1,51 @@
-# BEGIN LICENSE BLOCK
-# 
-# Copyright (c) 1996-2003 Jesse Vincent <jesse@bestpractical.com>
-# 
-# (Except where explictly superceded by other copyright notices)
-# 
+# BEGIN BPS TAGGED BLOCK {{{
+#
+# COPYRIGHT:
+#
+# This software is Copyright (c) 1996-2011 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.
-# 
-# Unless otherwise specified, all modifications, corrections or
-# extensions to this work which alter its source code become the
-# property of Best Practical Solutions, LLC when submitted for
-# inclusion in the work.
-# 
-# 
-# END LICENSE BLOCK
+#
+# 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::Groups - a collection of RT::Group objects
@@ -28,8 +53,8 @@
 =head1 SYNOPSIS
 
   use RT::Groups;
-  my $groups = $RT::Groups->new($CurrentUser);
-  $groups->LimitToReal();
+  my $groups = RT::Groups->new($CurrentUser);
+  $groups->UnLimit();
   while (my $group = $groups->Next()) {
      print $group->Id ." is a group id\n";
   }
 =head1 METHODS
 
 
-=begin testing
 
-ok (require RT::Groups);
+=cut
 
-=end testing
 
-=cut
+package RT::Groups;
 
 use strict;
 no warnings qw(redefine);
 
+use RT::Users;
+
+# XXX: below some code is marked as subject to generalize in Groups, Users classes.
+# RUZ suggest name Principals::Generic or Principals::Base as abstract class, but
+# Jesse wants something that doesn't imply it's a Principals.pm subclass.
+# See comments below for candidats.
+
 
 # {{{ sub _Init
 
@@ -58,17 +88,49 @@ sub _Init {
   my $self = shift;
   $self->{'table'} = "Groups";
   $self->{'primary_key'} = "id";
+  $self->{'with_disabled_column'} = 1;
+
+  my @result = $self->SUPER::_Init(@_);
 
   $self->OrderBy( ALIAS => 'main',
                  FIELD => 'Name',
                  ORDER => 'ASC');
 
-
-  return ( $self->SUPER::_Init(@_));
+  # XXX: this code should be generalized
+  $self->{'princalias'} = $self->Join(
+    ALIAS1 => 'main',
+    FIELD1 => 'id',
+    TABLE2 => 'Principals',
+    FIELD2 => 'id'
+  );
+
+  # even if this condition is useless and ids in the Groups table
+  # only match principals with type 'Group' this could speed up
+  # searches in some DBs.
+  $self->Limit( ALIAS => $self->{'princalias'},
+                FIELD => 'PrincipalType',
+                VALUE => 'Group',
+              );
+
+  return (@result);
 }
 # }}}
 
-# {{{ LimiToSystemInternalGroups
+=head2 PrincipalsAlias
+
+Returns the string that represents this Users object's primary "Principals" alias.
+
+=cut
+
+# XXX: should be generalized, code duplication
+sub PrincipalsAlias {
+    my $self = shift;
+    return($self->{'princalias'});
+
+}
+
+
+# {{{ LimitToSystemInternalGroups
 
 =head2 LimitToSystemInternalGroups
 
@@ -87,9 +149,9 @@ sub LimitToSystemInternalGroups {
 
 # }}}
 
-# {{{ LimiToUserDefinedGroups
+# {{{ LimitToUserDefinedGroups
 
-=head2 LimitToUserDefined Groups
+=head2 LimitToUserDefinedGroups
 
 Return only UserDefined Groups
 
@@ -106,7 +168,7 @@ sub LimitToUserDefinedGroups {
 
 # }}}
 
-# {{{ LimiToPersonalGroups
+# {{{ LimitToPersonalGroupsFor
 
 =head2 LimitToPersonalGroupsFor PRINCIPAL_ID
 
@@ -123,8 +185,7 @@ sub LimitToPersonalGroupsFor {
     $self->Limit(FIELD => 'Domain', OPERATOR => '=', VALUE => 'Personal');
     $self->Limit(   FIELD => 'Instance',   
                     OPERATOR => '=', 
-                    VALUE => $princ,
-                    ENTRY_AGGREGATOR => 'OR');
+                    VALUE => $princ);
 }
 
 
@@ -132,7 +193,7 @@ sub LimitToPersonalGroupsFor {
 
 # {{{ LimitToRolesForQueue
 
-=item LimitToRolesForQueue QUEUE_ID
+=head2 LimitToRolesForQueue QUEUE_ID
 
 Limits the set of groups found to role groups for queue QUEUE_ID
 
@@ -149,7 +210,7 @@ sub LimitToRolesForQueue {
 
 # {{{ LimitToRolesForTicket
 
-=item LimitToRolesForTicket Ticket_ID
+=head2 LimitToRolesForTicket Ticket_ID
 
 Limits the set of groups found to role groups for Ticket Ticket_ID
 
@@ -166,7 +227,7 @@ sub LimitToRolesForTicket {
 
 # {{{ LimitToRolesForSystem
 
-=item LimitToRolesForSystem System_ID
+=head2 LimitToRolesForSystem System_ID
 
 Limits the set of groups found to role groups for System System_ID
 
@@ -183,30 +244,6 @@ sub LimitToRolesForSystem {
 
 Limits the set of groups returned to groups which have
 Principal PRINCIPAL_ID as a member
-   
-=begin testing
-
-my $u = RT::User->new($RT::SystemUser);
-$u->Create(Name => 'Membertests');
-my $g = RT::Group->new($RT::SystemUser);
-my ($id, $msg) = $g->CreateUserDefinedGroup(Name => 'Membertests');
-ok ($id,$msg);
-
-my ($aid, $amsg) =$g->AddMember($u->id);
-ok ($aid, $amsg);
-ok($g->HasMember($u->PrincipalObj),"G has member u");
-
-my $groups = RT::Groups->new($RT::SystemUser);
-$groups->LimitToUserDefinedGroups();
-$groups->WithMember(PrincipalId => $u->id);
-ok ($groups->Count == 1,"found the 1 group - " . $groups->Count);
-ok ($groups->First->Id == $g->Id, "it's the right one");
-
-
-
-
-=end testing
-
 
 =cut
 
@@ -228,117 +265,108 @@ sub WithMember {
     $self->Limit(ALIAS => $members, FIELD => 'MemberId', OPERATOR => '=', VALUE => $args{'PrincipalId'});
 }
 
+sub WithoutMember {
+    my $self = shift;
+    my %args = (
+        PrincipalId => undef,
+        Recursively => undef,
+        @_
+    );
 
-=head2 WithRight { Right => RIGHTNAME, Object => RT::Record, IncludeSystemRights => 1, IncludeSuperusers => 0 }
-
-
-Find all groups which have RIGHTNAME for RT::Record. Optionally include global rights and superusers. By default, include the global rights, but not the superusers.
-
-=begin testing
-
-my $q = RT::Queue->new($RT::SystemUser);
-my ($id, $msg) =$q->Create( Name => 'GlobalACLTest');
-ok ($id, $msg);
+    my $members = $args{'Recursively'} ? 'CachedGroupMembers' : 'GroupMembers';
+    my $members_alias = $self->Join(
+        TYPE   => 'LEFT',
+        FIELD1 => 'id',
+        TABLE2 => $members,
+        FIELD2 => 'GroupId',
+    );
+    $self->Limit(
+        LEFTJOIN => $members_alias,
+        ALIAS    => $members_alias,
+        FIELD    => 'MemberId',
+        OPERATOR => '=',
+        VALUE    => $args{'PrincipalId'},
+    );
+    $self->Limit(
+        ALIAS    => $members_alias,
+        FIELD    => 'MemberId',
+        OPERATOR => 'IS',
+        VALUE    => 'NULL',
+        QUOTEVALUE => 0,
+    );
+}
 
-my $testuser = RT::User->new($RT::SystemUser);
-($id,$msg) = $testuser->Create(Name => 'JustAnAdminCc');
-ok ($id,$msg);
+=head2 WithRight { Right => RIGHTNAME, Object => RT::Record, IncludeSystemRights => 1, IncludeSuperusers => 0, EquivObjects => [ ] }
 
-my $global_admin_cc = RT::Group->new($RT::SystemUser);
-$global_admin_cc->LoadSystemRoleGroup('AdminCc');
-ok($global_admin_cc->id, "Found the global admincc group");
-my $groups = RT::Groups->new($RT::SystemUser);
-$groups->WithRight(Right => 'OwnTicket', Object => $q);
-is($groups->Count, 1);
-($id, $msg) = $global_admin_cc->PrincipalObj->GrantRight(Right =>'OwnTicket', Object=> $RT::System);
-ok ($id,$msg);
-ok (!$testuser->HasRight(Object => $q, Right => 'OwnTicket') , "The test user does not have the right to own tickets in the test queue");
-($id, $msg) = $q->AddWatcher(Type => 'AdminCc', PrincipalId => $testuser->id);
-ok($id,$msg);
-ok ($testuser->HasRight(Object => $q, Right => 'OwnTicket') , "The test user does have the right to own tickets now. thank god.");
 
-$groups = RT::Groups->new($RT::SystemUser);
-$groups->WithRight(Right => 'OwnTicket', Object => $q);
-ok ($id,$msg);
-is($groups->Count, 2);
+Find all groups which have RIGHTNAME for RT::Record. Optionally include global rights and superusers. By default, include the global rights, but not the superusers.
 
-=end testing
 
 
 =cut
 
-
+#XXX: should be generilized
 sub WithRight {
     my $self = shift;
     my %args = ( Right                  => undef,
                  Object =>              => undef,
                  IncludeSystemRights    => 1,
                  IncludeSuperusers      => undef,
+                 IncludeSubgroupMembers => 0,
+                 EquivObjects           => [ ],
                  @_ );
 
-    my $acl        = $self->NewAlias('ACL');
-
-    # {{{ Find only rows where the right granted is the one we're looking up or _possibly_ superuser 
-    $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' );
-    }
-    # }}}
-
-    my ($or_check_ticket_roles, $or_check_roles);
-    my $which_object = "$acl.ObjectType = 'RT::System'";
-
-    if ( defined $args{'Object'} ) {
-        if ( ref($args{'Object'}) eq 'RT::Ticket' ) {
-            $or_check_ticket_roles =
-                " OR ( main.Domain = 'RT::Ticket-Role' AND main.Instance = " . $args{'Object'}->Id . ") ";
-
-            # 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.
-            $args{'Object'}   = $args{'Object'}->QueueObj;
-        }
-        # TODO XXX This really wants some refactoring
-        if ( ref($args{'Object'}) eq 'RT::Queue' ) {
-            $or_check_roles =
-                " OR ( ( (main.Domain = 'RT::Queue-Role' AND main.Instance = " .
-                $args{'Object'}->Id . ") $or_check_ticket_roles ) " .
-                " AND main.Type = $acl.PrincipalType) ";
-        }
-
-       if ( $args{'IncludeSystemRights'} ) {
-           $which_object .= ' OR ';
-       }
-       else {
-           $which_object = '';
-       }
-        $which_object .=
-            " ($acl.ObjectType = '" . ref($args{'Object'}) . "'" .
-            " AND $acl.ObjectId = " . $args{'Object'}->Id . ") ";
-    }
+    my $from_role = $self->Clone;
+    $from_role->WithRoleRight( %args );
 
-    $self->_AddSubClause( "WhichObject", "($which_object)" );
-
-    $self->_AddSubClause( "WhichGroup",
-        qq{
-          ( (    $acl.PrincipalId = main.id
-             AND $acl.PrincipalType = 'Group'
-             AND (   main.Domain = 'SystemInternal'
-                  OR main.Domain = 'UserDefined'
-                  OR main.Domain = 'ACLEquivalence'))
-           $or_check_roles)
-        }
-    );
+    my $from_group = $self->Clone;
+    $from_group->WithGroupRight( %args );
+
+    #XXX: DIRTY HACK
+    use DBIx::SearchBuilder 1.50; #no version on ::Union :(
+    use DBIx::SearchBuilder::Union;
+    my $union = new DBIx::SearchBuilder::Union;
+    $union->add($from_role);
+    $union->add($from_group);
+    %$self = %$union;
+    bless $self, ref($union);
+
+    return;
+}
+
+#XXX: methods are active aliases to Users class to prevent code duplication
+# should be generalized
+sub _JoinGroups {
+    my $self = shift;
+    my %args = (@_);
+    return 'main' unless $args{'IncludeSubgroupMembers'};
+    return $self->RT::Users::_JoinGroups( %args );
+}
+sub _JoinGroupMembers {
+    my $self = shift;
+    my %args = (@_);
+    return 'main' unless $args{'IncludeSubgroupMembers'};
+    return $self->RT::Users::_JoinGroupMembers( %args );
+}
+sub _JoinGroupMembersForGroupRights {
+    my $self = shift;
+    my %args = (@_);
+    my $group_members = $self->_JoinGroupMembers( %args );
+    unless( $group_members eq 'main' ) {
+        return $self->RT::Users::_JoinGroupMembersForGroupRights( %args );
+    }
+    $self->Limit( ALIAS => $args{'ACLAlias'},
+                  FIELD => 'PrincipalId',
+                  VALUE => "main.id",
+                  QUOTEVALUE => 0,
+                );
 }
+sub _JoinACL                  { return (shift)->RT::Users::_JoinACL( @_ ) }
+sub _RoleClauses              { return (shift)->RT::Users::_RoleClauses( @_ ) }
+sub _WhoHaveRoleRightSplitted { return (shift)->RT::Users::_WhoHaveRoleRightSplitted( @_ ) }
+sub _GetEquivObjects          { return (shift)->RT::Users::_GetEquivObjects( @_ ) }
+sub WithGroupRight            { return (shift)->RT::Users::WhoHaveGroupRight( @_ ) }
+sub WithRoleRight             { return (shift)->RT::Users::WhoHaveRoleRight( @_ ) }
 
 # {{{ sub LimitToEnabled
 
@@ -350,19 +378,13 @@ Only find items that haven\'t been disabled
 
 sub LimitToEnabled {
     my $self = shift;
-    
-    my $alias = $self->Join(
-       TYPE   => 'left',
-       ALIAS1 => 'main',
-       FIELD1 => 'id',
-       TABLE2 => 'Principals',
-       FIELD2 => 'id'
-    );
 
-    $self->Limit( ALIAS => $alias,
-                 FIELD => 'Disabled',
-                 VALUE => '0',
-                 OPERATOR => '=' );
+    $self->{'handled_disabled_column'} = 1;
+    $self->Limit(
+        ALIAS => $self->PrincipalsAlias,
+        FIELD => 'Disabled',
+        VALUE => '0',
+    );
 }
 # }}}
 
@@ -377,23 +399,38 @@ Only find items that have been deleted.
 sub LimitToDeleted {
     my $self = shift;
     
-    my $alias = $self->Join(
-       TYPE   => 'left',
-       ALIAS1 => 'main',
-       FIELD1 => 'id',
-       TABLE2 => 'Principals',
-       FIELD2 => 'id'
+    $self->{'handled_disabled_column'} = $self->{'find_disabled_rows'} = 1;
+    $self->Limit(
+        ALIAS => $self->PrincipalsAlias,
+        FIELD => 'Disabled',
+        VALUE => 1,
     );
-
-    $self->{'find_disabled_rows'} = 1;
-    $self->Limit( ALIAS => $alias,
-                 FIELD => 'Disabled',
-                 OPERATOR => '=',
-                 VALUE => '1'
-               );
 }
+
 # }}}
 
+# {{{ sub Next
+
+sub Next {
+    my $self = shift;
+
+    # Don't show groups which the user isn't allowed to see.
+
+    my $Group = $self->SUPER::Next();
+    if ((defined($Group)) and (ref($Group))) {
+       unless ($Group->CurrentUserHasRight('SeeGroup')) {
+           return $self->Next();
+       }
+       
+       return $Group;
+    }
+    else {
+       return undef;
+    }
+}
+
+
+
 sub _DoSearch {
     my $self = shift;