api.senddogadvanced.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. <?php
  2. /**
  3. * Multi-service SendDog implementation
  4. */
  5. class SendDogAdvanced extends SendDog {
  6. /**
  7. * Placeholder for SMS services IDs => APINames
  8. *
  9. * @var array
  10. */
  11. protected $servicesApiId = array();
  12. /**
  13. * Placeholder for default SMS service ID
  14. *
  15. * @var string
  16. */
  17. protected $defaultSmsServiceId = '';
  18. /**
  19. * Placeholder for default SMS service API name
  20. *
  21. * @var string
  22. */
  23. protected $defaultSmsServiceApi = '';
  24. /**
  25. * Placeholder for SMS_SERVICES_ADVANCED_PHPMAILER_ON alter.ini option
  26. *
  27. * @var bool
  28. */
  29. protected $phpMailerOn = false;
  30. /**
  31. * Contains path to files with services APIs implementations
  32. */
  33. const API_IMPL_PATH = 'api/vendor/sms_services_APIs/';
  34. public function __construct() {
  35. global $ubillingConfig;
  36. $this->ubConfig = $ubillingConfig;
  37. $this->loadAltCfg();
  38. $this->initSmsQueue();
  39. $this->initMessages();
  40. $this->loadTelegramConfig();
  41. $this->getServicesAPIsIDs();
  42. $this->loadPHPMailerConfig();
  43. $this->phpMailerOn = wf_getBoolFromVar($this->altCfg['SMS_SERVICES_ADVANCED_PHPMAILER_ON']);
  44. }
  45. /**
  46. * Loads PHPMailer config from storage
  47. */
  48. protected function loadPHPMailerConfig() {
  49. $mailerDebug = zb_StorageGet('SENDDOG_PHPMAILER_DEBUG');
  50. if (empty($mailerDebug)) {
  51. //Enable SMTP debugging
  52. // 1 - SMTP::DEBUG_OFF = off (for production use)
  53. // 2 - SMTP::DEBUG_CLIENT = client messages
  54. // 3 - SMTP::DEBUG_SERVER = client and server messages
  55. $mailerDebug = 1;
  56. zb_StorageSet('SENDDOG_PHPMAILER_DEBUG', $mailerDebug);
  57. }
  58. $mailerSMTPHost = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_HOST');
  59. if (empty($mailerSMTPHost)) {
  60. $mailerSMTPHost = 'smtp.mail.server';
  61. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_HOST', $mailerSMTPHost);
  62. }
  63. $mailerSMTPPort = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_PORT');
  64. if (empty($mailerSMTPPort)) {
  65. $mailerSMTPPort = '25';
  66. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_PORT', $mailerSMTPPort);
  67. }
  68. $mailerSMTPSecure = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_SECURE');
  69. if (empty($mailerSMTPSecure)) {
  70. $mailerSMTPSecure = 1;
  71. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_SECURE', $mailerSMTPSecure);
  72. }
  73. $mailerSMTPAuth = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_USEAUTH');
  74. if (empty($mailerSMTPAuth)) {
  75. $mailerSMTPAuth = '';
  76. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_USEAUTH', $mailerSMTPAuth);
  77. }
  78. $mailerSMTPUser = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_USER');
  79. if (empty($mailerSMTPUser)) {
  80. $mailerSMTPUser = '';
  81. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_USER', $mailerSMTPUser);
  82. }
  83. $mailerSMTPPasswd = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_PASSWD');
  84. if (empty($mailerSMTPPasswd)) {
  85. $mailerSMTPPasswd = '';
  86. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_PASSWD', $mailerSMTPPasswd);
  87. }
  88. $mailerSMTPDefaultFrom = zb_StorageGet('SENDDOG_PHPMAILER_SMTP_DEFAULTFROM');
  89. if (empty($mailerSMTPDefaultFrom)) {
  90. $mailerSMTPDefaultFrom = '';
  91. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_DEFAULTFROM', $mailerSMTPDefaultFrom);
  92. }
  93. $mailerAttachPath = zb_StorageGet('SENDDOG_PHPMAILER_ATTACHMENTS_PATH');
  94. if (empty($mailerAttachPath)) {
  95. $mailerAttachPath = 'exports/';
  96. zb_StorageSet('SENDDOG_PHPMAILER_ATTACHMENTS_PATH', $mailerAttachPath);
  97. }
  98. $this->settings['SENDDOG_PHPMAILER_DEBUG'] = $mailerDebug;
  99. $this->settings['SENDDOG_PHPMAILER_SMTP_HOST'] = $mailerSMTPHost;
  100. $this->settings['SENDDOG_PHPMAILER_SMTP_PORT'] = $mailerSMTPPort;
  101. $this->settings['SENDDOG_PHPMAILER_SMTP_SECURE'] = $mailerSMTPSecure;
  102. $this->settings['SENDDOG_PHPMAILER_SMTP_USEAUTH'] = $mailerSMTPAuth;
  103. $this->settings['SENDDOG_PHPMAILER_SMTP_USER'] = $mailerSMTPUser;
  104. $this->settings['SENDDOG_PHPMAILER_SMTP_PASSWD'] = $mailerSMTPPasswd;
  105. $this->settings['SENDDOG_PHPMAILER_SMTP_DEFAULTFROM'] = $mailerSMTPDefaultFrom;
  106. $this->settings['SENDDOG_PHPMAILER_ATTACHMENTS_PATH'] = $mailerAttachPath;
  107. }
  108. /**
  109. * Fills up $SrvsAPIsIDs with IDs => APINames
  110. *
  111. * @return void
  112. */
  113. protected function getServicesAPIsIDs() {
  114. $allSmsServices = $this->getSmsServicesConfigData();
  115. if (!empty($allSmsServices)) {
  116. foreach ($allSmsServices as $index => $record) {
  117. if ($record['default_service']) {
  118. $this->defaultSmsServiceId = $record['id'];
  119. $this->defaultSmsServiceApi = $record['api_file_name'];
  120. }
  121. $this->servicesApiId[$record['id']] = $record['api_file_name'];
  122. }
  123. }
  124. }
  125. /**
  126. * Returns array with contents of API_IMPL_PATH dir with names of implemented services APIs
  127. *
  128. * @param bool $useValueAsIndex - if true API name used as array index(key) also
  129. *
  130. * @return array
  131. */
  132. protected function getImplementedSmsServicesApiNames($useValueAsIndex = false) {
  133. $apiImplementations = rcms_scandir(self::API_IMPL_PATH, '*.php');
  134. foreach ($apiImplementations as $index => $item) {
  135. $apiName = str_replace('.php', '', $item);
  136. $apiImplementations[$index] = $apiName;
  137. if ($useValueAsIndex) {
  138. $apiImplementations[$apiName] = $apiImplementations[$index];
  139. unset($apiImplementations[$index]);
  140. }
  141. }
  142. return $apiImplementations;
  143. }
  144. /**
  145. * Gets SMS services config data from DB
  146. *
  147. * @param string $whereString of the query, including ' WHERE ' keyword
  148. *
  149. * @return array
  150. */
  151. public function getSmsServicesConfigData($whereString = '') {
  152. if (empty($whereString)) {
  153. $whereString = " ";
  154. }
  155. $query = "SELECT * FROM `sms_services` " . $whereString . " ;";
  156. $result = simple_queryall($query);
  157. return $result;
  158. }
  159. /**
  160. * Returns true if SMS service with such name already exists
  161. *
  162. * @param $serviceName
  163. * @param int $excludeEditedServiceId
  164. *
  165. * @return string
  166. */
  167. public function checkServiceNameExists($serviceName, $excludeEditedServiceId = 0) {
  168. $serviceName = trim($serviceName);
  169. if (empty($excludeEditedServiceId)) {
  170. $query = "SELECT `id` FROM `sms_services` WHERE `name` = '" . $serviceName . "';";
  171. } else {
  172. $query = "SELECT `id` FROM `sms_services` WHERE `name` = '" . $serviceName . "' AND `id` != '" . $excludeEditedServiceId . "';";
  173. }
  174. $result = simple_queryall($query);
  175. return ( empty($result) ) ? '' : $result[0]['id'];
  176. }
  177. /**
  178. * Returns reference to UbillingConfig object
  179. *
  180. * @return object
  181. */
  182. public function getUBConfigInstance() {
  183. return $this->ubConfig;
  184. }
  185. /**
  186. * Returns reference to UbillingSMS object
  187. *
  188. * @return object
  189. */
  190. public function getSmsQueueInstance() {
  191. return $this->smsQueue;
  192. }
  193. /**
  194. * Returns reference to UbillingMessageHelper object
  195. *
  196. * @return object
  197. */
  198. public function getUBMsgHelperInstance() {
  199. return $this->messages;
  200. }
  201. /**
  202. * Changes telegram bot token if differs from already stored
  203. *
  204. * @param $token
  205. */
  206. public function editTelegramBotToken($token) {
  207. //telegram bot token configuration
  208. if ($token != $this->settings['TELEGRAM_BOTTOKEN']) {
  209. zb_StorageSet('SENDDOG_TELEGRAM_BOTTOKEN', $token);
  210. log_register('SENDDOG CONFIG SET TELEGRAMBOTTOKEN');
  211. }
  212. }
  213. /**
  214. * Returns set of inputs, required for Telegram service configuration
  215. *
  216. * @return string
  217. */
  218. public function renderTelegramConfigInputs() {
  219. $inputs = wf_tag('h2');
  220. $inputs .= __('Telegram bot token') . '&nbsp' . wf_Link(self::URL_ME . '&showmisc=telegramcontacts', wf_img_sized('skins/icon_search_small.gif', __('Telegram bot contacts'), '16', '16'));
  221. $inputs .= wf_tag('h2', true);
  222. $inputs .= wf_TextInput('edittelegrambottoken', '', $this->settings['TELEGRAM_BOTTOKEN'], false, '50');
  223. return ($inputs);
  224. }
  225. /**
  226. * Changes PHPMailer settings
  227. */
  228. public function editPHPMailerConfig($smtpdebug, $smtphost, $smtpport, $smtpsecure, $smtpuser, $smtppasswd, $smtpfrom, $smtpauth, $attachpath) {
  229. zb_StorageSet('SENDDOG_PHPMAILER_DEBUG', $smtpdebug);
  230. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_HOST', $smtphost);
  231. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_PORT', $smtpport);
  232. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_SECURE', $smtpsecure);
  233. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_USER', $smtpuser);
  234. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_PASSWD', $smtppasswd);
  235. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_DEFAULTFROM', $smtpfrom);
  236. zb_StorageSet('SENDDOG_PHPMAILER_SMTP_USEAUTH', $smtpauth);
  237. zb_StorageSet('SENDDOG_PHPMAILER_ATTACHMENTS_PATH', $attachpath);
  238. log_register('SENDDOG PHPMailer settings changed');
  239. }
  240. public function renderPHPMailerConfigInputs() {
  241. // smtpDebug = 0, 1, 2 - off, client, server
  242. $inputs = wf_tag('h2');
  243. $inputs .= __('PHPMailer settings');
  244. $inputs .= wf_tag('h2', true);
  245. $inputs .= wf_TextInput('editsmtpdebug', 'SMTP debug feature(1 - off, 2 - client messages debug, 3 - server & client messages debug)', $this->settings['SENDDOG_PHPMAILER_DEBUG'], true, '5', 'digits');
  246. $inputs .= wf_TextInput('editsmtpsecure', 'SMTP secure connection type (1 - off, 2 - TLS, 3 - SSL)', $this->settings['SENDDOG_PHPMAILER_SMTP_SECURE'], true, '5', 'digits');
  247. $inputs .= wf_TextInput('editsmtphost', 'SMTP host', $this->settings['SENDDOG_PHPMAILER_SMTP_HOST'], true);
  248. $inputs .= wf_TextInput('editsmtpport', 'SMTP port', $this->settings['SENDDOG_PHPMAILER_SMTP_PORT'], true, '20', 'digits');
  249. $inputs .= wf_TextInput('editsmtpuser', 'SMTP user name', $this->settings['SENDDOG_PHPMAILER_SMTP_USER'], true);
  250. $inputs .= wf_PasswordInput('editsmtppasswd', 'SMTP user password', $this->settings['SENDDOG_PHPMAILER_SMTP_PASSWD'], true);
  251. $inputs .= wf_TextInput('editsmtpdefaultfrom', 'SMTP default "From" value', $this->settings['SENDDOG_PHPMAILER_SMTP_DEFAULTFROM'], true);
  252. $inputs .= wf_TextInput('editattachpath', 'Attachments temporary upload path', $this->settings['SENDDOG_PHPMAILER_ATTACHMENTS_PATH'], true, '25');
  253. $inputs .= wf_CheckInput('editsmtpuseauth', 'SMTP use authentication', true, wf_getBoolFromVar($this->settings['SENDDOG_PHPMAILER_SMTP_USEAUTH']));
  254. $inputs .= wf_delimiter(0);
  255. $inputs .= wf_Submit(__('Save'));
  256. $form = wf_Form('', 'POST', $inputs, 'glamour');
  257. return ($form);
  258. }
  259. /**
  260. * Renders JSON for JQDT
  261. *
  262. * @param $queryData
  263. */
  264. public function renderJSON($queryData) {
  265. $json = new wf_JqDtHelper();
  266. if (!empty($queryData)) {
  267. $data = array();
  268. foreach ($queryData as $eachRec) {
  269. foreach ($eachRec as $fieldName => $fieldVal) {
  270. switch ($fieldName) {
  271. case 'default_service':
  272. $data[] = ($fieldVal == 1) ? web_green_led() : web_red_led();
  273. break;
  274. case 'passwd':
  275. if (!$this->ubConfig->getAlterParam('PASSWORDSHIDE')) {
  276. $data[] = $fieldVal;
  277. }
  278. break;
  279. default:
  280. $data[] = $fieldVal;
  281. }
  282. }
  283. $linkId = wf_InputId();
  284. $linkId2 = wf_InputId();
  285. $linkId3 = wf_InputId();
  286. $actions = wf_JSAlert('#', web_delete_icon(), 'Removing this may lead to irreparable results', 'deleteSMSSrv(' . $eachRec['id'] . ', \'' . self::URL_ME . '\', \'deleteSMSSrv\', \'' . wf_InputId() . '\')') . ' ';
  287. $actions .= wf_tag('a', false, '', 'id="' . $linkId . '" href="#"');
  288. $actions .= web_edit_icon();
  289. $actions .= wf_tag('a', true);
  290. $actions .= wf_nbsp();
  291. $actions .= wf_tag('a', false, '', 'id="' . $linkId2 . '" href="#"');
  292. $actions .= wf_img_sized('skins/icon_dollar.gif', __('Balance'), '16', '16');
  293. $actions .= wf_tag('a', true);
  294. $actions .= wf_nbsp();
  295. $actions .= wf_tag('a', false, '', 'id="' . $linkId3 . '" href="#"');
  296. $actions .= wf_img_sized('skins/icon_sms_micro.gif', __('View SMS sending queue'), '16', '16');
  297. $actions .= wf_tag('a', true);
  298. $actions .= wf_tag('script', false, '', 'type="text/javascript"');
  299. $actions .= '
  300. $(\'#' . $linkId . '\').click(function(evt) {
  301. $.ajax({
  302. type: "POST",
  303. url: "' . self::URL_ME . '",
  304. data: {
  305. action:"editSMSSrv",
  306. smssrvid:"' . $eachRec['id'] . '",
  307. modalWindowId:"dialog-modal_' . $linkId . '",
  308. ModalWBID:"body_dialog-modal_' . $linkId . '"
  309. },
  310. success: function(result) {
  311. $(document.body).append(result);
  312. $(\'#dialog-modal_' . $linkId . '\').dialog("open");
  313. }
  314. });
  315. evt.preventDefault();
  316. return false;
  317. });
  318. $(\'#' . $linkId2 . '\').click(function(evt) {
  319. $.ajax({
  320. type: "POST",
  321. url: "' . self::URL_ME . '",
  322. data: {
  323. action:"getBalance",
  324. smssrvid:"' . $eachRec['id'] . '",
  325. SMSAPIName:"' . $eachRec['api_file_name'] . '",
  326. modalWindowId:"dialog-modal_' . $linkId2 . '",
  327. ModalWBID:"body_dialog-modal_' . $linkId2 . '"
  328. },
  329. success: function(result) {
  330. $(document.body).append(result);
  331. $(\'#dialog-modal_' . $linkId2 . '\').dialog("open");
  332. }
  333. });
  334. evt.preventDefault();
  335. return false;
  336. });
  337. $(\'#' . $linkId3 . '\').click(function(evt) {
  338. $.ajax({
  339. type: "POST",
  340. url: "' . self::URL_ME . '",
  341. data: {
  342. action:"getSMSQueue",
  343. smssrvid:"' . $eachRec['id'] . '",
  344. SMSAPIName:"' . $eachRec['api_file_name'] . '",
  345. modalWindowId:"dialog-modal_' . $linkId3 . '",
  346. ModalWBID:"body_dialog-modal_' . $linkId3 . '"
  347. },
  348. success: function(result) {
  349. $(document.body).append(result);
  350. $(\'#dialog-modal_' . $linkId3 . '\').dialog("open");
  351. }
  352. });
  353. evt.preventDefault();
  354. return false;
  355. });
  356. ';
  357. $actions .= wf_tag('script', true);
  358. $data[] = $actions;
  359. $json->addRow($data);
  360. unset($data);
  361. }
  362. }
  363. $json->getJson();
  364. }
  365. /**
  366. * Returns JQDT control and some JS bindings for dynamic forms
  367. *
  368. * @return string
  369. */
  370. public function renderJQDT() {
  371. $ajaxUrlStr = '' . self::URL_ME . '&ajax=true' . '';
  372. $jqdtId = 'jqdt_' . md5($ajaxUrlStr);
  373. $errorModalWindowId = wf_InputId();
  374. $hidePasswords = $this->ubConfig->getAlterParam('PASSWORDSHIDE');
  375. $columnTarget1 = ($hidePasswords) ? '4' : '5';
  376. $columnTarget2 = ($hidePasswords) ? '6' : '7';
  377. $columnTarget3 = ($hidePasswords) ? '7' : '8';
  378. $columnTarget4 = ($hidePasswords) ? '[5, 6, 7, 8]' : '[6, 7, 8, 9]';
  379. $columnTarget5 = ($hidePasswords) ? '[0, 1, 2, 3]' : '[0, 1, 2, 3, 4]';
  380. $columns = array();
  381. $opts = ' "order": [[ 0, "desc" ]],
  382. "columnDefs": [ {"className": "dt-head-center", "targets": ' . $columnTarget5 . '},
  383. {"width": "20%", "className": "dt-head-center jqdt_word_wrap", "targets": ' . $columnTarget1 . '},
  384. {"width": "8%", "targets": ' . $columnTarget2 . '},
  385. {"width": "10%", "targets": ' . $columnTarget3 . '},
  386. {"className": "dt-center", "targets": ' . $columnTarget4 . '} ]';
  387. $columns[] = ('ID');
  388. $columns[] = __('Name');
  389. $columns[] = __('Login');
  390. if (!$hidePasswords) {
  391. $columns[] = __('Password');
  392. }
  393. $columns[] = __('Gateway URL/IP');
  394. $columns[] = __('API key');
  395. $columns[] = __('Alpha name');
  396. $columns[] = __('Default service');
  397. $columns[] = __('API implementation file');
  398. $columns[] = __('Actions');
  399. $result = wf_JqDtLoader($columns, $ajaxUrlStr, false, __('results'), 100, $opts);
  400. $result .= wf_tag('script', false, '', 'type="text/javascript"');
  401. $result .= wf_JSEmptyFunc();
  402. $result .= wf_JSElemInsertedCatcherFunc();
  403. $result .= '
  404. // making an event binding for "SMS service edit form" Submit action
  405. // to be able to create "SMS service add/edit form" dynamically
  406. function toggleAlphaNameFieldReadonly() {
  407. if ( $(".__SMSSrvAlphaAsLoginChk").is(\':checked\') ) {
  408. $(".__SMSSrvAlphaName").val("");
  409. $(".__SMSSrvAlphaName").attr("readonly", "readonly");
  410. $(".__SMSSrvAlphaName").css(\'background-color\', \'#CECECE\');
  411. } else {
  412. $(".__SMSSrvAlphaName").removeAttr("readonly");
  413. $(".__SMSSrvAlphaName").css(\'background-color\', \'#FFFFFF\');
  414. }
  415. }
  416. onElementInserted(\'body\', \'.__SMSSrvAlphaAsLoginChk\', function(element) {
  417. toggleAlphaNameFieldReadonly();
  418. });
  419. $(document).on("change", ".__SMSSrvAlphaAsLoginChk", function(evt) {
  420. toggleAlphaNameFieldReadonly();
  421. });
  422. function chekEmptyVal(ctrlCalssName) {
  423. $(document).on("focus keydown", ctrlCalssName, function(evt) {
  424. if ( $(ctrlCalssName).css("border-color") == "rgb(255, 0, 0)" ) {
  425. $(ctrlCalssName).val("");
  426. $(ctrlCalssName).css("border-color", "");
  427. $(ctrlCalssName).css("color", "");
  428. }
  429. });
  430. }
  431. onElementInserted(\'body\', \'.__EmptyCheck\', function(element) {
  432. chekEmptyVal(\'.__EmptyCheck\');
  433. });
  434. $(document).on("submit", ".__SMSSrvForm", function(evt) {
  435. var AlphaNameAsLogin = ( $(".__SMSSrvAlphaAsLoginChk").is(\':checked\') ) ? 1 : 0;
  436. //var DefaultService = ( $(".__SMSSrvDefaultSrvChk").is(\':checked\') ) ? 1 : 0;
  437. var DefaultService = ( $(".__SMSSrvDefaultSrvChk").is(\':checked\') ) ? 1 : ( $(".__DefaultServHidID").val() ) ? 1 : 0;
  438. var FrmAction = $(".__SMSSrvForm").attr("action");
  439. var FrmData = $(".__SMSSrvForm").serialize() + \'&smssrvalphaaslogin=\' + AlphaNameAsLogin + \'&smssrvdefault=\' + DefaultService + \'&errfrmid=' . $errorModalWindowId . '\';
  440. //var modalWindowId = $(".__SMSSrvForm").closest(\'div\').attr(\'id\');
  441. evt.preventDefault();
  442. var emptyCheckClass = \'.__EmptyCheck\';
  443. if ( empty( $(emptyCheckClass).val() ) || $(emptyCheckClass).css("border-color") == "rgb(255, 0, 0)" ) {
  444. $(emptyCheckClass).css("border-color", "red");
  445. $(emptyCheckClass).css("color", "grey");
  446. $(emptyCheckClass).val("' . __('Mandatory field') . '");
  447. } else {
  448. $.ajax({
  449. type: "POST",
  450. url: FrmAction,
  451. data: FrmData,
  452. success: function(result) {
  453. if ( !empty(result) ) {
  454. $(document.body).append(result);
  455. $( \'#' . $errorModalWindowId . '\' ).dialog("open");
  456. } else {
  457. $(\'#' . $jqdtId . '\').DataTable().ajax.reload();
  458. $( \'#\'+$(".__SMSSrvFormModalWindowID").val() ).dialog("close");
  459. }
  460. }
  461. });
  462. }
  463. });
  464. function deleteSMSSrv(SMSSrvID, AjaxURL, ActionName, ErrFrmID) {
  465. $.ajax({
  466. type: "POST",
  467. url: AjaxURL,
  468. data: {action:ActionName, smssrvid:SMSSrvID, errfrmid:ErrFrmID},
  469. success: function(result) {
  470. if ( !empty(result) ) {
  471. $(document.body).append(result);
  472. $(\'#\'+ErrFrmID).dialog("open");
  473. }
  474. $(\'#' . $jqdtId . '\').DataTable().ajax.reload();
  475. }
  476. });
  477. }
  478. ';
  479. $result .= wf_tag('script', true);
  480. return $result;
  481. }
  482. /**
  483. * Returns SMS srvice addition form
  484. *
  485. * @return string
  486. */
  487. public function renderAddForm($modalWindowId) {
  488. $formId = 'Form_' . wf_InputId();
  489. $alphaAsLoginChkId = 'AlphaAsLoginChkID_' . wf_InputId();
  490. $defaultServiceChkId = 'DefaultServChkID_' . wf_InputId();
  491. $defaultServiceHidId = 'DefaultServHidID_' . wf_InputId();
  492. $closeFormChkId = 'CloseFrmChkID_' . wf_InputId();
  493. $apiImplementations = $this->getImplementedSmsServicesApiNames(true);
  494. // check if there is any services already added
  495. $query = "SELECT `id` FROM `sms_services`;";
  496. $result = simple_queryall($query);
  497. $useAsDefaultService = ( empty($result) ); // if no services yet - use the first added as default
  498. $inputs = wf_TextInput('smssrvname', __('Name'), '', true, '', '', '__EmptyCheck');
  499. $inputs .= wf_TextInput('smssrvlogin', __('Login'), '', true);
  500. $inputs .= wf_CheckInput('smssrvalphaaslogin', __('Use login as alpha name'), true, false, $alphaAsLoginChkId, '__SMSSrvAlphaAsLoginChk');
  501. $inputs .= ($this->ubConfig->getAlterParam('PASSWORDSHIDE')) ? wf_PasswordInput('smssrvpassw', __('Password'), '', true) :
  502. wf_TextInput('smssrvpassw', __('Password'), '', true);
  503. $inputs .= wf_TextInput('smssrvurlip', __('Gateway URL/IP'), '', true);
  504. $inputs .= wf_TextInput('smssrvapikey', __('API key'), '', true);
  505. $inputs .= wf_TextInput('smssrvalphaname', __('Alpha name'), '', true, '', '', '__SMSSrvAlphaName');
  506. $inputs .= wf_Selector('smssrvapiimplementation', $apiImplementations, __('API implementation file'), '', true);
  507. if ($useAsDefaultService) {
  508. $inputs .= wf_tag('span', false, '', 'style="display: block; margin: 5px 2px"');
  509. $inputs .= __('Will be used as a default SMS service');
  510. $inputs .= wf_tag('span', true);
  511. $inputs .= wf_HiddenInput('smssrvdefault', 'true', $defaultServiceHidId, '__DefaultServHidID');
  512. } else {
  513. $inputs .= wf_CheckInput('smssrvdefault', __('Use as default SMS service'), true, false, $defaultServiceChkId, '__SMSSrvDefaultSrvChk');
  514. }
  515. $inputs .= wf_HiddenInput('', $modalWindowId, '', '__SMSSrvFormModalWindowID');
  516. $inputs .= wf_CheckInput('FormClose', __('Close form after operation'), false, true, $closeFormChkId);
  517. $inputs .= wf_HiddenInput('smssrvcreate', 'true');
  518. $inputs .= wf_delimiter();
  519. $inputs .= wf_Submit(__('Create'));
  520. $form = wf_Form(self::URL_ME, 'POST', $inputs, 'glamour __SMSSrvForm', '', $formId);
  521. return ($form);
  522. }
  523. /**
  524. * Returns SMS service editing form
  525. *
  526. * @return string
  527. */
  528. public function renderEditForm($smsServiceId, $modalWindowId) {
  529. $formId = 'Form_' . wf_InputId();
  530. $alphaAsLoginChkId = 'AlphaAsLoginChkID_' . wf_InputId();
  531. $defaultServiceChkId = 'DefaultServChkID_' . wf_InputId();
  532. $closeFormChkId = 'CloseFrmChkID_' . wf_InputId();
  533. $apiImplementations = $this->getImplementedSmsServicesApiNames(true);
  534. $smsServiceData = $this->getSmsServicesConfigData(" WHERE `id` = " . $smsServiceId);
  535. $serviceName = $smsServiceData[0]['name'];
  536. $serviceLogin = $smsServiceData[0]['login'];
  537. $servicePassword = $smsServiceData[0]['passwd'];
  538. $serviceGatewayAddr = $smsServiceData[0]['url_addr'];
  539. $serviceAlphaName = $smsServiceData[0]['alpha_name'];
  540. $serviceApiKey = $smsServiceData[0]['api_key'];
  541. $serviceIsDefault = $smsServiceData[0]['default_service'];
  542. $serviceApiFile = $smsServiceData[0]['api_file_name'];
  543. $inputs = wf_TextInput('smssrvname', __('Name'), $serviceName, true, '', '', '__EmptyCheck');
  544. $inputs .= wf_TextInput('smssrvlogin', __('Login'), $serviceLogin, true);
  545. $inputs .= wf_CheckInput('smssrvalphaaslogin', __('Use login as alpha name'), true, (!empty($serviceLogin) and $serviceLogin == $serviceAlphaName), $alphaAsLoginChkId, '__SMSSrvAlphaAsLoginChk');
  546. $inputs .= ($this->ubConfig->getAlterParam('PASSWORDSHIDE')) ? wf_PasswordInput('smssrvpassw', __('Password'), $servicePassword, true) :
  547. wf_TextInput('smssrvpassw', __('Password'), $servicePassword, true);
  548. $inputs .= wf_TextInput('smssrvurlip', __('Gateway URL/IP'), $serviceGatewayAddr, true);
  549. $inputs .= wf_TextInput('smssrvapikey', __('API key'), $serviceApiKey, true);
  550. $inputs .= wf_TextInput('smssrvalphaname', __('Alpha name'), $serviceAlphaName, true, '', '', '__SMSSrvAlphaName');
  551. $inputs .= wf_Selector('smssrvapiimplementation', $apiImplementations, __('API implementation file'), $serviceApiFile, true);
  552. $inputs .= wf_CheckInput('smssrvdefault', __('Use as default SMS service'), true, $serviceIsDefault, $defaultServiceChkId, '__SMSSrvDefaultSrvChk');
  553. $inputs .= wf_CheckInput('FormClose', __('Close form after operation'), false, true, $closeFormChkId);
  554. $inputs .= wf_HiddenInput('', $modalWindowId, '', '__SMSSrvFormModalWindowID');
  555. $inputs .= wf_HiddenInput('action', 'editSMSSrv');
  556. $inputs .= wf_HiddenInput('smssrvid', $smsServiceId);
  557. $inputs .= wf_delimiter();
  558. $inputs .= wf_Submit(__('Edit'));
  559. $form = wf_Form(self::URL_ME, 'POST', $inputs, 'glamour __SMSSrvForm', '', $formId);
  560. return $form;
  561. }
  562. /**
  563. * Adds SMS service to DB
  564. *
  565. * @param $smsServiceName
  566. * @param $smsServiceLogin
  567. * @param $smsServicePassword
  568. * @param $smsServiceBaseUrl
  569. * @param $smsServiceApiKey
  570. * @param $smsServiceAlphaName
  571. * @param $smsServiceApiImplName
  572. * @param int $useAsDefaultService
  573. */
  574. public function addSmsService($smsServiceName, $smsServiceLogin, $smsServicePassword, $smsServiceBaseUrl, $smsServiceApiKey, $smsServiceAlphaName, $smsServiceApiImplName, $useAsDefaultService = 0) {
  575. if ($useAsDefaultService) {
  576. $tQuery = "UPDATE `sms_services` SET `default_service` = 0;";
  577. nr_query($tQuery);
  578. }
  579. $tQuery = "INSERT INTO `sms_services` ( `id`,`name`,`login`,`passwd`, `url_addr`, `api_key`, `alpha_name`, `default_service`, `api_file_name`)
  580. VALUES ( NULL, '" . $smsServiceName . "','" . $smsServiceLogin . "','" . $smsServicePassword . "','" . $smsServiceBaseUrl . "','" .
  581. $smsServiceApiKey . "','" . $smsServiceAlphaName . "','" . $useAsDefaultService . "','" . $smsServiceApiImplName . "');";
  582. nr_query($tQuery);
  583. log_register('CREATE SMS service [' . $smsServiceName . '] alpha name: `' . $smsServiceAlphaName . '`');
  584. }
  585. /**
  586. * Edits SMS service
  587. *
  588. * @param $smsServiceId
  589. * @param $smsServiceName
  590. * @param $smsServiceLogin
  591. * @param $smsServicePassword
  592. * @param $smsServiceBaseUrl
  593. * @param $smsServiceApiKey
  594. * @param $smsServiceAlphaName
  595. * @param $smsServiceApiImplName
  596. * @param int $useAsDefaultService
  597. */
  598. public function editSmsService($smsServiceId, $smsServiceName, $smsServiceLogin, $smsServicePassword, $smsServiceBaseUrl, $smsServiceApiKey, $smsServiceAlphaName, $smsServiceApiImplName, $useAsDefaultService = 0) {
  599. if ($useAsDefaultService) {
  600. $tQuery = "UPDATE `sms_services` SET `default_service` = 0;";
  601. nr_query($tQuery);
  602. }
  603. $tQuery = "UPDATE `sms_services`
  604. SET `name` = '" . $smsServiceName . "',
  605. `login` = '" . $smsServiceLogin . "',
  606. `passwd` = '" . $smsServicePassword . "',
  607. `url_addr` = '" . $smsServiceBaseUrl . "',
  608. `api_key` = '" . $smsServiceApiKey . "',
  609. `alpha_name` = '" . $smsServiceAlphaName . "',
  610. `default_service` = '" . $useAsDefaultService . "',
  611. `api_file_name` = '" . $smsServiceApiImplName . "'
  612. WHERE `id`= '" . $smsServiceId . "' ;";
  613. nr_query($tQuery);
  614. log_register('CHANGE SMS service [' . $smsServiceId . '] `' . $smsServiceName . '` alpha name: `' . $smsServiceAlphaName . '`');
  615. }
  616. /**
  617. * Deletes SMS service
  618. *
  619. * @param $smsServiceId
  620. * @param string $smsServiceName
  621. * @param string $smsServiceAlphaName
  622. */
  623. public function deleteSmsService($smsServiceId, $smsServiceName = '', $smsServiceAlphaName = '') {
  624. $query = "DELETE FROM `sms_services` WHERE `id` = '" . $smsServiceId . "';";
  625. nr_query($query);
  626. log_register('DELETE SMS service [' . $smsServiceId . '] `' . $smsServiceName . '` alpha name: `' . $smsServiceAlphaName . '`');
  627. }
  628. /**
  629. * Check if SMS service is protected from deletion
  630. *
  631. * @param $smsServiceId
  632. *
  633. * @return bool
  634. */
  635. public function checkSmsServiceProtected($smsServiceId) {
  636. $query = "SELECT `id` FROM `sms_services_relations` WHERE `sms_srv_id` = " . $smsServiceId . ";";
  637. $result = simple_queryall($query);
  638. return (!empty($result));
  639. }
  640. /**
  641. * Loads and sends all stored SMS from system queue
  642. * Or checks statuses of already sent SMS
  643. *
  644. * @param bool $checkStatuses
  645. *
  646. * @return integer
  647. */
  648. public function smsProcessing($checkStatuses = false) {
  649. $allMessages = array();
  650. $smsCount = 0;
  651. if ($checkStatuses) {
  652. $smsCheckStatusExpireDays = $this->altCfg['SMS_CHECKSTATUS_EXPIRE_DAYS'];
  653. $query = "UPDATE `sms_history` SET `no_statuschk` = 1,
  654. `send_status` = '" . __('SMS status check period expired') . "'
  655. WHERE ABS( DATEDIFF(NOW(), `date_send`) ) > " . $smsCheckStatusExpireDays . "
  656. AND no_statuschk < 1 AND `delivered` < 1;";
  657. nr_query($query);
  658. $query = "SELECT * FROM `sms_history` WHERE `no_statuschk` < 1 AND `delivered` < 1;";
  659. $messages = simple_queryall($query);
  660. $smsCount = count($messages);
  661. if ($smsCount > 0) {
  662. $allMessages = zb_sortArray($messages, 'smssrvid');
  663. }
  664. } else {
  665. $smsCount = $this->smsQueue->getQueueCount();
  666. if ($smsCount > 0) {
  667. $allMessages = zb_sortArray($this->smsQueue->getQueueData(), 'smssrvid');
  668. }
  669. }
  670. /*
  671. Annie, are you okay, you okay, you okay, Annie?
  672. Annie, are you okay, you okay, you okay, Annie?
  673. Annie, are you okay, you okay, you okay, Annie?
  674. Annie, are you okay, you okay, you okay, Annie?
  675. */
  676. if (!empty($smsCount)) {
  677. $nextServiceId = null;
  678. $currentServiceId = null;
  679. $tmpMessagePack = array();
  680. $arrayEnd = false;
  681. end($allMessages);
  682. $lastArrayKey = key($allMessages);
  683. foreach ($allMessages as $io => $eachmessage) {
  684. // checking, if we're at the end of array and current element is the last one
  685. if ($io === $lastArrayKey) {
  686. $arrayEnd = true;
  687. // if we're at the end of array and $TmpMessPack is empty - that means that probably array consists only of one element
  688. // but if $TmpMessPack is NOT empty - that probably means that we've reached the last message for the current SMS service(smssrvid)
  689. //if (empty($tmpMessagePack)) {
  690. $tmpMessagePack[] = $eachmessage;
  691. //}
  692. }
  693. if (is_null($nextServiceId) and is_null($currentServiceId)) {
  694. // init the values on the very begining of the array
  695. $nextServiceId = $eachmessage['smssrvid'];
  696. $currentServiceId = $eachmessage['smssrvid'];
  697. } else {
  698. // just getting next SMS service ID
  699. $nextServiceId = $eachmessage['smssrvid'];
  700. }
  701. // checking if SMS service ID is changed comparing to previous one or we reached the end of an array
  702. // if so - we need to process accumulated messages in $TmpMessPack
  703. // if not - keep going to the next array element and accumulate messages to $TmpMessPack
  704. if (($nextServiceId !== $currentServiceId or $arrayEnd) and ! empty($tmpMessagePack)) {
  705. $this->actualSmsProcessing($tmpMessagePack, $currentServiceId, $checkStatuses);
  706. $tmpMessagePack = array();
  707. }
  708. $tmpMessagePack[] = $eachmessage;
  709. // checking and processing the very last element of the $AllMessages array if it has different SMS service ID
  710. if (($nextServiceId !== $currentServiceId and $arrayEnd) and ! empty($tmpMessagePack)) {
  711. $this->actualSmsProcessing($tmpMessagePack, $nextServiceId, $checkStatuses);
  712. }
  713. $currentServiceId = $eachmessage['smssrvid'];
  714. }
  715. }
  716. return ($smsCount);
  717. }
  718. /**
  719. * Creates SMS service object from given API file name and processes the
  720. *
  721. * @param $messagePack
  722. * @param int $serviceId
  723. * @param bool $checkStatuses
  724. *
  725. * @return void
  726. */
  727. protected function actualSmsProcessing($messagePack, $serviceId = 0, $checkStatuses = false) {
  728. // if for some reason $serviceId is empty - use SMS service chosen as default
  729. if (empty($serviceId) or $serviceId == $this->defaultSmsServiceId) {
  730. $serviceId = $this->defaultSmsServiceId;
  731. $serviceApi = $this->defaultSmsServiceApi;
  732. } else {
  733. $serviceApi = (empty($this->servicesApiId[$serviceId])) ? '' : $this->servicesApiId[$serviceId];
  734. }
  735. if (empty($serviceApi)) {
  736. log_register('SENDDOG SMS service with ID [' . $serviceId . '] does not exists');
  737. } else {
  738. include_once (self::API_IMPL_PATH . $serviceApi . '.php');
  739. $tmpApiObj = new $serviceApi($serviceId, $messagePack);
  740. if ($checkStatuses) {
  741. $tmpApiObj->checkMessagesStatuses();
  742. } else {
  743. $tmpApiObj->pushMessages();
  744. }
  745. }
  746. }
  747. /**
  748. * Loads and sends all email messages from system queue via PHPMailer
  749. *
  750. * @return int
  751. */
  752. public function phpMailProcessing() {
  753. $email = new UbillingPHPMail();
  754. $messagesCount = $email->getQueueCount();
  755. if ($messagesCount > 0) {
  756. $allMessagesData = $email->getQueueData();
  757. if (!empty($allMessagesData)) {
  758. foreach ($allMessagesData as $io => $eachmessage) {
  759. $email->directPushEmail($eachmessage['email'], $eachmessage['subj'], $eachmessage['message'], $eachmessage['attachpath'], $eachmessage['bodyashtml'], $eachmessage['from'], $eachmessage['customheaders']);
  760. $email->phpMailer->clearAllRecipients();
  761. $email->phpMailer->clearAttachments();
  762. $email->deleteAttachment($eachmessage['attachpath']);
  763. $email->deleteEmail($eachmessage['filename']);
  764. }
  765. }
  766. }
  767. return ($messagesCount);
  768. }
  769. /**
  770. * Dirty input data filtering
  771. *
  772. * @param $string - string to filter
  773. *
  774. * @return string
  775. */
  776. public function safeEscapeString($string) {
  777. @$result = preg_replace("#[~@\?\%\/\;=\*\>\<\"\']#Uis", '', $string);
  778. return ($result);
  779. }
  780. }