PHP: Script failing after PDO query - php

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().

Related

wasRecentlyCreated in PHP not detecting newly created campaign

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';
}

JSON is overwriting the old data how to keep on adding data with new ID

so, I am working on a JSON file that should keep on incrementing IDs.
However I get stuck at id:0 and when I insert new data the old data will be replaced by the new one (it keeps id:0).
I am not entirely sure what code is related and what not, so I will post whatever I think should be related and if someone with more knowledge related to JSON could adjust (in case it needs any) it, I would appreciate it a lot.
The include database_json.php contains the following code:
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
EDIT: someone wanted me to post how the JSON itself looked like... so this is how it looks:
The file is called: database.json
{
"data":
[
{
"id":0,
"exercisetitle":"Test300520180924",
"exerciseWord":["huiswerk"],
"syllables":["Huis","werk"],
"file":"jsonData_.json",
"audio":null,"language":null
}
]
}
(do not mind the audio and language, that's something for later on.
The best I could do was this, yes I read the stuff about making a post and how to properly format stuff etc. but I people would often say I need to include certain code etc etc. and it mostly would turn out messy as hell, so I would rather have a bit too much code (the code I think is related) then not have enough.
Cheers!

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.

cakephp error while saving data

i am working on a cakephp 2.x ... well the scenario is that i am sending messages to my webapp ... there are almost 509 messages ... the problem is it is saving some messages into db and on some messages it gives me an error on android console ... ...so first thing i want to ask what u all think that where the actual problem lies or can be lie..and the other think is there a way that i can throw some exception error on data which is not saving into the db .. so i can track the particular messages which is not saving into and causing the problem ...i need some help in debugging this code
here is my code
public function message(){
$this->loadModel('Message');
if ($this->request->isPost()){
$json = $this->request->data('json');
$data = json_decode($json, TRUE);
foreach($data as $datas){
$date = $datas['date'];
$mobileNo = $datas['mobileNo'];
$mobileNo = AllSecure::replaceDashesAndSpaces($mobileNo);
$body = $datas['body'];
$timestamp = $date/1000;
$date = date('Y-m-d h:i' , $timestamp);
$this->request->data['Message']['mobileNo'] = $mobileNo;
$this->request->data['Message']['body'] = $datas['body'];
$this->request->data['Message']['type'] = $datas['type'];
$this->request->data['Message']['User_id'] = $datas['idUser'];
$this->request->data['Message']['dateTime'] = $date;
$count = $this->Message->checkTextMessages($mobileNo,$body,$date,$datas['idUser']);
if($mobileNo!=null){
if($count>0){
}else{
$this->Message->create();
$this->Message->save($this->request->data
}
}
}
}
}
well i solved my problem by self ... i dont know why it is causing the problem ... so i did this .. and it works
foreach($data as $datas){
$i=0
$this->request->data['Message'][$i]['mobileNo'] = $datas['mobileNo'];;
$this->request->data['Message'][$i]['body'] = $datas['body'];
$this->request->data['Message'][$i]['type'] = $datas['type'];
$this->request->data['Message'][$i]['User_id'] = $datas['idUser'];
$i++;
if($mobileNo!=null){
}
}
$isSave = $this->Message->saveAll($this->request->data["Message"]);
echo $isSave;

PHP curl questions - running multiple times

I have this code:
<?php
foreach($items as $item) {
$site = $item['link'];
$id = $item['id'];
$newdata = $item['data_a'];
$newdata2 = $item['data_b'];
$ch = curl_init($site.'updateme.php?id='.$id.'&data1='.$newdata.'&data2='.$newdata2);
curl_exec ($ch);
// do some checking here
curl_close ($ch);
}
?>
Sample input:
$site = 'http://www.mysite.com/folder1/folder2/';
$id = 512522;
$newdata = 'Short string here';
$newdata = 'Another short string here with numbers';
Here the main process of updateme.php
if (!$id = intval(Tools::getValue('id')))
$this->_errors[] = Tools::displayError('Invalid ID!');
else
{
$history = new History();
$history->id = $id;
$history->changeState($newdata1, intval($id));
$history->id_employee = intval($employee->id_employee);
$carrier = new Carrier(intval($info->id_carrier), intval($info->id_lang));
$templateVars = array('{delivery}' => ($history->id_data_state == _READY_TO_SEND AND $info->shipping_number) ? str_replace('#', $info->shipping_number, $carrier->url) : '');
if (!$history->addWithemail(true, $templateVars))
$this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the employee');
}
The site will always be changing and each $items will have atleast 20 data inside it so the foreach loop will run atleast 20 times or more depending on the number of data.
The target site will update it's database with the passed variables, it will probably pass thru atleast 5 functions before it is saved to the DB so it could probably take some time too.
My question is will there be a problem with this approach? Will the script encounter a timeout error while going thru the curl process? How about if the $items data is around 50 or in the hundreds now?
Or is there a better way to do this?
UPDATES:
* Added updateme.php main process code. Additional info: updateme.php will also send an email depending on the variables passed.
Right now all of the other site are hosted in the same server.
You can have a php execution time problem.
For your curl timeout problem, you can "fix" it using the option CURLOPT_TIMEOUT.
Since the cURL script that calls updateme.php doesn't expect a response, you should make updateme.php return early.
http://gr.php.net/register_shutdown_function
function shutdown() {
if (!$id = intval(Tools::getValue('id')))
$this->_errors[] = Tools::displayError('Invalid ID!');
else
{
$history = new History();
$history->id = $id;
$history->changeState($newdata1, intval($id));
$history->id_employee = intval($employee->id_employee);
$carrier = new Carrier(intval($info->id_carrier), intval($info->id_lang));
$templateVars = array('{delivery}' => ($history->id_data_state == _READY_TO_SEND AND $info->shipping_number) ? str_replace('#', $info->shipping_number, $carrier->url) : '');
if (!$history->addWithemail(true, $templateVars))
$this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the employee');
}
}
register_shutdown_function('shutdown');
exit();
You can use set_time_limit(0) (0 means no time limit) to change the timeout of the PHP script execution. CURLOPT_TIMEOUT is the cURL option for setting the timeout, but I think it's unlimited by default, so you don't need to set this option on your handle.

Categories