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