How to manually create a user in Moodle? - php

I am trying to create an authentication plugin, but I am having problems when the user does not exist in the moodle database. Therefore I am trying to find a way to manually create a user.
I tried:
$user = new StdClass();
$user->username = $ucUser;
$user->auth = 'ucauth';
$user->firstname = "First";
$user->lastname = "Last";
$user->id = $DB->insert_record('user', $user);
But it didn't work... I got an insert error. What else do I need in the $user object?

User object should have the following values:
$user = new StdClass();
$user->auth = 'manual';
$user->confirmed = 1;
$user->mnethostid = 1;
$user->email = "email";
$user->username = "username";
$user->password = md5('password');
$user->lastname = "lastname";
$user->firstname = "firstname";
$user->id = $DB->insert_record('user', $user);
Please try this.

Well, I recommend you to use authenticate_user_login($username, null) this is going to give you an empty user, wich you can complete later on in the proccess. Then you can use complete_user_login($user); and if you want to send the user to the edit page something like
if (user_not_fully_set_up($USER)) {
$urltogo = $CFG->wwwroot.'/user/edit.php';
}else{
$urltogo = $CFG->wwwroot.'/';
}
redirect($urltogo);
I don't know exactly what are you trying to achieve. But I've made a plugin to connect with an external web service and it took me a while to figure out how to do it properly. I'm able to help you with anything you need.

There are some values that needs to be setted when creating a user manually. I was facing the same situation and ended up with this solution:
global $DB;
$user = new StdClass();
$user->email = strtolower('someemail'); //MOODLE requires lowercase
$user->username = strtolower('someusername');//MOODLE requires lowercase
$user->password = hash_internal_user_password('somepassword');
$user->lastname = 'somelastname';
$user->firstname = 'somename';
// These values are required.
// Default values are stored in moodle config files but... this is easier.
$user->auth = 'manual';
$user->confirmed = 1;
$user->mnethostid = 1;
$user->country = 'ES'; //Or another country
$user->lang = 'es'; //Or another country
$user->timecreated = time();
$user->maildisplay= 0;
$user->id = $DB->insert_record('user', $user); // returns new userid
If you prefer, you can retrieve the whole user's data:
$lastid = $DB->insert_record('user', $user);
$user2 = get_complete_user_data('id', $lastid);

Related

Return Array values from PHP Function

I'm trying to get the users from PHP form. PHP Function has to create new users (username, first name & email) with registeruser($user),that is to insert to database.
I was able to insert only one row to database. Could you guide me to insert more than one user
and return all the users.
The new users come from $array['newuser'].
function newusers() {
foreach($array['newuser'] as $row) {
$user = new stdClass();
$user->username = $row['username'];
$user->firstname = $row['firstname'];
$user->email = $row['email'];
$userreg = registeruser($user);
return array($userreg)
}
}
i think you are searching for this answer;here whenever new user comes it will store to an array $userreg[] =registeruser($user); and return that array after the loop
function newusers($array_of_new_users) {
$userreg=array();
foreach($array_of_new_users as $row)
{
$user = new stdClass();
$user->username = $row['username'];
$user->firstname = $row['firstname'];
$user->email = $row['email'];
$userreg[] = registeruser($user);
}
return $userreg;
}

Undefined Variable : user

I am trying to send message with activation code. I have an registration form. The forms sends data to the controller and the controller saves the data into database . But somehow it fails to grab the $user variable after saving data into profiles table.
Here is my controller:
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
});//inside a transaction
if($user){
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !'); }
return Redirect::to('/message');
I think my code is absolutely right. Can you please explain why it fails to define the $user variable ?
This is because of the scope of the $user variable. Define $user above DB::transaction(function() {});
Though defining
$user = false;
above
DB::transaction
might do the trick for now but I won't recommend it as a good practice the best solution would be to use the
Mail::send()
inside the Database transaction block and you might can improve your code as well and the above code should be
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code,$user){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
if( !$profile || !$user )
{
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !');
} else {
// Else commit the queries
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
}
});//inside a transaction
That is because $user is inside that DB transaction block; it goes out of scope with the closing brace. Define it above the transaction
Solution
Copy & Replace above.
$user = false;
DB::transaction(function() use($first_name,$last_name,$email,
$password,$address,$phone,$country_id,$state,$city,
$zip_code,$skype,$birth_date,$code,$user){
//add info to user table
$user = new User;
$user->username = $email;
$user->password = $password;
$user->email = $email;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->active = 0;
$user->code = $code;
$user->save();
//Get the user ID ceated just now
$new_users = $new_user->id;
// add information to Profile table
$profile = new Profile;
$profile->user_id = $new_users;
$profile->phone = $phone;
$profile->address = $address;
$profile->country_id = 1;
$profile->state = $state;
$profile->skype = $skype;
$profile->city = $city;
$profile->zip_code = $zip_code;
$profile->birth_date = $birth_date;
$profile->timezone_id = 1;
$profile->save();
});//inside a transaction
if($user){
Mail::send('emails.welcome',
array('link'=> URL::route('account-activate', $code),'user'=>$user->first_name),
function($message) use ($user) {
$message->to($user->email , $user->user)->from('admin#spandango.net')->subject('Active your account !');
}
);
return Redirect::back()
->with('message' , 'Your account is created ! Please check you email to activate your account !'); }
return Redirect::to('/message');

Laravel Eloquent Save Item Error?

When I try saving an item's to my database I get
Method Clients::__toString() must return a string value
Current code
$name = Input::get('email');
$client = Input::get('client');
$website = Input::get('website');
$userassign = Input::get('userassign');
$client = new Clients();
$client->name = $name;
$client->client = $client;
$client->website = $website;
$client->parent = $userassign;
$client->save();
Any ideas?
You're redefining $client.
$name = Input::get('email');
$clientInput = Input::get('client');
$website = Input::get('website');
$userassign = Input::get('userassign');
$client = new Clients();
$client->name = $name;
$client->client = $clientInput; //Here was your problem
$client->website = $website;
$client->parent = $userassign;
$client->save();

Redbeanphp one to one relation

In my project have 2 entites in my db namely User and Account. One User has one account.User table has account_id field as foreign key to reference Account entity.
I am generating automaticly a new account for user. Everything gets created as I expect.But how can I reference an account for a parcticular user. Here is my registration script
public function register ($data = null)
{
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$user->account = $account;
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}
}
Would be grateful for any help
You don't need to change anything - your way is correct. The line
$user->account = $account;
is the right way to do it - assuming you are running in fluid mode, your schema will be updated automatically to create the foreign key relationship for you this way.
To access the account, you just need to use $user->account.
echo $user->account;
will show you all the properties of the account bean.
Instead of giving account bean as foreign reference to user bean, just add account_id field as foreign key to user table.
public function register ($data = null){
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$account_id = R::store($account);
$user->account_id = $account_id; // this is the line you have to change
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}}
And when loading a bean you can directly access account instance from user bean
(constraint being if there is a one-to-one or one-to-many maaping)
$account = $user->account;

update mysql and add value to existing value

I am trying to edit this code so that instead of just inserting the info - it checks to see if the file already exists in the database, if it does it inserts as it does now. If it does exist... it should just update the info, adding the "value" amount to the value amount already in there instead of replacing it. But this is very new to me and I am lost so any help with really be appreciated!
<?php
define('JPATH_BASE',$_SERVER['DOCUMENT_ROOT']);
require_once($_SERVER['DOCUMENT_ROOT']."/b2/configuration.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/factory.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/base/object.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/database/database.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/database/database/mysql.php");
$config = new JConfig;
$options = array();
$options['host'] = $config->host;
$options['user'] = $config->user;
$options['password'] = $config->password;
$options['database'] = $config->db;
$options['prefix'] = $config->dbprefix;
$options['select'] = true;
$db = new JDatabaseMySQL($options);
//$user = JFactory::getUser();
$userId = 0;
//($user->id > 0) ? $user->id : 0;
$numbervote = $_REQUEST['w'];
$folder = $_REQUEST['w2'];
$name = $_REQUEST['w1'];
$date = date('Y-m-d H-i-s');
$sql = "INSERT INTO jos_image_ratetting (id,userid,datecreated,value,filename,folder,md5name) VALUES(NULL,'".$userId."','".$date."','".$numbervote."','".$name."','".$folder."',MD5('".$name."'))";
$db->setQuery($sql);
if($db->query()){
$msg = "Thanks for rate!";
}else{
$msg = mysql_error();
}
echo $msg;
//echo 'Hello';
?>
Take a look at the ON DUPLICATE KEY UPDATE syntax for MySQL

Categories