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 = [];
26 const MAX_SMS_CHAR
= 460;
29 * Singleton function used to manage this object.
31 * @param array $providerParams
35 * @throws CRM_Core_Exception
37 public static function &singleton($providerParams = [], $force = FALSE) {
38 $mailingID = $providerParams['mailing_id'] ??
NULL;
39 $providerID = $providerParams['provider_id'] ??
NULL;
40 $providerName = $providerParams['provider'] ??
NULL;
42 if (!$providerID && $mailingID) {
43 $providerID = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_Mailing', $mailingID, 'sms_provider_id', 'id');
44 $providerParams['provider_id'] = $providerID;
47 $providerName = CRM_SMS_BAO_Provider
::getProviderInfo($providerID, 'name');
51 throw new CRM_Core_Exception('Provider not known or not provided.');
54 $providerName = CRM_Utils_Type
::escape($providerName, 'String');
55 $cacheKey = "{$providerName}_" . (int) $providerID . "_" . (int) $mailingID;
57 if (!isset(self
::$_singleton[$cacheKey]) ||
$force) {
58 $ext = CRM_Extension_System
::singleton()->getMapper();
59 if ($ext->isExtensionKey($providerName)) {
60 $providerClass = $ext->keyToClass($providerName);
61 require_once "{$providerClass}.php";
64 // If we are running unit tests we simulate an SMS provider with the name "CiviTestSMSProvider"
65 if ($providerName !== 'CiviTestSMSProvider') {
66 throw new CRM_Core_Exception("Could not locate extension for {$providerName}.");
68 $providerClass = 'CiviTestSMSProvider';
71 self
::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
73 return self
::$_singleton[$cacheKey];
77 * Send an SMS Message via the API Server.
79 * @param array $recipients
80 * @param string $header
81 * @param string $message
84 abstract public function send($recipients, $header, $message, $dncID = NULL);
87 * Return message text.
89 * Child class could override this function to have better control over the message being sent.
91 * @param string $message
92 * @param int $contactID
93 * @param array $contactDetails
97 public function getMessage($message, $contactID, $contactDetails) {
98 $html = $message->getHTMLBody();
99 $text = $message->getTXTBody();
101 return $html ?
$html : $text;
105 * Get recipient details.
107 * @param array $fields
108 * @param array $additionalDetails
112 public function getRecipientDetails($fields, $additionalDetails) {
113 // we could do more altering here
114 $fields['To'] = $fields['phone'];
119 * @param int $apiMsgID
121 * @param array $headers
125 * @return self|null|object
126 * @throws CRM_Core_Exception
128 public function createActivity($apiMsgID, $message, $headers = [], $jobID = NULL, $userID = NULL) {
131 SELECT scheduled_id FROM civicrm_mailing m
132 INNER JOIN civicrm_mailing_job mj ON mj.mailing_id = m.id AND mj.id = %1";
133 $sourceContactID = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($jobID, 'Integer')));
136 $sourceContactID = $userID;
139 $session = CRM_Core_Session
::singleton();
140 $sourceContactID = $session->get('userID');
143 if (!$sourceContactID) {
144 $sourceContactID = $headers['Contact'] ??
NULL;
146 if (!$sourceContactID) {
150 // note: lets not pass status here, assuming status will be updated by callback
151 $activityParams = array(
152 'source_contact_id' => $sourceContactID,
153 'target_contact_id' => $headers['contact_id'],
154 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
155 'activity_date_time' => date('YmdHis'),
156 'details' => $message,
157 'result' => $apiMsgID,
159 return CRM_Activity_BAO_Activity
::create($activityParams);
163 * @param string $name
166 * @param null $default
167 * @param string $location
171 public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
172 static $store = NULL;
173 $value = CRM_Utils_Request
::retrieve($name, $type, $store,
174 FALSE, $default, $location
176 if ($abort && $value === NULL) {
177 Civi
::log()->warning("Could not find an entry for $name in $location");
178 echo "Failure: Missing Parameter<p>";
188 * @param int $trackID
190 * @return self|null|object
191 * @throws CRM_Core_Exception
193 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
194 $message = new CRM_SMS_Message();
195 $message->from
= $from;
197 $message->body
= $body;
198 $message->trackID
= $trackID;
199 // call hook_civicrm_inboundSMS
200 CRM_Utils_Hook
::inboundSMS($message);
202 if (!$message->fromContactID
) {
203 // find sender by phone number if $fromContactID not set by hook
204 $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from
), $like, "like");
205 $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(
206 1 => array($formatFrom, 'String'),
210 if (!$message->fromContactID
) {
211 // unknown mobile sender -- create new contact
212 // use fake @mobile.sms email address for new contact since civi
213 // requires email or name for all contacts
214 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
215 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
216 $phoneloc = array_search('Home', $locationTypes);
217 $phonetype = array_search('Mobile', $phoneTypes);
218 $stripFrom = $this->stripPhone($message->from
);
219 $contactparams = array(
220 'contact_type' => 'Individual',
223 'location_type_id' => $phoneloc,
224 'email' => $stripFrom . '@mobile.sms',
229 'phone_type_id' => $phonetype,
230 'location_type_id' => $phoneloc,
231 'phone' => $stripFrom,
235 $fromContact = CRM_Contact_BAO_Contact
::create($contactparams, FALSE, TRUE, FALSE);
236 $message->fromContactID
= $fromContact->id
;
239 if (!$message->toContactID
) {
240 // find recipient if $toContactID not set by hook
242 $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(
243 1 => array('%' . $message->to
, 'String'),
247 $message->toContactID
= $message->fromContactID
;
251 if ($message->fromContactID
) {
252 // note: lets not pass status here, assuming status will be updated by callback
253 $activityParams = array(
254 'source_contact_id' => $message->toContactID
,
255 'target_contact_id' => $message->fromContactID
,
256 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
257 'activity_date_time' => date('YmdHis'),
258 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
259 'details' => $message->body
,
260 'phone_number' => $message->from
,
262 if ($message->trackID
) {
263 $activityParams['result'] = CRM_Utils_Type
::escape($message->trackID
, 'String');
266 $result = CRM_Activity_BAO_Activity
::create($activityParams);
267 Civi
::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
275 * @return mixed|string
277 public function stripPhone($phone) {
278 $newphone = preg_replace('/[^0-9x]/', '', $phone);
279 while (substr($newphone, 0, 1) == "1") {
280 $newphone = substr($newphone, 1);
282 while (strpos($newphone, "xx") !== FALSE) {
283 $newphone = str_replace("xx", "x", $newphone);
285 while (substr($newphone, -1) == "x") {
286 $newphone = substr($newphone, 0, -1);
294 * @param string $format
296 * @return mixed|string
298 public function formatPhone($phone, &$kind, $format = "dash") {
299 $phoneA = explode("x", $phone);
300 switch (strlen($phoneA[0])) {
310 $kind = $phoneA[1] ?
"LocalX" : "Local";
312 $exch = substr($phone, 0, 3);
313 $uniq = substr($phone, 3, 4);
318 $kind = $phoneA[1] ?
"LongX" : "Long";
319 $area = substr($phone, 0, 3);
320 $exch = substr($phone, 3, 3);
321 $uniq = substr($phone, 6, 4);
332 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
333 $newphone = str_replace('%%', '%', $newphone);
334 $newphone = str_replace('%%', '%', $newphone);
338 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
339 $newphone = trim(trim(trim($newphone, "x"), "-"));
343 $newphone = $area . $exch . $uniq . "x" . $ext;
344 $newphone = trim(trim(trim($newphone, "x"), "-"));
360 public function urlEncode($values) {
362 foreach ($values as $key => $value) {
363 $value = urlencode($value);
364 $uri .= "&{$key}={$value}";
367 $uri = substr($uri, 1);