APIv4 - Add Address::getCoordinates action
[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 * @param int $apiMsgID
88 * @param $message
89 * @param array $headers
90 * @param int $jobID
91 * @param int $userID
92 *
93 * @return self|null|object
94 * @throws CRM_Core_Exception
95 */
96 public function createActivity($apiMsgID, $message, $headers = [], $jobID = NULL, $userID = NULL) {
97 if ($jobID) {
98 $sql = "
99 SELECT scheduled_id FROM civicrm_mailing m
100 INNER JOIN civicrm_mailing_job mj ON mj.mailing_id = m.id AND mj.id = %1";
101 $sourceContactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($jobID, 'Integer')));
102 }
103 elseif ($userID) {
104 $sourceContactID = $userID;
105 }
106 else {
107 $session = CRM_Core_Session::singleton();
108 $sourceContactID = $session->get('userID');
109 }
110
111 if (!$sourceContactID) {
112 $sourceContactID = $headers['Contact'] ?? NULL;
113 }
114 if (!$sourceContactID) {
115 return FALSE;
116 }
117
118 // note: lets not pass status here, assuming status will be updated by callback
119 $activityParams = array(
120 'source_contact_id' => $sourceContactID,
121 'target_contact_id' => $headers['contact_id'],
122 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
123 'activity_date_time' => date('YmdHis'),
124 'details' => $message,
125 'result' => $apiMsgID,
126 );
127 return CRM_Activity_BAO_Activity::create($activityParams);
128 }
129
130 /**
131 * @param string $name
132 * @param $type
133 * @param bool $abort
134 * @param null $default
135 * @param string $location
136 *
137 * @return mixed
138 */
139 public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
140 static $store = NULL;
141 $value = CRM_Utils_Request::retrieve($name, $type, $store,
142 FALSE, $default, $location
143 );
144 if ($abort && $value === NULL) {
145 Civi::log()->warning("Could not find an entry for $name in $location");
146 echo "Failure: Missing Parameter<p>";
147 exit();
148 }
149 return $value;
150 }
151
152 /**
153 * @param $from
154 * @param $body
155 * @param null $to
156 * @param int $trackID
157 *
158 * @return self|null|object
159 * @throws CRM_Core_Exception
160 */
161 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
162 $message = new CRM_SMS_Message();
163 $message->from = $from;
164 $message->to = $to;
165 $message->body = $body;
166 $message->trackID = $trackID;
167 // call hook_civicrm_inboundSMS
168 CRM_Utils_Hook::inboundSMS($message);
169
170 if (!$message->fromContactID) {
171 // find sender by phone number if $fromContactID not set by hook
172 $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from), $like, "like");
173 $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(
174 1 => array($formatFrom, 'String'),
175 ));
176 }
177
178 if (!$message->fromContactID) {
179 // unknown mobile sender -- create new contact
180 // use fake @mobile.sms email address for new contact since civi
181 // requires email or name for all contacts
182 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
183 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
184 $phoneloc = array_search('Home', $locationTypes);
185 $phonetype = array_search('Mobile', $phoneTypes);
186 $stripFrom = $this->stripPhone($message->from);
187 $contactparams = array(
188 'contact_type' => 'Individual',
189 'email' => array(
190 1 => array(
191 'location_type_id' => $phoneloc,
192 'email' => $stripFrom . '@mobile.sms',
193 ),
194 ),
195 'phone' => array(
196 1 => array(
197 'phone_type_id' => $phonetype,
198 'location_type_id' => $phoneloc,
199 'phone' => $stripFrom,
200 ),
201 ),
202 );
203 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
204 $message->fromContactID = $fromContact->id;
205 }
206
207 if (!$message->toContactID) {
208 // find recipient if $toContactID not set by hook
209 if ($message->to) {
210 $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(
211 1 => array('%' . $message->to, 'String'),
212 ));
213 }
214 else {
215 $message->toContactID = $message->fromContactID;
216 }
217 }
218
219 if ($message->fromContactID) {
220 // note: lets not pass status here, assuming status will be updated by callback
221 $activityParams = array(
222 'source_contact_id' => $message->toContactID,
223 'target_contact_id' => $message->fromContactID,
224 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
225 'activity_date_time' => date('YmdHis'),
226 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
227 'details' => $message->body,
228 'phone_number' => $message->from,
229 );
230 if ($message->trackID) {
231 $activityParams['result'] = CRM_Utils_Type::escape($message->trackID, 'String');
232 }
233
234 $result = CRM_Activity_BAO_Activity::create($activityParams);
235 Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
236 return $result;
237 }
238 }
239
240 /**
241 * @param $phone
242 *
243 * @return mixed|string
244 */
245 public function stripPhone($phone) {
246 $newphone = preg_replace('/[^0-9x]/', '', $phone);
247 while (substr($newphone, 0, 1) == "1") {
248 $newphone = substr($newphone, 1);
249 }
250 while (strpos($newphone, "xx") !== FALSE) {
251 $newphone = str_replace("xx", "x", $newphone);
252 }
253 while (substr($newphone, -1) == "x") {
254 $newphone = substr($newphone, 0, -1);
255 }
256 return $newphone;
257 }
258
259 /**
260 * @param $phone
261 * @param $kind
262 * @param string $format
263 *
264 * @return mixed|string
265 */
266 public function formatPhone($phone, &$kind, $format = "dash") {
267 $phoneA = explode("x", $phone);
268 switch (strlen($phoneA[0])) {
269 case 0:
270 $kind = "XOnly";
271 $area = "";
272 $exch = "";
273 $uniq = "";
274 $ext = $phoneA[1];
275 break;
276
277 case 7:
278 $kind = $phoneA[1] ? "LocalX" : "Local";
279 $area = "";
280 $exch = substr($phone, 0, 3);
281 $uniq = substr($phone, 3, 4);
282 $ext = $phoneA[1];
283 break;
284
285 case 10:
286 $kind = $phoneA[1] ? "LongX" : "Long";
287 $area = substr($phone, 0, 3);
288 $exch = substr($phone, 3, 3);
289 $uniq = substr($phone, 6, 4);
290 $ext = $phoneA[1];
291 break;
292
293 default:
294 $kind = "Unknown";
295 return $phone;
296 }
297
298 switch ($format) {
299 case "like":
300 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
301 $newphone = str_replace('%%', '%', $newphone);
302 $newphone = str_replace('%%', '%', $newphone);
303 return $newphone;
304
305 case "dash":
306 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
307 $newphone = trim(trim(trim($newphone, "x"), "-"));
308 return $newphone;
309
310 case "bare":
311 $newphone = $area . $exch . $uniq . "x" . $ext;
312 $newphone = trim(trim(trim($newphone, "x"), "-"));
313 return $newphone;
314
315 case "area":
316 return $area;
317
318 default:
319 return $phone;
320 }
321 }
322
323 /**
324 * @param $values
325 *
326 * @return string
327 */
328 public function urlEncode($values) {
329 $uri = '';
330 foreach ($values as $key => $value) {
331 $value = urlencode($value);
332 $uri .= "&{$key}={$value}";
333 }
334 if (!empty($uri)) {
335 $uri = substr($uri, 1);
336 }
337 return $uri;
338 }
339
340 }