Merge pull request #19484 from eileenmcnaughton/upit
[civicrm-core.git] / CRM / SMS / Provider.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 abstract class CRM_SMS_Provider {
18
19 /**
20 * We only need one instance of this object. So we use the singleton
21 * pattern and cache the instance in this variable
22 *
23 * @var object
24 */
25 static private $_singleton = [];
26 const MAX_SMS_CHAR = 460;
27
28 /**
29 * Singleton function used to manage this object.
30 *
31 * @param array $providerParams
32 * @param bool $force
33 *
34 * @return object
35 * @throws CRM_Core_Exception
36 */
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;
41
42 if (!$providerID && $mailingID) {
43 $providerID = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_Mailing', $mailingID, 'sms_provider_id', 'id');
44 $providerParams['provider_id'] = $providerID;
45 }
46 if ($providerID) {
47 $providerName = CRM_SMS_BAO_Provider::getProviderInfo($providerID, 'name');
48 }
49
50 if (!$providerName) {
51 throw new CRM_Core_Exception('Provider not known or not provided.');
52 }
53
54 $providerName = CRM_Utils_Type::escape($providerName, 'String');
55 $cacheKey = "{$providerName}_" . (int) $providerID . "_" . (int) $mailingID;
56
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";
62 }
63 else {
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}.");
67 }
68 $providerClass = 'CiviTestSMSProvider';
69 }
70
71 self::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
72 }
73 return self::$_singleton[$cacheKey];
74 }
75
76 /**
77 * Send an SMS Message via the API Server.
78 *
79 * @param array $recipients
80 * @param string $header
81 * @param string $message
82 * @param int $dncID
83 */
84 abstract public function send($recipients, $header, $message, $dncID = NULL);
85
86 /**
87 * Return message text.
88 *
89 * Child class could override this function to have better control over the message being sent.
90 *
91 * @param string $message
92 * @param int $contactID
93 * @param array $contactDetails
94 *
95 * @return string
96 */
97 public function getMessage($message, $contactID, $contactDetails) {
98 $html = $message->getHTMLBody();
99 $text = $message->getTXTBody();
100
101 return $html ? $html : $text;
102 }
103
104 /**
105 * Get recipient details.
106 *
107 * @param array $fields
108 * @param array $additionalDetails
109 *
110 * @return mixed
111 */
112 public function getRecipientDetails($fields, $additionalDetails) {
113 // we could do more altering here
114 $fields['To'] = $fields['phone'];
115 return $fields;
116 }
117
118 /**
119 * @param int $apiMsgID
120 * @param $message
121 * @param array $headers
122 * @param int $jobID
123 * @param int $userID
124 *
125 * @return self|null|object
126 * @throws CRM_Core_Exception
127 */
128 public function createActivity($apiMsgID, $message, $headers = [], $jobID = NULL, $userID = NULL) {
129 if ($jobID) {
130 $sql = "
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')));
134 }
135 elseif ($userID) {
136 $sourceContactID = $userID;
137 }
138 else {
139 $session = CRM_Core_Session::singleton();
140 $sourceContactID = $session->get('userID');
141 }
142
143 if (!$sourceContactID) {
144 $sourceContactID = $headers['Contact'] ?? NULL;
145 }
146 if (!$sourceContactID) {
147 return FALSE;
148 }
149
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,
158 );
159 return CRM_Activity_BAO_Activity::create($activityParams);
160 }
161
162 /**
163 * @param string $name
164 * @param $type
165 * @param bool $abort
166 * @param null $default
167 * @param string $location
168 *
169 * @return mixed
170 */
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
175 );
176 if ($abort && $value === NULL) {
177 Civi::log()->warning("Could not find an entry for $name in $location");
178 echo "Failure: Missing Parameter<p>";
179 exit();
180 }
181 return $value;
182 }
183
184 /**
185 * @param $from
186 * @param $body
187 * @param null $to
188 * @param int $trackID
189 *
190 * @return self|null|object
191 * @throws CRM_Core_Exception
192 */
193 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
194 $message = new CRM_SMS_Message();
195 $message->from = $from;
196 $message->to = $to;
197 $message->body = $body;
198 $message->trackID = $trackID;
199 // call hook_civicrm_inboundSMS
200 CRM_Utils_Hook::inboundSMS($message);
201
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'),
207 ));
208 }
209
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',
221 'email' => array(
222 1 => array(
223 'location_type_id' => $phoneloc,
224 'email' => $stripFrom . '@mobile.sms',
225 ),
226 ),
227 'phone' => array(
228 1 => array(
229 'phone_type_id' => $phonetype,
230 'location_type_id' => $phoneloc,
231 'phone' => $stripFrom,
232 ),
233 ),
234 );
235 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
236 $message->fromContactID = $fromContact->id;
237 }
238
239 if (!$message->toContactID) {
240 // find recipient if $toContactID not set by hook
241 if ($message->to) {
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'),
244 ));
245 }
246 else {
247 $message->toContactID = $message->fromContactID;
248 }
249 }
250
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,
261 );
262 if ($message->trackID) {
263 $activityParams['result'] = CRM_Utils_Type::escape($message->trackID, 'String');
264 }
265
266 $result = CRM_Activity_BAO_Activity::create($activityParams);
267 Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
268 return $result;
269 }
270 }
271
272 /**
273 * @param $phone
274 *
275 * @return mixed|string
276 */
277 public function stripPhone($phone) {
278 $newphone = preg_replace('/[^0-9x]/', '', $phone);
279 while (substr($newphone, 0, 1) == "1") {
280 $newphone = substr($newphone, 1);
281 }
282 while (strpos($newphone, "xx") !== FALSE) {
283 $newphone = str_replace("xx", "x", $newphone);
284 }
285 while (substr($newphone, -1) == "x") {
286 $newphone = substr($newphone, 0, -1);
287 }
288 return $newphone;
289 }
290
291 /**
292 * @param $phone
293 * @param $kind
294 * @param string $format
295 *
296 * @return mixed|string
297 */
298 public function formatPhone($phone, &$kind, $format = "dash") {
299 $phoneA = explode("x", $phone);
300 switch (strlen($phoneA[0])) {
301 case 0:
302 $kind = "XOnly";
303 $area = "";
304 $exch = "";
305 $uniq = "";
306 $ext = $phoneA[1];
307 break;
308
309 case 7:
310 $kind = $phoneA[1] ? "LocalX" : "Local";
311 $area = "";
312 $exch = substr($phone, 0, 3);
313 $uniq = substr($phone, 3, 4);
314 $ext = $phoneA[1];
315 break;
316
317 case 10:
318 $kind = $phoneA[1] ? "LongX" : "Long";
319 $area = substr($phone, 0, 3);
320 $exch = substr($phone, 3, 3);
321 $uniq = substr($phone, 6, 4);
322 $ext = $phoneA[1];
323 break;
324
325 default:
326 $kind = "Unknown";
327 return $phone;
328 }
329
330 switch ($format) {
331 case "like":
332 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
333 $newphone = str_replace('%%', '%', $newphone);
334 $newphone = str_replace('%%', '%', $newphone);
335 return $newphone;
336
337 case "dash":
338 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
339 $newphone = trim(trim(trim($newphone, "x"), "-"));
340 return $newphone;
341
342 case "bare":
343 $newphone = $area . $exch . $uniq . "x" . $ext;
344 $newphone = trim(trim(trim($newphone, "x"), "-"));
345 return $newphone;
346
347 case "area":
348 return $area;
349
350 default:
351 return $phone;
352 }
353 }
354
355 /**
356 * @param $values
357 *
358 * @return string
359 */
360 public function urlEncode($values) {
361 $uri = '';
362 foreach ($values as $key => $value) {
363 $value = urlencode($value);
364 $uri .= "&{$key}={$value}";
365 }
366 if (!empty($uri)) {
367 $uri = substr($uri, 1);
368 }
369 return $uri;
370 }
371
372 }