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