-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.php
629 lines (518 loc) · 23 KB
/
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
<?php
/**
*
* SMS Gateway (BULK) (Version 1) integration with SMSLink.ro
*
* using SMS Gateway (BULK) Version 1 Endpoint
*
* Supports HTTP and HTTPS protocols
*
* (New) SMS Gateway (BULK) Version 3 Endpoint is available, see other examples for new features.
*
* System Requirements:
*
* PHP 5+ with
*
* PHP cURL
*
* Optional, for transmission compression the following compression libraries are needed:
*
* for Zlib Gzip compression PHP is required to be compiled --with-zlib[=DIR] [and/or]
* for bzip2 compression PHP is required to be compiled --with-bz2[=DIR] [and/or]
* for LZF compression PHP is required to be compiled --with-lzf[=DIR]
*
* Usage:
*
* See Usage Examples for the SMSLinkSMSGatewayBulkPackage() class starting on line 391
*
* Get your SMSLink / SMS Gateway Connection ID and Password from
* https://www.smslink.ro/get-api-key/
*
* @version 2.1
* @updated 2021-03-04
* @see https://www.smslink.ro/sms-gateway-documentatie-sms-gateway.html
*
*/
class SMSLinkSMSGatewayBulkPackage
{
private $connection_id = null;
private $password = null;
private $doHTTPS = true;
private $testMode = false;
protected $endpointHTTP = "http://www.smslink.ro/sms/gateway/communicate/bulk.php";
protected $endpointHTTPS = "https://secure.smslink.ro/sms/gateway/communicate/bulk.php";
private $temporaryDirectory = "/tmp";
public $remoteMessageIDs = array();
public $errorMessage = "";
public $transactionTime = 0;
private $packageContents = array();
private $packageStatus = 0;
private $packageFile = array(
"contentPlain" => "",
"contentCompressed" => ""
);
private $packageValidation = array(
"hashMD5" => array(
"contentPlain" => "",
"contentCompressed" => ""
)
);
protected $clientVersion = "2.1";
protected $compressionMethods = array(
0 => array("CompressionID" => 0, "Compression" => "No Compression"),
1 => array("CompressionID" => 1, "Compression" => "Compression using Zlib Gzip"),
2 => array("CompressionID" => 2, "Compression" => "Compression using bzip2"),
3 => array("CompressionID" => 3, "Compression" => "Compression using LZF"),
);
private $compressionMethod = 1;
/**
* Initialize SMSLink - SMS Gateway
*
* Initializing SMS Gateway will require the parameters $connection_id and $password. $connection_id and $password can be generated at
* https://www.smslink.ro/sms/gateway/setup.php after authenticated with your account credentials.
*
* @param string $connection_id SMSLink - SMS Gateway - Connection ID
* @param string $password SMSLink - SMS Gateway - Password
* @param bool $testMode SMSLink - SMS Gateway - Test Mode (true or false)
*
* @return void
*/
public function __construct($connection_id, $password, $testMode = false)
{
if (!is_null($connection_id))
$this->connection_id = $connection_id;
if (!is_null($password))
$this->password = $password;
if (($testMode == true) or ($testMode == false))
$this->testMode = $testMode;
if ((is_null($this->connection_id)) or (is_null($this->password)))
exit("SMS Gateway initialization failed, credentials not provided. Please see documentation.");
}
public function __destruct()
{
$this->connection_id = null;
$this->password = null;
$this->doHTTPS = true;
}
/**
* Sets the compression method to be used during sending
*
* @param int $compressionMethod the following values are accepted:
*
* 0 for No Compression (default)
* 1 for Zlib Gzip (requires PHP to be compiled --with-zlib[=DIR])
* 2 for bzip2 (requires PHP to be compiled --with-bz2[=DIR])
* 3 for LZF (requires PHP to be compiled --with-lzf[=DIR])
*
* @return bool true if method was set or false otherwise
*/
public function setCompression($compressionMethod)
{
if ($this->packageStatus == 0)
{
if (array_key_exists($compressionMethod, $this->compressionMethods))
$this->compressionMethod = $compressionMethod;
return true;
}
return false;
}
private function applyCompression($contentPlain)
{
$contentCompressed = "";
switch ($this->compressionMethod)
{
case 0:
$contentCompressed = $contentPlain;
break;
case 1:
$contentCompressed = gzcompress($contentPlain, 9);
break;
case 2:
$contentCompressed = bzcompress($contentPlain, 9);
break;
case 3:
$contentCompressed = lzf_compress($contentPlain);
break;
}
return $contentCompressed;
}
private function microtimeFloat()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* Sets the protocol that will be used by SMS Gateway (HTTPS or HTTP).
*
* @param string $protocolName HTTPS or HTTP
*
* @return bool true if method was set or false otherwise
*/
public function setProtocol($protocolName = "HTTPS")
{
$protocolName = strtoupper($protocolName);
if ($protocolName == "HTTPS") $this->doHTTPS = true;
elseif ($protocolName == "HTTP") $this->doHTTPS = false;
else return false;
return true;
}
/**
* Returns the protocol that is used by SMS Gateway (HTTPS or HTTP)
*
* @return string HTTPS or HTTP possible values
*/
public function getProtocol()
{
return ($this->doHTTPS) ? "HTTPS" : "HTTP";
}
private function structureCharactersEncode($messageText)
{
$messageText = str_replace("\n", "%0A", $messageText);
$messageText = str_replace(";", "%3B", $messageText);
return $messageText;
}
private function cleanCharacters($messageText)
{
$messageText = str_replace("\t", "", $messageText); // Tab
$messageText = str_replace("\r", "", $messageText); // Carriage Return
return $messageText;
}
/**
* Inserts a SMS to SMS Bulk Package
*
* @param int $localMessageId Local Message ID from Your System
*
* @param string $receiverNumber Receiver mobile phone number. Phone numbers should be formatted as a Romanian national mobile phone number (07xyzzzzzz).
*
* @param string $senderId (Optional) Sender alphanumeric string:
*
* numeric - sending will be done with a shortcode (ex. 18xy, 17xy)
* SMSLink.ro - sending will be done with SMSLink.ro (use this for tests only)
*
* Any other preapproved alphanumeric sender assigned to your account:
*
* Your alphanumeric sender list:
* http://www.smslink.ro/sms/sender-list.php
*
* Your alphanumeric sender application:
* http://www.smslink.ro/sms/sender-id.php
*
* Please Note:
*
* SMSLink.ro sender should be used only for testing and is not recommended to be used in production. Instead, you
* should use numeric sender or your alphanumeric sender, if you have an alphanumeric sender activated with us.
*
* If you set an alphanumeric sender for a mobile number that is in a network where the alphanumeric sender has not
* been activated, the system will override that setting with numeric sender.
*
* @param string $messageText Message of the SMS, up to 160 alphanumeric characters.
*
* @param int $timestampProgrammed (Optional) Should be 0 (zero) for immediate sending or other UNIX timestamp in the future for future sending
*
* @return bool true on success or false on failure
*/
public function insertMessage($localMessageId, $receiverNumber, $senderId, $messageText, $timestampProgrammed = 0)
{
if (!is_numeric($localMessageId))
return false;
$receiverNumber = str_replace("+", "00", $receiverNumber); // Converts + to 00
$receiverNumber = preg_replace("/[^0-9]/", "", $receiverNumber); // Remove all non-numeric characters
if (substr($receiverNumber, 0, 4) == "0040")
$receiverNumber = substr($receiverNumber, 3); // Converts 00407xyzzzzzz to 07xyzzzzzz
if (!is_numeric($receiverNumber))
return false;
$messageText = trim($messageText); // Strip whitespace from the beginning and end of the message
$messageText = str_replace("\r\n", "\n", $messageText); // Converts Carriage Return + Line Feed to Line Feed
$messageText = $this->structureCharactersEncode($messageText); // Encode structure characters
$messageText = $this->cleanCharacters($messageText); // Clean unsuported characters
$this->packageContents[] = array(
"localMessageId" => $localMessageId,
"receiverNumber" => $receiverNumber,
"senderId" => $senderId,
"messageText" => $messageText,
"timestampProgrammed" => $timestampProgrammed
);
return true;
}
/**
* Removes a SMS from SMS Bulk Package
*
* @param int $localMessageId Local Message ID from Your System
*
* @return void
*/
public function removeMessage($localMessageId)
{
foreach ($this->packageContents as $messageKey => $messageData)
if ($messageData["localMessageId"] == $localMessageId)
unset($this->packageContents[$messageKey]);
}
/**
* Returns the Size of the SMS Bulk Package
*
* @return int
*/
public function packageSize()
{
return sizeof($this->packageContents);
}
/**
* Sends the SMS Bulk Package to SMSLink
*
* @return bool true on success or false on failure
*/
public function sendPackage()
{
$timestampStart = $this->microtimeFloat();
$this->remoteMessageIDs = array();
$this->errorMessage = "";
if (($this->packageStatus == 0) and ($this->packageSize() > 0))
{
$temporaryFile = array();
foreach ($this->packageContents as $messageKey => $messageData)
$temporaryFile[] = implode(";", $messageData);
$this->packageFile["contentPlain"] = implode("\r\n", $temporaryFile);
$this->packageValidation["hashMD5"]["contentPlain"] = md5($this->packageFile["contentPlain"]);
$this->packageFile["contentCompressed"] = $this->applyCompression($this->packageFile["contentPlain"]);
$this->packageValidation["hashMD5"]["contentCompressed"] = md5($this->packageFile["contentCompressed"]);
$temporaryFilename = tempnam($this->temporaryDirectory, "sms-package-");
if ($temporaryFilename != false)
{
file_put_contents($temporaryFilename, $this->packageFile["contentCompressed"]);
$requestData = array(
"connection_id" => $this->connection_id,
"password" => $this->password,
"test" => ($this->testMode == true) ? 1 : 0,
"Compression" => $this->compressionMethod,
"MD5Plain" => $this->packageValidation["hashMD5"]["contentPlain"],
"MD5Compressed" => $this->packageValidation["hashMD5"]["contentCompressed"],
"SizePlain" => strlen($this->packageFile["contentPlain"]),
"SizeCompressed" => strlen($this->packageFile["contentCompressed"]),
"Timestamp" => date("U"),
"Buffering" => 1,
"Version" => $this->clientVersion,
"Receivers" => $this->packageSize(),
"Package" => "@".$temporaryFilename
);
$ch = curl_init((($this->doHTTPS == true) ? $this->endpointHTTPS : $this->endpointHTTP)."?timestamp=".date("U"));
curl_setopt($ch, CURLOPT_POST, 1);
if ((version_compare(PHP_VERSION, '5.5') >= 0))
{
$requestData["Package"] = new CURLFile($temporaryFilename);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
if ($this->doHTTPS == true)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$requestResponse = curl_exec($ch);
$connectionErrorCode = curl_errno($ch);
$connectionErrorMessage = curl_error($ch);
$requestStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($connectionErrorCode == 0)
{
if (($requestStatusCode >= 200) and ($requestStatusCode <= 299))
{
$requestResponse = explode(";", $requestResponse);
if ((is_array($requestResponse)) and (sizeof($requestResponse) >= 3))
{
if ($requestResponse[0] == "MESSAGE")
{
$messagesAssoc = explode(",", $requestResponse[3]);
for($i = 0; $i < sizeof($messagesAssoc); $i++)
{
$temporaryMessageData = explode(":", $messagesAssoc[$i]);
$this->remoteMessageIDs[$temporaryMessageData[0]] = array(
"localMessageId" => $temporaryMessageData[0],
"remoteMessageId" => $temporaryMessageData[1],
"messageStatus" => $temporaryMessageData[2]
);
}
$this->packageStatus = 1;
$timestampEnd = $this->microtimeFloat();
$this->transactionTime = round($timestampEnd - $timestampStart, 2);
return true;
}
else
{
$this->errorMessage = implode(";", $requestResponse);
}
}
else
{
$this->errorMessage = "ERROR;0;Unexpected response format";
}
}
else
{
$this->errorMessage = "ERROR;0;Unexpected HTTP code ".$requestStatusCode;
}
}
else
{
$this->errorMessage = "ERROR;0;".$connectionErrorMessage;
}
curl_close($ch);
}
}
return false;
}
}
/**
*
*
* Usage Examples for the SMSLinkSMSGatewayBulkPackage() class
*
*
*
*/
/*
*
*
* Initialize SMS Gateway Bulk Package
*
* Get your SMSLink / SMS Gateway Connection ID and Password from
* https://www.smslink.ro/get-api-key/
*
*
*
*/
$BulkSMSPackage = new SMSLinkSMSGatewayBulkPackage("MyConnectionID", "MyConnectionPassword");
/*
*
* Insert Messages to SMS Package
*
*/
$BulkSMSPackage->insertMessage(1, "07xyzzzzzz", "numeric", "Test 1");
$BulkSMSPackage->insertMessage(2, "07xyzzzzzz", "numeric", "Test 2");
$BulkSMSPackage->insertMessage(3, "07xyzzzzzz", "numeric", "Test 3");
$BulkSMSPackage->insertMessage(4, "07xyzzzzzz", "numeric", "Test 4");
$BulkSMSPackage->insertMessage(5, "07xyzzzzzz", "numeric", "Test 5");
/*
*
* Send SMS Package to SMSLink
*
*/
$BulkSMSPackage->sendPackage();
/*
*
* Process Result
*
*/
$statusCounters = array();
if (sizeof($BulkSMSPackage->remoteMessageIDs) > 0)
{
foreach ($BulkSMSPackage->remoteMessageIDs as $key => $value)
{
switch ($value["messageStatus"])
{
/**
*
*
* Message Status: 1
* Status Description: Sender Failed
*
*
*/
case 1:
$timestamp_send = -1;
/*
.. do something ..
for example check the sender because is incorrect
*/
echo "Error for Local Message ID: ".$value["localMessageId"]." (Sender Failed).<br />";
$statusCounters["failedSenderCounter"]++;
break;
/**
*
*
* Message Status: 2
* Status Description: Number Failed
*
*
*/
case 2:
$timestamp_send = -2;
/*
.. do something ..
for example check the number because is incorrect
*/
echo "Error for Local Message ID: ".$value["localMessageId"]." (Incorrect Number).<br />";
$statusCounters["failedNumberCounter"]++;
break;
/**
*
*
* Message Status: 3
* Status Description: Success
*
*
*/
case 3:
$timestamp_send = date("U");
/*
.. do something ..
Save in database the Remote Message ID, sent in variabile: $value["RemoteMessageID"].
Delivery reports will identify your SMS using our Message ID. Data type for the
variabile should be considered to be hundred milions (example: 220000000)
*/
echo "Succes for Local Message ID: ".
$value["localMessageId"].
", Remote Message ID: ".
$value["remoteMessageId"].
"<br />";
$statusCounters["successCounter"]++;
break;
/**
*
*
* Message Status: 4
* Status Description: Internal Error or Number Blacklisted
*
*
*/
case 4:
$timestamp_send = -4;
/*
.. do something ..
for example try again later
Internal Error may occur in the following circumstances:
(1) Number is Blacklisted (please check the Blacklist associated to your account), or
(2) An error occured at SMSLink (our technical support team is automatically notified)
*/
echo "Error for Local Message ID: ".$value["localMessageId"]." (Internal Error or Number Blacklisted).<br />";
$statusCounters["failedInternalCounter"]++;
break;
/**
*
*
* Message Status: 5
* Status Description: Insufficient Credit
*
*
*/
case 5:
$timestamp_send = -5;
/*
.. do something ..
for example top-up the account
*/
echo "Error for Local Message ID: ".$value["localMessageId"]." (Insufficient Credit).<br />";
$statusCounters["failedInsufficientCredit"]++;
break;
}
$statusCounters["totalCounter"]++;
}
}
else
{
echo "Error Transmitting Package to SMSLink: ".$BulkSMSPackage->errorMessage."<br />";
}
?>