wasRecentlyCreated in PHP not detecting newly created campaign - php

I'm currently working on a form to create a campaign and would like for the form to detect whether the user has already submitted the form and to display an alternative message.
I have the following if statement set up to determine what message to display to the user:
if ($campaign->wasRecentlyCreated) {
$response['message'] = 'Campaign edited successfully';
} else {
$response['message'] = 'Campaign created successfully';
}
I've tried other suggestions that I've also seen on stack overflow such as the following:
$campaign->exists === false
$campaign->getDirty
$campaign->getChanges
with the if statement stated earlier in the post, it's outputting the first message "Campaign edited successfully". This message displays, even though I haven't yet created a campaign. When I try submitting the form again and again, I get the same output message over and over again. Each time I click the save button, the entry is being saved into the database.
Any suggestions would be appreciated. Thanks.
Additional Code:
if ($_REQUEST['id']) {
$campaign = Campaign::find($_REQUEST['id']);
} else {
$campaign = new Campaign();
}
$campaign->name = $_REQUEST['name'];
$campaign->is_draft = $_REQUEST['is_draft'];
$campaign->is_closed = $_REQUEST['is_closed'];
$campaign->summary = $_REQUEST['summary'];
$campaign->requirements = $_REQUEST['requirements'];
$campaign->additional_details = $_REQUEST['additional_details'];
$campaign->key_information = $_REQUEST['key_information'];
$campaign->opportunity_type = $_REQUEST['opportunity_type'];
$campaign->number_of_stores = $_REQUEST['number_of_stores'];
$campaign->logo_image = $_REQUEST['logo_image'];
$campaign->started_at = Carbon::parse($_REQUEST['started_at']);
$campaign->ended_at = Carbon::parse($_REQUEST['ended_at']);
// only set this when saving a new campaign
if ($campaign->wasRecentlyCreated()) {
$campaign->member_id = $member->id;
}
$campaign->save();
$members = $_REQUEST['members'];
// only do this for a newly created campaign
if ($campaign->wasRecentlyCreated) {
if (!array_key_exists($member->id, (array) $members)) {
$members[$member->id] = CampaignMember::ADMIN;
}
}
$campaign->addMembers($members);
$campaign->addCategories($_REQUEST['categories']);
if ($campaign->wasRecentlyCreated) {
$response['message'] = 'Campaign edited successfully';
} else {
$response['message'] = 'Campaign created successfully';
}

Related

PHP: Script failing after PDO query

During my create user process I make a few queries to various database's to get the new user setup. This script has been working fine for about a year and a half, but now something is off.
So the first thing I do is I check to see if a user exists with the credentials being submitted. I've thoroughly tested the check and I'm confident my issue isn't there.
If that check comes back false then the script continues to create the user.
public function registerUser() {
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
$check = json_decode($this->checkUserExists($data->email));
if ($check->res) {
$res = new \stdClass();
$res->res = false;
$res->user_status = $check->user_status;
$res->msg = 'User exists.';
echo json_encode($res);
}
if (!$check->res) {
$this->createUser($data);
}
}
The problem arises after all the queries have been completed, the script does not seem to want to run the if statement at the bottom. I marked it with comment characters so it's easier to find, but I included the entire function for clarity, maybe I'm doing something that is causing the issue.
I tried invoking an error manually at various points during the script. And I am able to trigger an error all the way down to the bottom of the script.
private function createUser($data) {
$Crypt = new CryptController();
$AuthSelect = new AuthController();
$Time = new TimeController();
$remote_address = new RemoteAddressController();
$Session = new SessionController();
$AuthInsert = new AuthModel_Insert();
$hashed_password = $Crypt->create_hash($data->password);
$data->password = '';
$AuthData = json_decode($AuthSelect->getAuth());
$system_auth_id = $AuthData->system_auth_id;
$user_id = $Crypt->get_uuid();
$user_auth_id = $Crypt->get_uuid();
$user_createddate = $Time->time();
$user_updateddate = $Time->time();
$user_lastupdateddate = $Time->time();
$agent_ip = $remote_address->getIpAddress();
$userData = $this->createUserObject(
$user_id,
$user_auth_id,
$system_auth_id,
$hashed_password,
$user_createddate,
$user_updateddate,
$user_lastupdateddate,
$data
);
$agentData = $this->createAgentObject(
$user_id,
$agent_ip,
$data
);
//////////////////////////////////////////
$create_user = $AuthInsert->createNewUser(
$userData
);
$create_user_agent = $this->setUserAgent(
$agentData
);
$sessionKeyData = new \stdClass();
$sessionKeyData->user_id = $user_id;
$sessionKeyData->user_auth_id = $user_auth_id;
$sessionKeyData->system_auth_id = $system_auth_id;
$sessionKeyData->agent_id = $create_user_agent->agent->agent_id;
$set_session_key = $Session->setSessionKey(
$sessionKeyData
);
$send_activation_email = $this->createUserActivation(
$userData
);
if (
$create_user &&
$create_user_agent->res &&
$set_session_key->res &&
$send_activation_email->res) {
$res = new \stdClass();
$res->res = true;
$res->msg = 'New user successfully created.';
echo json_encode($res);
} else {
$res = new \stdClass();
$res->res = false;
$res->msg = 'Error: User creation process incomplete.';
echo json_encode($res);
}
//////////////////////////////////////////
trigger_error("Invoked Error: ",E_USER_ERROR);
}
The queries themselves go through just fine, all the tables are populated just fine. The issue is that after that happens the script doesn't finish. It seems to end the createUser() function and return to the registerUser() function at which point the user will exist so it will return false and echo that back to the client.
In my testing it seems my issue might be at the bottom with that if statement. But I've tested each of those queries individually and they do return the desired booleans to get the true condition. But, even the false condition doesn't go through which should return 'Error: User creation process incomplete.'. That doesn't happen either.
I'm hoping someone sees something I'm missing because I've been stuck on this problem for too long. I appreciate any guidance that might lead me to an answer. Thanks in advance.
Just for clarification the message I'm getting back is $res->msg = 'User exists.'; which comes from registeruser(). The message I'm expecting back is $res->msg = 'New user successfully created.'; which should come from createUser().

PHP Page is posting multiple times occasionally

I have a registration form which posts data to save.php. But occasionally the data is getting posted multiple times.
Below is my code for save.php
<?php
session_start();
//save registration details in my table
include('connect_database.php');
include('my_functions.php');
$_SESSION['newUser'] = '0'; // new user
//POSTED DATA--------------------------
$t_email = $_POST['email'];
$t_psw = $_POST['psw'];
$t_first_name = addslashes($_POST['first_name']);
$_SESSION['lastname'] = $t_last_name = addslashes($_POST['last_name']);
$t_mobile = $_POST['mobile'];
$_SESSION['licNum'] = $t_lic_no = $_POST['lic_no'];
$t_dob = $_POST['dob'];
$t_abn = $_POST['abn'];
$tx_expiry = $_POST['tx_expiry'];
$drv_for = $_POST['driven_for'];
$lng_drv = $_POST['long_driven'];
//referred by
$ref_drLic = $_POST['ref_driLic'];
$ref_drName = $_POST['ref_driName'];
$t_dr_front = get_image('dr_front',$_POST['last_name'].'_dr_front');
$t_dr_bck = get_image('dr_bck',$_POST['last_name'].'_dr_bck');
//if tx required-------
if($_SESSION['ce_cr_tx'] == 1){
$t_tx_front = get_image('tx_front',$_POST['last_name'].'_tx_front');
$t_tx_bck = get_image('tx_bck',$_POST['last_name'].'_tx_bck');
}
else{
$t_tx_front = "";
$t_tx_bck = "";
}
//store data in logfile
$nwtxt = "Email is - ".$_POST['email'].". Mobile no - ".$_POST['mobile'];
writeFile($nwtxt);
//---------------------------------------
//query to save data in my table
$ad_sql = "INSERT INTO myTable (email, password, firstname, lastname, mobile, licence, drfront, drbck, txfront, txbck, cnfrm, dob, abnf, texpiry, drifor, driven, reLic, reNname)
VALUES('".$t_email."','".$t_psw."','".$t_first_name."','".$t_last_name."','".$t_mobile."','".$t_lic_no."','".$t_dr_front."','".$t_dr_bck."','".$t_tx_front."','".$t_tx_bck."','0','".$t_dob."','".$t_abn."','".$tx_expiry."','".$drv_for."','".$lng_drv."','".$ref_drLic."','".$ref_drName."')";
if(!empty($t_email)){
if($conn->query($ad_sql) == true){
//echo'Success';
$lst_id = $conn->insert_id;
$_SESSION['ls_id'] = $lst_id;
$_SESSION['s_email'] = $t_email;
$_SESSION['s_code'] = mt_rand(11111,99999);
//email code to user--------------------------
$subjct = "Email Verification Code";
$usr_msg = "Hi ".$_POST['first_name']." ".$_POST['last_name'].",<br><br>
A new account has been requested at 'Portal'
using your email address.<br><br>
To confirm your new account, please enter this code in the web page:<br>
<h3>".$_SESSION['s_code']."</h3><br><br>
If you need help, please call us<br><br>
Thank you,
Administrator";
sendEmail($t_email, $usr_msg, $subjct); //sends and email
writeFile('Code is :'.$_SESSION['s_code']); // write a log in file
//--------------------------------------------
//redirect to verify email page----------------------
header("location: verifyEmail.php");
exit();
}
else{
echo'Error creating account- '.$conn->error.'. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms=Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
}
else{
echo'Error creating account. Please try again.';
$gbck = "cr=".$_SESSION['ce_cr_id']."&crs=".$_SESSION['ce_cr_nm']."&tx=".$_SESSION['ce_cr_tx']."&erms= EMPTY data. Error creating account. Please try again";
header('location: Enroll.php?'.$gbck);
exit();
}
?>
I checked my code multiple times but couldn't find anything that is triggering it. When someone registers, the page keeps loading for sometime and I receive multiple entries in database and user receives multiple verification emails.
Is something wrong in my code?
The code itself looks fine, but i get the growing suspicion that it might be a config issue or whats happening before this executes. If your looking for a patchwork fix i would probably put a condition near your if(!empty($t_email)) that checks if the sql table row already exists dont execute, which would rectify the fact that multiple requests are coming in.

Adding Address Fields to the Registeration form in Prestashop

When a customer or user registers, I want to capture the address details in one click and save that in ps_address table , ie when he clicks on the register button his address details must be also saved to the ps_address table , how to do this?
I have managed to customize the registration form and able to plug the address details form to my registration form as shown in the attached image :
Now what I am stuck with is : when am clicking on the Register button ,the address field details are not saved in the database and I am getting server error
What I tried to do is ,I created a new function called processPostAddress and I am calling processPostAddress from processSubmitAccount() in controller/front/Authcontroller.php page before the redirection to the account page.
$this->processPostAddress(); //// custom function call
Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));
Below is the custom function which i created in controller/front/Authcontroller.php page
public function processPostAddress()
{
if($this->context->customer->id_customer!=''){
$address = new Address();
$address->id_customer = 40;
$address->firstname = trim(Tools::getValue('firstname'));
$address->lastname = trim(Tools::getValue('lastname'));
$address->address1 = trim(Tools::getValue('address1'));
$address->address2 = trim(Tools::getValue('address2'));
$address->postcode = trim(Tools::getValue('postcode'));
$address->city = trim(Tools::getValue('city'));
$address->country = trim(Tools::getValue('country'));
$address->state = trim(Tools::getValue('state'));
$address->phone = trim(Tools::getValue('phone'));
$address->phone_mobile = trim(Tools::getValue('phone_mobile'));
$address->add(); // This should add the address to the addresss table }
}
Please help me or tell me if I am doing anything wrong or how to achieve this
I solved it by adding $address->alias, since alias was required and was validated .
Also in order to save in the database I modified $address->add(); to $address->save();
public function processPostAddress()
{
///Address::postProcess(); // Try this for posting address and check if its working
// Preparing Address
$address = new Address();
$this->errors = $address->validateController();
$address->id_customer = (int)$this->context->customer->id;
$address->firstname = trim(Tools::getValue('firstname'));
$address->lastname = trim(Tools::getValue('lastname'));
$address->address1 = trim(Tools::getValue('address1'));
$address->address2 = trim(Tools::getValue('address2'));
$address->postcode = trim(Tools::getValue('postcode'));
$address->city = (int)trim(Tools::getValue('city'));
$address->country = (int)trim(Tools::getValue('country'));
$address->state = (int)trim(Tools::getValue('state'));
$address->phone = trim(Tools::getValue('phone'));
$address->alias = "My Default Address";
// Check the requires fields which are settings in the BO
$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
// Don't continue this process if we have errors !
if (!$this->errors && !$this->ajax) {
return;
}else{
// Save address
$address->save();
}
}

extjs4 and php issue - 500 Internal server error when creating entries

I've been stuck with this problem for a day now. I think I'm overlooking something simple but I can't see it.
I am developing a web application where the user fills up forms and the forms get saved in the database. However, I'm having a problem inserting values to a form. The database does not update and I get a 500 Internal Server Error at the console.
Here is the controller that I call when the user saves the form that was filled up
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var id = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'app.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
caStore.getProxy().extraParams = {
selectedUserID: id
};
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log("Failed syncing ca");
}
});
I have checked with various console.log statements that all of the variables here have the proper values.
Here is the php file that gives the 500 Internal Server Error problem:
<?php
require_once('../../db_connection.php');
require_once '../../lib/response.php';
require_once '../../lib/request.php';
class creditApplication{
var $ID_PERSON;
var $APPLICATION_TYPE;
var $APPLICATION_SUB_TYPE;
var $APPLICATION_NUMBER;
var $CUSTOMER_NUMBER;
var $DATE;
var $STATUS;
var $ID_UNIT;
}
$request = new Request(array());
if(isset($request->params)){
var $selectedCustomer = '';
if(isset($_GET['selectedUserID'])){
$selectedCustomer = $_GET['selectedUserID'];
$array_r=$request->params;
$inputData = new creditApplication();
$inputData->ID_PERSON=$selectedCustomer;
$inputData->APPLICATION_TYPE=($array_r->APPLICATION_TYPE);
$inputData->APPLICATION_SUB_TYPE=($array_r->APPLICATION_SUB_TYPE);
$inputData->APPLICATION_NUMBER='sample application number';
$inputData->CUSTOMER_NUMBER='sample customer number';
$inputData->DATE='2014-4-4';
$inputData->STATUS=42;
$inputData->ID_UNIT='sampleUnit';
$query="INSERT INTO CREDIT_APPLICATION (ID_PERSON, APPLICATION_TYPE, APPLICATION_SUB_TYPE, APPLICATION_NUMBER,
CUSTOMER_NUMBER, DATE, STATUS, ID_UNIT)
VALUES ($inputData->ID_PERSON,
'$inputData->APPLICATION_TYPE',
'$inputData->APPLICATION_SUB_TYPE',
'$inputData->APPLICATION_NUMBER',
'$inputData->CUSTOMER_NUMBER',
'$inputData->DATE',
$inputData->STATUS,
'$inputData->ID_UNIT')";
$result = mysql_query($query);
//object response
$res = new Response();
$res->success = true;
$res->message = "Created user";
print_r($res->to_json());
}
else{
$res = new Response();
$res->success = false;
$res->message = "Error - no userID";
$res->data = array();
print_r($res->to_json());
}
}
else{
$res = new Response();
$res->success = false;
$res->message = "Error - no request";
$res->data = array();
print_r($res->to_json());
}
?>
All the database rows are varchars except for ID_PERSON and STATUS which are ints (hence the single quotes in the insert) and the DATE which is of date format.
Now, I've tried hard coding the values, commenting out the if else conditions, and calling the php file through localhost:8888/..../createCreditApplication.php and it actually works. The problem happens when I bring back the if-else blocks and get the values passed to the php file.
I appreciate any help.

Undefined variable with OpenID

I have a website running on a less well known CMS called Ushahidi. There is built in OpenID functionality where folk can login with Facebook or Google.
I don't have enough dev skills to understand whats happening here but, it appears that I've almost got it working, except, I'm receiving the following error when trying to test it out on my own Google login:
An error was detected which prevented the loading of this page. If
this problem persists, please contact the website administrator.
application/controllers/login.php [503]: Undefined variable: user
I suspect, but am not sure, that defining a variable is easy enough but since I lack the knowledge I hoped to ask someone on here if they could see where I need to define the variable. Line 503 is part of a larger code block of about 100 lines, I know that it's not good practice to post larger chunks of code on here but I'm really unsure of what is and is not relevant. So forgive me. I have highlighted in bold where line 503 is. Can anyone point out what I must do here?
// OpenID Post
try
{
$openid = new OpenID;
// Retrieve the Name (if available) and Email
$openid->required = array("namePerson", "contact/email");
if( ! $openid->mode)
{
if(isset($_POST["openid_identifier"]))
{
$openid->identity = $_POST["openid_identifier"];
header("Location: " . $openid->authUrl());
}
}
elseif ($openid->mode == "cancel")
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = "You have canceled authentication!";
}
else
{
if ($openid->validate())
{
// Does User Exist?
$openid_user = ORM::factory("openid")
->where("openid", $openid->identity)
->find();
if ($openid_user->loaded AND $openid_user->user)
{
// First log all other sessions out
$auth->logout();
// Initiate Ushahidi side login + AutoLogin
$auth->force_login($openid_user->user->username);
// Exists Redirect to Dashboard
**(THIS IS LINE 503)** url::redirect($user->dashboard());
}
else
{
// Does this openid have the required email??
$new_openid = $openid->getAttributes();
if ( ! isset($new_openid["contact/email"]) OR
empty($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . " has not been logged in. No Email Address Found.";
}
else
{
// Create new User and save OpenID
$user = ORM::factory("user");
// But first... does this email address already exist
// in the system?
if ($user->email_exists($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $new_openid["contact/email"] . " is already registered in our system.";
}
else
{
$username = "user".time(); // Random User Name from TimeStamp - can be changed later
$password = text::random("alnum", 16); // Create Random Strong Password
// Name Available?
$user->name = (isset($new_openid["namePerson"]) AND ! empty($new_openid["namePerson"]))
? $new_openid["namePerson"]
: $username;
$user->username = $username;
$user->password = $password;
$user->email = $new_openid["contact/email"];
// Add New Roles
$user->add(ORM::factory('role', 'login'));
$user->add(ORM::factory('role', 'member'));
$user->save();
// Save OpenID and Association
$openid_user->user_id = $user->id;
$openid_user->openid = $openid->identity;
$openid_user->openid_email = $new_openid["contact/email"];
$openid_user->openid_server = $openid->server;
$openid_user->openid_date = date("Y-m-d H:i:s");
$openid_user->save();
// Initiate Ushahidi side login + AutoLogin
$auth->login($username, $password, TRUE);
// Redirect to Dashboard
url::redirect($user->dashboard());
}
}
}
}
else
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . "has not been logged in.";
}
}
}
catch (ErrorException $e)
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $e->getMessage();
}
The problem is that the code is using $user several lines before it's actually defined. It might be a typo, though - maybe $openid_user->user->dashboard() at line 503 might work, though it's a WAG.

Categories