3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 * This class provides the common functionality for sending sms to one or a group of contact ids.
37 class CRM_Contact_Form_Task_SMSCommon
{
38 const RECIEVED_SMS_ACTIVITY_SUBJECT
= "SMS Received";
40 public $_contactDetails = array();
42 public $_allContactDetails = array();
44 public $_toContactPhone = array();
48 * Pre process the provider.
50 * @param CRM_Core_Form $form
52 public static function preProcessProvider(&$form) {
53 $form->_single
= FALSE;
54 $className = CRM_Utils_System
::getClassName($form);
56 if (property_exists($form, '_context') &&
57 $form->_context
!= 'search' &&
58 $className == 'CRM_Contact_Form_Task_SMS'
60 $form->_single
= TRUE;
63 $providersCount = CRM_SMS_BAO_Provider
::activeProviderCount();
65 if (!$providersCount) {
66 CRM_Core_Error
::statusBounce(ts('There are no SMS providers configured, or no SMS providers are set active'));
69 if ($className == 'CRM_Activity_Form_Task_SMS') {
71 foreach ($form->_activityHolderIds
as $value) {
72 if (CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $value, 'subject', 'id') != self
::RECIEVED_SMS_ACTIVITY_SUBJECT
) {
76 if ($activityCheck == count($form->_activityHolderIds
)) {
77 CRM_Core_Error
::statusBounce(ts("The Reply SMS Could only be sent for activities with '%1' subject.",
78 array(1 => self
::RECIEVED_SMS_ACTIVITY_SUBJECT
)
85 * Build the form object.
87 * @param CRM_Core_Form $form
89 public static function buildQuickForm(&$form) {
93 $providers = CRM_SMS_BAO_Provider
::getProviders(NULL, NULL, TRUE, 'is_default desc');
95 $providerSelect = array();
96 foreach ($providers as $provider) {
97 $providerSelect[$provider['id']] = $provider['title'];
100 //here we are getting logged in user id as array but we need target contact id. CRM-5988
101 $cid = $form->get('cid');
104 $form->_contactIds
= array($cid);
107 $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE);
108 $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE);
110 $toSetDefault = TRUE;
111 if (property_exists($form, '_context') && $form->_context
== 'standalone') {
112 $toSetDefault = FALSE;
115 // when form is submitted recompute contactIds
117 if ($to->getValue()) {
118 $allToPhone = explode(',', $to->getValue());
120 $form->_contactIds
= array();
121 foreach ($allToPhone as $value) {
122 list($contactId, $phone) = explode('::', $value);
124 $form->_contactIds
[] = $contactId;
125 $form->_toContactPhone
[] = $phone;
128 $toSetDefault = TRUE;
131 //get the group of contacts as per selected by user in case of Find Activities
132 if (!empty($form->_activityHolderIds
)) {
133 $extendTargetContacts = 0;
134 $invalidActivity = 0;
135 $validActivities = 0;
136 foreach ($form->_activityHolderIds
as $key => $id) {
137 //valid activity check
138 if (CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self
::RECIEVED_SMS_ACTIVITY_SUBJECT
) {
143 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
144 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
145 //target contacts limit check
146 $ids = array_keys(CRM_Activity_BAO_ActivityContact
::getNames($id, $targetID));
148 if (count($ids) > 1) {
149 $extendTargetContacts++
;
153 $form->_contactIds
= empty($form->_contactIds
) ?
$ids : array_unique(array_merge($form->_contactIds
, $ids));
156 if (!$validActivities) {
158 if ($extendTargetContacts) {
159 $errorMess = ts('One selected activity consists of more than one target contact.', array(
160 'count' => $extendTargetContacts,
161 'plural' => '%count selected activities consist of more than one target contact.',
164 if ($invalidActivity) {
165 $errorMess = ($errorMess ?
' ' : '');
166 $errorMess .= ts('The selected activity is invalid.', array(
167 'count' => $invalidActivity,
168 'plural' => '%count selected activities are invalid.',
171 CRM_Core_Error
::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess)));
175 if (is_array($form->_contactIds
) && !empty($form->_contactIds
) && $toSetDefault) {
176 $returnProperties = array(
184 list($form->_contactDetails
) = CRM_Utils_Token
::getTokenDetails($form->_contactIds
,
190 // make a copy of all contact details
191 $form->_allContactDetails
= $form->_contactDetails
;
193 foreach ($form->_contactIds
as $key => $contactId) {
194 $value = $form->_contactDetails
[$contactId];
196 //to check if the phone type is "Mobile"
197 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
199 if (CRM_Utils_System
::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
200 //to check for "if the contact id belongs to a specified activity type"
201 $actDetails = CRM_Activity_BAO_Activity
::getContactActivity($contactId);
202 if (self
::RECIEVED_SMS_ACTIVITY_SUBJECT
!=
203 CRM_Utils_Array
::retrieveValueRecursive($actDetails, 'subject')
206 unset($form->_contactDetails
[$contactId]);
211 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'])) {
213 //if phone is not primary check if non-primary phone is "Mobile"
214 if (!empty($value['phone'])
215 && $value['phone_type_id'] != CRM_Utils_Array
::value('Mobile', $phoneTypes) && empty($value['is_deceased'])
217 $filter = array('do_not_sms' => 0);
218 $contactPhones = CRM_Core_BAO_Phone
::allPhones($contactId, FALSE, 'Mobile', $filter);
219 if (count($contactPhones) > 0) {
220 $mobilePhone = CRM_Utils_Array
::retrieveValueRecursive($contactPhones, 'phone');
221 $form->_contactDetails
[$contactId]['phone_id'] = CRM_Utils_Array
::retrieveValueRecursive($contactPhones, 'id');
222 $form->_contactDetails
[$contactId]['phone'] = $mobilePhone;
223 $form->_contactDetails
[$contactId]['phone_type_id'] = CRM_Utils_Array
::value('Mobile', $phoneTypes);
227 unset($form->_contactDetails
[$contactId]);
233 unset($form->_contactDetails
[$contactId]);
238 if (isset($mobilePhone)) {
239 $phone = $mobilePhone;
241 elseif (empty($form->_toContactPhone
)) {
242 $phone = $value['phone'];
245 $phone = CRM_Utils_Array
::value($key, $form->_toContactPhone
);
250 'text' => '"' . $value['sort_name'] . '" (' . $phone . ')',
251 'id' => "$contactId::{$phone}",
256 if (empty($toArray)) {
257 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'));
261 //activity related variables
262 if (isset($invalidActivity)) {
263 $form->assign('invalidActivity', $invalidActivity);
265 if (isset($extendTargetContacts)) {
266 $form->assign('extendTargetContacts', $extendTargetContacts);
269 $form->assign('toContact', json_encode($toArray));
270 $form->assign('suppressedSms', $suppressedSms);
271 $form->assign('totalSelectedContacts', count($form->_contactIds
));
273 $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE);
275 CRM_Mailing_BAO_Mailing
::commonCompose($form);
277 if ($form->_single
) {
278 // also fix the user context stack
279 if ($form->_context
) {
280 $url = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
283 $url = CRM_Utils_System
::url('civicrm/contact/view',
284 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
288 $session = CRM_Core_Session
::singleton();
289 $session->replaceUserContext($url);
290 $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel');
293 $form->addDefaultButtons(ts('Send SMS'), 'upload');
296 $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form);
302 * @param array $fields
303 * The input form values.
304 * @param array $dontCare
306 * Additional values form 'this'.
309 * true if no errors, else array of errors
311 public static function formRule($fields, $dontCare, $self) {
314 $template = CRM_Core_Smarty
::singleton();
316 if (empty($fields['sms_text_message'])) {
317 $errors['sms_text_message'] = ts('Please provide Text message.');
320 if (!empty($fields['sms_text_message'])) {
321 $messageCheck = CRM_Utils_Array
::value('sms_text_message', $fields);
322 $messageCheck = str_replace("\r\n", "\n", $messageCheck);
323 if ($messageCheck && (strlen($messageCheck) > CRM_SMS_Provider
::MAX_SMS_CHAR
)) {
324 $errors['sms_text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider
::MAX_SMS_CHAR
));
330 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
331 $errors['saveTemplateName'] = ts("Enter name to save message template");
334 return empty($errors) ?
TRUE : $errors;
338 * Process the form after the input has been submitted and validated.
340 * @param CRM_Core_Form $form
342 public static function postProcess(&$form) {
344 // check and ensure that
345 $thisValues = $form->controller
->exportValues($form->getName());
347 $fromSmsProviderId = $thisValues['sms_provider_id'];
349 // process message template
350 if (!empty($thisValues['saveTemplate']) ||
!empty($thisValues['updateTemplate'])) {
351 $messageTemplate = array(
352 'msg_text' => $thisValues['sms_text_message'],
356 if (!empty($thisValues['saveTemplate'])) {
357 $messageTemplate['msg_title'] = $thisValues['saveTemplateName'];
358 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
361 if (!empty($thisValues['template']) && !empty($thisValues['updateTemplate'])) {
362 $messageTemplate['id'] = $thisValues['template'];
363 unset($messageTemplate['msg_title']);
364 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
368 // format contact details array to handle multiple sms from same contact
369 $formattedContactDetails = array();
370 $tempPhones = array();
372 foreach ($form->_contactIds
as $key => $contactId) {
373 $phone = $form->_toContactPhone
[$key];
376 $phoneKey = "{$contactId}::{$phone}";
377 if (!in_array($phoneKey, $tempPhones)) {
378 $tempPhones[] = $phoneKey;
379 if (!empty($form->_contactDetails
[$contactId])) {
380 $formattedContactDetails[] = $form->_contactDetails
[$contactId];
386 // $smsParams carries all the arguments provided on form (or via hooks), to the provider->send() method
387 // this gives flexibity to the users / implementors to add their own args via hooks specific to their sms providers
388 $smsParams = $thisValues;
389 unset($smsParams['sms_text_message']);
390 $smsParams['provider_id'] = $fromSmsProviderId;
391 $contactIds = array_keys($form->_contactDetails
);
392 $allContactIds = array_keys($form->_allContactDetails
);
394 list($sent, $activityId, $countSuccess) = CRM_Activity_BAO_Activity
::sendSMS($formattedContactDetails,
400 if ($countSuccess > 0) {
401 CRM_Core_Session
::setStatus(ts('One message was sent successfully.', array(
402 'plural' => '%count messages were sent successfully.',
403 'count' => $countSuccess,
404 )), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $countSuccess)), 'success');
407 if (is_array($sent)) {
408 // At least one PEAR_Error object was generated.
409 // Display the error messages to the user.
411 foreach ($sent as $errMsg) {
412 $status .= '<li>' . $errMsg . '</li>';
415 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array(
416 'count' => count($sent),
417 'plural' => '%count Messages Not Sent',
421 //Display the name and number of contacts for those sms is not sent.
422 $smsNotSent = array_diff_assoc($allContactIds, $contactIds);
424 if (!empty($smsNotSent)) {
426 foreach ($smsNotSent as $index => $contactId) {
427 $displayName = $form->_allContactDetails
[$contactId]['display_name'];
428 $phone = $form->_allContactDetails
[$contactId]['phone'];
429 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid=$contactId");
430 $not_sent[] = "<a href='$contactViewUrl' title='$phone'>$displayName</a>";
432 $status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased');
433 if (CRM_Utils_System
::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
434 $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self
::RECIEVED_SMS_ACTIVITY_SUBJECT
));
436 $status .= ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
437 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array(
438 'count' => count($smsNotSent),
439 'plural' => '%count Messages Not Sent',