Sending SMS message using Nexmo, failed when using private network - php

My code is working when I am using a direct internet (open network). but when I tried to use a private network (which i am currently using in my company) I am getting this error.
Warning: Invalid argument supplied for foreach() in E:\Files\xampp\xampp\htdocs\nexmo\src\NexmoMessage.php on line 228
Below is my code for sending the message..
<?php
include ( "src/NexmoMessage.php" );
if(isset($_POST['sendMessage'])){
$to = $_POST['to'];
$message = $_POST['smsMessage'];
// Step 1: Declare new NexmoMessage.
$nexmo_sms = new NexmoMessage('xxxxxxxx', 'xxxxxxxxx');
// Step 2: Use sendText( $to, $from, $message ) method to send a message.
$info = $nexmo_sms->sendText( $to, 'NexmoWorks', $message );
// Step 3: Display an overview of the message
//echo $nexmo_sms->displayOverview($info);
// Done!
}
?>
and below is the code where i am having an error.
foreach($obj as $key => $val){
// If we come across another class/array, normalise it
if ($val instanceof stdClass || is_array($val)) {
$val = $this->normaliseKeys($val);
}
// Replace any unwanted characters in they key name
if ($is_obj) {
$new_obj->{str_replace('-', '', $key)} = $val;
} else {
$new_obj[str_replace('-', '', $key)] = $val;
}
}

Related

Sodium Crypto box seal open not working in PHP

So I'm trying to get libsodium's sodium_crypto_box_seal and sodium_crypto_box_seal_open working but for some reason, the open is failing and I can't work out why.
So in all my trying to get this working, I have built a test system that a single PHP file that tests how it would work cross server.
<pre>
<?php
/*** Client Sending ***/
// saved argument
$remotePublic = "DXOCV4BU6ptxt2IwKZaP23S4CjLESfLE+ng1tMS3tg4=";
// create out key for this message
$key = sodium_crypto_box_keypair();
// encrypt our message using the remotePublic
$sealed = sodium_crypto_box_seal("This is a test", base64_decode($remotePublic));
$send = json_encode((object)array("pub" => base64_encode(sodium_crypto_box_publickey($key)), "msg" => base64_encode($sealed)));
echo "Sending : {$send} \r\n";
/*** Server Setup ***/
$payload = json_decode($send);
$apps =
array (
'test' =>
array (
'S' => 'lv/dT3YC+Am1MCllkHeA2r3D25HW0zPjRrqzR8sepv4=',
'P' => 'DXOCV4BU6ptxt2IwKZaP23S4CjLESfLE+ng1tMS3tg4=',
),
);
/*** Server Opening ***/
$msg = $payload->msg;
$key = sodium_crypto_box_keypair_from_secretkey_and_publickey(base64_decode($apps['test']['S']), base64_decode($apps['test']['P']));
$opened = sodium_crypto_box_seal_open(base64_decode($msg), $key);
echo "Opened : {$opened} \r\n";
/*** Server Responding ***/
$sealedResp = base64_encode(sodium_crypto_box_seal("We Got your message '{$opened}'", base64_decode($payload->pub)));
echo "Responding : {$sealedResp}\r\n";
/*** Client Receiving ***/
$received = sodium_crypto_box_seal_open(base64_decode($sealedResp), $key);
echo "Received : {$received}\r\n";
/*** Sanity Checking ***/
if($received == "We Got your message 'This is a test'"){
echo "Test Successfull.\r\n";
}else{
echo "Test Failed got '{$received}' is not \"We Got your message 'This is a test'\"\r\n";
}
?>
</pre>
Output is:
Sending : {"pub":"DS2uolF5lXZ1E3rw0V2WHELAKj6+vRKnxGPQFlhTEFU=","msg":"VVYfphc2RnQL2E8A0oOdc6E\/+iUgWO1rPd3rfodjLhE+slEWsivB6QiaLiMuQ31XMP\/1\/s+t+CSHu8QukoY="}
Opened : This is a test
Responding : cvDN9aT9Xj7DPRhYZFGOR4auFnAcI3qlwVBBRY4mN28JmagaR8ZR9gt6W5C0xyt06AdrQR+sZFcyb500rx6iDTEC4n/H77cUM81vy2WfV8m5iRgp
Received :
Test Failed got '' is not "We Got your message 'This is a test'"
There's two problems here.
First -- in this step under "Server Opening":
$opened = sodium_crypto_box_seal_open($msg, $key);
$msg is still Base64 encoded, so trying to decrypt it will fail.
Second -- the public key that is included in the "pub" field of $send is the public key of a random keypair that was generated by sodium_crypto_box_keypair(), not the same public key as $remotePublic or the pair in $apps. This key is overwritten by a call to sodium_crypto_box_keypair_from_secretkey_and_publickey() later in the application, making the original message unrecoverable.

Telegram bot send file and text PHP

I've got a basic bot set up that will send text back to the user, now I also want to send the user an audio message. But that I cannot do, here is the code.
I'm also using this https://github.com/Eleirbag89/TelegramBotPHP to send the audio
include("Telegram.php);
define('BOT_TOKEN', 'tokentoken');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$telegram = new Telegram(BOT_TOKEN);
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$reply = sendMessage($message);
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
function sendMessage(&$string) {
switch ($string) {
case "Hi":
$message = "Hi Back";
sendAudio();
break;
case "Bye":
$message = "Bye Bye";
break;
default:
$message = "Default";
}
return $message
}
func sendAudio() {
$sound = curl_file_create('sampleAudio.mp3', 'audio/mp3');
$newContent = array('chat_id' => $chatID, 'audio' => $sound);
$telegram->sendAudio($newContent);
}
Calling the code outside of the functions works, but than the user gets the file each time they type something. I experimenting so a bit of explanation would be great.
You have some errors:
First line " is unclosed
Last function, you've typed "func" instead of "function"
In sendAudio() you've used $chatID but you've to pass it as a parameter of sendAudio() or to set is as global.

SMPP: the UDH (User Data Header) appears in the body of sms

I would like to send long SMS with SMPP. I use this class php-smpp: https://github.com/agladkov/php-smpp/tree/master
and the doc http://opensmpp.org/specs/smppv34_gsmumts_ig_v10.pdf
However when I receive sms they are not concatenated.
Each sms Contains the following characters at the beginning: é¥ò#$$ (first sms) and é#¥$$$ (second sms)
These characters correspond to the UDH
esm_class = 0x40 ( for enable UDH )
public function sendSMS(SmppAddress $from, SmppAddress $to, $message, $tags=null, $dataCoding=SMPP::DATA_CODING_ISO8859_1, $priority=0x00, $scheduleDeliveryTime=null, $validityPeriod=null)
{
...
$seqnum = 1;
foreach ($parts as $part)
{
$udh = pack('cccccc',5,0,3,substr($csmsReference,1,1),count($parts),$seqnum);
$res = $this->submit_sm($from, $to, $udh.$part, $tags, $dataCoding, $priority, $scheduleDeliveryTime, $validityPeriod, (SmppClient::$sms_esm_class|0x40));
$seqnum++;
}
...
}
protected function submit_sm(SmppAddress $source, SmppAddress $destination, $short_message=null, $tags=null, $dataCoding=SMPP::DATA_CODING_DEFAULT, $priority=0x00, $scheduleDeliveryTime=null, $validityPeriod=null, $esmClass=null)
{
if (is_null($esmClass)) $esmClass = self::$sms_esm_class;
// Construct PDU with mandatory fields
$pdu = pack('a2cca'.(strlen($source->value)+1).'cca'.(strlen($destination->value)+1).'ccc'.($scheduleDeliveryTime ? 'a16x' : 'a1').($validityPeriod ? 'a16x' : 'a1').'ccccca'.(strlen($short_message)+(self::$sms_null_terminate_octetstrings ? 1 : 0)),
self::$sms_service_type,
$source->ton,
$source->npi,
$source->value,
$destination->ton,
$destination->npi,
$destination->value,
$esmClass,
self::$sms_protocol_id,
$priority,
$scheduleDeliveryTime,
$validityPeriod,
self::$sms_registered_delivery_flag,
self::$sms_replace_if_present_flag,
$dataCoding,
self::$sms_sm_default_msg_id,
strlen($short_message),//sm_length
$short_message//short_message
);
// Add any tags
if (!empty($tags)) {
foreach ($tags as $tag) {
$pdu .= $tag->getBinary();
}
}
$response=$this->sendCommand(SMPP::SUBMIT_SM,$pdu);
$body = unpack("a*msgid",$response->body);
return $body['msgid'];
}
Any help is appreciated.
When I added UDH fragmentaion support in "esme", I had same problem. But my problem was that UDHI was ignored (by my test server - i fixed that after that messages :)). If you receive wrong SMS on MS then you can try to implement SAR fragmentation, because it is used widely. SAR fragmentation is very similar, but you should set optional TLV parameters which start with sar_*

JSON encoding headers using Sendgrid

I am trying to change the filter status for the 'subscriptiontrack' using sendgrid. I think I am sending the headers incorrectly, but not totally sure. Working inside a symfony 1.4 framework.
First I create an object of the header settings
$hdr = new SmtpApiHeader();
$hdr->addFilterSetting('subscriptiontrack', 'enable', 0);
$hdr->as_string();
which sets the filter settings and encodes the string
Then I send it off the email class
sendTestEmail::sendEmail($contents, $mailFrom, $testGroup, $subject, $hdr);
SvaSmtpApiHeader.class.php
class SmtpApiHeader
{
function addFilterSetting($filter, $setting, $value)
{
if (!isset($this->data['filters'])) {
$this->data['filters'] = array();
}
if (!isset($this->data['filters'][$filter])) {
$this->data['filters'][$filter] = array();
}
if (!isset($this->data['filters'][$filter]['settings'])) {
$this->data['filters'][$filter]['settings'] = array();
}
$this->data['filters'][$filter]['settings'][$setting] = $value;
}
function asJSON()
{
$json = json_encode($this->data);
// Add spaces so that the field can be folded
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
return $json;
}
function as_string()
{
$json = $this->asJSON();
$str = "X-SMTPAPI: " . wordwrap($json, 76, "\n ");
return $str;
}
}
myEmail.class.php
<?php
class sendTestEmail
{
public static function sendEmail($contents, $mailFrom, $mailTo, $subject, $sgHeaders = null, $attachments = null)
{
try {
/*
* Load connection for mailer
*/
$connection = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 465, 'ssl')->setUsername(sfconfig::get('app_sendgrid_username'))->setPassword(sfconfig::get('app_sendgrid_password'));
// setup connection/content
$mailer = Swift_Mailer::newInstance($connection);
$message = Swift_Message::newInstance()->setSubject($subject)->setTo($mailTo);
$message->setBody($contents, 'text/html');
// if contains SMTPAPI header add it
if (null !== $sgHeaders) {
$message->getHeaders()->addTextHeader('X-SMTPAPI', $sgHeaders);
}
// update the from address line to include an actual name
if (is_array($mailFrom) and count($mailFrom) == 2) {
$mailFrom = array(
$mailFrom['email'] => $mailFrom['name']
);
}
// add attachments to email
if ($attachments !== null and is_array($attachments)) {
foreach ($attachments as $attachment) {
$attach = Swift_Attachment::fromPath($attachment['file'], $attachment['mime'])->setFilename($attachment['filename']);
$message->attach($attach);
}
}
// Send
$message->setFrom($mailFrom);
$mailer->send($message);
}
catch (Exception $e) {
throw new sfException('Error sending email out - ' . $e->getMessage());
}
}
}
The email is getting sent properly, but the unsubscribe option is still showing up at the bottom. Is this an issue with the header object or a problem with encoding for the header? Is the variable is still an object when getting added to the headers?
You're misunderstanding how JSON encoding works. Let's take a look at your as_string method:
function as_string()
{
$json = $this->asJSON();
$str = "X-SMTPAPI: " . wordwrap($json, 76, "\n ");
return $str;
}
This would output something to the effect of:
X-SMTPAPI: { "filters": { "subscriptiontrack": { "settings": { "enable": 0 } } } }
You should note that this isn't valid JSON because it is prefixed with "X-SMTPAPI". Instead, you should be calling asJSON, but SwiftMailer doesn't know that.
Try switching the header line to:
$message->getHeaders()->addTextHeader('X-SMTPAPI', $sgHeaders->asJSON());
If that doesn't work, can you give us a dump of:
$headers = $message->getHeaders();
echo $headers->toString();
And have you thought about using the official PHP library instead? https://github.com/sendgrid/sendgrid-php

Zend_Mail and =0D=0A=3D=3D=3D=3D=3D

I'm writing a help desk pipe handler to pipe incoming e-mails as helpdesk ticket replies. Some e-mails are coming in perfectly fine, others are coming in as a jumble of the text and =3D's all munged into one giant string. Does anyone have an idea on how to decode that into plain text.
For reference, this is my mail parser function:
public function parseEmailMessage(Zend_Mail_Message $msg)
{
if ($msg->isMultiPart()) {
$arrAttachments = array();
$body = '';
// Multipart Mime Message
foreach (new RecursiveIteratorIterator($msg) as $part) {
try {
$mimeType = strtok($part->contentType, ';');
// Parse file name
preg_match('/name="(?<filename>[a-zA-Z0-9.\-_]+)"/is', $part->contentType, $attachmentName);
// Append plaintext results to $body
// All other content parts will be treated as attachments
switch ($mimeType) {
case 'text/plain':
$body .= trim($part->getContent()) . "\n";
break;
case 'text/html':
$body .= trim(strip_tags($part->getContent));
break;
default:
$arrAttachments[] = array(
'attachment_mime' => $mimeType,
'attachment_name' => $this->filterFileName($attachmentName['filename']),
'base64data' => trim($part->getContent())
);
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
return array($body, $arrAttachments);
} else {
// Plain text message
return array(trim($msg->getContent()), array());
}
}
I'll take a guess that somehow the content type is not correctly specified and Zend doesn't know how to decode it. I know I've seen this before, but I can't remember where or how it was 'solved'.
It looks like quoted-printable being treated like plain text.

Categories