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