3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class provides the common functionality for sending sms to
38 * one or a group of contact ids.
40 class CRM_Contact_Form_Task_SMSCommon
{
41 CONST RECIEVED_SMS_ACTIVITY_SUBJECT
= "SMS Received";
43 public $_contactDetails = array();
45 public $_allContactDetails = array();
47 public $_toContactPhone = array();
53 static function preProcessProvider(&$form) {
54 $form->_single
= FALSE;
55 $className = CRM_Utils_System
::getClassName($form);
57 if (property_exists($form, '_context') &&
58 $form->_context
!= 'search' &&
59 $className == 'CRM_Contact_Form_Task_SMS'
61 $form->_single
= TRUE;
64 $providersCount = CRM_SMS_BAO_Provider
::activeProviderCount();
66 if (!$providersCount) {
67 CRM_Core_Error
::statusBounce(ts('There are no SMS providers configured, or no SMS providers are set active'));
70 if ($className == 'CRM_Activity_Form_Task_SMS') {
72 foreach ($form->_activityHolderIds
as $value) {
73 if (CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $value, 'subject', 'id') != self
::RECIEVED_SMS_ACTIVITY_SUBJECT
) {
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
)
94 static function buildQuickForm(&$form) {
98 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
100 $providers = CRM_SMS_BAO_Provider
::getProviders(NULL, NULL, TRUE, 'is_default desc');
102 $providerSelect = array();
103 foreach ($providers as $provider) {
104 $providerSelect[$provider['id']] = $provider['title'];
107 //here we are getting logged in user id as array but we need target contact id. CRM-5988
108 $cid = $form->get('cid');
111 $form->_contactIds
= array($cid);
114 $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE);
115 $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE);
117 $toSetDefault = TRUE;
118 if (property_exists($form, '_context') && $form->_context
== 'standalone') {
119 $toSetDefault = FALSE;
122 // when form is submitted recompute contactIds
124 if ($to->getValue()) {
125 $allToPhone = explode(',', $to->getValue());
127 $form->_contactIds
= array();
128 foreach ($allToPhone as $value) {
129 list($contactId, $phone) = explode('::', $value);
131 $form->_contactIds
[] = $contactId;
132 $form->_toContactPhone
[] = $phone;
135 $toSetDefault = TRUE;
138 //get the group of contacts as per selected by user in case of Find Activities
139 if (!empty($form->_activityHolderIds
)) {
140 $extendTargetContacts = 0;
141 $invalidActivity = 0;
142 $validActivities = 0;
143 foreach ($form->_activityHolderIds
as $key => $id) {
144 //valid activity check
145 if (CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self
::RECIEVED_SMS_ACTIVITY_SUBJECT
) {
150 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
151 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
152 //target contacts limit check
153 $ids = array_keys(CRM_Activity_BAO_ActivityContact
::getNames($id, $targetID));
155 if (count($ids) > 1) {
156 $extendTargetContacts++
;
160 $form->_contactIds
= empty($form->_contactIds
) ?
$ids : array_unique(array_merge($form->_contactIds
, $ids));
163 if (!$validActivities) {
165 if ($extendTargetContacts) {
166 $errorMess = ts('One selected activity consists of more than one target contact.', array(
167 'count' => $extendTargetContacts,
168 'plural' => '%count selected activities consist of more than one target contact.'));
170 if ($invalidActivity) {
171 $errorMess = ($errorMess ?
' ' : '');
172 $errorMess .= ts('The selected activity is invalid.', array(
173 'count' => $invalidActivity,
174 'plural' => '%count selected activities are invalid.'));
176 CRM_Core_Error
::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess)));
180 if (is_array($form->_contactIds
) && !empty($form->_contactIds
) && $toSetDefault) {
181 $returnProperties = array(
189 list($form->_contactDetails
) = CRM_Utils_Token
::getTokenDetails($form->_contactIds
,
195 // make a copy of all contact details
196 $form->_allContactDetails
= $form->_contactDetails
;
198 foreach ($form->_contactIds
as $key => $contactId) {
199 $value = $form->_contactDetails
[$contactId];
201 //to check if the phone type is "Mobile"
202 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
204 if (CRM_Utils_System
::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
205 //to check for "if the contact id belongs to a specified activity type"
206 $actDetails = CRM_Activity_BAO_Activity
::getContactActivity($contactId);
207 if (self
::RECIEVED_SMS_ACTIVITY_SUBJECT
!=
208 CRM_Utils_Array
::retrieveValueRecursive($actDetails, 'subject')
211 unset($form->_contactDetails
[$contactId]);
216 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'])) {
218 //if phone is not primary check if non-primary phone is "Mobile"
219 if (!empty($value['phone'])
220 && $value['phone_type_id'] != CRM_Utils_Array
::value('Mobile', $phoneTypes) && empty($value['is_deceased'])) {
221 $filter = array('do_not_sms' => 0);
222 $contactPhones = CRM_Core_BAO_Phone
::allPhones($contactId, FALSE, 'Mobile', $filter);
223 if (count($contactPhones) > 0) {
224 $mobilePhone = CRM_Utils_Array
::retrieveValueRecursive($contactPhones, 'phone');
225 $form->_contactDetails
[$contactId]['phone_id'] = CRM_Utils_Array
::retrieveValueRecursive($contactPhones, 'id');
226 $form->_contactDetails
[$contactId]['phone'] = $mobilePhone;
227 $form->_contactDetails
[$contactId]['phone_type_id'] = CRM_Utils_Array
::value('Mobile', $phoneTypes);
231 unset($form->_contactDetails
[$contactId]);
237 unset($form->_contactDetails
[$contactId]);
242 if (isset($mobilePhone)) {
243 $phone = $mobilePhone;
245 elseif (empty($form->_toContactPhone
)) {
246 $phone = $value['phone'];
249 $phone = CRM_Utils_Array
::value($key, $form->_toContactPhone
);
254 'text' => '"' . $value['sort_name'] . '" (' . $phone . ')',
255 'id' => "$contactId::{$phone}",
260 if (empty($toArray)) {
261 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'));
265 //activity related variables
266 if (isset($invalidActivity)) {
267 $form->assign('invalidActivity', $invalidActivity);
269 if (isset($extendTargetContacts)) {
270 $form->assign('extendTargetContacts', $extendTargetContacts);
274 $form->assign('toContact', json_encode($toArray));
275 $form->assign('suppressedSms', $suppressedSms);
276 $form->assign('totalSelectedContacts', count($form->_contactIds
));
278 $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE);
280 CRM_Mailing_BAO_Mailing
::commonCompose($form);
282 if ($form->_single
) {
283 // also fix the user context stack
284 if ($form->_context
) {
285 $url = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
288 $url = CRM_Utils_System
::url('civicrm/contact/view',
289 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
293 $session = CRM_Core_Session
::singleton();
294 $session->replaceUserContext($url);
295 $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel');
298 $form->addDefaultButtons(ts('Send SMS'), 'upload');
301 $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form);
307 * @param array $fields the input form values
308 * @param array $dontCare
309 * @param array $self additional values form 'this'
311 * @return true if no errors, else array of errors
315 static function formRule($fields, $dontCare, $self) {
318 $template = CRM_Core_Smarty
::singleton();
320 if (empty($fields['text_message'])) {
321 $errors['text_message'] = ts('Please provide Text message.');
324 if (!empty($fields['text_message'])) {
325 $messageCheck = CRM_Utils_Array
::value('text_message', $fields);
326 $messageCheck = str_replace("\r\n", "\n", $messageCheck);
327 if ($messageCheck && (strlen($messageCheck) > CRM_SMS_Provider
::MAX_SMS_CHAR
)) {
328 $errors['text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider
::MAX_SMS_CHAR
));
334 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
335 $errors['saveTemplateName'] = ts("Enter name to save message template");
338 return empty($errors) ?
TRUE : $errors;
342 * process the form after the input has been submitted and validated
350 static function postProcess(&$form) {
352 // check and ensure that
353 $thisValues = $form->controller
->exportValues($form->getName());
355 $fromSmsProviderId = $thisValues['sms_provider_id'];
357 // process message template
358 if (!empty($thisValues['saveTemplate']) ||
!empty($thisValues['updateTemplate'])) {
359 $messageTemplate = array(
360 'msg_text' => $thisValues['text_message'],
364 if (!empty($thisValues['saveTemplate'])) {
365 $messageTemplate['msg_title'] = $thisValues['saveTemplateName'];
366 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
369 if (!empty($thisValues['template']) && !empty($thisValues['updateTemplate'])) {
370 $messageTemplate['id'] = $thisValues['template'];
371 unset($messageTemplate['msg_title']);
372 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
376 // format contact details array to handle multiple sms from same contact
377 $formattedContactDetails = array();
378 $tempPhones = array();
380 foreach ($form->_contactIds
as $key => $contactId) {
381 $phone = $form->_toContactPhone
[$key];
384 $phoneKey = "{$contactId}::{$phone}";
385 if (!in_array($phoneKey, $tempPhones)) {
386 $tempPhones[] = $phoneKey;
387 if (!empty($form->_contactDetails
[$contactId])) {
388 $formattedContactDetails[] = $form->_contactDetails
[$contactId];
394 // $smsParams carries all the arguments provided on form (or via hooks), to the provider->send() method
395 // this gives flexibity to the users / implementors to add their own args via hooks specific to their sms providers
396 $smsParams = $thisValues;
397 unset($smsParams['text_message']);
398 $smsParams['provider_id'] = $fromSmsProviderId;
399 $contactIds = array_keys($form->_contactDetails
);
400 $allContactIds = array_keys($form->_allContactDetails
);
402 list($sent, $activityId, $countSuccess) = CRM_Activity_BAO_Activity
::sendSMS($formattedContactDetails,
408 if ($countSuccess > 0) {
409 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');
412 if (is_array($sent)) {
413 // At least one PEAR_Error object was generated.
414 // Display the error messages to the user.
416 foreach ($sent as $errMsg) {
417 $status .= '<li>' . $errMsg . '</li>';
420 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array('count' => count($sent), 'plural' => '%count Messages Not Sent')), 'info');
422 //Display the name and number of contacts for those sms is not sent.
423 $smsNotSent = array_diff_assoc($allContactIds, $contactIds);
425 if (!empty($smsNotSent)) {
427 foreach ($smsNotSent as $index => $contactId) {
428 $displayName = $form->_allContactDetails
[$contactId]['display_name'];
429 $phone = $form->_allContactDetails
[$contactId]['phone'];
430 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid=$contactId");
431 $not_sent[] = "<a href='$contactViewUrl' title='$phone'>$displayName</a>";
433 $status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased');
434 if (CRM_Utils_System
::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
435 $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self
::RECIEVED_SMS_ACTIVITY_SUBJECT
));
437 $status .= ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
438 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array('count' => count($smsNotSent), 'plural' => '%count Messages Not Sent')), 'info');