How to get a users usergroup?$user->get('usertype')depricate

For Joomla! 2.5 Coding related discussions, please use: http://groups.google.com/group/joomla-dev-general
Note: All 1.6, 1.7 and 3.5 releases have reached end of life and should be updated to 3.x.

Moderator: ooffick

Forum rules
Please use the mailing list here: http://groups.google.com/group/joomla-dev-general rather than this forum.
Locked
User avatar
carsten888
Joomla! Ace
Joomla! Ace
Posts: 1224
Joined: Sat Feb 11, 2006 8:32 am
Contact:

How to get a users usergroup?$user->get('usertype')depricate

Post by carsten888 » Tue Jul 06, 2010 8:11 am

Code: Select all

$user =& JFactory::getUser();
$user_type = $user->get('usertype');
this used to be a nice way to get the users' usergroup. This is depricated in 1.6.

What has it been replaced by?

And how does that work when users can be assigned to more then one usergroup?
http://www.pages-and-items.com my extensions:
User-Private-Page, Redirect-on-Login, Admin-Help-Pages, Dynamic-Menu-Links, Admin-Menu-Manager, plugin load module in article, plugin pure css tooltip and more...

Quinten
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 22, 2009 3:01 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Quinten » Wed Jul 07, 2010 5:25 pm

As a rather new user I might be getting ahead of myelf trying to answer this question. But I took your question and jumped into the code. Hope this helps.

The attribute 'usergroup' appears to have been replaced by an n-to-n mapping table: jos_user_usergroup_map. This must have been done to support multiple usergroups per user. So an array is to be expected.

I can find two method of interest to you: The first gives the option to include inherited user groups. JAccess also defines getUsersByGroup, by the way. It probably is easy for you to check whether the array contains a certain group, or have all sorts of other fun with it :)

User avatar
carsten888
Joomla! Ace
Joomla! Ace
Posts: 1224
Joined: Sat Feb 11, 2006 8:32 am
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by carsten888 » Wed Jul 07, 2010 7:11 pm

thank you!

(how did you find that stuff? If I search for 'usergroup' in docs.joomla.org I don't find it.)

Code: Select all

jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser(43);
print_r($groups);
returns:
Array ( [0] => 1 [1] => 2 )
which is an array of all usergroup id's including those which are not in the usergroup_map table (the usergroups which checkbox go disabled in the user-manager, example: public)

Code: Select all

jimport( 'joomla.user.helper' );
$groups = JUserHelper::getUserGroups(43);
print_r($groups);
returns:
Array ( [2] => Registered )
which is an array of the actual usergoup names the user is connected to, without the 'hidden' groups.

i tried to deduct a slimmer version, like $user_type = $user->get('usertype'); in 1.5

Code: Select all

$user =& JFactory::getUser();
$groups = isset($user->groups) ? $user->groups : array();
print_r($groups);
http://www.pages-and-items.com my extensions:
User-Private-Page, Redirect-on-Login, Admin-Help-Pages, Dynamic-Menu-Links, Admin-Menu-Manager, plugin load module in article, plugin pure css tooltip and more...

Quinten
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 22, 2009 3:01 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Quinten » Wed Jul 07, 2010 8:56 pm

carsten888 wrote:

Code: Select all

jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser(43);
print_r($groups);
returns:
Array ( [0] => 1 [1] => 2 )
which is an array of all usergroup id's including those which are not in the usergroup_map table (the usergroups which checkbox go disabled in the user-manager, example: public)
You mean that the array holds the values 1 and 2?
Well, since the function is declared as "static getGroupsByUser($userId, $recursive=true)", I guess that "JAccess::getGroupsByUser(43);" gives the recursive result. And checking the jos_usergroups table (in PHPMyAdmin) reveals that 1 is parent of 2, and 0 is parent of 1 (but evidently, 0 is not returned). Unless you hacked you usergroups table, it should hold 8 values, so your result is not all values. So you might try

Code: Select all

jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser(43, false);
print_r($groups);
This should return the same result as

Code: Select all

jimport( 'joomla.user.helper' );
$groups = JUserHelper::getUserGroups(43);
print_r($groups);
Please note that I haven't tried any of this myself.

User avatar
carsten888
Joomla! Ace
Joomla! Ace
Posts: 1224
Joined: Sat Feb 11, 2006 8:32 am
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by carsten888 » Thu Jul 08, 2010 5:41 am

I tested this and confirm that when adding false it returns only the most valid usergroups

Code: Select all

JAccess::getGroupsByUser(43, false);
http://www.pages-and-items.com my extensions:
User-Private-Page, Redirect-on-Login, Admin-Help-Pages, Dynamic-Menu-Links, Admin-Menu-Manager, plugin load module in article, plugin pure css tooltip and more...

Quickheads
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Wed Jul 22, 2009 8:58 pm
Location: Kingston, PA - USA
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Quickheads » Sat Jan 28, 2012 2:55 pm

PHP nube here. . . Sorry.

When I use the code above namely:

Code: Select all

jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser($Joomla_userId, false);
print_r($groups);
"print_r" seems to give output like: Array ( [0] => 8 )

When I try "echo $groups;" it simply says Array

I need to know how to grab just the "8" above so that I can output content based on a user's group. So for example, I would like Admins to see one version, Editor's to see another version, Author's another, and Guests to see a different version of the page content.

How do I access the user's group number or name to tell my code how to output different things.

I appreciate any help you could provide.

Thanks,
Dan Yager
Manual Signature Removed
Last edited by imanickam on Thu May 24, 2012 4:10 pm, edited 1 time in total.
Reason: Manual Signature Removed
It is not the critic who counts ... The credit belongs to the man who is actually in the arena ... so that his place shall never be with those cold and timid souls who neither know victory nor defeat. –Theodore Roosevelt

User avatar
carsten888
Joomla! Ace
Joomla! Ace
Posts: 1224
Joined: Sat Feb 11, 2006 8:32 am
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by carsten888 » Sat Jan 28, 2012 3:57 pm

A user could be in one or more groups, thats why always an array is returned, even thou there is only one value in it.

So depending on how you check.
Show if users is assigned to at least one particular group

Code: Select all

//only visible for super-users (= group 8)
if(in_array(8, $groups)){
   echo 'only visible for super-users';
}
show if user is assigned to 2 particular groups

Code: Select all

if(in_array(8, $groups) && in_array(1, $groups)){
   echo 'only visible for users assigned to super-users AND public';
}
http://www.pages-and-items.com my extensions:
User-Private-Page, Redirect-on-Login, Admin-Help-Pages, Dynamic-Menu-Links, Admin-Menu-Manager, plugin load module in article, plugin pure css tooltip and more...

sovainfo
Joomla! Exemplar
Joomla! Exemplar
Posts: 8808
Joined: Sat Oct 01, 2011 7:06 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by sovainfo » Sat Jan 28, 2012 4:04 pm

In addition to the above arrays are accessed like: $groups[0] which is 8 in your case.
Issue with migrating? Include logs/joomla_update.php in your report!
Blank screen? Verify pagesource for HTML code (javascript error)
Installation failing on populating database? Install with set_time_limit(0)
Document your customizations!

Quickheads
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Wed Jul 22, 2009 8:58 pm
Location: Kingston, PA - USA
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Quickheads » Mon Jan 30, 2012 4:50 pm

Carsten/Sovai,
Beautiful! Thanks for the quick responses!

I will give this a try. I believe this is the final missing piece in a google map project I am working on for my site! This will help me show different versions of the map to different user types.

Again thank you very much.

Warm regards,
Dan Yager
Manual Signature Removed
Last edited by imanickam on Thu May 24, 2012 4:09 pm, edited 1 time in total.
Reason: Manual Signature Removed
It is not the critic who counts ... The credit belongs to the man who is actually in the arena ... so that his place shall never be with those cold and timid souls who neither know victory nor defeat. –Theodore Roosevelt

ArnoldBlack
Joomla! Apprentice
Joomla! Apprentice
Posts: 7
Joined: Sun Aug 22, 2010 8:38 am
Location: Thailand.
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by ArnoldBlack » Sun Feb 12, 2012 11:51 am

Quickheads wrote:Carsten/Sovai,
Beautiful! Thanks for the quick responses!

I will give this a try. I believe this is the final missing piece in a google map project I am working on for my site! This will help me show different versions of the map to different user types.

Again thank you very much.

Warm regards,
Dan Yager
If you get it done please share a link to it so we can all see how well it works.
Last edited by imanickam on Thu May 24, 2012 4:20 pm, edited 1 time in total.
Reason: Manual Signature in the Quote Removed

Quickheads
Joomla! Apprentice
Joomla! Apprentice
Posts: 10
Joined: Wed Jul 22, 2009 8:58 pm
Location: Kingston, PA - USA
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Quickheads » Sun Feb 12, 2012 1:30 pm

Thanks to Sova and Carsten I got it working just fine. You can check out the results here:

http://www.quickheads.com/member/map.html

If you are not logged-in, the map centers on the United States. If you are logged-in and you have an icon, the map will center and zoom on your own icon. If you are a member of the Quickie Builders Association, you can see the contact info for everyone on the map when you click their icon.

I even used it to generate different versions of the underlying XML file so that you couldn't cheat and find the contact info without being a member!

Works like a champ! I love that "if (in_array)" statement. VERY Handy!

Thanks all!

Warm regards,
Dan Yager
Manual Signature Removed
Last edited by imanickam on Thu May 24, 2012 4:07 pm, edited 1 time in total.
Reason: Manual Signature Removed
It is not the critic who counts ... The credit belongs to the man who is actually in the arena ... so that his place shall never be with those cold and timid souls who neither know victory nor defeat. –Theodore Roosevelt

Mysmasken1
Joomla! Apprentice
Joomla! Apprentice
Posts: 16
Joined: Sat May 05, 2012 11:30 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Mysmasken1 » Thu May 10, 2012 2:00 am

Thanks! It took me a while to puzzle together the code I needed (as I'm a php noob), but if it can help anyone else I will post it:

<?
jimport( 'joomla.user.helper' );
$groups = JUserHelper::getUserGroups(2);
//only visible for the user group of your choice (= group 2)
if(in_array(2, $groups)){?>
Hi!
<? }
?>

And yes, "Hi!" would be where you put whatever content you want.

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Sun Jul 22, 2012 5:54 pm

I don't know if anyone might find this useful, but I wrote a function that returns a 'true' value if a given username is a member of a given group (or any of an array of groups, or a member of "always privileged" groups). I use this to restrict and change behavior of pages which display or change sensitive data on my site. Note that you need to provide your own database access parameters where specified.

Code: Select all

<?php

/*
 * Function isAdmin($userid, $group) returns true if logged-in user is a member of string or array $group
 *      Group names are case-insensitive. The array $privGroups contains the groups who will always be
 *      returned as admins
 * 
 * Temporary (one hopes) fix for a deficiency in Joomla
 * 
 */

//  Return true if $userid is a member of any of the $groups array, or is in $privGroups

function isAdmin($userid, $group){
    
    $privGroups = array('Administrator', 'Super Users'); // Always return true for these
    
    if(is_array($group))$mygroup = $group;
    else $mygroup[0]=$group;
    $j=0;
    $n=count($mygroup);
    for($i=count($mygroup); $i<($n+count($privGroups)); $i++) {
        $mygroup[$i] = $privGroups[$j];    //  Add "always" admins to argument admins
        $j++;
    }
    
//  DB access credentials: $db, $dbhost, $login, and $pw need to be defined here

    $link = mysql_connect($dbhost, $login, $pw)
        or die("Could not connect : " . mysql_error());
    mysql_select_db($db) or die("Could not select database");

// extract all groups user's a member of
    $SQL = "Select q.title FROM (j16_user_usergroup_map as p) 
        LEFT JOIN (j16_usergroups as q)
        on p.group_id=q.id 
        WHERE p.user_id=$userid;";
    $res=mysql_query($SQL) or die('<p>Groups select query failed<br />' . mysql_error()  . "<br />$SQL</p>");
    if (mysql_num_rows($res) == 0) {    //  No groups? Then user clearly isn't a mamber of "$group"
        if($termlink) mysql_close($link);
        return false;
    }
    while ($line = mysql_fetch_array($res, MYSQL_ASSOC)) {
        extract($line);
        $userGroups[]=$title;
    }
    mysql_close($link);   //  Close link
    for($i=0; $i<count($userGroups); $i++){
        for($j=0; $j<count($mygroup); $j++) {
            if(strtolower($userGroups[$i])==strtolower($mygroup[$j])) return true;
        }
    }
    return false;
}

?>

User avatar
carsten888
Joomla! Ace
Joomla! Ace
Posts: 1224
Joined: Sat Feb 11, 2006 8:32 am
Contact:

Re: How to get a users usergroup?$user->get('usertype')depri

Post by carsten888 » Mon Jul 23, 2012 6:36 am

that can be shorter.

Code: Select all

function check_group($group, $inherited){
$user =& JFactory::getUser();
$user_id = $user->get('id');
if($inherited){
//include inherited groups
jimport( 'joomla.access.access' );
$groups = JAccess::getGroupsByUser($user_id);
}else{
//exclude inherited groups
$user =& JFactory::getUser($user_id);
$groups = isset($user->groups) ? $user->groups : array();
}
$return = 0;
if(in_array($group, $groups)){
$return = true;
}
return $return;
}
http://www.pages-and-items.com my extensions:
User-Private-Page, Redirect-on-Login, Admin-Help-Pages, Dynamic-Menu-Links, Admin-Menu-Manager, plugin load module in article, plugin pure css tooltip and more...

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Tue Jul 24, 2012 12:33 am

Thanks to carsten888 for the post. If brevity is a virtue, here's an even shorter version:

Code: Select all

function check_group($group, $inherited){
	$user =& JFactory::getUser();
	$user_id = $user->get('id');
	if($inherited){
		//include inherited groups
		jimport( 'joomla.access.access' );
		$groups = JAccess::getGroupsByUser($user_id);
	}
	else {
		//exclude inherited groups
		$user =& JFactory::getUser($user_id);
		$groups = isset($user->groups) ? $user->groups : array();
	}
	return (in_array($group, $groups))?true:0;
}
This routine from carsten888 differs from my routine posted earlier in that this one requires a group number (the 'id' field in the j16_usergroups table) to be provided, while mine wants a group name. Also, mine will check to see if the user is in ANY of the groups in the input array, or is in the single group, if provided as a string, not an array. For clarity of meaning, I would use the group name rather than an ID field. Checking for any of a number of group memberships can be useful if different groups have some overlapping responsibilities but are not otherwise related, and we wish to check to see if the task at hand is among the responsibilities shared among groups.

It's a matter of style and preferences, I suppose, and I certainly would prefer to use a less arcane method of answering the simple question, "Is this user a member of the group(s) allowed to see the page being loaded?" When I was looking for a built-in way of addressing this question last Autumn, nothing close to carsten888's concise and very applicable code existed, nor was there any documentation that I could find about how to answer the question within the Joomla framework. So I rolled my own.

I did look at the website linked in carsten888's post, and find there a Joomla extension that may do the trick exactly, so will explore this option further. Anyway, thanks for the post and the function.

gtrennert
Joomla! Intern
Joomla! Intern
Posts: 61
Joined: Sun Mar 27, 2011 10:52 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by gtrennert » Mon Jun 23, 2014 9:22 pm

Hello,

Interesting function but Please could someone tell me where to put the function and how to call it ?

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Thu Jun 26, 2014 9:47 pm

I use my routine in the initialization of any PHP page that changes its behavior based on whether the user is privileged or not. The return from isAdmin(...) is saved and used whenever a page's behavior or appearance is altered based on privilege level. It could be invoked near the top of a template's index.php file, but in my site, it's used only within the many specialized PHP codes that implement functions like editing database files, hiding or revealing menu options, etc.

gtrennert
Joomla! Intern
Joomla! Intern
Posts: 61
Joined: Sun Mar 27, 2011 10:52 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by gtrennert » Fri Jun 27, 2014 7:57 pm

Hello - Thanks for your reply - I need to test privilege level only in one only page - its a Articles » Gallery View - I would like to make the changes in gallery_item.php (in html folder of the template)

Declaring the function in gallery_item.php does not work - the site render seems to stop at a moment
Then I declared the function in a first time in template index - OK
But when I try to call the function in gallery_item.php same problem as mentionned above - here's the code I inserted :

Code: Select all

<?php $varGroup = check_group('Registered', FALSE); ?>
Could you please help me to find the right way to call this function
And I would prefer to put the function not in the index file because as I said this should be availabvle only for this gallery page.

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Fri Jun 27, 2014 10:09 pm

It's been a while but: If you look at carsten888's code and my followup, it seems the $group argument to the function is the id number of the group you're trying to check against, not its name.

However, if you're just trying to see if the Joomla user is registered or not, this code should work:

Code: Select all

$user = & JFactory::getUser();
//  See if we have a logged-in user
$notLoggedIn = ($user->guest) ? true : false;     //  Set variable indicating guest status

andrewrv
Joomla! Intern
Joomla! Intern
Posts: 56
Joined: Wed Apr 15, 2009 10:26 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by andrewrv » Thu Nov 13, 2014 11:25 am

jimbrooking wrote:It's been a while but: If you look at carsten888's code and my followup, it seems the $group argument to the function is the id number of the group you're trying to check against, not its name.

However, if you're just trying to see if the Joomla user is registered or not, this code should work:

Code: Select all

$user = & JFactory::getUser();
//  See if we have a logged-in user
$notLoggedIn = ($user->guest) ? true : false;     //  Set variable indicating guest status
Thanks, this is helpful, how do I get the group of the current user?
For example if the current user is a member of group id 10 display content, if not display a message.

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Thu Nov 13, 2014 3:10 pm

In Joomla 2.5: Look at the database table JOS_user_usergroup_map - two fields: user_id and group_id. Run a query like

Code: Select all

SELECT * FROM JOS_user_usergroup_map WHERE user_id='current logged-in-user-id' AND group_id='10';
then

Code: Select all

if (mysqli_num_rows($result) > 0 )    //  found current user in group 10
    {display content};
else
    {don't do anything};

andrewrv
Joomla! Intern
Joomla! Intern
Posts: 56
Joined: Wed Apr 15, 2009 10:26 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by andrewrv » Thu Nov 13, 2014 4:11 pm

jimbrooking wrote:In Joomla 2.5: Look at the database table JOS_user_usergroup_map - two fields: user_id and group_id. Run a query like

Code: Select all

SELECT * FROM JOS_user_usergroup_map WHERE user_id='current logged-in-user-id' AND group_id='10';
then

Code: Select all

if (mysqli_num_rows($result) > 0 )    //  found current user in group 10
    {display content};
else
    {don't do anything};
Thanks for the reply, I'm playing around with this now, this site is 3.3.6, maybe I posted in the wrong forum, but this was the only thread I could find regarding this.

User avatar
jimbrooking
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 104
Joined: Thu Mar 17, 2011 12:38 am

Re: How to get a users usergroup?$user->get('usertype')depri

Post by jimbrooking » Thu Nov 13, 2014 4:16 pm

The JOS_user_usergroup_map table in J3 looks identical in structure to that in J2.5 so it out to work there as well.

sovainfo
Joomla! Exemplar
Joomla! Exemplar
Posts: 8808
Joined: Sat Oct 01, 2011 7:06 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by sovainfo » Thu Nov 13, 2014 4:37 pm

Advice against using mysql calls directly as suggested by @jimbrooking. Suggest to use the class methods suggested by others in earlier posts in this thread.

Don't understand why you would ask the question again as the answer are provided in earlier posts!
Issue with migrating? Include logs/joomla_update.php in your report!
Blank screen? Verify pagesource for HTML code (javascript error)
Installation failing on populating database? Install with set_time_limit(0)
Document your customizations!

User avatar
Per Yngve Berg
Joomla! Master
Joomla! Master
Posts: 30813
Joined: Mon Oct 27, 2008 9:27 pm
Location: Romerike, Norway

Re: How to get a users usergroup?$user->get('usertype')depri

Post by Per Yngve Berg » Thu Nov 13, 2014 5:05 pm

Use the JUser class. JUser::authorize() checks if the user have permission to an object.

http://api.joomla.org/cms-3/classes/JUs ... _authorise

andrewrv
Joomla! Intern
Joomla! Intern
Posts: 56
Joined: Wed Apr 15, 2009 10:26 pm

Re: How to get a users usergroup?$user->get('usertype')depri

Post by andrewrv » Thu Nov 13, 2014 5:16 pm

Thanks, I have it working using the following alone

Code: Select all

<?php if(in_array(10, $User->groups)):?>
Regards,
Andrew


Locked

Return to “Joomla! 2.5 Coding”