Support additional options for pseudoConstant::get CRM-12464
[civicrm-core.git] / CRM / SMS / Provider.php
CommitLineData
6a488035
TO
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
36abstract 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 = "
119SELECT scheduled_id FROM civicrm_mailing m
120INNER 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) {
1393e47e 129 $sourceContactID = CRM_Utils_Array::value('Contact', $headers);
6a488035
TO
130 }
131 if (!$sourceContactID) {
1393e47e 132 return false;
6a488035
TO
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
f53ea1ce 162 function processInbound($from, $body, $to = NULL, $trackID = NULL) {
1393e47e 163 $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like");
6a488035
TO
164 $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String');
165 $fromContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone WHERE phone LIKE "' . $escapedFrom . '"');
1393e47e 166
6a488035 167 if (! $fromContactID) {
1393e47e 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
b4f964d9
CW
171 $locationTypes = CRM_Core_PseudoConstant::locationType();
172 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
173 $phoneloc = array_search('Home', $locationTypes);
174 $phonetype = array_search('Mobile', $phoneTypes);
1393e47e 175 $stripFrom = $this->stripPhone($from);
b4f964d9
CW
176 $contactparams = array(
177 'contact_type' => 'Individual',
178 'email' => array(1 => array(
179 'location_type_id' => $phoneloc,
180 'email' => $stripFrom . '@mobile.sms'
181 )),
182 'phone' => array(1 => array(
183 'phone_type_id' => $phonetype,
184 'location_type_id' => $phoneloc,
185 'phone' => $stripFrom
186 )),
187 );
1393e47e 188 $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
6a488035
TO
189 $fromContactID = $fromContact->id;
190 }
191
192 if ($to) {
193 $to = CRM_Utils_Type::escape($to, 'String');
194 $toContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone WHERE phone LIKE "' . $to . '"');
195 }
196 else {
197 $toContactID = $fromContactID;
198 }
199
200 if ($fromContactID) {
201 $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
202 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name');
203
204 // note: lets not pass status here, assuming status will be updated by callback
205 $activityParams = array(
206 'source_contact_id' => $toContactID,
207 'target_contact_id' => $fromContactID,
208 'activity_type_id' => $activityTypeID,
209 'activity_date_time' => date('YmdHis'),
210 'subject' => 'SMS Received',
211 'status_id' => $actStatusIDs['Completed'],
212 'details' => $body,
213 'phone_number' => $from
214 );
215 if ($trackID) {
216 $trackID = CRM_Utils_Type::escape($trackID, 'String');
217 $activityParams['result'] = $trackID;
218 }
219
220 $result = CRM_Activity_BAO_Activity::create($activityParams);
221 CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}.");
222 return $result;
223 }
224 }
225
226 function stripPhone($phone) {
227 $newphone = preg_replace('/[^0-9x]/', '', $phone);
228 while (substr($newphone, 0, 1) == "1") {
229 $newphone = substr($newphone, 1);
230 }
231 while (strpos($newphone, "xx") !== FALSE) {
232 $newphone = str_replace("xx", "x", $newphone);
233 }
234 while (substr($newphone, -1) == "x") {
235 $newphone = substr($newphone, 0, -1);
236 }
237 return $newphone;
238 }
239
240 function formatPhone($phone, &$kind, $format = "dash") {
241 $phoneA = explode("x", $phone);
242 switch (strlen($phoneA[0])) {
243 case 0:
244 $kind = "XOnly";
245 $area = "";
246 $exch = "";
247 $uniq = "";
248 $ext = $phoneA[1];
249 break;
250
251 case 7:
252 $kind = $phoneA[1] ? "LocalX" : "Local";
253 $area = "";
254 $exch = substr($phone, 0, 3);
255 $uniq = substr($phone, 3, 4);
256 $ext = $phoneA[1];
257 break;
258
259 case 10:
260 $kind = $phoneA[1] ? "LongX" : "Long";
261 $area = substr($phone, 0, 3);
262 $exch = substr($phone, 3, 3);
263 $uniq = substr($phone, 6, 4);
264 $ext = $phoneA[1];
265 break;
266
267 default:
268 $kind = "Unknown";
269 return $phone;
270 }
271
272 switch ($format) {
273 case "like":
274 $newphone = '%' . $area . '%' . $exch . '%' . $uniq . '%' . $ext . '%';
275 $newphone = str_replace('%%', '%', $newphone);
276 $newphone = str_replace('%%', '%', $newphone);
277 return $newphone;
278
279 case "dash":
280 $newphone = $area . "-" . $exch . "-" . $uniq . " x" . $ext;
281 $newphone = trim(trim(trim($newphone, "x"), "-"));
282 return $newphone;
283
284 case "bare":
285 $newphone = $area . $exch . $uniq . "x" . $ext;
286 $newphone = trim(trim(trim($newphone, "x"), "-"));
287 return $newphone;
288
289 case "area":
290 return $area;
291
292 default:
293 return $phone;
294 }
295 }
1e2f5f25
DS
296
297 function urlEncode($values) {
298 $uri = '';
299 foreach ($values as $key => $value) {
300 $value = urlencode($value);
301 $uri .= "&{$key}={$value}";
302 }
303 if (!empty($uri)) {
304 $uri = substr($uri, 1);
305 }
306 return $uri;
307 }
6a488035
TO
308}
309