forked from onlinecity/php-smpp-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmssender.class.php
More file actions
241 lines (210 loc) · 7.09 KB
/
smssender.class.php
File metadata and controls
241 lines (210 loc) · 7.09 KB
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
<?php
require_once 'queuemodel.class.php';
require_once 'smpp'.DIRECTORY_SEPARATOR.'sockettransport.class.php';
require_once 'smpp'.DIRECTORY_SEPARATOR.'smppclient.class.php';
require_once 'smpp'.DIRECTORY_SEPARATOR.'gsmencoder.class.php';
/**
* SMS worker for sending SMSes.
* Uses a blocking operation to wait for new SMS'es and sends them using SMPP in batches of 10.
* It will store the ids from the SMSC for every batch.
*
* Copyright (C) 2011 OnlineCity
* Licensed under the MIT license, which can be read at: http://www.opensource.org/licenses/mit-license.php
* @author hd@onlinecity.dk
*/
class SmsSender
{
protected $options;
protected $transport;
protected $client;
protected $queue;
protected $debug;
private $lastEnquireLink;
/**
* Construct a new SmsSender worker
* @param array $options
*/
public function __construct($options)
{
$this->options = $options;
$this->debug = $this->options['sender']['debug'];
pcntl_signal(SIGTERM, array($this,"disconnect"), true);
gc_enable();
}
public function disconnect()
{
// Close queue
if (isset($this->queue)) $this->queue->close();
// Close transport
if (isset($this->transport) && $this->transport->isOpen()) {
if (isset($this->client)) {
$this->client->close();
} else {
$this->transport->close();
}
}
exit();
}
/**
* Shorthand method for calling debug handler
* @param string $s
*/
private function debug($s)
{
call_user_func($this->options['general']['debug_handler'], 'PID:'.getmypid().' - '.$s);
}
/**
* Connect to the queue backend.
* Construct and open the transport
* Construct client and bind as transmitter.
*
*/
protected function connect()
{
// Init queue
$this->queue = new QueueModel($this->options);
// Set some transport defaults first
SocketTransport::$defaultDebug = $this->debug;
SocketTransport::$forceIpv4 = $this->options['connection']['forceIpv6'];
SocketTransport::$forceIpv4 = $this->options['connection']['forceIpv4'];
// Construct the transport
$h = $this->options['connection']['hosts'];
$p = $this->options['connection']['ports'];
$d = $this->options['general']['debug_handler'];
$this->transport = new SocketTransport($h,$p,false,$d);
// Set connection timeout and open connnection
$this->transport->setRecvTimeout($this->options['sender']['recv_timeout']);
$this->transport->setSendTimeout($this->options['sender']['connect_timeout']);
$this->transport->open();
$this->transport->setSendTimeout($this->options['sender']['send_timeout']);
// Construct client and login
$this->client = new SmppClient($this->transport, $this->options['general']['protocol_debug_handler']);
$this->client->debug = $this->options['sender']['smpp_debug'];
$this->client->bindTransmitter($this->options['connection']['login'], $this->options['connection']['password']);
// Set other client options
SmppClient::$sms_registered_delivery_flag = ($this->options['connection']['registered_delivery']) ? SMPP::REG_DELIVERY_SMSC_BOTH : SMPP::REG_DELIVERY_NO;
SmppClient::$csms_method = $this->options['connection']['csms_method'];
SmppClient::$sms_null_terminate_octetstrings = $this->options['connection']['null_terminate_octetstrings'];
}
/**
* Keep our connections alive.
* Send enquire link to SMSC, respond to any enquire links from SMSC and ping the queue server
*/
protected function ping()
{
$this->queue->ping();
$this->client->enquireLink();
$this->client->respondEnquireLink();
}
/**
* Run garbage collect and check memory limit
*/
private function checkMemory()
{
// Run garbage collection
gc_collect_cycles();
// Check the memory usage for a limit, and exit when 64MB is reached. Parent will re-fork us
if ((memory_get_usage(true)/1024/1024)>64) {
$this->debug('Reached memory max, exiting');
$this->disconnect();
}
}
/**
* This workers main loop
*/
public function run()
{
$this->connect();
$this->lastEnquireLink = 0;
try {
while (true) {
// commit suicide if the parent process no longer exists
if (posix_getppid() == 1) {
$this->disconnect();
exit();
}
// Make sure to send enquire link periodically to keep the link alive
if (time()-$this->lastEnquireLink >= $this->options['connection']['enquire_link_timeout']) {
$this->ping();
$this->lastEnquireLink = time();
}
// Queue->consume will block until there is something to do, or a 5 sec timeout is reached
$sms = $this->queue->consume(getmypid(),5);
if ($sms === false || is_null($sms)) { // idle
$this->checkMemory();
continue;
}
// Prepare message
$encoded = GsmEncoder::utf8_to_gsm0338($sms->message);
$encSender = iconv('UTF-8',$this->options['connection']['originator_encoding'],$sms->sender);
if (strlen($encSender)>11) $encSender = substr($encSender,0,11); // truncate
// Contruct SMPP Address objects
if (!ctype_digit($sms->sender)) {
$sender = new SmppAddress($encSender,SMPP::TON_ALPHANUMERIC);
} else if ($sms->sender < 10000) {
$sender = new SmppAddress($sms->sender,SMPP::TON_NATIONAL,SMPP::NPI_E164);
} else {
$sender = new SmppAddress($sms->sender,SMPP::TON_INTERNATIONAL,SMPP::NPI_E164);
}
// Deal with flash sms (dest_addr_subunit: 0x01 - show on display only)
if ($sms->isFlashSms) {
$tags = array(new SmppTag(SmppTag::DEST_ADDR_SUBUNIT, 1, 1, 'c'));
} else {
$tags = null;
}
// Send message
$ids = array();
$msisdns = array();
try {
$i = 0;
foreach ($sms->recipients as $number) {
$address = new SmppAddress($number,SMPP::TON_INTERNATIONAL,SMPP::NPI_E164);
$ids[] = $this->client->sendSMS($sender, $address, $encoded, $tags);
$msisdns[] = $number;
if (++$i % 10 == 0) {
// relay back for every 10 SMSes
$this->queue->storeIds($sms->id, $ids, $msisdns);
// Pretty debug output
if ($this->debug) {
$s = 'Sent SMS: '.$sms->id.' with ids:';
foreach ($ids as $n => $id) {
if ($n % 2 == 0) $s .= "\n";
$s .= "\t".$msisdns[$n].":".$id;
}
$this->debug($s);
}
$ids = array();
$msisdns = array();
}
}
} catch (\Exception $e) {
if (!empty($ids)) {
// make sure to report any partial progress back
$this->queue->storeIds($sms->id, $ids, $msisdns);
$this->debug('SMS with partial progress: '.$sms->id.' with ids: '.implode(', ',$ids));
}
$this->debug('Deferring SMS id:'.$sms->id);
$sms->retries++;
$sms->lastRetry = time();
$this->queue->defer(getmypid(), $sms);
throw $e; // rethrow
}
if (!empty($ids)) {
$this->queue->storeIds($sms->id, $ids, $msisdns);
// Pretty debug output
if ($this->debug) {
$s = 'Sent SMS: '.$sms->id.' with ids:';
foreach ($ids as $n => $id) {
if ($n % 2 == 0) $s .= "\n";
$s .= "\t".$msisdns[$n].":".$id;
}
$this->debug($s);
}
}
}
} catch (Exception $e) {
$this->debug('Caught '.get_class($e).': '.$e->getMessage()."\n\t".$e->getTraceAsString());
$this->disconnect();
}
}
}