Call a user again if he/she did not answer using Twilio - php

EDIT: working now, editted this post to the working script.
I'm setting up an alarm which calls the user if a sensor reaches a certain value. I've got the calling part working but I need Twilio to call the user again if the user did not pick up the phone.
Currently, Twilio calls the user telling him that the alarm is going. If the user does not pick up in 15 seconds Twilio will end the call so it doesn't go to voicemail. Now the status of the call will be 'No Answer' in the Twilio console. I've tried the following code:
In my call.php:
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// /include 'insertcall.php';
// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'xxx';
$auth_token = 'xxx';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]
// A Twilio number you own with Voice capabilities
$twilio_number = "+12242631292";
// Where to make a voice call (your cell phone?)
$time = time();
$call_id = $sensor_id . $time;
echo "callid: ";
echo $call_id;
echo "<br><br>";
$client = new Client($account_sid, $auth_token);
$client->account->calls->create(
$callto,
$twilio_number,
array(
"machineDetection" => "DetectMessageEnd",
"url" => "https://link.nl/includes/alarmbot/includes/cas_xml.inc.php?sensor=$sensor_id",
"statusCallbackMethod" => "POST",
"statusCallback" => "https://link.nl/includes/alarmbot/callback.php?sensor=$sensor_id&callid=$call_id",
"statusCallbackEvent" => array(
"completed"
),
"timeout" => 15 // Wanneer niemand op neemt na 15 sec -> No Answer zodat we niet naar voicemail gaan en alsnog als completed gaat.
)
);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql5 = "INSERT INTO twilio_calls (id, sensor_id, completed) VALUES ($call_id, '$sensor_id', '0')";
if ($conn->query($sql5) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql5 . "<br>" . $conn->error;
}
In my callback.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
setlocale(LC_ALL, 'nl_NL');
require 'includes/boot.php';
use Twilio\Rest\Client;
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = 'xxx';
$account_sid = 'xxx';
$auth_token = 'xxx';
if (isset($_REQUEST['CallStatus'])) {
$call_status = $_REQUEST['CallStatus'];
$call_id = $_REQUEST['callid'];
$twilio_number = "+mynumber";
echo $call_status;
echo "<br>";
echo $call_id;
echo "<br>";
if ($call_status !== 'completed' && $call_status !== 'busy') {
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM twilio_calls WHERE id='$call_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sensor_id = $row['sensor_id'];
$sql_2 = "SELECT telefoonnummer FROM alarmnummers WHERE sensor_id='$sensor_id' AND backup = 1";
$result_2 = $conn->query($sql_2);
if ($result_2->num_rows > 0) {
while ($row_2 = $result_2->fetch_assoc()) {
$telefoonnummer = $row_2['telefoonnummer'];
echo $telefoonnummer;
$client = new Client($account_sid, $auth_token);
$client->account->calls->create(
$telefoonnummer,
$twilio_number,
array(
"url" => "https://link.nl/includes/alarmbot/includes/callback.php?sensor=$sensor_id",
"timeout" => 15
)
);
}
} else {
echo "query ni goed";
}
$sql_3 = "UPDATE twilio_calls SET completed=1 WHERE id='$call_id'";
$conn->query($sql_3);
}
} else {
echo "andere query ni goed";
}
} else {
$sql = "UPDATE twilio_calls SET completed=1 WHERE id='$call_id'";
$conn->query($sql);
echo "Updated, call busy or completed";
}
} else {
echo 'No valid callback';
}
So I need to call the user again when he/she did not pick up. I am not really sure how I am supposed to do this.

Related

PHP-script: Write IP-Adress in mySQL-Database. Doing that twice is not working

I use a PHP-Script to submit my IPv4 Address to my own PowerDNS-Server using that link:
script.php?domain=test.dns.com&ipaddr=11.22.33.44&passwd=auth-phrase
Therefore I modified the link in a way that the IPv4 and IPv6 are being updated simultaneously. I modified the update script, but then only one version will be updated (IPv4):
script.php?domain=test.dns.com&ipaddr=11.22.33.44&passwd=auth-phrase&ip6addr=2001:0db8:1234:0000:0000:0000:0000:0000
Here is the script I'm using:
<?php
// DynDNS-Service für PowerDNS
// #date 06.09.2012
$dsn = 'mysql:dbname=pdns;host=127.0.0.1'; // Datenbank DSN
$user = 'pdns'; // Name der Datenbank
$pass = 'password'; // Datenbank Passwort
// Auth-String der als GET-Parameter übermittelt werden muss
$auth = 'auth-phrase';
// Für alle im Array enthaltenen Records dürfen Updates gefahren werden
$allowed = array('ip4.test.dns.tld');
$domain = (isset($_GET['domain'])) ? $_GET['domain'] : null;
$ip = (isset($_GET['ipaddr'])) ? $_GET['ipaddr'] : null;
$ip6 = (isset($_GET['ip6addr'])) ? $_GET['ip6addr'] : null;
$domain6 = 'ip6.test.dns.tld';
if ((empty($domain) || is_null($domain)) || (empty($ip6) || is_null($ip6))) {
die('missing parameter');
exit;
}
if (!in_array($domain, $allowed)) {
die('forbidden domain name');
exit;
}
if (!isset($_GET['passwd']) || $_GET['passwd'] != $auth) {
die('authentification failed');
exit;
}
try {
$dbh = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// HERE THE PROBLEM STARTS
//IPv4 UPDATE
$check = $dbh->prepare('SELECT id FROM records WHERE name = :name AND type = :type');
$check->bindParam(':name', $domain);
$check->bindValue(':type', 'A');
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
if (empty($result)) {
die('record not found');
exit;
} else {
$update = $dbh->prepare('UPDATE records SET content = :content WHERE id = :id LIMIT 1');
$update->bindParam(':content', $ip);
$update->bindParam(':id', $result['id']);
// if ($update->execute()) {
// die('update successful (' . htmlentities($ip, ENT_QUOTES) . ')');
// exit;
// }
// die('update returned false');
// exit;
}
//IPv6 UPDATE
$check2 = $dbh->prepare('SELECT id FROM records WHERE name = :name AND type = :type');
$check2->bindParam2(':name', $domain6);
$check2->bindValue2(':type', 'AAAA');
$check2->execute2();
$result2 = $check2->fetch(PDO::FETCH_ASSOC);
if (empty($result2)) {
die('record not found');
exit;
} else {
$update2 = $dbh->prepare('UPDATE records SET content = :content WHERE id = :id LIMIT 1');
$update2->bindParam2(':content', $ip6);
$update2->bindParam2(':id', $result2['id']);
if ($update2->execute2()) {
die('update successful (' . htmlentities($ip, ENT_QUOTES) . ')');
exit;
}
die('update returned false');
exit;
}
?>
I already removed the die(); part in the first part of the code. I also tried to rename the variable of the second part (check -> check2). But it's still not working. What did I do wrong? Why isn't it possible to write two times in the mysql-database?
I receive a blank site without any errors. But still: The update didn't work. There is no new updated IPv6 entry in my database.

php page redirection to another page

i am using html canvas page for drawing online and i am linking it with save.php file which saves the drawing data from the canvas on my database
and this is the code of save.php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
//echo "ok1";
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$file = ''.rand().'';
$fp = fopen( $file.'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//echo "ok2";
$servername = "example";
$username = "example";
$password = "example";
$dbname = "example";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$usr = wp_get_current_user();
//$uid = (int) $usr->ID;
//echo "ok3";
//global $current_user1;
//$current_user = wp_get_current_user();
//global $current_user;
//get_currentuserinfo();
$root = dirname(dirname(__FILE__));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
//echo "EXISTS";
}
$user_id = get_current_user_id();
//echo "ok4";
$content1 = '<img class="alignnone wp-image-11" src="http://example.com/wp-includes/'.$file.'.png" alt="" />';
// $usr=get_current_user_id();
$sql = "INSERT INTO wp_njvt_posts (post_date,post_date_gmt,post_author, post_content, post_title, post_excerpt, post_password, post_name, to_ping, pinged, post_content_filtered, guid, post_mime_type)
VALUES (NOW(),NOW(),'$user_id','$content1', '', '', '','$file','','','','http://www.example.com/?p=$file','')";
$row_id = 0;
// $usr=0;
if ($conn->query($sql) === TRUE) {
echo "".$file.".png";
$row_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql2 = "UPDATE wp_njvt_posts SET guid = 'http://www.example.com/?p=$row_id' WHERE ID = $row_id" ;
if ($conn->query($sql2) === TRUE) {
echo " ***your drawing was published SUCCESSFULY!*** ";
//header("Location: http://www.example.com/?p=$row_id");
} else {
echo "Error:". $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
now the drawing gets a link like http://www.example.com/?p=$row_id and i tried redirect the user after publishing the drawing to that link and i tried it with
header("Location: http://www.example.com/?p=$row_id");
but it is not working with me!
any other solutions other than (header) ?

Weird behaviour of PHP Login

This is more like a debugging problem than an actual question. I have a login script in PHP which should check for user information from a local database and if present, then display them. Or else, redirect them to the Google OAuth2 Login process. The following php files concern the login flow :
google_login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require('http.php');
require('oauth_client.php');
require('../config.php');
require('StructuredQuery.php');
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile' );
$client = new oauth_client_class;
$sq= new StructuredQuery();
// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = GOOGLE_REDIRECT_URL;
$client->client_id = GOOGLE_CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = GOOGLE_CLIENT_SECRET;
if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('Please go to Google APIs console page ' .
'http://code.google.com/apis/console in the API access tab, ' .
'create a new client ID, and in the line ' . $application_line .
' set the client_id to Client ID and client_secret with Client Secret. ' .
'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->authorization_error)) {
$client->error = $client->authorization_error;
$success = false;
} elseif (strlen($client->access_token)) {
$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
}
}
$success = $client->Finalize($success);
}
if ($client->exit)
exit;
if ($success) {
// Now check if user exist with same email ID
try {
$result = $sq->getUserInfo($user->id);
if ($result["count"] > 0) {
// User Exist
$_SESSION["name"] = $result["name"];
$_SESSION["email"] = $result["email"];
$_SESSION["clevel"]=$result["clevel"];
$_SESSION["new_user"] = "no";
} else {
// New user, Insert in database
$result = $sq->putNewUserInfo($user->id,$user->name,$user->email);
if ($result===true) {
$_SESSION["name"] = $user->name;
$_SESSION["email"] = $user->email;
$_SESSION["new_user"] = "yes";
$_SESSION["e_msg"] = "";
}
}
$_SESSION["login_type"]="Google";
} catch (Exception $ex) {
$_SESSION["e_msg"] = $ex->getMessage();
}>
$_SESSION["user_id"] = $user->id;
} else {
$_SESSION["e_msg"] = $client->error;
}
header("Location: ".ROOT_DIR."homepage.php");
exit;
?>
StructuredQuery.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'config.php';
class StructuredQuery{
var $opt;
var $pdo;
function __construct(){
$opt = [
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO(DB_DRIVER.":host=".DB_SERVER.";dbname=".DB_NAME, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $opt);
}
// Cross Site Script & Code Injection Sanitization
function xss_cleaner($input_str) {
$return_str = str_replace( array('<',';','|','&','>',"'",'"',')','('), array('<',':','|','&','>','&apos;','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
//SQLInjection detect
function sql_injection_detect($input_query){
try{
$blacklist=array('SELECT','WHERE','UPDATE','DELETE','INSERT','FROM','DROP','MERGE','SET','INSERT','REMOVE','REPLACE','QUERY');
$err_level=0;
foreach($blacklist as $blacklist_item){
if(stripos($input_query,$blacklist_item)!==false){
$err_level++; //Counter for number of blacklist words used. 2 means dangerous. Terminate immediately.
if($err_level==2){
die('Was that an IT joke? Cause I am a 12th grader, not an IT Pro.');
}
}
}
return true;
}catch(Exception $e){
echo 'Exception Occured:',$e->getMessage(),"\n";
die('You\'ve been Terminated');
}
}
function getUserInfo($user_id){
$user_id=xss_cleaner($user_id);
if(sql_injection_detect($user_id)){
$query=$pdo->prepare("select statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->execute();
$result=$query->fetch();
$result["count"]=$query->rowCount();
return $result;
}
}
function putNewUserInfo($user_id,$name,$email){
$user_id=$this->xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email)){
$query=$pdo->prepare("insert statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->execute();
return true;
}else{
return false;
}
}
function modifyUserInfo($user_id,$name,$email,$clevel){
$user_id=xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
$clevel=xss_cleaner($clevel);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email) && sql_injection_detect($clevel)){
$query=$pdo->prepare("update statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->bindParam(":clevel",$clevel,PDO::PARAM_INT);
$query->execute();
return true;
}else{
return false;
}
}
}
Now the issue that bothers me is this- whenever i press Login With Google, it redirects to google_login.php, well and fine. And then, directly to the homepage as if I am already logged in even though I am not. Even weirder is that it displays my e-mail and my username as blank, even though it says that I am an existing user.
P.S. No, the database does not contain any blank entries and it works fine, I double-checked.

PDO Connection issue cannot Insert data into mysql DB

I just wanted to create PDO connection rather than old connection but I can't get form fields to be inserted into MYSQL DB. I am sure I am making a stupid mistake however I can't figure it out what exactly.
Here is my database.php file
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'dbaname';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
die( "Connection failed: " . $e->getMessage());
}
and after submit action is taking place at my process.php
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$Date = strip_tags(trim($_POST["Date"]));
$ToolSerial = strip_tags(trim($_POST["ToolSerial"]));
$CartridgeSerial = strip_tags(trim($_POST["CartridgeSerial"]));
$TorqueSerial = strip_tags(trim($_POST["TorqueSerial"]));
$LastCalibration = strip_tags(trim($_POST["LastCalibration"]));
$ThreadCond = strip_tags(trim($_POST["ThreadCond"]));
$HardfacingCond = strip_tags(trim($_POST["HardfacingCond"]));
$PocketCond = strip_tags(trim($_POST["PocketCond"]));
//$emailaddress = strip_tags(trim($_POST["emailaddress"]));
/*------------------ STEP 2 ------------------*/
$TorquedOEM = strip_tags(trim($_POST["TorquedOEM"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
//$file_url = strip_tags(trim($_POST["file_url"]));
$Notes = strip_tags(trim($_POST["Notes"]));
/*------------------ STEP 3 ------------------*/
//$Signature = strip_tags(trim($_POST["Signature"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
try {
$q = "INSERT INTO tportal (TechName, Date, ToolSerial, CartridgeSerial, TorqueSerial, LastCalibration, ThreadCond, HardfacingCond, PocketCond, TorquedOEM, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :Date, :ToolSerial, :CartridgeSerial, :TorqueSerial, :LastCalibration, :ThreadCond, :HardfacingCond, :PocketCond, :TorquedOEM, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":Date" => $Date,
":ToolSerial" => $ToolSerial,
":CartridgeSerial" => $CartridgeSerial,
":TorqueSerial" => $TorqueSerial,
":LastCalibration" => $LastCalibration,
":ThreadCond" => $ThreadCond,
":HardfacingCond" => $HardfacingCond,
":PocketCond" => $PocketCond,
":TorquedOEM" => $TorquedOEM,
":TorqueSerial" => $TorqueSerial,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
After I click on submit button I get a "Data not successfully inserted pass" pass: is variable result from $PocketCondvariable I placed to test the data.
Thank you for your time.
Apparently after refreshing the database I realized my entries were added to the database however my error scripts were creating problem.
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}

PHP get data from jquery

Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.

Categories