From 70e9b346ae98bf7211d88e72394f956f77ed1083 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Sun, 19 Nov 2017 20:01:49 +0100 Subject: [PATCH] Handle incoming message and delivered datetime --- bin/smsq | 71 +++++++++++++++++++++++----- data/mysql.init.sql | 12 +++-- includes/config.inc.php | 3 ++ includes/core.php | 1 + includes/db.php | 101 +++++++++++++++++++++++++++++++++++++--- includes/mail.php | 53 +++++++++++++++++++++ public_html/index.php | 12 +++-- 7 files changed, 228 insertions(+), 25 deletions(-) create mode 100644 includes/mail.php diff --git a/bin/smsq b/bin/smsq index 4da3f3d..65a842d 100755 --- a/bin/smsq +++ b/bin/smsq @@ -13,6 +13,8 @@ use GetOptionKit\OptionPrinter\ConsoleOptionPrinter; $specs = new OptionCollection; $specs->add('done', 'Show done queue.' ); +$specs->add('incoming', 'Show incoming queue.' ); +$specs->add('incoming-done', 'Show incomingi done queue.' ); $specs->add('h|help', 'Show this help message.' ); $specs->add('v|verbose', 'Enable verbose mode.' ); $specs->add('d|debug', 'Enable debug mode.' ); @@ -178,6 +180,9 @@ if (!empty($subcommandOptions)) { logging('DEBUG', 'Handle outgoing pending messages'); if (handle_outgoing_msgs() !== True) logging('ERROR', 'Error handling outgoing pending messages'); + logging('DEBUG', 'Handle incoming pending messages'); + if (handle_incoming_msgs() !== True) + logging('ERROR', 'Error handling incoming pending messages'); exit(0); break; case 'check-gateway': @@ -192,8 +197,11 @@ if (!empty($subcommandOptions)) { $uuid=$subcommandArgs[$subcmd][0]; $msg=get_outgoing_msg($uuid); if (!$msg) { - echo "Message $uuid not found.\n"; - exit(1); + $msg=get_incoming_msg($uuid); + if (!$msg) { + echo "Message $uuid not found.\n"; + exit(1); + } } echo "Message $uuid :\n"; echo "----------------------------------------------\n"; @@ -204,6 +212,8 @@ if (!empty($subcommandOptions)) { echo "Unique SMS gateway message ID : ".$msg['uniqueid']."\n"; if ($msg['nbfrag']) echo "Number of fragment(s) : ".$msg['nbfrag']."\n"; + if ($msg['delivered_datetime'] && $msg['delivered_datetime']!='0000-00-00 00:00:00') + echo "Delivered at : ".$msg['delivered_datetime']."\n"; echo "Last update : ".$msg['lastupdate']."\n"; echo "\nText :\n------\n"; echo preg_replace('/(^|\n)/',"\n ",wordwrap($msg['text'], 70, "\n", true)); @@ -228,15 +238,26 @@ if (!empty($subcommandOptions)) { $uuid=$subcommandArgs[$subcmd][0]; $msg=get_outgoing_msg($uuid); if (!$msg) { - echo "Message $uuid not found.\n"; + $msg=get_incoming_msg($uuid); + if (!$msg) { + echo "Message $uuid not found.\n"; + exit(1); + } + if (handle_incoming_msg($msg)===True) { + echo "Incoming SMS forwarded\n"; + exit(0); + } + echo "An error occured forwarding incoming SMS. Please see log file for more informations.\n"; exit(1); } - if (handle_outgoing_msg($msg)===True) { - echo "Message push on SMS gateway\n"; - exit(0); + else { + if (handle_outgoing_msg($msg)===True) { + echo "Message push on SMS gateway\n"; + exit(0); + } + echo "An error occured sending message on SMS gateway. Please see log file for more informations.\n"; + exit(1); } - echo "An error occured sending message on SMS gateway. Please see log file for more informations.\n"; - exit(1); break; case 'delete': $uuid=$subcommandArgs[$subcmd][0]; @@ -259,10 +280,16 @@ if (!empty($subcommandOptions)) { // Main command // Format messages queue output -function show_queue($q) { +function show_queue($q, $done=false) { $tbl = new Console_Table(); $tbl->setHeaders( - array('Id', 'Date', 'Recipient', 'Status', 'Text') + array( + 'Id', + 'Date', + 'Number', + ($done?'Delivered date':'Status'), + 'Text' + ) ); foreach($q as $msg) { $tbl->addRow( @@ -270,7 +297,7 @@ function show_queue($q) { $msg['uuid'], $msg['datetime'], $msg['number'], - $msg['status'], + ($done?$msg['delivered_datetime']:$msg['status']), (strlen($msg['text'])>40?substr($msg['text'],0,37)."...":$msg['text']) ) ); @@ -286,7 +313,29 @@ if (array_key_exists('done', $app_options->keys)) { echo "SMS done queue is empty.\n"; exit(0); } + show_queue($q, true); + echo count($q)." message(s) in done queue\n"; +} +elseif (array_key_exists('incoming', $app_options->keys)) { + $q = get_incoming_msgs('pending'); + if (!is_array($q)) + die("Invalid get_incoming_msgs() result !\n"); + if (empty($q)) { + echo "SMS incoming queue is empty.\n"; + exit(0); + } show_queue($q); + echo count($q)." message(s) in queue\n"; +} +elseif (array_key_exists('incoming-done', $app_options->keys)) { + $q = get_incoming_msgs('delivered'); + if (!is_array($q)) + die("Invalid get_incoming_msgs() result !\n"); + if (empty($q)) { + echo "SMS incoming done queue is empty.\n"; + exit(0); + } + show_queue($q, true); echo count($q)." message(s) in done queue\n"; } else { diff --git a/data/mysql.init.sql b/data/mysql.init.sql index 2f1fd3e..9452efd 100644 --- a/data/mysql.init.sql +++ b/data/mysql.init.sql @@ -8,7 +8,7 @@ SET time_zone = "+00:00"; /*!40101 SET NAMES utf8mb4 */; -- --- Database: `smsgw` +-- Database: `smsq` -- -- -------------------------------------------------------- @@ -18,11 +18,14 @@ SET time_zone = "+00:00"; -- CREATE TABLE `incoming_msg` ( + `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `uuid` varchar(40) NOT NULL, `number` text NOT NULL, `text` text NOT NULL, - `timestampms` int(11) NOT NULL, - `status` varchar(20) NOT NULL + `timestampms` bigint(20) NOT NULL, + `status` varchar(20) NOT NULL DEFAULT 'pending', + `lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `delivered_datetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- @@ -39,7 +42,8 @@ CREATE TABLE `outgoing_msg` ( `uniqueid` bigint(11) UNSIGNED NOT NULL, `nbfrag` int(11) NOT NULL, `status` varchar(30) NOT NULL DEFAULT 'pending', - `lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP + `lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `delivered_datetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- diff --git a/includes/config.inc.php b/includes/config.inc.php index 1096bac..a7802ff 100644 --- a/includes/config.inc.php +++ b/includes/config.inc.php @@ -29,6 +29,9 @@ $db_options=array(); * Config Mail */ +// Forward incoming SMS destination (mail address) +$forward_incoming_sms_to="user@domain.tld"; + $phpmail_path="Mail.php"; /* diff --git a/includes/core.php b/includes/core.php index c0ef413..7b3cefc 100644 --- a/includes/core.php +++ b/includes/core.php @@ -20,3 +20,4 @@ require_once('sms_gw_api.php'); $smsgw = new sms_gw_api($smsgw_url, $smsgw_ssl_verify, $smsgw_ws_connect_timeout, $smsgw_ws_timeout); require('db.php'); +require('mail.php'); diff --git a/includes/db.php b/includes/db.php index d130397..2b84538 100644 --- a/includes/db.php +++ b/includes/db.php @@ -44,6 +44,21 @@ function get_incoming_msg($uuid) { return -1; } +function get_incoming_msgs($status=false) { + global $fpdo; + $where=array(); + if ($status) + $where['status']=$status; + $result = $fpdo -> from('incoming_msg') + -> where($where) + -> execute(); + + if ($result !== false) { + return $result -> fetchAll(); + } + return -1; +} + function create_incoming_msg($number, $text, $timestampms) { global $fpdo; @@ -62,6 +77,76 @@ function create_incoming_msg($number, $text, $timestampms) { return $uuid; } +function handle_incoming_msg($msg) { + global $fpdo, $mail_sender, $forward_incoming_sms_to; + if (!is_array($msg)) + $msg=get_outgoing_msg($msg); + if (is_array($msg)) { + if ($msg['status']=='pending') { + /* + var_dump($msg); + array(6) { + ["datetime"]=> + string(19) "2017-11-19 19:05:26" + ["uuid"]=> + string(36) "c87e8945-94fd-45db-a32c-e5bf7f42fc28" + ["number"]=> + string(12) "+33612345678" + ["text"]=> + string(4) "test" + ["timestampms"]=> + string(13) "1511112645376" + ["status"]=> + string(7) "pending" + } + */ + $subject = "SMS from ".$msg['number']; + $body = "SMS received from ".$msg['number']." at ".$msg['datetime']."\n\n"; + $body .= "Text :\n"; + $body .= "------\n"; + $body .= wordwrap($msg['text'], 70, "\n", true); + + $headers = array ( + 'X-SMS-UUID' => $msg['uuid'], + ); + + if (send_mail($mail_sender ,$forward_incoming_sms_to ,$subject, $body, $headers) !== True) { + return -1; + } + + $result = $fpdo -> update('incoming_msg') + -> set( + array ( + 'status' => 'delivered', + 'lastupdate' => db_now(), + 'delivered_datetime' => db_now(), + ) + ) + -> where( + array ( + 'uuid' => $msg['uuid'], + ) + ) + -> execute(); + if ($result === false) + return -1; + } + return True; + } + return -1; +} + +function handle_incoming_msgs() { + $msgs=get_incoming_msgs('pending'); + if (!is_array($msgs)) + return -1; + foreach($msgs as $msg) { + if (handle_incoming_msg($msg) !== True) + return -1; + } + return True; +} + function get_outgoing_msg($uuid, $status=false) { global $fpdo; $where=array(); @@ -287,13 +372,15 @@ function get_outgoing_msg_status_from_frags($msg) { function update_outgoing_msg_status($uuid, $status) { global $fpdo; + $changes=array ( + 'status' => $status, + 'lastupdate' => db_now(), + ); + if ($status=='delivered') { + $changes['delivered_datetime'] = db_now(); + } $result = $fpdo -> update('outgoing_msg') - -> set( - array ( - 'status' => $status, - 'lastupdate' => db_now(), - ) - ) + -> set($changes) -> where( array ( 'uuid' => $uuid, @@ -314,7 +401,7 @@ function create_outgoing_msg_frag($msguid, $fragid, $status=false) { ); if ($status) $values['status']=strtolower($status); - + $result = $fpdo -> insertInto('outgoing_msg_frag',$values) -> execute(); if ($result === false) diff --git a/includes/mail.php b/includes/mail.php new file mode 100644 index 0000000..ce27b81 --- /dev/null +++ b/includes/mail.php @@ -0,0 +1,53 @@ + $to + ); + + foreach(array_keys($headers) as $header) { + if(strtoupper($header) == 'BCC') { + $to['BCC'] = $headers[$header]; + } + elseif(strtoupper($header) == 'CC') { + $to['CC'] = $headers[$header]; + } + } + + $ret = $mail_obj -> send($to,$headers,$msg); + + if ($ret instanceof PEAR_Error) { + logging('ERROR',"Error sending email to $to : ".$ret -> getMessage()); + return -1; + } + return true; +} diff --git a/public_html/index.php b/public_html/index.php index 7f391aa..0964e1a 100644 --- a/public_html/index.php +++ b/public_html/index.php @@ -6,6 +6,7 @@ $go=false; if (isset($_REQUEST['go'])) { $go=$_REQUEST['go']; } +logging('DEBUG',"Request (Go : $go) : ".print_r($_REQUEST,1)); $post_body=file_get_contents('php://input'); if ($post_body) { @@ -80,9 +81,14 @@ switch($go) { */ if (is_array($post_body) && check_phone_number($post_body['number']) && check_sms_text($post_body['text']) && check_integer($post_body['timestampMillis'])) { logging('INFO','Incoming SMS from '.$post_body['number']); - $msg=create_incoming_msg($post_body['number'], $post_body['text'], $post_body['timestampMillis']); - if (is_array($msg)) { - $data['status']='ok'; + $uuid=create_incoming_msg($post_body['number'], $post_body['text'], $post_body['timestampMillis']); + if (check_uuid($uuid)) { + if(handle_incoming_msg($uuid)===True) { + $data['status']='delivered'; + } + else { + $data['status']='pending'; + } } else { $data['status']='error';