Merge pull request #4776 from webaccess/master
[civicrm-core.git] / CRM / Contact / Form / Task / SMSCommon.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 /**
37 * This class provides the common functionality for sending sms to
38 * one or a group of contact ids.
39 */
40 class CRM_Contact_Form_Task_SMSCommon {
41 CONST RECIEVED_SMS_ACTIVITY_SUBJECT = "SMS Received";
42
43 public $_contactDetails = array();
44
45 public $_allContactDetails = array();
46
47 public $_toContactPhone = array();
48
49
50 /**
51 * @param CRM_Core_Form $form
52 */
53 static function preProcessProvider(&$form) {
54 $form->_single = FALSE;
55 $className = CRM_Utils_System::getClassName($form);
56
57 if (property_exists($form, '_context') &&
58 $form->_context != 'search' &&
59 $className == 'CRM_Contact_Form_Task_SMS'
60 ) {
61 $form->_single = TRUE;
62 }
63
64 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
65
66 if (!$providersCount) {
67 CRM_Core_Error::statusBounce(ts('There are no SMS providers configured, or no SMS providers are set active'));
68 }
69
70 if ($className == 'CRM_Activity_Form_Task_SMS') {
71 $activityCheck = 0;
72 foreach ($form->_activityHolderIds as $value) {
73 if (CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'subject', 'id') != self::RECIEVED_SMS_ACTIVITY_SUBJECT) {
74 $activityCheck++;
75 }
76 }
77 if ($activityCheck == count($form->_activityHolderIds)) {
78 CRM_Core_Error::statusBounce(ts("The Reply SMS Could only be sent for activities with '%1' subject.",
79 array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT)
80 ));
81 }
82 }
83 }
84
85 /**
86 * Build the form object
87 *
88 * @access public
89 *
90 * @param CRM_Core_Form $form
91 *
92 * @return void
93 */
94 static function buildQuickForm(&$form) {
95
96 $toArray = array();
97
98 $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
99
100 $providerSelect = array();
101 foreach ($providers as $provider) {
102 $providerSelect[$provider['id']] = $provider['title'];
103 }
104 $suppressedSms = 0;
105 //here we are getting logged in user id as array but we need target contact id. CRM-5988
106 $cid = $form->get('cid');
107
108 if ($cid) {
109 $form->_contactIds = array($cid);
110 }
111
112 $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE);
113 $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE);
114
115 $toSetDefault = TRUE;
116 if (property_exists($form, '_context') && $form->_context == 'standalone') {
117 $toSetDefault = FALSE;
118 }
119
120 // when form is submitted recompute contactIds
121 $allToSMS = array();
122 if ($to->getValue()) {
123 $allToPhone = explode(',', $to->getValue());
124
125 $form->_contactIds = array();
126 foreach ($allToPhone as $value) {
127 list($contactId, $phone) = explode('::', $value);
128 if ($contactId) {
129 $form->_contactIds[] = $contactId;
130 $form->_toContactPhone[] = $phone;
131 }
132 }
133 $toSetDefault = TRUE;
134 }
135
136 //get the group of contacts as per selected by user in case of Find Activities
137 if (!empty($form->_activityHolderIds)) {
138 $extendTargetContacts = 0;
139 $invalidActivity = 0;
140 $validActivities = 0;
141 foreach ($form->_activityHolderIds as $key => $id) {
142 //valid activity check
143 if (CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self::RECIEVED_SMS_ACTIVITY_SUBJECT) {
144 $invalidActivity++;
145 continue;
146 }
147
148 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
149 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
150 //target contacts limit check
151 $ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID));
152
153 if (count($ids) > 1) {
154 $extendTargetContacts++;
155 continue;
156 }
157 $validActivities++;
158 $form->_contactIds = empty($form->_contactIds) ? $ids : array_unique(array_merge($form->_contactIds, $ids));
159 }
160
161 if (!$validActivities) {
162 $errorMess = "";
163 if ($extendTargetContacts) {
164 $errorMess = ts('One selected activity consists of more than one target contact.', array(
165 'count' => $extendTargetContacts,
166 'plural' => '%count selected activities consist of more than one target contact.'));
167 }
168 if ($invalidActivity) {
169 $errorMess = ($errorMess ? ' ' : '');
170 $errorMess .= ts('The selected activity is invalid.', array(
171 'count' => $invalidActivity,
172 'plural' => '%count selected activities are invalid.'));
173 }
174 CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess)));
175 }
176 }
177
178 if (is_array($form->_contactIds) && !empty($form->_contactIds) && $toSetDefault) {
179 $returnProperties = array(
180 'sort_name' => 1,
181 'phone' => 1,
182 'do_not_sms' => 1,
183 'is_deceased' => 1,
184 'display_name' => 1,
185 );
186
187 list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_contactIds,
188 $returnProperties,
189 FALSE,
190 FALSE
191 );
192
193 // make a copy of all contact details
194 $form->_allContactDetails = $form->_contactDetails;
195
196 foreach ($form->_contactIds as $key => $contactId) {
197 $value = $form->_contactDetails[$contactId];
198
199 //to check if the phone type is "Mobile"
200 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
201
202 if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
203 //to check for "if the contact id belongs to a specified activity type"
204 $actDetails = CRM_Activity_BAO_Activity::getContactActivity($contactId);
205 if (self::RECIEVED_SMS_ACTIVITY_SUBJECT !=
206 CRM_Utils_Array::retrieveValueRecursive($actDetails, 'subject')
207 ) {
208 $suppressedSms++;
209 unset($form->_contactDetails[$contactId]);
210 continue;
211 }
212 }
213
214 if ((isset($value['phone_type_id']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes)) || $value['do_not_sms'] || empty($value['phone']) || !empty($value['is_deceased'])) {
215
216 //if phone is not primary check if non-primary phone is "Mobile"
217 if (!empty($value['phone'])
218 && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) && empty($value['is_deceased'])) {
219 $filter = array('do_not_sms' => 0);
220 $contactPhones = CRM_Core_BAO_Phone::allPhones($contactId, FALSE, 'Mobile', $filter);
221 if (count($contactPhones) > 0) {
222 $mobilePhone = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'phone');
223 $form->_contactDetails[$contactId]['phone_id'] = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'id');
224 $form->_contactDetails[$contactId]['phone'] = $mobilePhone;
225 $form->_contactDetails[$contactId]['phone_type_id'] = CRM_Utils_Array::value('Mobile', $phoneTypes);
226 }
227 else {
228 $suppressedSms++;
229 unset($form->_contactDetails[$contactId]);
230 continue;
231 }
232 }
233 else {
234 $suppressedSms++;
235 unset($form->_contactDetails[$contactId]);
236 continue;
237 }
238 }
239
240 if (isset($mobilePhone)) {
241 $phone = $mobilePhone;
242 }
243 elseif (empty($form->_toContactPhone)) {
244 $phone = $value['phone'];
245 }
246 else {
247 $phone = CRM_Utils_Array::value($key, $form->_toContactPhone);
248 }
249
250 if ($phone) {
251 $toArray[] = array(
252 'text' => '"' . $value['sort_name'] . '" (' . $phone . ')',
253 'id' => "$contactId::{$phone}",
254 );
255 }
256 }
257
258 if (empty($toArray)) {
259 CRM_Core_Error::statusBounce(ts('Selected contact(s) do not have a valid Phone, or communication preferences specify DO NOT SMS, or they are deceased'));
260 }
261 }
262
263 //activity related variables
264 if (isset($invalidActivity)) {
265 $form->assign('invalidActivity', $invalidActivity);
266 }
267 if (isset($extendTargetContacts)) {
268 $form->assign('extendTargetContacts', $extendTargetContacts);
269 }
270
271
272 $form->assign('toContact', json_encode($toArray));
273 $form->assign('suppressedSms', $suppressedSms);
274 $form->assign('totalSelectedContacts', count($form->_contactIds));
275
276 $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE);
277
278 CRM_Mailing_BAO_Mailing::commonCompose($form);
279
280 if ($form->_single) {
281 // also fix the user context stack
282 if ($form->_context) {
283 $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
284 }
285 else {
286 $url = CRM_Utils_System::url('civicrm/contact/view',
287 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
288 );
289 }
290
291 $session = CRM_Core_Session::singleton();
292 $session->replaceUserContext($url);
293 $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel');
294 }
295 else {
296 $form->addDefaultButtons(ts('Send SMS'), 'upload');
297 }
298
299 $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form);
300 }
301
302 /**
303 * Form rule
304 *
305 * @param array $fields the input form values
306 * @param array $dontCare
307 * @param array $self additional values form 'this'
308 *
309 * @return true if no errors, else array of errors
310 * @access public
311 *
312 */
313 static function formRule($fields, $dontCare, $self) {
314 $errors = array();
315
316 $template = CRM_Core_Smarty::singleton();
317
318 if (empty($fields['sms_text_message'])) {
319 $errors['sms_text_message'] = ts('Please provide Text message.');
320 }
321 else {
322 if (!empty($fields['sms_text_message'])) {
323 $messageCheck = CRM_Utils_Array::value('sms_text_message', $fields);
324 $messageCheck = str_replace("\r\n", "\n", $messageCheck);
325 if ($messageCheck && (strlen($messageCheck) > CRM_SMS_Provider::MAX_SMS_CHAR)) {
326 $errors['sms_text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider::MAX_SMS_CHAR));
327 }
328 }
329 }
330
331 //Added for CRM-1393
332 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
333 $errors['saveTemplateName'] = ts("Enter name to save message template");
334 }
335
336 return empty($errors) ? TRUE : $errors;
337 }
338
339 /**
340 * Process the form after the input has been submitted and validated
341 *
342 * @access public
343 *
344 * @param CRM_Core_Form $form
345 *
346 * @return void
347 */
348 static function postProcess(&$form) {
349
350 // check and ensure that
351 $thisValues = $form->controller->exportValues($form->getName());
352
353 $fromSmsProviderId = $thisValues['sms_provider_id'];
354
355 // process message template
356 if (!empty($thisValues['saveTemplate']) || !empty($thisValues['updateTemplate'])) {
357 $messageTemplate = array(
358 'msg_text' => $thisValues['sms_text_message'],
359 'is_active' => TRUE,
360 );
361
362 if (!empty($thisValues['saveTemplate'])) {
363 $messageTemplate['msg_title'] = $thisValues['saveTemplateName'];
364 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
365 }
366
367 if (!empty($thisValues['template']) && !empty($thisValues['updateTemplate'])) {
368 $messageTemplate['id'] = $thisValues['template'];
369 unset($messageTemplate['msg_title']);
370 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
371 }
372 }
373
374 // format contact details array to handle multiple sms from same contact
375 $formattedContactDetails = array();
376 $tempPhones = array();
377
378 foreach ($form->_contactIds as $key => $contactId) {
379 $phone = $form->_toContactPhone[$key];
380
381 if ($phone) {
382 $phoneKey = "{$contactId}::{$phone}";
383 if (!in_array($phoneKey, $tempPhones)) {
384 $tempPhones[] = $phoneKey;
385 if (!empty($form->_contactDetails[$contactId])) {
386 $formattedContactDetails[] = $form->_contactDetails[$contactId];
387 }
388 }
389 }
390 }
391
392 // $smsParams carries all the arguments provided on form (or via hooks), to the provider->send() method
393 // this gives flexibity to the users / implementors to add their own args via hooks specific to their sms providers
394 $smsParams = $thisValues;
395 unset($smsParams['sms_text_message']);
396 $smsParams['provider_id'] = $fromSmsProviderId;
397 $contactIds = array_keys($form->_contactDetails);
398 $allContactIds = array_keys($form->_allContactDetails);
399
400 list($sent, $activityId, $countSuccess) = CRM_Activity_BAO_Activity::sendSMS($formattedContactDetails,
401 $thisValues,
402 $smsParams,
403 $contactIds
404 );
405
406 if ($countSuccess > 0) {
407 CRM_Core_Session::setStatus(ts('One message was sent successfully.', array('plural' => '%count messages were sent successfully.', 'count' => $countSuccess)), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $countSuccess)), 'success');
408 }
409
410 if (is_array($sent)) {
411 // At least one PEAR_Error object was generated.
412 // Display the error messages to the user.
413 $status = '<ul>';
414 foreach ($sent as $errMsg) {
415 $status .= '<li>' . $errMsg . '</li>';
416 }
417 $status .= '</ul>';
418 CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($sent), 'plural' => '%count Messages Not Sent')), 'info');
419 } else {
420 //Display the name and number of contacts for those sms is not sent.
421 $smsNotSent = array_diff_assoc($allContactIds, $contactIds);
422
423 if (!empty($smsNotSent)) {
424 $not_sent = array();
425 foreach ($smsNotSent as $index => $contactId) {
426 $displayName = $form->_allContactDetails[$contactId]['display_name'];
427 $phone = $form->_allContactDetails[$contactId]['phone'];
428 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=$contactId");
429 $not_sent[] = "<a href='$contactViewUrl' title='$phone'>$displayName</a>";
430 }
431 $status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased');
432 if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
433 $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT));
434 }
435 $status .= ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
436 CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($smsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
437 }
438 }
439 }
440 }
441