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