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