Files
booking/booking.email_manually.inc
2018-06-26 18:23:47 +10:00

595 lines
26 KiB
PHP

<?php
/**
* Function to allow admin user to manually generate and send a workflow or custom email
*
* @param
* @return form render array
*/
function booking_manual_email_form($form, &$form_state)
{
global $event;
//see http://www.jaypan.com/blog/themeing-drupal-7-forms-tables-checkboxes-or-radios
/*
create hidden form element that we will populate with JSON data via ajax
create select element defining the pre-selections available
create submit button that calls ajax to update hidden form element, then calls ajax to check the checkboxes based on the hidden form element
info on turning JSON data back to array
http://stackoverflow.com/questions/29076219/javascript-storing-array-of-objects-in-hidden-field
ajax references:
http://www.maged.me/blog/drupal-7-execute-javascript-code-after-ajax-call
https://www.drupal.org/node/1028410
https://www.drupal.org/node/2046693
jquery to check the checkboxes:
http://jsfiddle.net/nanoquantumtech/dnhwz/
*/
$form = array();
$options = array();
$preselection_options = array();
$values = array();
$group_text = "";
$prefix = t("<p>Send a manual email to people registered for this event. ");
$prefix .= t("Click !workflow to update builtin-workflow emails, or click !custom to update custom email definitions.</p>",
array ('!workflow' => l('here', 'admin/config/booking/emails'), '!custom' => l('here', 'admin/config/booking/emails/definitions')));
$prefix .= t("<p>Highlighted rows have welfare requirements.</p>");
$email_options_array = array();
$email_options_array['NULL'] = "---";
$email_options_array['registration'] = 'Registration Successful Email';
$email_options_array['balance'] = 'Balance Outstanding Email';
$email_options_array['complete'] = 'Payment Complete Email';
$email_options_array['withdrawal'] = 'Withdrawal Processed Email';
$email_options_array['waitinglistpromotion'] = 'Position Available (Balance outstanding)';
$email_options_array['waitinglistpromotionfullypaid'] = 'Position Available (Fully Paid)';
$email_options_array['missedpayment'] = 'Missed Payment Email';
$email_options_array['initialtravelrequired'] = 'Initial Travel Form Required Email';
$email_options_array['remindertravelrequired'] = 'Reminder Travel Form Required Email';
$email_options_array['travelcomplete'] = 'Travel Form Complete Email';
$preselection_options['---'] = "---";
$preselection_options['notpaid'] = 'People who have not yet paid';
$preselection_options['bookedin'] = 'People who are booked-in';
$preselection_options['waitinglist'] = 'People on waiting list';
$preselection_options['unpaid'] = 'People booked-in with outstanding balance';
$preselection_options['refundreqd'] = 'Refund Required';
$preselection_options['notravelform'] = "People booked-in no travel form received";
$preselection_options['notravelforminclwaiting'] = "People booked-in/waiting no travel form received";
$preselection_options['leaderhelper'] = "Leaders/Helpers";
$preselection_options['readinggroup-leader'] = "Reading Group Leaders";
$header = array(
'booking_nid' => array('data' => t('Id'), 'field' => 'nid', 'sort' => 'asc'),
'booking_name' => array('data' => t('Name'), 'field' => 'booking_lastname'),
'booking_gender' => array('data' => t('Gender'), 'field' => 'booking_gender'),
'booking_email' => array('data' => t('Email'), 'field' => 'booking_email'),
'booking_state' => array('data' => t('State'), 'field' => 'booking_state'),
'booking_status' => array('data' => t('Status'), 'field' => 'booking_status'),
'amount_paid' => array('data' => t('Payment To Date'), 'field' => 'booking_amount_paid'),
'amount_reqd' => array('data' => t('Total Payment Required'), 'field' => 'booking_total_pay_reqd'),
'booking_fully_paid' => array('data' => t('Fully paid?'), 'field' => 'booking_payment_complete'),
'welfare_required' => array('data' => t('Welfare Required?'), 'field' => 'booking_welfare_required'),
);
//add in the custom email types
for ($i = 1; $i <= variable_get('booking_custom_email_count','5'); $i++) {
$email_options_array['custom' . $i] = variable_get('booking_email_subject_custom' . $i, $event->booking_eventname . ' custom ' . $i);
}
//add in the custom email types from logistics
for ($i = 1; $i <= 5; $i++) {
$email_options_array['customlogistics' . $i] = variable_get('booking_email_subject_customlogistics' . $i,
$event->booking_eventname . ' logistics custom ' . $i) . " **Logistics**";
}
//attach css so we can customise colours for some people
$form['#attached']['css'] = array(
drupal_get_path('module', 'booking') . '/booking.css',
);
//attach js for dynamically setting checkboxes
$form['#attached']['js'][] = drupal_get_path("module", "booking")."/booking.js";
$form['pretext'] = array(
'#type' => 'container',
'#children' => $prefix,
);
//@todo add booking prefix
$form['email-type'] = array(
'#type' => 'select',
'#title' => t('Email Type'),
'#required' => TRUE,
'#default_value' => 'NULL',
'#options' => $email_options_array,
'#ajax' => array(
'event' => 'change',
'callback' => '_booking_email_get_preview_callback',
'wrapper' => 'booking_email_preview_wrapper',
),
);
$form['booking-email-default-ids'] = array (
'#type' => 'hidden',
'#value' => "[]",
'#prefix' => '<div id="booking_email_default_ids_wrapper">',
'#suffix' => '</div>',
'#attributes' => array('id' => 'booking_email_default_ids'),
);
$form['booking-email-preselection'] = array(
'#type' => 'select',
'#title' => t('Pre-select attendees from list'),
'#description' => t('Use this to select a large group of people based on pre-defined criteria.'),
'#options' => $preselection_options,
'#default_value' => '---',
'#suffix' => '<div id="booking_email_preselection_suffix_wrapper"></div>',
'#ajax' => array(
'event' => 'change',
'callback' => '_booking_email_get_default_selection_callback',
'wrapper' => 'booking_email_default_ids_wrapper',
),
);
$form['booking-email-preview'] = array(
'#type' => 'container',
'#children' => "<h3>Email Preview</h3><pre>No email type selected.</pre>",
'#prefix' => '<div id="booking_email_preview_wrapper">',
'#suffix' => '</div>',
);
$form['attachments'] = array(
'#type' => 'fieldset',
'#title' => 'Attach Files',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['attachments']['booking-email-attachment-1'] = array(
'#type' => 'managed_file',
'#title' => t('Email attachment 1'),
'#description' => t('Attach a file to be emailed. Note that this only works with custom email types. File must be 10MB or less, and extension must be one of: ' . variable_get('booking_email_allowed_attachments', 'pdf docx')),
'#upload_location' => 'public://bookings/emails',
'#upload_validators' => array(
'file_validate_size' => array(10*1024*1024),
'file_validate_extensions' => array(variable_get('booking_email_allowed_attachments', 'pdf docx')),
),
);
$form['attachments']['booking-email-attachment-2'] = array(
'#type' => 'managed_file',
'#title' => t('Email attachment 2'),
'#description' => t('Attach a file to be emailed. Note that this only works with custom email types. File must be 10MB or less, and extension must be one of: ' . variable_get('booking_email_allowed_attachments', 'pdf docx')),
'#upload_location' => 'public://bookings/emails',
'#upload_validators' => array(
'file_validate_size' => array(10*1024*1024),
'file_validate_extensions' => array(variable_get('booking_email_allowed_attachments', 'pdf docx')),
),
);
/*
// See https://drupal.stackexchange.com/questions/108583/how-to-save-file-uploaded-with-plupload-integration-module-and-make-it-managed
// For info on saving the attachments from plupload
// Submit handler:
if (!empty($form_state['values']['upload'])) {
$form_state['uploaded_files'] = quotes_file_save_files($form_state['values']['upload']);
}
function quotes_file_save_files($files) {
$saved_files = array();
$scheme = 'private://'; // Change to "public://" if you want to move to public files folder.
foreach ($files as $uploaded_file) {
if ($uploaded_file['status'] == 'done') {
$source = $uploaded_file['tmppath'];
$destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
$destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
$file = plupload_file_uri_to_object($destination);
file_save($file);
// Check the $file object to see if all necessary properties are set. Otherwise, use file_load($file->fid) to populate all of them.
// $file = file_load($file->fid);
$saved_files[] = $file;
}
}
return $saved_files;
}
$form['booking-email-attachment'] = array(
'#type' => 'plupload',
'#title' => t('Email attachment'),
'#description' => t('Attach any files to be attached to email. Note that this only works with custom email types.'),
'#upload_validators' => array(
'file_validate_size' => array(10*1024*1024),
'file_validate_extensions' => array(variable_get('booking_email_allowed_attachments', 'pdf docx')),
),
'#plupload_settings' => array(
'runtimes' => 'html5',
'chunk_size' => '1mb',
),
);
*/
$form['submit'] = array (
'#type' => 'submit',
'#value' => t('Send Email'),
);
if (variable_get('booking_enable_travelform', 0) == 1) {
$header['travel_form'] = array('data' => t('Travel Submitted?'), 'field' => 'tid');
}
//query the database for studygroup info if it is enabled
if (variable_get('booking_enable_studygroups', 0) == 1) {
//select entries from the study groups mapping table
$query = db_select('booking_studygroup_mapping', 'm');
$query->join('booking_studygroup_list', 's', 's.sid = m.booking_studygroup_id');
$query->condition('m.booking_eventid', $event->eid, '=');
$query->fields('m')->fields('s', array('booking_studygroup_descrip'));
$group_mapping = $query->execute()->fetchAllAssoc('sid');
//add a column to the table header
$header['group_roles'] = array('data' => t('Group Role'));
}
//query for attendee data
$query = db_select('booking_person', 'p');
$query->join('booking_price', 'pr', 'pr.pid = p.booking_payment_id');
$query->leftJoin('booking_travel', 't', 'p.nid = t.booking_person_nid');
$query->fields('p')
->fields('pr', array('booking_price', 'booking_late_price'))
->fields('t')
->condition('p.booking_eventid', $event->eid, '=');
//make the result user-sortable
$table_sort = $query->extend('TableSort')->orderbyHeader($header);
$result = $table_sort->execute();
//generate the tableselect data
foreach($result as $data) {
$group_text = "";
$class = $data->booking_welfare_required == 'Y' ? "welfare-row" : "normal-row";
$options[$data->nid] = array (
'#attributes' => array('class' => array($class)),
'booking_nid' => l(t('!id', array('!id' => $data->nid)), t('node/!id', array('!id' => $data->nid))),
'booking_name' => $data->booking_firstname . " " . $data->booking_lastname,
'booking_gender' => $data->booking_gender == 'M' ? 'Male' : 'Female',
'booking_email' => $data->booking_email,
'booking_state' => $data->booking_state,
'booking_status' => _booking_status_generate($data->booking_status),
'amount_paid' => $data->booking_amount_paid,
'amount_reqd' => $data->booking_total_pay_reqd,
'booking_fully_paid' => $data->booking_payment_complete == 'Y' ? 'Yes' : 'No',
'welfare_required' => $data->booking_welfare_required == 'Y' ? 'Yes' : 'No',
);
//add optional columns if those features are enabled
if (variable_get('booking_enable_travelform', 0) == 1) {
$options[$data->nid]['travel_form'] = $data->tid > 0 ? 'Yes' : 'No';
}
if (variable_get('booking_enable_studygroups', 0) == 1) {
foreach ($group_mapping as $group) {
$role = $group->booking_studygroup_role;
if ($group->booking_node_id == $data->nid && $role > 0) {
$text = _booking_studygroup_role_lookup($role);
$group_text .= "<b>" . $text . "</b> for " . $group->booking_studygroup_descrip . " #" . $group->booking_session_id . "; ";
}
}
$options[$data->nid]['group_roles'] = $group_text;
}
}
$form['table'] = array (
'#type' => 'tableselect',
//'#multiple' => TRUE,
'#header' => $header,
'#options' => $options,
'#default_value' => $values,
'#empty' => t('No attendees found.'),
'#attributes' => array('id' => 'sort-table'),
);
//watchdog('booking_debug', "<pre>Manual email form default values\n@info</pre>", array('@info' => print_r( $values, true)));
//watchdog('booking_debug', "<pre>Manual email form table\n@info</pre>", array('@info' => print_r( $form['table'], true)));
$form['submit-bottom'] = array (
'#type' => 'submit',
'#value' => t('Send Email'),
);
return array (
/*
'first_para' => array (
'#type' => 'markup',
'#markup' => $prefix,
),
*/
'form' => $form,
);
}
/**
* Callback to update preview of email that will be sent
*
*/
function _booking_email_get_preview_callback($form, $form_state) {
global $event;
$text = "";
$emailtype = $form_state['values']['email-type'];
switch ($emailtype) {
case "registration":
$text = variable_get('booking_email_bookedin_text');
break;
case "balance":
$text = variable_get('booking_email_paymentoutstanding_text');
// perform the checking of HTML value now since we're pre-pending text to it
$text = isset($text['format']) ? $text['value'] : $text;
if (variable_get('booking_enable_combined_pricing', 0) == 1) {
// no <pre> tags necessary if its a HTML mail
if(variable_get('booking_enable_html_mail', 0) == 1) {
$text .= "\n<h3>If married</h3>\n";
}
else {
$text .= "\n</pre><h3>If married</h3>\n<pre>";
}
$married_text = variable_get('booking_email_paymentoutstanding_married_text');
// repeat HTML check for rest of preview
$text .= isset($married_text['format']) ? $married_text['value'] : $married_text;
}
break;
case "complete":
$text = variable_get('booking_email_regn_complete_text');
break;
case "withdrawal":
$text = variable_get('booking_email_notcoming_demotion');
break;
case "missedpayment":
$text = variable_get('booking_email_missedpayment');
break;
case "initialtravelrequired":
$text = variable_get('booking_email_travel_initial_email_text');
break;
case "remindertravelrequired":
$text = variable_get('booking_email_travel_reminder_email_text');
break;
case "travelcomplete":
$text = variable_get('booking_email_travel_complete_text');
break;
case "waitinglistpromotion":
$text = variable_get('booking_email_waitinglistpromotion');
break;
case "waitinglistpromotionfullypaid":
$text = variable_get('booking_email_waitinglistpromotion_fullypaid');
break;
}
//handle custom email types
if (strpos($emailtype, 'custom') !== false) {
$text = variable_get('booking_email_' . $form_state['values']['email-type']);
}
//use the html value if it is set, otherwise use the plaintext input which is just a string
$text = isset($text['format']) ? $text['value'] : $text;
//watchdog('booking_debug', "<pre>Email generation:\n@info</pre>", array('@info' => print_r( $text, true)));
if(variable_get('booking_enable_html_mail', 0) == 1) {
$markup_pre = "<div id=\"booking_email_preview_wrapper\"><h3>Email Preview</h3>";
$markup_post = "<br /><br /></div>";
}
else {
$markup_pre = "<div id=\"booking_email_preview_wrapper\"><h3>Email Preview</h3><pre>";
$markup_post = "</pre><br /><br /></div>";
}
//generate html that will be used to update div booking_email_preview_wrapper
return $markup_pre . $text . $markup_post;
}
/**
* Callback to update hidden form value with default checkbox details
*
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable array (or an
* array of commands), we can just return a piece of the form.
* Source: http://www.maged.me/blog/drupal-7-execute-javascript-code-after-ajax-call
*/
function _booking_email_get_default_selection_callback($form, $form_state) {
global $event;
$defaults = array();
$replacementform_data = array();
//get type of selection from $form_state['values']['booking-email-preselection']
$selection = $form_state['values']['booking-email-preselection'];
//load nodes
$people = booking_load_query(NULL, TRUE);
// Check for the reading group ID
$readinggroup_query = db_query("SELECT * FROM {booking_studygroup_list} WHERE booking_eventid = :eid AND booking_is_readinggroup = 'Y'",
array(':eid' => $event->eid));
$readinggroups = $readinggroup_query->fetchObject();
//watchdog('booking_debug', "<pre>Reading Group ID is :\n@info</pre>", array('@info' => print_r($readinggroups, true)));
$readinggroup_regex = '/^session' . $readinggroups->sid . '_role/';
//populate $defaults based on type of selection
foreach ($people as $person) {
switch ($selection) {
case 'notpaid':
if ($person->booking_status == 0) {
$defaults[] = $person->nid;
}
break;
case 'bookedin':
if ($person->booking_status == 1) {
$defaults[] = $person->nid;
}
break;
case 'waitinglist':
if ($person->booking_status == 2) {
$defaults[] = $person->nid;
}
break;
case 'refundreqd':
if ($person->booking_status == 3 && $person->booking_refund_processed == 'N') {
$defaults[] = $person->nid;
}
break;
case 'unpaid':
if ($person->booking_payment_complete == 'N' && $person->booking_status == 1) {
$defaults[] = $person->nid;
}
break;
case 'notravelform':
if ($person->booking_status == 1 && $person->tid == 0) {
$defaults[] = $person->nid;
}
break;
case 'notravelforminclwaiting':
if (($person->booking_status == 1 || $person->booking_status == 2) && $person->tid == 0) {
$defaults[] = $person->nid;
}
break;
case 'leaderhelper':
foreach ($person as $key => $value) {
if (preg_match('/^session(\d+)_role/', $key, $matches) && $value > 0) {
//don't add the person multiple times if they're leading/helping multiple groups
if (! in_array($person->nid, $defaults)) {
$defaults[] = $person->nid;
}
}
}
break;
case 'readinggroup-leader':
foreach ($person as $key => $value) {
if (preg_match($readinggroup_regex, $key, $matches) && $value == 1) {
//don't add the person multiple times if they're leading/helping multiple groups
if (! in_array($person->nid, $defaults)) {
$defaults[] = $person->nid;
}
}
}
break;
} //end switch
} //loop attendees
//create new hidden form element to return
$replacementform_data['booking-email-default-ids'] = array (
'#type' => 'hidden',
'#value' => drupal_json_encode($defaults), //encode the data as json so we can process it with jQuery
'#prefix' => '<div id="booking_email_default_ids_wrapper">',
'#suffix' => '</div>',
'#attributes' => array('id' => 'booking_email_default_ids'),
);
$output_html = render($replacementform_data['booking-email-default-ids']);
$feedback_html = t("<div id=\"booking_email_preselection_suffix_wrapper\">Number of people selected: <b>!num</b></div>",
array('!num' => count($defaults)));
//watchdog('booking_debug', "<pre>Manual Email ajax html\n@info</pre>", array('@info' => print_r( $output_html, true)));
//return a sequence of commands to run
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace("#booking_email_default_ids_wrapper", $output_html),
ajax_command_replace("#booking_email_preselection_suffix_wrapper", $feedback_html),
// This will call the command bookingEmailIDs in our custom JS file.
array('command' => 'bookingAjaxCheckboxes',
'formDataElement' => 'booking_email_default_ids', //name of the hidden form element that contains the json data
'formName' => 'booking-manual-email-form', //note the dashes instead of underscores!
'checkboxName' => 'table', //form element for tableselect
),
)
);
}
/**
* Function to handle sending the manual emails
*/
function booking_manual_email_form_submit($form, &$form_state) {
$counter = 0;
$message = "";
$attachments = array();
$update_messages = array();
$checkboxes = $form_state['values']['table']; //$values['booking_price_active'];
//watchdog('booking', 'Formstate when setting buttons: @info', array ('@info' => var_export($form_state['values'], TRUE)));
//watchdog('booking', 'Checkboxes when setting buttons: @info', array ('@info' => var_export($checkboxes, TRUE)));
// Add attachments if present
if (isset($form_state['values']['booking-email-attachment-1']) && $form_state['values']['booking-email-attachment-1'] != 0) {
$attachments[] = file_load($form_state['values']['booking-email-attachment-1']);
watchdog('booking_debug', 'File attachment 1 detected: @info', array ('@info' => print_r($attachments, TRUE)));
// NOTE: Since we do nothing to save this file, it should get cleaned up by cron
// As per https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#managed_file
}
if (isset($form_state['values']['booking-email-attachment-2']) && $form_state['values']['booking-email-attachment-2'] != 0) {
$attachments[] = file_load($form_state['values']['booking-email-attachment-2']);
watchdog('booking_debug', 'File attachment 2 detected: @info', array ('@info' => print_r($attachments, TRUE)));
}
foreach($checkboxes as $key => $value) {
//do a sanity check on the key => value pair from the form submission
if (is_numeric($key) && $value != 0) {
//check the person exists in the database
$person = db_query("SELECT person.nid " .
"FROM {booking_person} person " .
"WHERE nid = :nid",
array(':nid' => $key))
->fetchObject();
if ($person) {
if ($form_state['values']['email-type'] == 'registration') {
$message = t('Processing a manual registration email to id @info', array ('@info' => $key));
_booking_registration_email($key, false, true);
}
elseif ($form_state['values']['email-type'] == 'initialtravelrequired') {
$message = t('Processing a manual initial travel form request email to id @info', array ('@info' => $key));
_booking_travelform_initial_request_email($key);
}
elseif ($form_state['values']['email-type'] == 'remindertravelrequired') {
$message = t('Processing a manual reminder travel form request email to id @info', array ('@info' => $key));
_booking_travelform_reminder_request_email($key);
}
elseif ($form_state['values']['email-type'] == 'balance') {
$message = t('Processing a manual outstanding balance email to id @info', array ('@info' => $key));
_booking_balance_payment_email($key);
}
elseif ($form_state['values']['email-type'] == 'complete') {
$message = t('Processing a manual registration complete email to id @info', array ('@info' => $key));
_booking_registration_email($key, true, true);
}
elseif ($form_state['values']['email-type'] == 'travelcomplete') {
$message = t('Processing a manual travelform complete email to id @info', array ('@info' => $key));
_booking_travelform_confirmation_email($key);
}
elseif ($form_state['values']['email-type'] == 'withdrawal') {
$message = t('Processing a manual withdrawal email to id @info', array ('@info' => $key));
_booking_demoted_to_notcoming_email($key);
}
elseif ($form_state['values']['email-type'] == 'missedpayment') {
$message = t('Processing a manual missedpayment email to id @info', array ('@info' => $key));
_booking_missedpayment_email($key);
}
elseif ($form_state['values']['email-type'] == 'waitinglistpromotion') {
$message = t('Processing a manual waitinglistpromotion email to id @info', array ('@info' => $key));
_booking_promoted_from_waitinglist_email($key);
}
elseif ($form_state['values']['email-type'] == 'waitinglistpromotionfullypaid') {
$message = t('Processing a manual waitinglistpromotionfullypaid email to id @info', array ('@info' => $key));
_booking_promoted_from_waitinglist_email($key);
}
elseif (strpos($form_state['values']['email-type'], 'customlogistics') !== false) {
$message = t('Processing a @custom type email from logistics to id @info', array ('@custom' => $form_state['values']['email-type'], '@info' => $key));
_booking_custom_email($key, $form_state['values']['email-type'], 'logistics', $attachment);
}
elseif (strpos($form_state['values']['email-type'], 'custom') !== false) {
$message = t('Processing a @custom type email to id @info', array ('@custom' => $form_state['values']['email-type'], '@info' => $key));
_booking_custom_email($key, $form_state['values']['email-type'], 'contact', $attachments);
}
//increase the counter of people we've emailed
$counter++;
//store info about the email
$update_messages[] = $message;
}
}
}
$final_message = "Sent manual email for $counter people of type " . $form_state['values']['email-type'];
drupal_set_message($final_message, 'status', FALSE);
watchdog('booking', "<pre>" . $final_message . "\n" . implode("\n", $update_messages) . "</pre>");
//watchdog('booking', "Sent manual email for $counter people.");
}