I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.
Related
Im trying to find a session by PART of its ID in laravel.
I only have the first part of the id, and I need to find if the session has a key/value associated with it.
I have tried various forms of the below code. Its fairly simple but not sure if possible in laravel.
Note
Im not sure if this helps or not, but the laravel system is using file based sessions, not DB based sessions.
$value = 'do i have this value';
// Session::all()->whereLike('id','aVhN8u' . '%')->get();
foreach( Session::all()->where('id')->startsWith('aVhN8u') as $session)
{
if($session->has('key', $value)
{
// Do something interesting
}
}
Something like this should work.
use Illuminate\Support\Str;
$value = 'my cool value';
$prefix = 'aVhN8u';
$stored = session()->all();
$filtered = collect($stored)->filter(function ($session, $key) use ($prefix, $value) {
return Str::startsWith($key, $prefix) && $session == $value;
})->all();
I use function onUserAfterSave and $isnew, but I can't get phone and address of user registered in Joomla 3.X. I only can get name, username, email, but no data from profile.
To access the user profile data you need to use JUserHelper class
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$userProfile = JUserHelper::getProfile( $user->id ); //Get userprofile data
//You can get all the user input of profile data. If you want to get country of user use
echo "Country :" . $userProfile->profile['country'];
Amit Ray,
I use in my plugin:
public function onUserAfterSave($user, $isnew, $success, $msg)
{
//die(print_r($user));
if ($isnew){
.............
$pluginParams = new JRegistry($plugin->params);
$name = $user['name'];
$name_usuario = $user['username'];
$email_user = $user['email'];
$id_usuario = $user['id'];
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$userProfile = JUserHelper::getProfile( $id_usuario );
//You can get all the user input of profile data. If you want to get country of user use
$user_phone = $userProfile->profile['phone'];
$user_address = $userProfile->profile['address1'];
But $user_phone and $user_address no have data... whats is error? Thanks
$credit = $this->db->select('credits');
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$data1 = array('credits'=>$credit + 10);
$this->db->update('users',$data1);
I need to update a column in a database..
When a user signs up, he will give a referral code.
I need to check whether that code exists in the database and need to update the referral code for the user by giving him with 10 more credits.
The above code shows error, Can anyone help me me figure why?
Try this
$credit = $this->db->select('credits');
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$data = $this->db->get();
if($data->num_rows()>0)
{
$res = $data->row_object();
$this->db->where('refferal_code',$refferal_code);
$update = $this->db->update('users',array('credits'=>$res->credits + 10));
}
OR
Simplest one as #Shaiful Islam mentioned in comment
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$this->db->set('credits', 'credits+10', FALSE);
$this->db->update('users');
I'm starting with Codeigniter and i have a question. How (if possible) to create authorization api to other sites (no facebook, twitter etc.).
I have three sites - CI system, IP.Board and WordPress, and my point is a integrating all those systems in one auth api.
I heared about Oauth and OpenId, but I don't know how this things has postponement to CI. Is complicated?
Hello It can be possible
I can suggestion you can use temporary table store that table logged user id and current date& time and also ip address ,and store that one in to Sharing Cookies Across Multiple Domains/send hidden stored id to your multiple site.based on id and ip and time you can implement logic
note: logout and session time out times you can delete the record form table
I have written small example plz check it once . it my be helpful you
Session will most likely not to work. I thought of using JSON but I failed to figure out how to make the Javascript to be dynamic as I always prefer to use jQuery (if you have an idea, feel free to share). In the end, I decided to use PHP along with MySQL and cURL.
We will first start by creating a table to handle the login session:
CREATE TABLE IF NOT EXISTS `sso_login` (`user_id` int(11) NOT NULL)
Purpose of the table is to store logged in users and remove then upon signing out.
Next is the PHP script which will insert new user id upon signing in (file name: register.php):
<?php
/**
*
* #
*/
$userId = $_GET['id'];
$sql = sprintf("INSERT INTO sso_login VALUES ('%s')", $userId);
mysql_query($sql);
?>
Simple, isn’t it? All it does is inserting the user id into the table.
Next is the file which delete the user id when user is signing out (file name: drop.php):
<?php
/**
*
*
*/
$userId = $_GET['id'];
$sql = sprintf("DELETE FROM sso_login WHERE user_id = '%s'", $userId);
mysql_query($sql);
?>
I believe the script is pretty much self-explainatory.
Next is the file which checks whether user is already logged in or vice versa (file name: check.php):
<?php
/**
*
*
*/
$userId = $_GET['userId'];
$sql = sprintf("SELECT COUNT(*) FROM sso_login WHERE user_id = '%s'", $userId);
$query = mysql_query($sql);
if (mysql_result($query, 0, 0) > 0)
{
echo 'User '.$userId.' has logged in';
}
else
{
echo 'User '.$userId.' is not logged in.';
}
?>
This script will check whether the user id being passed is available in the table or not. If not it means that the user have not logged in.
These three scripts will be store on the other party’s server. Next are scripts which will be store on BC’s server where the login and logout process being done. All these processes are using cURL.
First is the script which will update the other site when user is logged in (file name: login.php):
<
?php
/**
*
*
*/
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if (($username == "bcoffee") && ($password == "demo"))
{
$userId = 10;
$target_site = sprintf("http://the-other-site.com/register.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: index.php');
}
}
?>
You might notice that the username and password are hard coded, this was for P.O.C purpose, so it does not matter. Back to the tutorial.
As you can see, it will reach register.php with the user’s id. Refer back to content of register.php which will then insert the user id into the table. This way, the other server will know that user is already logged in.
Next is the script which will notify the other server when the user is signing out (file name: logout.php):
<?php
/**
*
*
*/
$userId = 10;
$target_site = sprintf("http://the-other-site.com/drop.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: login.html');
?>
Similar to login.php but this time, it will remove the user id when user is signing out. Hence when the system checks (using check.php) and found that the user id is not available, it will know that the user is not currently logged in.
I want to add an external script which gets a sku via GET check the ID and then redirect to the cart if available otherwise it sets en error and also redirecting to the cart.
The script is called from a product page:
http://myhost/scripts/addto.php?sku=12345
Here is the colmplete code
<?php
include_once '../../../../../app/Mage.php';
Mage::app();
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
$sku = $_GET['sku'];
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if ($id == '') {
$id = $sku;
Mage::getSingleton('checkout/session')->addError("Product not found!");
}
Works fine, but after logout and relogin the error message is missing. I found out that's because of a cookie which is set. After deleting that cookie the error message is working again after relogin.
What does not work?
You logout and login and then the script stop working? So the session is not found? The product ist not found? The product is not loaded? The user is not forwarded? :-)
Sure it does not. The Message is a Notice. If it is shown once, it is deleted.
What behaviour do you want?
use Mage::getSingleton('core/session')->addError("Product not found!");, maybe checkout/session is user specific...
cheers