joomla - Storing user parameters in custom component issue - database

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.

Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

Related

Getting "Webpage" Redirected You Too Many Times Error. Can't Seem To Figure Out Why

I'm having issues with this error message popping upon user login. From what I've gathered, I think there is an issue with the following code since this is the page on which it stops and gives me this error. This code is at the beginning of the page they see once logged in.
It first verifies the user is logged in and that the correct sessions are set. Then it pulls the additional info from the database and verifies that the user has the correct level of permission. If so, it allows them to access the page. If not it redirects them to the login page.
<?php
require_once 'account-management/reset-password-script.php';
$email = $_SESSION['email'];
$password = $_SESSION['password'];
if($email != false && $password != false){
$sql = "SELECT * FROM administration WHERE email = '$email'";
$run_Sql = mysqli_query($conn, $sql);
if($run_Sql){
$fetch_info = mysqli_fetch_assoc($run_Sql);
$name = $fetch_info['name'];
$rank = $fetch_info['rank'];
$job_title = $fetch_info['job_title'];
$user_id = $fetch_info['id'];
if($rank == "Admin" || $rank == "Moderator" || $rank == "Editor"){
header('Location: stats.php');
}
}
}else{
header('Location: login.php');
}
?>
Here is the code that logs the user on.
It verifies the email, password, and permission settings, and then brings them to the stats page if the info checks out.
session_start();
require 'db_connect.php';
$email = "";
$errors = array();
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$check_email = "SELECT * FROM administration WHERE email = '$email'";
$res = mysqli_query($conn, $check_email);
if(mysqli_num_rows($res) > 0){
$fetch = mysqli_fetch_assoc($res);
$fetch_pass = $fetch['password'];
if(password_verify($password, $fetch_pass)){
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$rank = $fetch['rank'];
if($rank == "Admin" || $rank == "Moderator" || $rank == "Editor"){
header('location: stats.php');
}else{
$info = "It's looks like you don't have this permission.";
}
}else{
$errors['email'] = "Incorrect email or password!";
}
}else{
$errors['email'] = "<div id='alert-messages-normal'>It looks like you're not yet a member! Click on the sidebar link to signup.<br/></div>";
}
}
Again, the issue is that once it passes the login face, it goes to the stats page which is locked to non-users. It then loads for a few seconds and then just displays the error that it redirected too many times. The goal is for it to just stay on the users-only page.
I've tried rewriting the code a few times and cleared the browser cache several times. I can't seem to find the issue. I feel like the error is definitely within the code to verify the user is logged in before displaying the content. Something is making it loop between the login page and the user-only page, and my eyes can't seem to figure it out.

CodeIgniter - displaying view based on variable from database

I've been learning codeigniter recently and trying to push an application out. im running into problems with the if else statements displaying views. i am trying to pull in_party from the databaseci_admin_info and display views depending if its set to 1 or 0. its bypassing any condition and just displaying the first view set.
Model
function get_in_par(){
$this->db->select('in_party');
$this->db->from('ci_admin_info');
$query = $this->db->get();
$ret = $query->row();
return $ret->in_party;
}
Controller
public function index(){
$data['title'] = 'Party';
$data['party'] = $this->party_model->get_party();
$data['prov'] = $this->party_model->get_prov_name();
$data['info'] = $this->party_model->get_all();
$data['res'] = $this->party_model->get_party_res();
$data['rank'] = $this->party_model->get_pa_rank();
$this->load->view('admin/includes/_header', $data);
$inpar = $this->party_model->get_in_par();
if(isset($inpar['in_party'])==0){
$this->load->view('admin/party/join');
} else {
$this->load->view('admin/party/index');
}
$this->load->view('admin/includes/_footer');
}
I've tried rearranging it into the parent construct as well and it just bypassed it completely. just trying to make it load the join view if in_party = 0 . i've tried without isset bypasses it as well. i've tried switch but don't think it registered that as well. i think i'm missing something in my model
$query = $this->db->select('*')
->from('ci_admin_info')
->get();
$result = $query->result_array();
return $result[0];
$inpar = $this->party_model->get_in_par();
if(!isset($inpar['in_party']) || $inpar['in_party']=="0"){....

Get user uid from name (Drupal 7)

I can't figure out how to get an user's UID knowing the user's name.
The user's name will be entered by a variable. I just need to pick up the UID in another variable.
I've found this code, which would be perfect, but it doesn't work on Drupal 7:
$account = user_load(array('name' => check_plain($name)));
Can anybody help me?
Thank you very much!!
try
$user = user_load_by_name($username);
$user_id = $user->uid;
or you can use
function get_uid($username)
{
// Function that returns the uid based on the username given
$user = db_fetch_object(db_query("SELECT uid FROM users WHERE name=':username'", array(":username" => $username)));
return $user->uid;
}
One way to look up the user is to use the entity_load('user');. Here is an example how to do it:
// Add the user you want to find here
$user_to_lookup = 'test';
$users = entity_load('user');
$found_user = null;
foreach ($users as $user) {
if ($user->name == $user_to_lookup ) {
$found_user = $user;
}
}
The user object is stored in $found_user now. Note that its an stdClass so you need to use the arrow notation to access the properties. For example to access mail write $found_user->mail.

CakePHP save field to associated table

I have my 'PatientCase' model with a hasOne relationship to my 'PatientCaseOrder' model. (This table simply stored the patientCase id along with an integer position)
I am using an ajax function to update the position fields in 'PatientCaseOrder' using the function below in my PatientCase controller
public function update_position(){
Configure::write('debug', 0);
$this->autoRender = false;
$this->loadModel('PatientCaseOrder');
$list = $_POST['list'];
$errs = false;
if($list){
foreach($list as $position){
$id = $position[0];
$pos = $position[1];
$this->PatientCase->id = $id;
if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
}
}
echo json_encode ($errs);
}
I am passing to it an array containing the PatientCaseId and position.
The code produces a 500 server error, where am i going wrong, or am i taking the wrong approach to this?
NOTE: I previously had the position field in the PatientCase model, and this line of code worked with the above segment of code
$this->PatientCase->saveField('position', $pos)
You need to change your controller function for better debugging:
change to Configure::write('debug', 2);
add $this->layout = 'ajax';
and change : if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
to:
pr($this->PatientCase->PatientCaseOrder->saveField('position', $pos)); die;
and then in your ajax function log the callback
console.log(returned_data);
and check for errors.

SqlCacheDependecy command notification not working

I been trying to get sqlcachedependecy working, but it doesn't appear to work
I got the proper settings in my web.config and also global.asa, however when I run this query and the changes are made to the database from either with in or outside the web site the cached objects are not updated please someone help? I know its not because this query is querying a view, because I tested this using straight SqlDependecy and the notification works fine.
public IQueryable<VictoryList> GetVictoryList()
{
string cacheKey = HttpContext.Current.User.Identity.Name + "victoryCacheKey";
IQueryable<VictoryList> cachednews = (IQueryable<VictoryList>)HttpContext.Current.Cache.Get(cacheKey);
if (cachednews == null)
{
var results = from v in _datacontext.ViewVictoryLists
orderby _datacontext.GetNewId()
select new VictoryList
{
MemberID = v.MemberID,
Username = v.Aspnetusername,
Location = v.Location,
DaimokuGoal = v.DaimokuGoal,
PreviewImageID = v.PreviewImageID,
TotalDaimoku = v.TotalDaimoku,
TotalDeterminations = v.TotalDeterminations,
DeterminationID = v.DeterminationID,
DeterminationName = v.DeterminationName
};
results = results.ToList().AsQueryable();
SqlCacheDependencyAdmin.EnableNotifications(_datacontext.Connection.ConnectionString);
SqlCacheDependency dependency =
new SqlCacheDependency(_datacontext.GetCommand(results) as SqlCommand);
HttpContext.Current.Cache.Insert(cacheKey, results, dependency);
return results;
}
return cachednews;
}
According to the stated Limitations for creating a query for notification, listed at msdn...
The statement must not reference a view.

Resources