Merge pull request #11821 from michaelmcandrew/500-http-response-code
[civicrm-core.git] / CRM / SMS / Provider.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33 abstract class CRM_SMS_Provider {
34
35 /**
36 * We only need one instance of this object. So we use the singleton
37 * pattern and cache the instance in this variable
38 *
39 * @var object
40 */
41 static private $_singleton = array();
42 const MAX_SMS_CHAR = 460;
43
44 /**
45 * Singleton function used to manage this object.
46 *
47 * @param array $providerParams
48 * @param bool $force
49 *
50 * @return object
51 */
52 public static function &singleton($providerParams = array(), $force = FALSE) {
53 $mailingID = CRM_Utils_Array::value('mailing_id', $providerParams);
54 $providerID = CRM_Utils_Array::value('provider_id', $providerParams);
55 $providerName = CRM_Utils_Array::value('provider', $providerParams);
56
57 if (!$providerID && $mailingID) {
58 $providerID = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_Mailing', $mailingID, 'sms_provider_id', 'id');
59 $providerParams['provider_id'] = $providerID;
60 }
61 if ($providerID) {
62 $providerName = CRM_SMS_BAO_Provider::getProviderInfo($providerID, 'name');
63 }
64
65 if (!$providerName) {
66 CRM_Core_Error::fatal('Provider not known or not provided.');
67 }
68
69 $providerName = CRM_Utils_Type::escape($providerName, 'String');
70 $cacheKey = "{$providerName}_" . (int) $providerID . "_" . (int) $mailingID;
71
72 if (!isset(self::$_singleton[$cacheKey]) || $force) {
73 $ext = CRM_Extension_System::singleton()->getMapper();
74 if ($ext->isExtensionKey($providerName)) {
75 $providerClass = $ext->keyToClass($providerName);
76 require_once "{$providerClass}.php";
77 }
78 else {
79 // If we are running unit tests we simulate an SMS provider with the name "CiviTestSMSProvider"
80 if ($providerName !== 'CiviTestSMSProvider') {
81 CRM_Core_Error::fatal("Could not locate extension for {$providerName}.");
82 }
83 $providerClass = 'CiviTestSMSProvider';
84 }
85
86 self::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
87 }
88 return self::$_singleton[$cacheKey];
89 }
90
91 /**
92 * Send an SMS Message via the API Server.
93 *
94 * @param array $recipients
95 * @param string $header
96 * @param string $message
97 * @param int $dncID
98 */
99 abstract public function send($recipients, $header, $message, $dncID = NULL);
100
101 /**
102 * Return message text.
103 *
104 * Child class could override this function to have better control over the message being sent.
105 *
106 * @param string $message
107 * @param int $contactID
108 * @param array $contactDetails
109 *
110 * @return string
111 */
112 public function getMessage($message, $contactID, $contactDetails) {
113 $html = $message->getHTMLBody();
114 $text = $message->getTXTBody();
115
116 return $html ? $html : $text;
117 }
118
119 /**
120 * Get recipient details.
121 *
122 * @param array $fields
123 * @param array $additionalDetails
124 *
125 * @return mixed
126 */
127 public function getRecipientDetails($fields, $additionalDetails) {
128 // we could do more altering here
129 $fields['To'] = $fields['phone'];
130 return $fields;
131 }
132
133 /**
134 * @param int $apiMsgID
135 * @param $message
136 * @param array $headers
137 * @param int $jobID
138 * @param int $userID
139 *
140 * @return self|null|object
141 * @throws CRM_Core_Exception
142 */
143 public function createActivity($apiMsgID, $message, $headers = array(), $jobID = NULL, $userID = NULL) {
144 if ($jobID) {
145 $sql = "
146 SELECT scheduled_id FROM civicrm_mailing m
147 INNER JOIN civicrm_mailing_job mj ON mj.mailing_id = m.id AND mj.id = %1";
148 $sourceContactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($jobID, 'Integer')));
149 }
150 elseif ($userID) {
151 $sourceContactID = $userID;
152 }
153 else {
154 $session = CRM_Core_Session::singleton();
155 $sourceContactID = $session->get('userID');
156 }
157
158 if (!$sourceContactID) {
159 $sourceContactID = CRM_Utils_Array::value('Contact', $headers);
160 }
161 if (!$sourceContactID) {
162 return FALSE;
163 }
164
165 // note: lets not pass status here, assuming status will be updated by callback
166 $activityParams = array(
167 'source_contact_id' => $sourceContactID,
168 'target_contact_id' => $headers['contact_id'],
169 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
170 'activity_date_time' => date('YmdHis'),
171 'details' => $message,
172 'result' => $apiMsgID,
173 );
174 return CRM_Activity_BAO_Activity::create($activityParams);
175 }
176
177 /**
178 * @param string $name
179 * @param $type
180 * @param bool $abort
181 * @param null $default
182 * @param string $location
183 *
184 * @return mixed
185 */
186 public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
187 static $store = NULL;
188 $value = CRM_Utils_Request::retrieve($name, $type, $store,
189 FALSE, $default, $location
190 );
191 if ($abort && $value === NULL) {
192 Civi::log()->warning("Could not find an entry for $name in $location");
193 echo "Failure: Missing Parameter<p>";
194 exit();
195 }
196 return $value;
197 }
198
199 /**
200 * @param $from
201 * @param $body
202 * @param null $to
203 * @param int $trackID
204 *
205 * @return self|null|object
206 * @throws CRM_Core_Exception
207 */
208 public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
209 $message = new CRM_SMS_Message();
210 $message->from = $from;
211 $message->to = $to;
212 $message->body = $body;
213 $message->trackID = $trackID;
214 // call hook_civicrm_inboundSMS
215 CRM_Utils_Hook::inboundSMS($message);
216
217 if (!$message->fromContactID) {
218 // find sender by phone number if $fromContactID not set by hook
219 $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from), $like, "like");
220 $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(
221 1 => array($formatFrom, 'String')));
222 }
223
224 if (!$message->fromContactID) {
225 // unknown mobile sender -- create new contact
226 // use fake @mobile.sms email address for new contact since civi
227 // requires email or name for all contacts
228 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
229 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
230 $phoneloc = array_search('Home', $locationTypes);
231 $phonetype = array_search('Mobile', $phoneTypes);
232 $stripFrom = $this->stripPhone($message->from);
233 $contactparams = array(
234 'contact_type' => 'Individual',
235 'email' => array(
236 1 => array(
237 'location_type_id' => $phoneloc,
238 'email' => $stripFrom . '@mobile.sms',
239 ),
240 ),
241 'phone' => array(
242 1 => array(
243 'phone_type_id' => $phonetype,
244 'location_type_id' => $phoneloc,
245 'phone' => $stripFrom,
246 ),
247 ),
248 );
249 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
250 $message->fromContactID = $fromContact->id;
251 }
252
253 if (!$message->toContactID) {
254 // find recipient if $toContactID not set by hook
255 if ($message->to) {
256 $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(
257 1 => array('%' . $message->to, 'String')));
258 }
259 else {
260 $message->toContactID = $message->fromContactID;
261 }
262 }
263
264 if ($message->fromContactID) {
265 // note: lets not pass status here, assuming status will be updated by callback
266 $activityParams = array(
267 'source_contact_id' => $message->toContactID,
268 'target_contact_id' => $message->fromContactID,
269 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
270 'activity_date_time' => date('YmdHis'),
271 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
272 'details' => $message->body,
273 'phone_number' => $message->from,
274 );
275 if ($message->trackID) {
276 $activityParams['result'] = CRM_Utils_Type::escape($message->trackID, 'String');
277 }
278
279 $result = CRM_Activity_BAO_Activity::create($activityParams);
280 Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
281 return $result;
282 }
283 }
284
285 /**
286 * @param $phone
287 *
288 * @return mixed|string
289 */
290 public function stripPhone($phone) {
291 $newphone = preg_replace('/[^0-9x]/', '', $phone);
292 while (substr($newphone, 0, 1) == "1") {
293 $newphone = substr($newphone, 1);
294 }
295 while (strpos($newphone, "xx") !== FALSE) {
296 $newphone = str_replace("xx", "x", $newphone);
297 }
298 while (substr($newphone, -1) == "x") {
299 $newphone = substr($newphone, 0, -1);
300 }
301 return $newphone;
302 }
303
304 /**
305 * @param $phone
306 * @param $kind
307 * @param string $format
308 *
309 * @return mixed|string
310 */
311 public function formatPhone($phone, &$kind, $format = "dash") {
312 $phoneA = explode("x", $phone);
313 switch (strlen($phoneA[0])) {
314 case 0:
315 $kind = "XOnly";
316 $area = "";
317 $exch = "";
318 $uniq = "";
319 $ext = $phoneA[1];
320 break;
321
322 case 7:
323 $kind = $phoneA[1] ? "LocalX" : "Local";
324 $area = "";
325 $exch = substr($phone, 0, 3);
326 $uniq = substr($phone, 3, 4);
327 $ext = $phoneA[1];
328 break;
329
330 case 10:
331 $kind = $phoneA[1] ? "LongX" : "Long";
332 $area = substr($phone, 0, 3);
333 $exch = substr($phone, 3, 3);
334 $uniq = substr($phone, 6, 4);
335 $ext = $phoneA[1];
336 break;
337
338 default:
339 $kind = "Unknown";
340 return $phone;
341 }
342
343 switch ($format) {
344 case "like":
345 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
346 $newphone = str_replace('%%', '%', $newphone);
347 $newphone = str_replace('%%', '%', $newphone);
348 return $newphone;
349
350 case "dash":
351 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
352 $newphone = trim(trim(trim($newphone, "x"), "-"));
353 return $newphone;
354
355 case "bare":
356 $newphone = $area . $exch . $uniq . "x" . $ext;
357 $newphone = trim(trim(trim($newphone, "x"), "-"));
358 return $newphone;
359
360 case "area":
361 return $area;
362
363 default:
364 return $phone;
365 }
366 }
367
368 /**
369 * @param $values
370 *
371 * @return string
372 */
373 public function urlEncode($values) {
374 $uri = '';
375 foreach ($values as $key => $value) {
376 $value = urlencode($value);
377 $uri .= "&{$key}={$value}";
378 }
379 if (!empty($uri)) {
380 $uri = substr($uri, 1);
381 }
382 return $uri;
383 }
384
385 }