Odyssey
cu_sms.i
1 <?php
2 
3  // ** HOMECU LONG CODE
4  $HOMECU_LONGCODE_API_KEY = "2A5625EB08229DA1179F36ED064EF52F9ED14E30";
5  $HOMECU_LONGCODE_URL = 'https://sms.tsgglobal.com/jsonrpc?apiVersion=1.0&key=#key#'; // ** JSON URL
6  $HOMECU_LOGFILE = "/home/homecu/smslog/transport_longcode.log";
7 
8 
9 /*
10  * Function: SendLongCodeSMS
11  * Purpose: This will be used to send messages using the TSG Global
12  * Long Code API
13  * Parameters: p_hb_api_key -- This is the HomeBanking API Key, I am passing it in
14  * to help encapsulate this function AND at this time I don't know if there
15  * is a separate API Key for each long code
16  * p_hb_url -- This is the URL that the message will be posted to, the API KEY will
17  * be coded with #key# so I can easily replace
18  * p_hb_from_nbr -- This is the Credit Union Long Code that the message is being sent from
19  * p_hb_to_nbr -- This is the Member's phone number that is receiving the message
20  * p_hb_msg -- This is the actual message being sent. It should be limited to 160 chars,
21  * but I will trim as well to ensure length restriction
22  * Returns: Will return a true or false. Will only return false if no response from server.. -- At this time
23  * I do not know what I want to do with failed requests
24 */
25 function SendLongCodeSMS($p_hb_api_key, $p_hb_url, $p_hb_from_nbr, $p_hb_to_nbr, $p_hb_msg) {
26  $retVal = true;
27 
28  $debug = 0;
29 
30 
31  if ($debug) {WriteTransportLog($GLOBALS['HOMECU_LOGFILE'], "\nStart: " . date('Ymd-H:i:s'));}
32  // ** VALIDATE THE INFORMATION BEFORE CONTINUING -- Make sure they appear to be valid numbers
33  $pattern = '/^[+]{0,1}[0-9]{1,12}$/';
34  if (!preg_match($pattern, $p_hb_from_nbr)) {
35  if ($debug) {WriteTransportLog($GLOBALS['HOMECU_LOGFILE'], "Fail: Invalid FROM: {$p_hb_from_nbr}");}
36  return false;
37  }
38 
39  if (!preg_match($pattern, $p_hb_to_nbr)) {
40  if ($debug) {WriteTransportLog($GLOBALS['HOMECU_LOGFILE'], "Fail: Invalid To: {$p_hb_to_nbr}");}
41  return false;
42  }
43 
44 /*
45  * TSG updated their service. If the destination DID does NOT have a 1 for before the area code, the request fails
46  * If the length is exactly 10, then assume it does not have the area code and add it there
47  */
48  if (strlen($p_hb_to_nbr) == 10) {
49  $p_hb_to_nbr = "1" . $p_hb_to_nbr;
50  }
51  // ** SETUP THE API URL
52  $api_url = str_replace('#key#', $p_hb_api_key, $p_hb_url);
53 
54  // * the api will accept json values. So I will first create the Associative array, then translate to json
55  // * then send to url
56 
57  $api_msg_ary = Array(
58  "method"=>"sms.send",
59  "params"=>Array($p_hb_from_nbr, $p_hb_to_nbr, $p_hb_msg, 1),
60  "id"=>""
61  );
62  $api_msg_json = json_encode($api_msg_ary);
63 
64  // ** MWS
65  // I had previously preforemd the Escape Cmd prior to the json_encode when I was building the array. However, when an apostrophe showed up in the
66  // message it was causing a syntax error from escaped double quotes. The message was never sent.
67  // I believe calling EscapeCmd after encoding json should work. Apostrophes are not created by json_encode.
68  $api_msg_json = EscapeCmd($api_msg_json);
69  $pipe_err=0;
70 
71  $api_response = "";
72 
73  $opts = "--connect-timeout 5 --retry 3 --retry-delay 2";
74 
75  // ** ALSO pass a -3 on the command. This fixes an error where I was getting an error similar to * error:14077458:SSL routines:SSL23_GET_SERVER_HELLO:reason(1112)
76  // ** the error seems to be when the server was expecting SSLv3
77 
78  if ($debug) {WriteTransportLog($GLOBALS['HOMECU_LOGFILE'], "PHCMD: " . "/usr/bin/curl -k -N --silent $opts -X POST -H 'Content-Type: application/json' -d '$api_msg_json' '$api_url'");}
79 
80  $fd = popen("/usr/bin/curl -k -N --silent $opts -X POST -H 'Content-Type: application/json' -d '$api_msg_json' '$api_url'","r");
81 
82  if (!$fd) {
83  // ** CREATE THE ERROR in the same expected format as the JSON-RPC
84  $api_response = '{"result":null,"error":{"code":"FAILOPEN","message":"Unable to open open portal.","data":null},"id":null}';
85  } else {
86  while ($buff = fread ($fd, 1500)) {
87  $api_response .= $buff;
88  }
89  $pipe_err = pclose($fd);
90  }
91 
92  // ** AT THIS POINT -- I WANT SAVE THE LOG
93  if ($debug) {WriteTransportLog($GLOBALS['HOMECU_LOGFILE'], "From:{$p_hb_from_nbr}\tTo:{$p_hb_to_nbr}\tSEND:{$api_msg_json}\tAPI:$api_url\tRESPONSE:{$api_response}");}
94  // ** We can now decode the response
95  $api_response = json_decode($api_response, true);
96  if (!is_array($api_response)) {
97  // ** PROBLEM THIS SHOULD BE AN ARRAY
98  $retVal = false;
99  /*
100  * FIRST check to see if an error was returned from the request
101  */
102  } elseif (HCU_array_key_value('error', $api_response) != '') {
103  // ** Error happened
104  $retVal = false;
105  /*
106  * TSG GLobal SMS API
107  * Returns a value nvs_code with the request
108  * -- S - SMS Request successful
109  * -- I - Invalid Request
110  *
111  */
112  } elseif (HCU_array_key_value('nvs_code', $api_response['result']['status']) != 'S') {
113  // ** Invalid Request
114  $retVal = false;
115  }
116 
117  return $retVal;
118 
119 }
120 
121 
122 /**
123  * Use the AWS SMS service for sending out the function.
124  * This function will make a shell call to the python script sendAwsSms.py
125  *
126  * @param string $pPhoneNbr - The phone number receiving the message
127  * @param string $pSubject - Subject that will be attached to the message
128  * @param string $pMessage - The message being sent to user
129  * @param boolean $pTransaction - Treat this message as Critical? Setting to True will identify the message as Transactional instead of Promotional
130  *
131  * @return boolean - Success or not
132  */
133 function SendAwsSMS($pPhoneNbr, $pSubject, $pMessage, $pTransaction=false) {
134  $bolRet = false;
135 
136  try {
137  /*
138  * If any option is empty then send an error
139  */
140 
141  /* ** Validation ** */
142  if ($pPhoneNbr == '' || $pSubject == '' || $pMessage == '') {
143  throw new exception ("Empty parameters");
144  }
145 
146  // ** sanitize phone number and make sure it starts with 1..
147  // Presuming 10 digits does not have a 1
148  if (strlen($pPhoneNbr) == 10) {
149  $pPhoneNbr = "1" . $pPhoneNbr;
150  }
151  /* ** Configuration ** */
152  // Python script name
153 
154  $pyFile = dirname(__FILE__) . "/../../shared/scripts/sendAwsSms.py";
155 
156  /* ** Options ** */
157  $opts = "-p " . escapeshellarg($pPhoneNbr) . " -s " . escapeshellarg($pSubject) . " -m " . escapeshellarg($pMessage) . " ";
158 
159  if ($pTransaction) {
160  $opts .= " -t ";
161  }
162  /* ** Create Command ** */
163  $command = escapeshellcmd('python3') . " {$pyFile} $opts ";
164 
165  /* ** Execute Command ** */
166  $smsResponse = exec($command);
167 
168  if ($smsResponse != '') {
169  // ** Try and decode the json value that is being returned
170 
171  $dataResp = json_decode($smsResponse, true);
172  switch (json_last_error()) {
173  case JSON_ERROR_NONE:
174  // ** ALL IS GOOD
175  break;
176  case JSON_ERROR_DEPTH:
177  case JSON_ERROR_STATE_MISMATCH:
178  case JSON_ERROR_CTRL_CHAR:
179  case JSON_ERROR_SYNTAX:
180  case JSON_ERROR_UTF8:
181  default:
182  throw new Exception ("Invalid Format");
183  break;
184  }
185  /*
186  * Program should normally return the array
187  * [status]
188  * [response]
189  * [error]
190  *
191  */
192  if (is_array($dataResp)) {
193  if (array_key_exists('status', $dataResp)) {
194  $respStatus = $dataResp['status'];
195 
196  if ($respStatus == '000') {
197  $bolRet = true;
198  }
199  }
200  }
201  }
202 
203  } catch (exception $ex) {
204  // ** catch most generic errors --
205  // ** When logging gets enabled, would be nice to track the error
206 
207  $bolRet = false;
208  }
209 
210 
211  return $bolRet;
212 }
213 
214 
215 /*
216  * Function: WriteTransportLog
217  * Purpose: This will be used mainly in testing / developing while we are evaluating this new TXT 2.0 feature
218  * Parameters:
219  p_logfile - Name of the logfile
220  p_msg - Message that will be saved to the file
221  * Returns: Nothing returned
222  * Purpose: To open the log file p_logfile, and append the message p_msg
223 */
224 function WriteTransportLog($p_logfile, $p_msg) {
225 
226  $fh = fopen ($p_logfile, "a");
227  fwrite($fh, $p_msg. "\n");
228  fclose($fh);
229 
230 }
231 
232 
233 /*
234  * Function: EscapeCmd
235  * Purpose: I want to try and protect the information being passed to teh command line, however, for the most part
236  * it is already protected because I am using ' apostrophe, however, I need to make sure they don't exist
237  * and if they do I need to replace them with a string that will not break the command
238  * Parameters:
239  p_str -- The string to be parsed
240  * Returns: the altered string
241 */
242 function EscapeCmd ($p_str) {
243 
244  $p_str = preg_replace("/'/", "'\"'\"'", $p_str);
245 
246  return $p_str;
247 }
248 
249 /*
250  TSG GLOBAL Reponses can be
251 Array
252 (
253  [result] => Array
254  (
255  [sender] => +CU_LONGCODE
256  [recipient] => +MBR_NBR
257  [location] => Idaho, United States
258  [status] => Array
259  (
260  [code] => 200
261  [nvs_code] => S
262  [message] => Valid number, SMS delivered
263  )
264 
265  [carrier] => 999
266  [sms_id] =>
267  )
268 
269  [id] =>
270  [error] =>
271 )
272 
273 
274 Array
275 (
276  [response] =>
277  [error] => Decoding failed: Syntax error
278 )
279 
280 
281 
282 */
283