BxDolTwilio.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. class BxDolTwilio extends BxDolFactory implements iBxDolSingleton
  10. {
  11. protected $_sSid;
  12. protected $_sToken;
  13. protected $_sFromNumber;
  14. protected function __construct()
  15. {
  16. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  17. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  18. parent::__construct();
  19. $this->_sSid = getParam('sys_twilio_gate_sid');
  20. $this->_sToken = getParam('sys_twilio_gate_token');
  21. $this->_sFromNumber = getParam('sys_twilio_gate_from_number');
  22. }
  23. /**
  24. * Prevent cloning the instance
  25. */
  26. public function __clone()
  27. {
  28. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  29. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  30. }
  31. /**
  32. * Get singleton instance of the class
  33. */
  34. public static function getInstance()
  35. {
  36. if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
  37. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolTwilio();
  38. return $GLOBALS['bxDolClasses'][__CLASS__];
  39. }
  40. public function sendSms($sTo, $sMessage, $sFrom = '')
  41. {
  42. try{
  43. require_once BX_DIRECTORY_PATH_PLUGINS . 'Twilio/autoload.php'; // Loads the library
  44. $client = new Twilio\Rest\Client($this->_sSid, $this->_sToken);
  45. $aParams = array('body' => $sMessage, 'from' => $sFrom != '' ? $this->normalizePhone($sFrom) : $this->normalizePhone($this->_sFromNumber));
  46. $client->messages->create($this->normalizePhone($sTo), $aParams);
  47. return true;
  48. }
  49. catch (Exception $oException) {
  50. $this->writeLog($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
  51. return false;
  52. }
  53. }
  54. public function normalizePhone($sPhone){
  55. $sPhone = trim($sPhone);
  56. if (substr($sPhone, 0, 1) != '+'){
  57. $sPhone = '+' . $sPhone;
  58. }
  59. return $sPhone;
  60. }
  61. private function writeLog($sString)
  62. {
  63. bx_log('sys_twilio', $sString);
  64. }
  65. }
  66. /** @} */