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