Remove unused functions
[civicrm-core.git] / CRM / SMS / Provider.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035 16 */
6a488035
TO
17abstract 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
6a488035 24 */
affcc9d2 25 static private $_singleton = [];
7da04cde 26 const MAX_SMS_CHAR = 460;
6a488035
TO
27
28 /**
fe482240 29 * Singleton function used to manage this object.
6a488035 30 *
77b97be7
EM
31 * @param array $providerParams
32 * @param bool $force
33 *
6a488035 34 * @return object
4a0e3fe7 35 * @throws CRM_Core_Exception
6a488035 36 */
affcc9d2 37 public static function &singleton($providerParams = [], $force = FALSE) {
9c1bc317
CW
38 $mailingID = $providerParams['mailing_id'] ?? NULL;
39 $providerID = $providerParams['provider_id'] ?? NULL;
40 $providerName = $providerParams['provider'] ?? NULL;
6a488035
TO
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) {
4a0e3fe7 51 throw new CRM_Core_Exception('Provider not known or not provided.');
6a488035
TO
52 }
53
54 $providerName = CRM_Utils_Type::escape($providerName, 'String');
353ffa53 55 $cacheKey = "{$providerName}_" . (int) $providerID . "_" . (int) $mailingID;
6a488035
TO
56
57 if (!isset(self::$_singleton[$cacheKey]) || $force) {
58 $ext = CRM_Extension_System::singleton()->getMapper();
59 if ($ext->isExtensionKey($providerName)) {
36f5faa3
MW
60 $providerClass = $ext->keyToClass($providerName);
61 require_once "{$providerClass}.php";
0db6c3e1
TO
62 }
63 else {
1a7f0799
MW
64 // If we are running unit tests we simulate an SMS provider with the name "CiviTestSMSProvider"
65 if ($providerName !== 'CiviTestSMSProvider') {
4a0e3fe7 66 throw new CRM_Core_Exception("Could not locate extension for {$providerName}.");
36f5faa3 67 }
1a7f0799 68 $providerClass = 'CiviTestSMSProvider';
6a488035
TO
69 }
70
36f5faa3 71 self::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
6a488035
TO
72 }
73 return self::$_singleton[$cacheKey];
74 }
75
76 /**
fe482240 77 * Send an SMS Message via the API Server.
54957108 78 *
79 * @param array $recipients
80 * @param string $header
81 * @param string $message
82 * @param int $dncID
6a488035 83 */
2da40d21 84 abstract public function send($recipients, $header, $message, $dncID = NULL);
6a488035 85
fd0e0077 86 /**
100fef9d 87 * @param int $apiMsgID
fd0e0077
EM
88 * @param $message
89 * @param array $headers
100fef9d
CW
90 * @param int $jobID
91 * @param int $userID
fd0e0077 92 *
6c552737 93 * @return self|null|object
fd0e0077
EM
94 * @throws CRM_Core_Exception
95 */
affcc9d2 96 public function createActivity($apiMsgID, $message, $headers = [], $jobID = NULL, $userID = NULL) {
6a488035
TO
97 if ($jobID) {
98 $sql = "
99SELECT scheduled_id FROM civicrm_mailing m
100INNER 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 }
353ffa53 103 elseif ($userID) {
44fb209e 104 $sourceContactID = $userID;
e8cb3963 105 }
6a488035
TO
106 else {
107 $session = CRM_Core_Session::singleton();
108 $sourceContactID = $session->get('userID');
109 }
110
111 if (!$sourceContactID) {
9c1bc317 112 $sourceContactID = $headers['Contact'] ?? NULL;
6a488035
TO
113 }
114 if (!$sourceContactID) {
44fb209e 115 return FALSE;
6a488035
TO
116 }
117
6a488035
TO
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'],
36f5faa3 122 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
6a488035 123 'activity_date_time' => date('YmdHis'),
6a488035
TO
124 'details' => $message,
125 'result' => $apiMsgID,
126 );
127 return CRM_Activity_BAO_Activity::create($activityParams);
128 }
129
fd0e0077 130 /**
100fef9d 131 * @param string $name
fd0e0077
EM
132 * @param $type
133 * @param bool $abort
134 * @param null $default
135 * @param string $location
136 *
137 * @return mixed
138 */
00be9182 139 public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
6a488035
TO
140 static $store = NULL;
141 $value = CRM_Utils_Request::retrieve($name, $type, $store,
142 FALSE, $default, $location
143 );
144 if ($abort && $value === NULL) {
36f5faa3 145 Civi::log()->warning("Could not find an entry for $name in $location");
6a488035
TO
146 echo "Failure: Missing Parameter<p>";
147 exit();
148 }
149 return $value;
150 }
151
fd0e0077
EM
152 /**
153 * @param $from
154 * @param $body
155 * @param null $to
100fef9d 156 * @param int $trackID
fd0e0077 157 *
6c552737 158 * @return self|null|object
fd0e0077
EM
159 * @throws CRM_Core_Exception
160 */
00be9182 161 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
caed3ddc
SL
162 $message = new CRM_SMS_Message();
163 $message->from = $from;
164 $message->to = $to;
165 $message->body = $body;
166 $message->trackID = $trackID;
0613768a 167 // call hook_civicrm_inboundSMS
caed3ddc 168 CRM_Utils_Hook::inboundSMS($message);
0613768a 169
caed3ddc 170 if (!$message->fromContactID) {
0613768a 171 // find sender by phone number if $fromContactID not set by hook
caed3ddc 172 $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from), $like, "like");
d20cd5d4 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(
3655bea4
SL
174 1 => array($formatFrom, 'String'),
175 ));
0613768a 176 }
1393e47e 177
caed3ddc 178 if (!$message->fromContactID) {
1393e47e 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
b2b0530a 182 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
b4f964d9
CW
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);
caed3ddc 186 $stripFrom = $this->stripPhone($message->from);
b4f964d9
CW
187 $contactparams = array(
188 'contact_type' => 'Individual',
44fb209e 189 'email' => array(
353ffa53
TO
190 1 => array(
191 'location_type_id' => $phoneloc,
192 'email' => $stripFrom . '@mobile.sms',
af9b09df 193 ),
353ffa53 194 ),
44fb209e 195 'phone' => array(
353ffa53
TO
196 1 => array(
197 'phone_type_id' => $phonetype,
198 'location_type_id' => $phoneloc,
199 'phone' => $stripFrom,
af9b09df 200 ),
353ffa53 201 ),
b4f964d9 202 );
1393e47e 203 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
caed3ddc 204 $message->fromContactID = $fromContact->id;
6a488035
TO
205 }
206
d20cd5d4 207 if (!$message->toContactID) {
0613768a 208 // find recipient if $toContactID not set by hook
caed3ddc 209 if ($message->to) {
d20cd5d4 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(
3655bea4
SL
211 1 => array('%' . $message->to, 'String'),
212 ));
0613768a
EE
213 }
214 else {
d20cd5d4 215 $message->toContactID = $message->fromContactID;
0613768a 216 }
6a488035
TO
217 }
218
caed3ddc 219 if ($message->fromContactID) {
6a488035
TO
220 // note: lets not pass status here, assuming status will be updated by callback
221 $activityParams = array(
caed3ddc
SL
222 'source_contact_id' => $message->toContactID,
223 'target_contact_id' => $message->fromContactID,
36f5faa3 224 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
6a488035 225 'activity_date_time' => date('YmdHis'),
36f5faa3 226 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
caed3ddc
SL
227 'details' => $message->body,
228 'phone_number' => $message->from,
6a488035 229 );
caed3ddc 230 if ($message->trackID) {
d20cd5d4 231 $activityParams['result'] = CRM_Utils_Type::escape($message->trackID, 'String');
6a488035
TO
232 }
233
234 $result = CRM_Activity_BAO_Activity::create($activityParams);
36f5faa3 235 Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
6a488035
TO
236 return $result;
237 }
238 }
239
fd0e0077
EM
240 /**
241 * @param $phone
242 *
243 * @return mixed|string
244 */
00be9182 245 public function stripPhone($phone) {
6a488035
TO
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
fd0e0077
EM
259 /**
260 * @param $phone
261 * @param $kind
262 * @param string $format
263 *
264 * @return mixed|string
265 */
00be9182 266 public function formatPhone($phone, &$kind, $format = "dash") {
6a488035
TO
267 $phoneA = explode("x", $phone);
268 switch (strlen($phoneA[0])) {
269 case 0:
270 $kind = "XOnly";
271 $area = "";
272 $exch = "";
273 $uniq = "";
353ffa53 274 $ext = $phoneA[1];
6a488035
TO
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);
353ffa53 282 $ext = $phoneA[1];
6a488035
TO
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);
353ffa53 290 $ext = $phoneA[1];
6a488035
TO
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 }
1e2f5f25 322
fd0e0077
EM
323 /**
324 * @param $values
325 *
326 * @return string
327 */
00be9182 328 public function urlEncode($values) {
1e2f5f25
DS
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 }
96025800 339
6a488035 340}