3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 abstract class CRM_SMS_Provider
{
20 * We only need one instance of this object. So we use the singleton
21 * pattern and cache the instance in this variable
25 static private $_singleton = array();
26 const MAX_SMS_CHAR
= 460;
29 * Singleton function used to manage this object.
31 * @param array $providerParams
36 public static function &singleton($providerParams = array(), $force = FALSE) {
37 $mailingID = CRM_Utils_Array
::value('mailing_id', $providerParams);
38 $providerID = CRM_Utils_Array
::value('provider_id', $providerParams);
39 $providerName = CRM_Utils_Array
::value('provider', $providerParams);
41 if (!$providerID && $mailingID) {
42 $providerID = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_Mailing', $mailingID, 'sms_provider_id', 'id');
43 $providerParams['provider_id'] = $providerID;
46 $providerName = CRM_SMS_BAO_Provider
::getProviderInfo($providerID, 'name');
50 CRM_Core_Error
::fatal('Provider not known or not provided.');
53 $providerName = CRM_Utils_Type
::escape($providerName, 'String');
54 $cacheKey = "{$providerName}_" . (int) $providerID . "_" . (int) $mailingID;
56 if (!isset(self
::$_singleton[$cacheKey]) ||
$force) {
57 $ext = CRM_Extension_System
::singleton()->getMapper();
58 if ($ext->isExtensionKey($providerName)) {
59 $providerClass = $ext->keyToClass($providerName);
60 require_once "{$providerClass}.php";
63 // If we are running unit tests we simulate an SMS provider with the name "CiviTestSMSProvider"
64 if ($providerName !== 'CiviTestSMSProvider') {
65 CRM_Core_Error
::fatal("Could not locate extension for {$providerName}.");
67 $providerClass = 'CiviTestSMSProvider';
70 self
::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
72 return self
::$_singleton[$cacheKey];
76 * Send an SMS Message via the API Server.
78 * @param array $recipients
79 * @param string $header
80 * @param string $message
83 abstract public function send($recipients, $header, $message, $dncID = NULL);
86 * Return message text.
88 * Child class could override this function to have better control over the message being sent.
90 * @param string $message
91 * @param int $contactID
92 * @param array $contactDetails
96 public function getMessage($message, $contactID, $contactDetails) {
97 $html = $message->getHTMLBody();
98 $text = $message->getTXTBody();
100 return $html ?
$html : $text;
104 * Get recipient details.
106 * @param array $fields
107 * @param array $additionalDetails
111 public function getRecipientDetails($fields, $additionalDetails) {
112 // we could do more altering here
113 $fields['To'] = $fields['phone'];
118 * @param int $apiMsgID
120 * @param array $headers
124 * @return self|null|object
125 * @throws CRM_Core_Exception
127 public function createActivity($apiMsgID, $message, $headers = array(), $jobID = NULL, $userID = NULL) {
130 SELECT scheduled_id FROM civicrm_mailing m
131 INNER JOIN civicrm_mailing_job mj ON mj.mailing_id = m.id AND mj.id = %1";
132 $sourceContactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($jobID, 'Integer')));
135 $sourceContactID = $userID;
138 $session = CRM_Core_Session
::singleton();
139 $sourceContactID = $session->get('userID');
142 if (!$sourceContactID) {
143 $sourceContactID = CRM_Utils_Array
::value('Contact', $headers);
145 if (!$sourceContactID) {
149 // note: lets not pass status here, assuming status will be updated by callback
150 $activityParams = array(
151 'source_contact_id' => $sourceContactID,
152 'target_contact_id' => $headers['contact_id'],
153 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
154 'activity_date_time' => date('YmdHis'),
155 'details' => $message,
156 'result' => $apiMsgID,
158 return CRM_Activity_BAO_Activity
::create($activityParams);
162 * @param string $name
165 * @param null $default
166 * @param string $location
170 public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
171 static $store = NULL;
172 $value = CRM_Utils_Request
::retrieve($name, $type, $store,
173 FALSE, $default, $location
175 if ($abort && $value === NULL) {
176 Civi
::log()->warning("Could not find an entry for $name in $location");
177 echo "Failure: Missing Parameter<p>";
187 * @param int $trackID
189 * @return self|null|object
190 * @throws CRM_Core_Exception
192 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
193 $message = new CRM_SMS_Message();
194 $message->from
= $from;
196 $message->body
= $body;
197 $message->trackID
= $trackID;
198 // call hook_civicrm_inboundSMS
199 CRM_Utils_Hook
::inboundSMS($message);
201 if (!$message->fromContactID
) {
202 // find sender by phone number if $fromContactID not set by hook
203 $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from
), $like, "like");
204 $message->fromContactID
= CRM_Core_DAO
::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array(
205 1 => array($formatFrom, 'String'),
209 if (!$message->fromContactID
) {
210 // unknown mobile sender -- create new contact
211 // use fake @mobile.sms email address for new contact since civi
212 // requires email or name for all contacts
213 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
214 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
215 $phoneloc = array_search('Home', $locationTypes);
216 $phonetype = array_search('Mobile', $phoneTypes);
217 $stripFrom = $this->stripPhone($message->from
);
218 $contactparams = array(
219 'contact_type' => 'Individual',
222 'location_type_id' => $phoneloc,
223 'email' => $stripFrom . '@mobile.sms',
228 'phone_type_id' => $phonetype,
229 'location_type_id' => $phoneloc,
230 'phone' => $stripFrom,
234 $fromContact = CRM_Contact_BAO_Contact
::create($contactparams, FALSE, TRUE, FALSE);
235 $message->fromContactID
= $fromContact->id
;
238 if (!$message->toContactID
) {
239 // find recipient if $toContactID not set by hook
241 $message->toContactID
= CRM_Core_DAO
::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array(
242 1 => array('%' . $message->to
, 'String'),
246 $message->toContactID
= $message->fromContactID
;
250 if ($message->fromContactID
) {
251 // note: lets not pass status here, assuming status will be updated by callback
252 $activityParams = array(
253 'source_contact_id' => $message->toContactID
,
254 'target_contact_id' => $message->fromContactID
,
255 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
256 'activity_date_time' => date('YmdHis'),
257 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
258 'details' => $message->body
,
259 'phone_number' => $message->from
,
261 if ($message->trackID
) {
262 $activityParams['result'] = CRM_Utils_Type
::escape($message->trackID
, 'String');
265 $result = CRM_Activity_BAO_Activity
::create($activityParams);
266 Civi
::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
274 * @return mixed|string
276 public function stripPhone($phone) {
277 $newphone = preg_replace('/[^0-9x]/', '', $phone);
278 while (substr($newphone, 0, 1) == "1") {
279 $newphone = substr($newphone, 1);
281 while (strpos($newphone, "xx") !== FALSE) {
282 $newphone = str_replace("xx", "x", $newphone);
284 while (substr($newphone, -1) == "x") {
285 $newphone = substr($newphone, 0, -1);
293 * @param string $format
295 * @return mixed|string
297 public function formatPhone($phone, &$kind, $format = "dash") {
298 $phoneA = explode("x", $phone);
299 switch (strlen($phoneA[0])) {
309 $kind = $phoneA[1] ?
"LocalX" : "Local";
311 $exch = substr($phone, 0, 3);
312 $uniq = substr($phone, 3, 4);
317 $kind = $phoneA[1] ?
"LongX" : "Long";
318 $area = substr($phone, 0, 3);
319 $exch = substr($phone, 3, 3);
320 $uniq = substr($phone, 6, 4);
331 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
332 $newphone = str_replace('%%', '%', $newphone);
333 $newphone = str_replace('%%', '%', $newphone);
337 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
338 $newphone = trim(trim(trim($newphone, "x"), "-"));
342 $newphone = $area . $exch . $uniq . "x" . $ext;
343 $newphone = trim(trim(trim($newphone, "x"), "-"));
359 public function urlEncode($values) {
361 foreach ($values as $key => $value) {
362 $value = urlencode($value);
363 $uri .= "&{$key}={$value}";
366 $uri = substr($uri, 1);