IF condition to show specific data to the logged in user - php

I need to separate the view of a specific user from the system to a specific client. For example; The logged in user (user1 - ID_1) can only view the client data (client2 - ID_2). Is it possible to do this in an IF condition as in the example below?
(Id_users comes from the users table, and id_clients, from the clients table)
public function view() {
if ($this-> 'id_users' = '1') {
data['view'] = 'idclients' = '2';
}
$this->data['custom_error'] = '';
$this->load->model('mapos_model');
$this->data['result'] = $this->os_model->getById($this->uri->segment(3));
$this->data['products'] = $this->os_model->getProducts($this->uri->segment(3));
$this->data['services'] = $this->os_model->getServices($this->uri->segment(3));
$this->data['emitent'] = $this->mapos_model->getEmitent();
$this->data['view'] = 'os/viewOs';
$this->load->view('theme/top', $this->data);
}

you can use session .any place to your project
if($this->session->userdata('session_name')){
echo "Your specific data";
}
else{
echo "Others Data";
}

Related

Laravel mysql data input.. Check if Users follow each other

public function follow(Request $request){
$response = array();
$response['code'] = 400;
$following_user_id = $request->input('following');
$follower_user_id = $request->input('follower');
$element = $request->input('element');
$size = $request->input('size');
$following = User::find($following_user_id);
$follower = User::find($follower_user_id);
if ($following && $follower && ($following_user_id == Auth::id() || $follower_user_id == Auth::id())){
$relation = UserFollowing::where('following_user_id', $following_user_id)->where('follower_user_id', $follower_user_id)->get()->first();
if ($relation){
if ($relation->delete()){
$response['code'] = 200;
if ($following->isPrivate()) {
$response['refresh'] = 1;
}
}
}else{
$relation = new UserFollowing();
$relation->following_user_id = $following_user_id;
$relation->follower_user_id = $follower_user_id;
if ($following->isPrivate()){
$relation->allow = 0;
}else{
$relation->allow = 1;
}
if ($relation->save()){
$response['code'] = 200;
$response['refresh'] = 0;
if ($following && $follower){
$relationz = new UserRelationship();
$relationz->main_user_id = $following_user_id;
$relationz->relation_type = 1;
$relationz->related_user_id = $follower_user_id;
$relationz->allow = 1;
$relationz->save();
}
}
}
if ($response['code'] == 200){
$response['button'] = sHelper::followButton($following_user_id, $follower_user_id, $element, $size);
}
}
return Response::json($response);
}
Hey guys, I have this code which creates a follow among two users.
I added a function to be personal friends 'relationz' as well.
Currently when you follow a user, you become 'relationz' automatically..
I would like to create a new 'relationz' only when the follower is also followed by the same person, my question is what change must I make here to either:
a) stop an auto-friend when only one user follows..
b) detect when each person follows each other..
I'm not sure which is the better logic?
I was wrongly thinking the simple "if (follower && following)" was enough, maybe it is just in the wrong place?
Thanks for any help!
How is your relations set up?
since i see a whole lot of code and if the follow function is in you controller, that will be a mess to sort out later when bug fixing.
so you have a many to many relation ship called followers in the user model?
so if user a would follow user b user a would give a follower result of 1
and if user b would have followers than it would be 0 correct?
so what i would do, if both are following each other you should have 2 rows with both users in the pivot table.
so I would create a new relationship relationz with a wherehas query in it
public function relationz {
return $this->belongsToMany(Follower::class)->whereHas('followers' , function($query) {
$query->where('followed_id', auth()->user_id);
})
}
Something like that.

Processing multi-step form in Laravel

I am quite new to laravel I have to insert many form fields in database so I divided the fields into multiple sections what I want to achieve is to store data of each section when user clicks next button and step changes and when user clicks previous button and makes some changes the database should be updated and if user leaves the form incomplete then when he logins next time form fill should fill up from the step he left in, till now i have successfully achieved to change steps and in first step 1 inserted the data into database and for other step i updated the database but I am having trouble if user comes to first step and again changes the forms fields how to update again first step data i am using ajax to send data and steps number
My Controller
function saveJobPostFirstStage(Request $request)
{
$currentEmployer = Auth::guard('employer')->user();
//$data['currentEmployer'] = $currentEmployer;
$employer_id = $currentEmployer->id;
$random = $this->generateRandomString();
$jobOne = new Job();
//Session::pull('insertedId');
if ($request->ajax()) {
try {
$stepPost = $request->all();
$step = $stepPost['stepNo'];
$insertedId = $stepPost['insertedId'];
switch ($step) {
case '1':
if ($insertedId == 0) {
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->save();
if ($stepOne) {
Session::put('insertedId',$jobOne->id);
//session(['insertedId'=>$jobOne->id]);
$success = ['success' => "Success",
'insertedId' => $jobOne->id];
//return json_encode($success);
}
}
else
{
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->whereId($insertedId)->update(['employer_id'=>$jobOne->employer_id,'job_title'=>$jobOne->job_title,'company_id'=> $jobOne->company_id,'state_id'=>$jobOne->state_id,'country_id'=>$jobOne->country_id,'city_id'=>$jobOne->city_id,'street_address'=>$jobOne->street_address,'job_code'=>$jobOne->job_code = $random]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
}
break;
case '2':
$jobOne->employment_type_id = (int)($stepPost['employmentType']);
$jobOne->job_type_id = (int)($stepPost['jobType']);
$jobOne->job_level_id = (int)($stepPost['jobLevel']);
$jobOne->industry_type_id = (int)($stepPost['industryType']);
$jobOne->job_category_id = (int)($stepPost['jobCategory']);
//$jobOne->salary = $stepPost['jobSalaryRange'];
$jobOne->salary_period_id = (int)$stepPost['salaryPeriod'];
//$jobOne->vacancy_end_date = $stepOne['applicationDeadline'];
$stepOne = $jobOne->whereId($insertedId)->update(['employment_type_id'=> $jobOne->employment_type_id,'job_type_id'=>$jobOne->job_type_id,'job_level_id'=> $jobOne->job_level_id,'industry_type_id'=>$jobOne->industry_type_id,'job_category_id'=>$jobOne->job_category_id,'salary_period_id'=>$jobOne->salary_period_id]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
break;
case '3':
$jobOne->job_description = $stepPost['jobDescription'];
$jobOne->job_specification = $stepPost['jobSpecifications'];
$jobOne->job_responsibilities = $stepPost['jobResponsibilities'];
$stepOne = $jobOne->whereId($insertedId)->update(['job_description'=>$jobOne->job_description,'job_specification'=>$jobOne->job_specification,'job_responsibilities'=>$jobOne->job_responsibilities]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
default:
# code...
break;
}
return json_encode($stepPost);
//$this->alertMessage = 'Your Phone has been added Successfully.';
//$this->alertType = 'success';
} catch (QueryException $e) {
return $e->getMessage();
}
/* return redirect()->route('employer-account-page')
->with([
'alertMessage' => $this->alertMessage,
'alertType' => $this->alertType
]);*/
// $stepPost = Input::all();
}
/*$stepOne = $request->all();
$country_Id = (int)$stepOne['country'];
return json_encode((getType($country_Id)));*/
}
First of, your code is messy.
You should have a single table per form where each form have it's parent id.
The next step to refactor the code would be to create a single controler per form (you don't need it, but you want this)
Each form (a model) should have a method that recalculates the values of itself based on other forms, so that if you change a first form, then you can call the method that recalculates the second form, then call method of second form that recalculates the third form, etc.
This interface could be helpful
interface IForm {
public function getPreviousForm() : ?IForm; // These notations are since PHP7.1
public function recalculate() : void;
public function getNextForm() : ?IForm;
}
A simple code how it should work in practice
$formX->save();
$formX->getNextForm()->recalculate(); // This will call formX->recalculate(); formX+1->getNextForm()->recalculate()
// which will call formX+1->recalculate(); formX+2->getNextForm()->recalculate()
// etc...
// while getNextForm() != null
You may also need this if you would need to insert another form in the middle of the chain.
Hope it helps

Login with User-Agent as token

I'm working on a website project (PHP, Fat-Free and mongodb) and I have a problem with only one user.
When the user does login, I call this function:
function login() {
$user = F3::get('POST.user');
$pass = F3::get('POST.pass');
if($user!=""&&$pass!=""){
$bcrypt = new Bcrypt(12);
$ismail = strrpos($user, "#");
$loginUser = new HT('user');
if($ismail===false){
$loginUser->load(array('nick' => $user));
}else{
$loginUser->load(array('email' => strtolower($user)));
}
if(!$loginUser->dry()){
if($loginUser->isActive == true){
$isValid = $bcrypt->verify($pass, $loginUser->password);
if($isValid){
$final_token = StringHelper::rand_str(30);
$tmp = $loginUser->token;
if(!is_array($tmp))
$tmp = array();
$cli_id = md5($_SERVER['HTTP_USER_AGENT']);
$tmp[$cli_id] = $final_token;
$loginUser->token = $tmp;
$user_id = $loginUser->_id."";
$loginUser->loginDate = new MongoDate();
$loginUser->updateFromId();
$isPremium = $loginUser->isPremium;
F3::set('user_id', $user_id);
if(isset($loginUser->preferences) && isset($loginUser->preferences['langPref'])){
$lang = $loginUser->preferences['langPref'];
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"$lang","schema"=>"$schema","isPremium"=>$isPremium));
}else{
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"en","schema"=>"$schema","isPremium"=>$isPremium));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}else{
echo json_encode(array("status"=>self::NOT_ACTIVE));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}
}
NOTE: dry() function checks if user is null in mongodb.
The user says that in his office computer can't do login, and he gets and "Invalid password" error. But he can login in the website in any other computer.
Sometimes, if he deletes cache or reset his password can access to the website.
I'm saving in the 'User' mongodb collection an array of tokens like this:
{
........ (Other params),
"token" : {
"d222b6a854d35c9c9584e695b623c468" : "nX0CuAraUQMGm5UsUWhUqZzgXZnapN",
"8c27b0d66a7ea6cec5dda9979cc92bd3" : "swdYhSQN5el0x9Pmn2YXZuwckpmuHP",
"28b825f204e7ebd320756bd6294a29c1" : "UFGd18db8W9gq1WDXgx4F9BZRVRY3K"
}
}
This token array contains:
key: MD5 encrypted User-Agent
value: Random string
This keeps session for different devices and browsers.
Everytime the user wants to do something in the web I put in the route the user id and the token (value), and I check if values are correct:
....
$uid = md5($_SERVER['HTTP_USER_AGENT']);
if(isset($user->token[$uid]) && $user->token[$uid]==$token){
....
return true;
}else{
return false;
}
I thought that the problem was with the User-Agent. Any solution?
Thanks!

Codeigniter Transaction inside Control

Since I have several functions executing in the following control as a single transaction I couldn't surround each function as a transaction in the model. So I did it the following way. Please someone let me know if there is any problem. Works fine for now, but have no idea whether it will get any concurrency issues or there is any other way?
if(isset($_POST['btnsave']))
{
$mcodes = $_POST['tblmcode'];
$count = count($mcodes);
//echo $count;
$issue = new Materialissue_model();
$this->db->trans_start(); //Here starts my transaction
$issue->setIssuecode($this->input->post('txtissuecode'));
if($issue->checkNoExistence()) {
$issue->setDate($this->input->post('txtdate'));
$issue->setCustomer($this->input->post('txtcustomer'));
$issue->setFromlocation($this->input->post('txtlocation'));
$issue->setResponsible($this->input->post('txtresponsible'));
$issue->setComments($this->input->post('txtcomments'));
$issue->setTotal($this->input->post('txttotal'));
$issue->setUser($this->session->userdata('username'));
$issue->setStatus($this->input->post('txtstatus'));
for ($i = 0; $i < $count; $i++) {
$issue->setMaterialcode($_POST['tblmcode'][$i]);
$issue->setMaterialname($_POST['tblmname'][$i]);
$issue->setCost($_POST['tblcost'][$i]);
$issue->setQty($_POST['tblqty'][$i]);
$issue->setSubtotal($_POST['tblsubtotal'][$i]);
$issue->saveIssueDetail();
$stock = new Materialstock_model();
$stock->setItemcode($_POST['tblmcode'][$i]);
$stock->setItemlocation($this->input->post('txtlocation'));
$stock->setQty($_POST['tblqty'][$i]);
$stock->setRefno($this->input->post('txtissuecode'));
$stock->setLasttransaction('MATERIAL-ISSUE');
$stock->updateMaterialIssueStock();
$transaction = new Transaction_model();
$transaction->setDescription("MATERIAL-ISSUE");
$transaction->setItemcode($_POST['tblmcode'][$i]);
$transaction->setRecqty("0");
$transaction->setTransqty("0");
$transaction->setIssueqty($_POST['tblqty'][$i]);
$transaction->setDate($this->input->post('txtdate'));
$transaction->setUser($this->session->userdata('username'));
$transaction->saveMaterialTransaction();
}
$result = $issue->saveIssue();
$this->db->trans_complete(); //Here ends my transaction
if ($result) {
$message = new Message_model();
$data['message'] = $message->recordadded;
$data['type'] = "success";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$data["print"] = base_url() . "index.php/Notegenerator_control/showMaterialIssueNote?code=".$issue->getIssuecode();
$this->load->view('messageprint_view', $data);
}
}else{
$message = new Message_model();
$data['message'] = $message->issuecodeexists;
$data['type'] = "error";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$this->load->view('message_view', $data);
}
}
I prefer like using trigger to handle many functions in one controller, this make mycode clean and easy to track. example:
user writes article, this action will call one action in model write_article combine with 1 transaction, but this function run any query :
1.insert post
2.lock count post category
3.lock count user post
4.lock count post by date
example in code
public function write_article($post) {
$this->cms->db->trans_start(TRUE);
$this->cms->db->set('content', $posts->get_content());
$this->cms->db->insert('t_posts');
$this->cms->db->trans_complete();
if($this->cms->db->trans_status() === TRUE){
$this->cms->db->trans_commit();
}else{
$this->cms->db->trans_rollback();
}
}
This reference about trigger
www.sitepoint.com/how-to-create-mysql-triggers

Adding another User ID if that wasn't present in a string

I'm using this function;
function add_profile_visitor($add_uid,$to_uid,$visitors_list)
{
global $db;
$list = trim($visitors_list);
$list_users = explode(",",$list);
if (in_array($add_uid,$list_users))
{
return;
}
else
{
if (strpos($list_users,",") || strlen($list_users) > 0)
{
$newlist = $list_users.",".intval($add_uid);
}
else
{
$newlist = intval($add_uid);
}
$db->query("UPDATE users SET profile_visitor='".$db->escape_string($newlist)."' WHERE uid=".$to_uid);
}
}
I want to add a User ID if its not present already in the field profile_visitor. For your notice, the profile_visitor list is comma separated list. Here are the variable's legend:
$add_uid = The user id that is going to be inserted in profile_visitor if its not present in already.
$to_uid = The User ID where profile_visitor column is present and the $add_uid add in if its not present.
$visitors_list = The comma separated list of profile visitors. Before adding any User ID that list will be empty (obviously)
The issue is: Each time the page loads (where that function is running) the list profile_visitor has the new User ID instead of adding the new User ID to the list.
Please help
Change your function to this:
function add_profile_visitor($add_uid,$to_uid,$visitors_list)
{
global $db;
$list = trim($visitors_list);
$list_users = explode(",",$list);
if (in_array($add_uid,$list_users))
{
return;
}
else
{
if (strpos($list,",") || strlen($list) > 0)
{
$newlist = $list.",".intval($add_uid);
}
else
{
$newlist = intval($add_uid);
}
$db->query("UPDATE users SET profile_visitor='".$db->escape_string($newlist)."' WHERE uid=".$to_uid);
}
}

Categories