Mobipace.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. class Mobipace extends SMSServiceApi {
  3. /**
  4. * Status message returned by service after any request
  5. *
  6. * @var string
  7. */
  8. protected $statusStr = '';
  9. /**
  10. * Status code returned by service after any request
  11. *
  12. * @var int
  13. */
  14. protected $statusCode = 0;
  15. /**
  16. * Session ID returned by service after successful auth
  17. *
  18. * @var string
  19. */
  20. protected $sessionID = '';
  21. /**
  22. * Service URL path suffix for a "auth" request
  23. *
  24. * @var string
  25. */
  26. protected $urlSuffixAuth = 'authorize';
  27. /**
  28. * Service URL path suffix for a "send" request
  29. *
  30. * @var string
  31. */
  32. protected $urlSuffixSend = 'Send';
  33. /**
  34. * Service URL path suffix for a "get msg statuses" request
  35. *
  36. * @var string
  37. */
  38. protected $urlSuffixStatuses = 'QueryMessages';
  39. /**
  40. * Service URL path suffix for a "get balance" request
  41. *
  42. * @var string
  43. */
  44. protected $urlSuffixBalance = 'QueryBalance';
  45. /**
  46. * Messages status codes as defined in API manual
  47. *
  48. * @var array
  49. */
  50. protected $msgStatusCodes = array(1 => 'Pending',
  51. 2 => 'Scheduled message',
  52. 3 => 'Sent',
  53. 4 => 'Insufficient funds to send messages',
  54. 5 => 'Invalid cell number format',
  55. 6 => 'Maximum message length of 500 chars reached',
  56. 7 => 'Invalid alpha-name - please, contact your manager',
  57. 8 => 'Invalid message route - please, contact your manager',
  58. 9 => 'Cell number blocked',
  59. 10 => 'System failure',
  60. 100 => 'Delivered',
  61. 101 => 'Undeliverable',
  62. 102 => 'Message sent, status unknown',
  63. 103 => 'Rejected',
  64. 104 => 'TimeOut'
  65. );
  66. /**
  67. * Error codes => messages as defined in API manual
  68. *
  69. * @var array
  70. */
  71. protected $errorCodes = array(100 => 'System failure',
  72. 101 => 'Request successful',
  73. 102 => 'Request format or parameters are incorrect',
  74. 103 => 'Session expired',
  75. 104 => 'System is processing request with such ID already or request with such ID temporarily can not be processed',
  76. 200 => 'Incorrect user name or password',
  77. 201 => 'Maximum amount of auth fails reached - please, contact your manager',
  78. 202 => 'User is blocked - please, contact your manager',
  79. 300 => 'Insufficient funds to send messages',
  80. 301 => 'Message count overflow: no more than 20000 messages per session supported',
  81. 302 => 'Account currency not defined - proceed to your personal page and check config'
  82. );
  83. public function __construct($smsServiceId, $smsPack = array()) {
  84. parent::__construct($smsServiceId, $smsPack);
  85. $this->doAuth();
  86. }
  87. protected function doCURL($url, $postFileds) {
  88. $curl = curl_init();
  89. curl_setopt($curl, CURLOPT_POST, true);
  90. curl_setopt($curl, CURLOPT_URL, $url);
  91. curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json; charset=utf-8", "Cache-Control: no-cache"));
  92. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  93. curl_setopt($curl, CURLOPT_POSTFIELDS, $postFileds);
  94. $result = curl_exec($curl);
  95. curl_close($curl);
  96. return ($result);
  97. }
  98. public function doAuth() {
  99. $url = rtrim($this->serviceGatewayAddr, '/') . '/' . $this->urlSuffixAuth;
  100. $authReq = json_encode(array('Username' => $this->serviceLogin, 'Password' => $this->servicePassword));
  101. $response = $this->doCURL($url, $authReq);
  102. if (!empty($response)) {
  103. $response = json_decode($response, true);
  104. $srvAnswerCode = (isset($response['StatusCode'])) ? $response['StatusCode'] : '42';
  105. if ($srvAnswerCode == 101) {
  106. $this->sessionID = $response['SessionId'];
  107. } else {
  108. $serverErrorMsg = $this->processError($srvAnswerCode);
  109. log_register('SENDDOG MOBIPACE ERROR auth failed: ' . $serverErrorMsg);
  110. }
  111. }
  112. }
  113. public function pushMessages() {
  114. if (empty($this->sessionID)) {
  115. log_register('SENDDOG MOBIPACE ERROR send messages failed - empty session ID, check auth parameters');
  116. } else {
  117. $url = rtrim($this->serviceGatewayAddr, '/') . '/' . $this->urlSuffixSend;
  118. $sender = $this->serviceAlphaName;
  119. $smsHistoryEnabled = $this->instanceSendDog->getUBConfigInstance()->getAlterParam('SMS_HISTORY_ON');
  120. $smsAdvancedEnabled = $this->instanceSendDog->getUBConfigInstance()->getAlterParam('SMS_SERVICES_ADVANCED_ENABLED');
  121. $smsHistTabFreshIds = array();
  122. $preSendStatus = __('Perparing for delivery');
  123. $telepatia = new Telepathy(false);
  124. if ($smsHistoryEnabled) {
  125. $telepatia->flushPhoneTelepathyCache();
  126. $telepatia->usePhones();
  127. }
  128. $allSmsQueue = $this->smsMessagePack;
  129. if (!empty($allSmsQueue)) {
  130. log_register('SENDDOG MOBIPACE sending SMS packet: ' . $this->sessionID);
  131. $smsArray = array('SessionId' => $this->sessionID,
  132. 'Sender' => $sender,
  133. 'Messages' => array()
  134. );
  135. foreach ($allSmsQueue as $eachsms) {
  136. $smsMsgId = strtoupper(md5(uniqid(rand(), true)));
  137. if ($smsHistoryEnabled) {
  138. $Login = $telepatia->getByPhoneFast($eachsms['number']);
  139. if ($smsAdvancedEnabled) {
  140. $query = "INSERT INTO `sms_history` (`smssrvid`, `login`, `phone`, `srvmsgself_id`, `srvmsgpack_id`, `send_status`, `msg_text`)
  141. VALUES (" . $this->serviceId . ", '" . $Login . "', '" . $eachsms['number'] . "', '". $smsMsgId . "', '" . $this->sessionID . "', '" . $preSendStatus . "', '" . $eachsms['message'] . "');";
  142. } else {
  143. $query = "INSERT INTO `sms_history` (`login`, `phone`, `srvmsgself_id`, `srvmsgpack_id`, `send_status`, `msg_text`)
  144. VALUES ('" . $Login . "', '" . $eachsms['number'] . "', '". $smsMsgId . "', '" . $this->sessionID . "', '" . $preSendStatus . "', '" . $eachsms['message'] . "');";
  145. }
  146. nr_query($query);
  147. $recId = simple_get_lastid('sms_history');
  148. $smsHistTabFreshIds[] = $recId;
  149. }
  150. $smsArray['Messages'][] = array('Recipient' => ltrim($eachsms['number'], '+0'),
  151. 'Body' => $eachsms['message'],
  152. 'Reference' => $smsMsgId
  153. );
  154. $this->instanceSendDog->getSmsQueueInstance()->deleteSms($eachsms['filename']);
  155. }
  156. $smsArray = json_encode($smsArray);
  157. $response = $this->doCURL($url, $smsArray);
  158. if (!empty($response)) {
  159. $response = json_decode($response, true);
  160. $srvAnswerCode = (isset($response['StatusCode'])) ? $response['StatusCode'] : '42';
  161. $msgsCnt = (isset($response['MessageCount'])) ? $response['MessageCount'] : '0';
  162. $priceTotal = (isset($response['TotalPrice'])) ? $response['TotalPrice'] : '0';
  163. $idsAsStr = implode(',', $smsHistTabFreshIds);
  164. if ($srvAnswerCode == 101) {
  165. $query = "UPDATE `sms_history` SET `date_send` = '" . curdatetime() . "',
  166. `send_status` = '" . __('Message queued') . "'
  167. WHERE `id` IN (" . $idsAsStr . ");";
  168. nr_query($query);
  169. log_register('SENDDOG MOBIPACE sending SMS packet: ' . $this->sessionID . ' successful. Packet messages count: ' . $msgsCnt . '. Packet price: ' . $priceTotal . '.');
  170. } else {
  171. $serverErrorMsg = $this->processError($srvAnswerCode);
  172. log_register('SENDDOG MOBIPACE sending SMS packet: ' . $this->sessionID . 'FAILED. Server answer: ' . $serverErrorMsg);
  173. $query = "UPDATE `sms_history` SET `date_send` = '" . curdatetime() . "',
  174. `date_statuschk` = '" . curdatetime() . "',
  175. `no_statuschk` = '1',
  176. `send_status` = '" . __('Failed to send message') . ': ' . $serverErrorMsg ."'
  177. WHERE `id` IN (" . $idsAsStr . ");";
  178. nr_query($query);
  179. }
  180. }
  181. }
  182. }
  183. }
  184. public function checkMessagesStatuses() {
  185. if (empty($this->sessionID)) {
  186. log_register('SENDDOG MOBIPACE ERROR check messages statuses failed - empty session ID, check auth parameters');
  187. } else {
  188. $url = rtrim($this->serviceGatewayAddr, '/') . '/' . $this->urlSuffixStatuses;
  189. $statusReq = array('SessionId' => $this->sessionID, 'References' => array());
  190. if ($this->isDefaultService) {
  191. $query = "SELECT DISTINCT `srvmsgself_id` FROM `sms_history` WHERE `no_statuschk` < 1 AND `delivered` < 1 AND (`smssrvid` = " . $this->serviceId . " OR `smssrvid` = 0);";
  192. } else {
  193. $query = "SELECT DISTINCT `srvmsgself_id` FROM `sms_history` WHERE `no_statuschk` < 1 AND `delivered` < 1 AND `smssrvid` = " . $this->serviceId . ";";
  194. }
  195. $checkMessages = simple_queryall($query);
  196. if (!empty($checkMessages)) {
  197. $messagesIDs = array();
  198. foreach ($checkMessages as $io => $eachmessage) {
  199. $messagesIDs[] = $eachmessage['srvmsgself_id'];
  200. }
  201. //$messagesIdsList = implode(';', $messagesIDs);
  202. $statusReq['References'] = $messagesIDs;
  203. $statusReq = json_encode($statusReq);
  204. $response = $this->doCURL($url, $statusReq);
  205. if (!empty($response)) {
  206. $response = json_decode($response, true);
  207. $srvAnswerCode = (isset($response['StatusCode'])) ? $response['StatusCode'] : '42';
  208. if ($srvAnswerCode == 101) {
  209. $msgStatuses = (empty($response['MessageStatuses'])) ? array() : $response['MessageStatuses'];
  210. foreach ($msgStatuses as $io => $eachMsgStatus) {
  211. $messageId = $eachMsgStatus['Reference'];
  212. $messageStatusCode = $eachMsgStatus['StatusCode'];
  213. $decodedMessageStatus = $this->decodeMobipaceStatusMsg($messageStatusCode);
  214. $query = "UPDATE `sms_history` SET `date_statuschk` = '" . curdatetime() . "',
  215. `delivered` = '" . $decodedMessageStatus['DeliveredStatus'] . "',
  216. `no_statuschk` = '" . $decodedMessageStatus['NoStatusCheck'] . "',
  217. `send_status` = '" . $decodedMessageStatus['StatusMsg'] . "'
  218. WHERE `srvmsgself_id` = '" . $messageId . "';";
  219. nr_query($query);
  220. }
  221. log_register('SENDDOG MOBIPACE checked statuses for ' . count($msgStatuses) . ' messages.');
  222. } else {
  223. $serverErrorMsg = $this->processError($srvAnswerCode);
  224. log_register('SENDDOG MOBIPACE ERROR failed to check messages statuses. Server answer: ' . $serverErrorMsg);
  225. }
  226. }
  227. }
  228. }
  229. }
  230. public function getBalance() {
  231. if (empty($this->sessionID)) {
  232. log_register('SENDDOG MOBIPACE ERROR get balance failed - empty session ID, check auth parameters');
  233. $errormes = $this->instanceSendDog->getUBMsgHelperInstance()->getStyledMessage(__('Getting balance failed - empty session ID, check auth parameters'), 'error', 'style="margin: auto 0; padding: 10px 3px; width: 100%;"');
  234. die(wf_modalAutoForm(__('Error'), $errormes, $_POST['modalWindowId'], '', true));
  235. } else {
  236. $result = '';
  237. $url = rtrim($this->serviceGatewayAddr, '/') . '/' . $this->urlSuffixBalance;
  238. $balanceReq = json_encode(array('SessionId' => $this->sessionID));
  239. $response = $this->doCURL($url, $balanceReq);
  240. $response = json_decode($response, true);
  241. $srvAnswerCode = (isset($response['StatusCode'])) ? $response['StatusCode'] : '42';
  242. if ($srvAnswerCode == 101) {
  243. $balance = wf_delimiter(1) . wf_nbsp(4) . __('Balance') . ': ' . $response['Balance']
  244. . wf_delimiter(0) . wf_nbsp(4) . __('Credit') . ': ' . $response['BalanceNegativeLimit'];
  245. } else {
  246. $balance = $this->processError($srvAnswerCode);
  247. log_register('SENDDOG MOBIPACE ERROR getting balance failed: ' . $balance);
  248. }
  249. $result.= $this->instanceSendDog->getUBMsgHelperInstance()->getStyledMessage(__('Current account balance') . ': ' . $balance, 'info');
  250. die(wf_modalAutoForm(__('Balance'), $result, $_POST['modalWindowId'], '', true, 'false', '700'));
  251. }
  252. }
  253. public function getSMSQueue() {
  254. $this->showErrorFeatureIsNotSupported();
  255. }
  256. protected function processError($errorCode) {
  257. $errMsg = (isset($this->errorCodes[$errorCode])) ? __($this->errorCodes[$errorCode]) : __('Unknown error code');
  258. return ('[' . $errorCode . '] - ' . $errMsg);
  259. }
  260. protected function decodeMobipaceStatusMsg($statusMsgCode) {
  261. $statusArray = array('StatusMsg' => '', 'DeliveredStatus' => 0, 'NoStatusCheck' => 0);
  262. $statusMsg = (isset($this->msgStatusCodes[$statusMsgCode])) ? __($this->msgStatusCodes[$statusMsgCode]) : __('Unknown status code');
  263. switch ($statusMsgCode) {
  264. case 1:
  265. case 2:
  266. case 3:
  267. $statusArray['StatusMsg'] = $statusMsg;
  268. $statusArray['DeliveredStatus'] = 0;
  269. $statusArray['NoStatusCheck'] = 0;
  270. break;
  271. case 4:
  272. case 5:
  273. case 6:
  274. case 7:
  275. case 8:
  276. case 9:
  277. case 10:
  278. case 101:
  279. case 102:
  280. case 103:
  281. case 104:
  282. $statusArray['StatusMsg'] = $statusMsg;
  283. $statusArray['DeliveredStatus'] = 0;
  284. $statusArray['NoStatusCheck'] = 1;
  285. break;
  286. case 100:
  287. $statusArray['StatusMsg'] = $statusMsg;
  288. $statusArray['DeliveredStatus'] = 1;
  289. $statusArray['NoStatusCheck'] = 0;
  290. break;
  291. default:
  292. $statusArray['StatusMsg'] = __('Sending status code is unknown:') . ' ' . $statusMsgCode;
  293. $statusArray['DeliveredStatus'] = 0;
  294. $statusArray['NoStatusCheck'] = 1;
  295. }
  296. return ($statusArray);
  297. }
  298. }