Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-08-05-11-07-08
[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 = 460;
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] = $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, $userID = 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 elseif($userID) {
124 $sourceContactID=$userID;
125 }
126 else {
127 $session = CRM_Core_Session::singleton();
128 $sourceContactID = $session->get('userID');
129 }
130
131 if (!$sourceContactID) {
132 $sourceContactID = CRM_Utils_Array::value('Contact', $headers);
133 }
134 if (!$sourceContactID) {
135 return false;
136 }
137
138 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS delivery', 'name');
139 // note: lets not pass status here, assuming status will be updated by callback
140 $activityParams = array(
141 'source_contact_id' => $sourceContactID,
142 'target_contact_id' => $headers['contact_id'],
143 'activity_type_id' => $activityTypeID,
144 'activity_date_time' => date('YmdHis'),
145 'details' => $message,
146 'result' => $apiMsgID,
147 );
148 return CRM_Activity_BAO_Activity::create($activityParams);
149 }
150
151 function retrieve($name, $type, $abort = TRUE, $default = NULL, $location = 'REQUEST') {
152 static $store = NULL;
153 $value = CRM_Utils_Request::retrieve($name, $type, $store,
154 FALSE, $default, $location
155 );
156 if ($abort && $value === NULL) {
157 CRM_Core_Error::debug_log_message("Could not find an entry for $name in $location");
158 echo "Failure: Missing Parameter<p>";
159 exit();
160 }
161 return $value;
162 }
163
164 function processInbound($from, $body, $to = NULL, $trackID = NULL) {
165 $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like");
166 $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String');
167 $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 . '"');
168
169 if (! $fromContactID) {
170 // unknown mobile sender -- create new contact
171 // use fake @mobile.sms email address for new contact since civi
172 // requires email or name for all contacts
173 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
174 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
175 $phoneloc = array_search('Home', $locationTypes);
176 $phonetype = array_search('Mobile', $phoneTypes);
177 $stripFrom = $this->stripPhone($from);
178 $contactparams = array(
179 'contact_type' => 'Individual',
180 'email' => array(1 => array(
181 'location_type_id' => $phoneloc,
182 'email' => $stripFrom . '@mobile.sms'
183 )),
184 'phone' => array(1 => array(
185 'phone_type_id' => $phonetype,
186 'location_type_id' => $phoneloc,
187 'phone' => $stripFrom
188 )),
189 );
190 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
191 $fromContactID = $fromContact->id;
192 }
193
194 if ($to) {
195 $to = CRM_Utils_Type::escape($to, 'String');
196 $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 . '"');
197 }
198 else {
199 $toContactID = $fromContactID;
200 }
201
202 if ($fromContactID) {
203 $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
204 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound SMS', 'name');
205
206 // note: lets not pass status here, assuming status will be updated by callback
207 $activityParams = array(
208 'source_contact_id' => $toContactID,
209 'target_contact_id' => $fromContactID,
210 'activity_type_id' => $activityTypeID,
211 'activity_date_time' => date('YmdHis'),
212 'status_id' => $actStatusIDs['Completed'],
213 'details' => $body,
214 'phone_number' => $from
215 );
216 if ($trackID) {
217 $trackID = CRM_Utils_Type::escape($trackID, 'String');
218 $activityParams['result'] = $trackID;
219 }
220
221 $result = CRM_Activity_BAO_Activity::create($activityParams);
222 CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}.");
223 return $result;
224 }
225 }
226
227 function stripPhone($phone) {
228 $newphone = preg_replace('/[^0-9x]/', '', $phone);
229 while (substr($newphone, 0, 1) == "1") {
230 $newphone = substr($newphone, 1);
231 }
232 while (strpos($newphone, "xx") !== FALSE) {
233 $newphone = str_replace("xx", "x", $newphone);
234 }
235 while (substr($newphone, -1) == "x") {
236 $newphone = substr($newphone, 0, -1);
237 }
238 return $newphone;
239 }
240
241 function formatPhone($phone, &$kind, $format = "dash") {
242 $phoneA = explode("x", $phone);
243 switch (strlen($phoneA[0])) {
244 case 0:
245 $kind = "XOnly";
246 $area = "";
247 $exch = "";
248 $uniq = "";
249 $ext = $phoneA[1];
250 break;
251
252 case 7:
253 $kind = $phoneA[1] ? "LocalX" : "Local";
254 $area = "";
255 $exch = substr($phone, 0, 3);
256 $uniq = substr($phone, 3, 4);
257 $ext = $phoneA[1];
258 break;
259
260 case 10:
261 $kind = $phoneA[1] ? "LongX" : "Long";
262 $area = substr($phone, 0, 3);
263 $exch = substr($phone, 3, 3);
264 $uniq = substr($phone, 6, 4);
265 $ext = $phoneA[1];
266 break;
267
268 default:
269 $kind = "Unknown";
270 return $phone;
271 }
272
273 switch ($format) {
274 case "like":
275 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
276 $newphone = str_replace('%%', '%', $newphone);
277 $newphone = str_replace('%%', '%', $newphone);
278 return $newphone;
279
280 case "dash":
281 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
282 $newphone = trim(trim(trim($newphone, "x"), "-"));
283 return $newphone;
284
285 case "bare":
286 $newphone = $area . $exch . $uniq . "x" . $ext;
287 $newphone = trim(trim(trim($newphone, "x"), "-"));
288 return $newphone;
289
290 case "area":
291 return $area;
292
293 default:
294 return $phone;
295 }
296 }
297
298 function urlEncode($values) {
299 $uri = '';
300 foreach ($values as $key => $value) {
301 $value = urlencode($value);
302 $uri .= "&{$key}={$value}";
303 }
304 if (!empty($uri)) {
305 $uri = substr($uri, 1);
306 }
307 return $uri;
308 }
309 }
310