<?php
/*
Plugin Name: Twilio
Description: Send Text messages and create voice apps
Version: 1.10
Requires at least: 2.52
Required System Plugin: True
*/

$GLOBALS['TWILIO_TEST_MODE']          = false;
//$GLOBALS['TWILIO_CONNECTION_URL']     = "http://borsdev.com/twilio_voice_test/test.php";

//TEST DETAILS.
$GLOBALS['TWILIO_TEST_PHONE_NUMBER']  = '+18667474424'; 
/*
  * Possible 'magic' test numbers:
  *   +15005550000  This phone number is unavailable.  21422
  *   +15005550001  This phone number is invalid.  21421
  *   +15005550006  This phone number is valid and available.  No error
*/
$GLOBALS['TWILIO_TEST_API_KEY']       = 'AC257fb814d5d0457516330fb3979ea9c5';
$GLOBALS['TWILIO_TEST_AUTH_TOKEN']    = '65777aa2c8d49c20d949c72d53df6470';

//LIVE DETAILS
$GLOBALS['TWILIO_LIVE_PHONE_NUMBER']  = '+18667474424';  //+14155992671
/*
  * Note: You can use your account test number here if you haven't registered a number,
  *       but you will still be charged for costs. You can find these details here:
  *       https://www.twilio.com/user/account/voice-sms-mms
*/
$GLOBALS['TWILIO_LIVE_API_KEY']       = 'AC257fb814d5d0457516330fb3979ea9c5'; //AC0fdbfefec9df760ce4aafa59efcd018d
$GLOBALS['TWILIO_LIVE_AUTH_TOKEN']    = '65777aa2c8d49c20d949c72d53df6470';   //dd22d86d41a84e5527c8b4f08f7d370b


//list($errors, $success) = twilio_sendSMS($phoneNumber, $message);
//This function is used to send messages via SMS.
function twilio_sendSMS($phoneNumber, $message, $dontLog) {

  //Set function variables.
  global $GLOBALS;
  $errorsAndAlerts = "";
  $success         = "";

  //Basic error checking.
  if(!$phoneNumber) { return false; }
  if(!$message)     { return false; }

  //Set the from phone number
  $fromPhoneNumber = ($GLOBALS['TWILIO_TEST_MODE']) ? $GLOBALS['TWILIO_TEST_PHONE_NUMBER'] : $GLOBALS['TWILIO_LIVE_PHONE_NUMBER'];

  //Set up the post data to be sent.
  $postData         = array();
  $postData['To']   = $phoneNumber;
  $postData['Body'] = $message;
  $postData['From'] = $fromPhoneNumber;

  //Carry out API call.
  list($html, $httpStatusCode, $headers, $request) =  getPage(_twilio_buildBaseAPIUrl()."Messages.json?". http_build_query($postData) ,  5, array(), true, '');

  //Convert returned json data into an array.
  $returnedData = json_decode($html, true);

  //Log returned data.
  twilio_logSMSMessageSend($message, $phoneNumber, $fromPhoneNumber, $html, $dontLog, $httpStatusCode);

  //If message sent successfully:
  if(in_array($httpStatusCode, array('200', '201')) && !@$returnedData['error_code']){
    $success = "Message successfully sent";
  }else{
    //Handle the various error code types here:
    if(@$returnedData['error_code']){
      $errorsAndAlerts .= "#{$returnedData['error_code']} : {$returnedData['error_message']}<br>\n";  
    }elseif(@$returnedData['code']){
      $errorsAndAlerts .= "#{$returnedData['code']} : {$returnedData['message']}<br>\n";   
    }else{
      $sid = @$returnedData['sid'];
      $errorsAndAlerts .= "Error with SID: $sid. Please contact the site developer!<br>\n";  
    }
    
  }

  //Return errors / success.
  return array($errorsAndAlerts, $success);

}


function validCellNumber($number){

  $number = preg_replace("/[^0-9+]/",  "", $number);
  $url    = "https://{$GLOBALS['TWILIO_LIVE_API_KEY']}:{$GLOBALS['TWILIO_LIVE_AUTH_TOKEN']}@lookups.twilio.com/v1/PhoneNumbers/".urlencode($number)."?Type=carrier";

  list($response, $statusCode) = getPage($url);
  
  if($statusCode == '200'){
    return true;
  }else{
    return false;
  }

  return true;
}


function formatCellNumber($number, $errorlog = true){

  $error = "";

  $number = preg_replace("/[^0-9+]/", "", $number);
  $url    = "https://{$GLOBALS['TWILIO_LIVE_API_KEY']}:{$GLOBALS['TWILIO_LIVE_AUTH_TOKEN']}@lookups.twilio.com/v1/PhoneNumbers/".urlencode($number)."?Type=carrier";

  list($response, $statusCode) = getPage($url);
  
  if($statusCode == '200'){
    $numberData = json_decode($response, true);
    if($errorlog)
      return $numberData['phone_number'];
    else
      return array($error, $numberData['phone_number']);
  }else{
    if($errorlog){
      trigger_error("Phone number $number is not in correct format.", E_USER_NOTICE);
    }else{
      $error = "Phone number $number is not in correct format.";
      return array($error, $number);
    }
  }
}



// ask Twilio to make a call
function twilio_makeCall($phoneNumber, $twimlUrl, $dontLog) {
  global $GLOBALS;

  $errorsAndAlerts = "";
  $success         = "";

  if (!$phoneNumber) { die(__FUNCTION__ . ": phoneNumber is required"); }
  
  $fromNumber = $GLOBALS['TWILIO_TEST_MODE'] ? $GLOBALS['TWILIO_TEST_PHONE_NUMBER'] : $GLOBALS['TWILIO_LIVE_PHONE_NUMBER'];
  
  $postData = array(
    'To'   => $phoneNumber,
    'From' => $fromNumber,
    'Url'  => realUrl($twimlUrl),
  );
  
  $apiUrl = _twilio_buildBaseAPIUrl() . "Calls.json?" . http_build_query($postData);
  
  
  list($html, $httpStatusCode, $headers, $request) = getPage($apiUrl, 5, array(), true, '');


  twilio_logPhoneCall($html, $phoneNumber, $fromNumber, $apiUrl, $dontLog, $httpStatusCode);

  //If message sent successfully:
  if(in_array($httpStatusCode, array('200', '201')) && !@$returnedData['error_code']){
    $success = "Message successfully sent";
  }else{
    //Handle the various error code types here:
    if(@$returnedData['error_code']){
      $errorsAndAlerts .= "#{$returnedData['error_code']} : {$returnedData['error_message']}<br>\n";  
    }elseif(@$returnedData['code']){
      $errorsAndAlerts .= "#{$returnedData['code']} : {$returnedData['message']}<br>\n";   
    }else{
      $sid = @$returnedData['sid'];
      $errorsAndAlerts .= "Error with SID: $sid. Please contact the site developer!<br>\n";  
    }
    
  }

  //Return errors / success.
  return array($errorsAndAlerts, $success);

}



function _twilio_buildBaseAPIUrl() {
  
  global $GLOBALS;

  if ($GLOBALS['TWILIO_TEST_MODE']) {
    return "https://{$GLOBALS['TWILIO_TEST_API_KEY']}:{$GLOBALS['TWILIO_TEST_AUTH_TOKEN']}@api.twilio.com/2010-04-01/Accounts/{$GLOBALS['TWILIO_TEST_API_KEY']}/";
  }else{
    return "https://{$GLOBALS['TWILIO_LIVE_API_KEY']}:{$GLOBALS['TWILIO_LIVE_AUTH_TOKEN']}@api.twilio.com/2010-04-01/Accounts/{$GLOBALS['TWILIO_LIVE_API_KEY']}/";
  }

}

function twilio_logCallConnectionData(){

  $insertArray                          = array();
  $insertArray['createdDate']           = date('Y-m-d H:i:s');
  $insertArray['updatedDate']           = date('Y-m-d H:i:s');
  $insertArray['request_data_recieved'] = @json_encode($_REQUEST);
  mysql_insert('twilio_connection_log', $insertArray);
}

function twilio_logSMSMessageSend($jsonData, $toPhoneNumber, $fromPhoneNumber, $apiData, $dontLog, $statusCode = 200){
  
  $insertArray                        = array();
  $insertArray['createdDate']         = date('Y-m-d H:i:s');
  $insertArray['updatedDate']         = date('Y-m-d H:i:s');
  $insertArray['message']             = $jsonData;
  $insertArray['http_status_code']    = $statusCode;
  $insertArray['from_phone_number']   = $fromPhoneNumber;
  $insertArray['to_phone_number']     = $toPhoneNumber;
  $insertArray['returned_api_values'] = $apiData;

  //Remove any items that shouldn't appear in the log.
  foreach($insertArray as $key => $item){
    foreach($dontLog as $remove){
      $insertArray[$key] = str_replace($remove, "xxxxx", $item);
    }
  }
  
  mysql_insert('twilio_sms_log', $insertArray);

}


function twilio_logPhoneCall($message, $toPhoneNumber, $fromPhoneNumber, $urlCalled, $dontLog,$statusCode = 200){
  
  //Create the insert array.
  $insertArray                          = array();
  $insertArray['createdDate']           = date('Y-m-d H:i:s');
  $insertArray['updatedDate']           = date('Y-m-d H:i:s');
  $insertArray['request_data_recieved'] = $message;
  $insertArray['http_status_code']      = $statusCode;
  $insertArray['from_phone_number']     = $fromPhoneNumber;
  $insertArray['to_phone_number']       = $toPhoneNumber;
  $insertArray['url_called']            = $urlCalled;  


  //Remove any items that shouldn't appear in the log.
  foreach($insertArray as $key => $item){
    foreach($dontLog as $remove){
      $insertArray[$key] = str_replace($remove, "xxxxx", $item);
    }
  }

  mysql_insert('twilio_phone_log', $insertArray);

}



