This code is for Telegram bot.
So I was trying to pass the value when user typed 'Category Check', which will return a news title and question asking if it's the correct category.
But after the user answered 'yes', for some reason the variables are reset so $title, $cat, and $check are blank.
How do I fix this?
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
$sender_id = $message['from']['id'];
$sender_first_name = $message['from']['first_name'];
$sender_last_name = $message['from']['last_name'];
$message_date = $message['date'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
//when user starts the bot
if (strpos($text, "/start") === 0) {
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => 'Please select an option:', 'reply_markup' => array(
'keyboard' => array(array('Category Check', 'Uncategorized')),
'one_time_keyboard' => false,
'resize_keyboard' => true)));
}
//category check that returns news title and category question to user
else if ($text === "Category Check") {
//MySQL Connection Details
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM `newsdata` WHERE `nb_count` OR `svm_count` <> 0 ORDER BY RAND() LIMIT 1 ";
$row = $result->fetch_assoc();
$nb_business = $row["nb_business"];
$nb_entertainment = $row["nb_entertainment"];
$nb_health = $row["nb_health"];
$nb_politics = $row["nb_politics"];
$nb_science = $row["nb_science"];
$nb_technology = $row["nb_technology"];
$nb_world = $row["nb_world"];
$svm_business = $row["svm_business"];
$svm_entertainment = $row["svm_entertainment"];
$svm_health = $row["svm_health"];
$svm_politics = $row["svm_politics"];
$svm_science = $row["svm_science"];
$svm_technology = $row["svm_technology"];
$svm_world = $row["svm_world"];
$title=$row["title"];
$nb_count=$row["nb_count"];
$svm_count=$row["svm_count"];
if($nb_business!=0)
{$cat='BUSINESS'; $track=1;}
else if ($nb_entertainment!=0)
{$cat='ENTERTAINMENT'; $track=1;}
else if ($nb_health!=0)
{$cat='HEALTH'; $track=1;}
else if ($nb_politics!=0)
{$cat='POLITICS'; $track=1;}
else if ($nb_science!=0)
{$cat='SCIENCE'; $track=1;}
else if ($nb_technology!=0)
{$cat='TECHNOLOGY'; $track=1;}
else if ($nb_world!=0)
{$cat='WORLD'; $track=1;}
else if ($svm_business!=0)
{$cat='BUSINESS'; $track=0;}
else if ($svm_entertainment!=0)
{$cat='ENTERTAINMENT'; $track=0;}
else if ($svm_health!=0)
{$cat='HEALTH'; $track=0;}
else if ($svm_politics!=0)
{$cat='POLITICS'; $track=0;}
else if ($svm_science!=0)
{$cat='SCIENCE'; $track=0;}
else if ($svm_technology!=0)
{$cat='TECHNOLOGY'; $track=0;}
else if ($svm_world!=0)
{$cat='WORLD'; $track=0;}
// output data of each row
//asking user if the category is correct
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => 'Is this news belongs to '.
$cat.' category? '.
$title.' '.$row["link"],
'reply_markup' => array(
'keyboard' => array(array('yes', 'no')),
'one_time_keyboard' => false,
'resize_keyboard' => true)));
}
//user answers
if ($text == "yes" || $text == "no"){
switch ($text) {
case "yes":
$nb_count=$nb_count--;
$svm_count=$svm_count--;
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => $cat.$track.$title."variable check")); //broken here, output: variable check
break;
case "no":
//dothat; break;
}
There are 3 possible solutions to this problem that I can think of depending on how you are re-calling the function.
USE STATIC OR GLOBAL VARIABLES
If the session does not end before you call the function again you could use static variables inside the function or global variables to store the data. If you use the global variable solution then remember to define the variable as "global $your_variable_name" in the function.
USE SESSION VARIABLES OR COOKIES
If the session will end before function calls but will be called again by the same user then you could use session variables of browser cookies to store the data that you want to remain persistent.
STORE THE PERSISTENT VALUES IN A DATABASE
From the title of your question I think that you may need the values to be persistent between calls from multiple users. If this is the case then you will need to store the persistent values in a database such as mySQL.
Related
I am trying to create a Api.I am trying to submit a form . Form is submitted and response message after form submission is Ok .but I am trying to validate this form if any filed is blank then form does not submitted and show validation message.
<?php
require('../../../../wp-blog-header.php');
header("HTTP/1.1 200 OK");
global $wpdb;
global $serverUrl;
global $current_user;
$id =isset($_REQUEST['store_id']) ? $_REQUEST['store_id'] : '';
$user_id =isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
$unit_data = isset($_REQUEST['unit_data']) ? $_REQUEST['unit_data'] : '';
$product = isset($_REQUEST['product']) ? $_REQUEST['product'] : '';
$checked_by = isset($_REQUEST['checked_by']) ? $_REQUEST['checked_by'] : '';
$username = isset($_POST['username']) ? $_POST['username'] : '';
$option = "signup";
$data = array(
'store_id' =>$id,
'user_id' =>$uid,
'unit_data' =>$unit_data,
'category_name'=>'delivery_form',
'checked_by'=>$checked_by,
'product' =>$product,
'suppliers'=>$suppliers,
'username' =>$username,
);
$insert=$wpdb->insert('diary_user_form_storage', $data);
echo json_encode(
array(
"status" => "1",
'user_id' => $user->ID,
'message' => 'Data submitted',
"token" => $token,
'token' => $token.$device_id.$device_type,
'serverUrl' => $serverUrl,
$data = array(
'store_id' =>$id,
'user_id' =>$uid,
'unit_data' =>$unit_data,
'product' =>$product,
'suppliers'=>$suppliers,
'checked_by'=>$checked_by,
'username' =>$username,
'option'=>$option
)
));
exit();
?>
If you want to stick to PHP, a simple:
if($value == ""){$value_err = "This field is required"};
And then have $value_err in a red span next to the content that needs an input. Also you can use the same practice:
$if(value_err == ""){
//Submit Values to Database
}
else{
//Don't
}
To submit your values or not.
You can also use JavaScript to check it dynamically using an onblur on one of your inputs you require to be validated, and then using
function checkEmpty(id, idErr){
var z = document.getElementById("myForm");
z.addEventListener("blur", checkEmpty, true);
var x = document.getElementById(id);
var y = document.getElementById(idErr);
if(x.value == ""){
//If direct value
y.value = "This field is required.";
//If inside a span as PHP example above
//y.innerHTML = "This field is required.";
}
}
How can i display all the otrs tickets using a soap api. Individual ticket can be displayed by passing ticket id in url like this:
$url = "https://url/otrs/rpc.pl"; //// URL for OTRS server
$username = "username"; //// SOAP username set in sysconfig
$password = "password"; //// SOAP password set in sysconfig
$TicketID = $_GET['id'];
//////// Initialize new client session ////////
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => "Core",
'trace' => 1,
'login' => $username,
'password' => $password,
'style' => SOAP_RPC,
'use' => SOAP_ENCODED
)
);
//////// Create and send the SOAP Function Call ////////
$sql =
$TicketDetails = $client->__soapCall("Dispatch",
array($username, $password,
"TicketObject", "TicketGet",
"TicketID", $TicketID,
));
$ticketInfo = array();
$i = 0;
foreach ($TicketDetails as $name => $value){ //// explode the xml response
if (false !== strpos($name, "s-gensym")){
$temp[$i] = $value;
$v = $temp[$i - 1];
if($i % 2 != 0){
$ticketInfo[$v] = $value;
}
$i++;
}
}
var_dump($ticketInfo);
exit();
How can i display all the tickets using api?????
Use the TicketSearch API call in order to retrieve a list of Ticket IDs. Then feed this list to TicketGet as you already showed in order to retrieve ticket details.
I am having problems regarding the shared sessions once the users logged in simultaneously to the website. When the last user logs in, every users views the account of the last user, which is not appropriate (security issue I guess). All users must login to the same website and must show an output for a specific user only.
I am using PHP code. Does anyone also experienced these scenario? here's the code
function validate_login(){
$userName= trim((isset($_POST['username']) === TRUE ? $_POST['username'] : ''));
$userPass= trim((isset($_POST['userpass']) === TRUE ? $_POST['userpass'] : ''));
$userNameArray = explode("#", $userName);
$userName = $userNameArray[0];
$compLogin = ((isset($userNameArray[1]) === TRUE ? $userNameArray[1]: ''));
$KeepAlive = new KeepAlive();
if(isset($userNameArray[1])){
if(!$this->Login->checkattempt('admin')){
$loginArray = array(
'login' => $userName,
'comp_login_string' => $compLogin,
'pass' => $cryptography->encryptPassword($userPass)
);
$userCredentials = $this->Login->getLogin($loginArray);
if(!empty($userCredentials)){
$_SESSION['userCredentials'] = $userCredentials[0];
header('Content-Type: application/json');
$_SESSION['employee_user'] = '0';
$_SESSION['emp_id'] = '0';
$_SESSION['page']['client_ip_address'] = $KeepAlive->get_client_ip();
$_SESSION['page']['last_trans_time'] = time();
$this->Login->clear_attempt_log($_POST, 'admin');
echo json_encode(array('id' => $userCredentials[0]['id']));
}
} else {
array_shift($loginArray);
$this->Login->attempt_log($_POST, 'admin');
header('Content-Type: application/json');
echo json_encode(array('id' => '-1'));
}
} else {
echo json_encode(array('id' => '-2'));
}
}
I'm trying to put a script together that will do some math for the user.
That works fine however when i try to put it in a session and try to show the value to the user it will only return 0 if its set to 0.
Does anybody know where i did wrong?
<?php
session_start();
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$class1 = filter_var($_POST['class1'], FILTER_SANITIZE_STRING);
$class2 = filter_var($_POST['class2'], FILTER_SANITIZE_STRING);
$class3 = filter_var($_POST['class3'], FILTER_SANITIZE_STRING);
$class4 = filter_var($_POST['class4'], FILTER_SANITIZE_STRING);
$class5 = filter_var($_POST['class5'], FILTER_SANITIZE_STRING);
$class1C = $class1 * 35;
$class2C = $class2 * 5;
$class3C = $class3 * 7.5;
$class4C = $class4 * 26;
$class5C = $class5 * 2.5;
$totaal1 = $class1C + $class2C + $class3C + $class4C + $class5C;
$res = array($class1C, $class2C, $class3C, $class4C, $class5C, $totaal1);
foreach($res as $name => $var) {
$_SESSION[$name] = $var;
}
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<h3>Session information: var_dump($_SESSION[$class1C]) ($_SESSION[$class2C]) ($_SESSION[$totaal1])</h3>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error</h3>";
}
echo json_encode($result);
exit;
?>
You cannot call var_dump inside the double quoted string, and var_dump does not return anything: it only display things.
Even if you could, $class1C is not a valid index for $_SESSION
Keeping the same logic as your code, you may change your line to the following:
$result["html"] = "<h3>Session information:";
ob_start();
var_dump($_SESSION[0]); // contains $class1C
echo $_SESSION[1]; // contains $class2C
echo $_SESSION[5]; // contains $totaal1
$result["html"] .= ob_get_clean();
$result["html"] .= "</h3>";
EDIT:
If you want to use the indexes 'class2C', 'totaal1' etc.. you need to init $res as follow:
$res = array(
'class1C' => $class1C,
'class2C' => $class2C,
'class3C' => $class3C,
'class4C' => $class4C,
'class5C' => $class5C,
'totaal1' => $totaal1
);
Then, your loop to set $_SESSION will set correct indexes, and you will be able to use $_SESSION['class1C'] to get proper values.
I've created several new child groups under registered users and when I create a new user from the backend, everything works fine. When trying to create an account on the frontend the system is giving them the gid of the parent group (registered users). I would like to know if you can pass the gid to joomla. Here's the script I'm using that's not working. Many thanks!
// Begin create user
global $mainframe;
JFactory::getLanguage()->load('com_user');
$this->execPieceByName('ff_InitLib');
$user = clone(JFactory::getUser());
$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
$authorize =& JFactory::getACL();
$document =& JFactory::getDocument();
// If user registration is not allowed, show 403 not authorized.
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0') {
echo '<script>alert("Access forbidden");history.go(-1);</script>';
return;
} else {
// Initialize new usertype setting
$newUsertype = $usersConfig->get( 'new_usertype' );
if (!$newUsertype) {
$newUsertype = 'Free User';
}
// Bind the post array to the user object
$post = array(
'name' => ff_getSubmit('ownerName'),
'username' => ff_getSubmit('ownerEmail'),
'email' => ff_getSubmit('ownerEmail'),
'password' => ff_getSubmit('password'),
'password2' => ff_getSubmit('password'),
'task' => 'register_save',
'id' => '0',
'gid' => ff_getSubmit('101'),
);
if (!$user->bind( $post, 'usertype' )) {
echo '<script>alert("'.addslashes($user- >getError()).'");history.go(-1);</script>';
return;
} else {
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', 'Free User');
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
echo '<script>alert("'.addslashes(JText::_( $user->getError())).'");history.go(-1);</script>';
return;
} else {
$db =& JFactory::getDBO();
$name = $user->get('name');
$email = $user->get('email');
$username = $user->get('username');
JFactory::getDBO()->setQuery("Update #__facileforms_records Set user_id = '".$user->get('id')."',
username = ".JFactory::getDBO()->Quote($username).", user_full_name = ".JFactory::getDBO()->Quote($name)." Where id = '".$this->record_id."'");
JFactory::getDBO()->query();
}
}
}
[SOLVED] Assigning gid to new user in joomla 1.5
I figured it out. If anyone else looking for an answer to this questions, just replace this line of code:
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
with
$user->set('gid', 'your gid#);