12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358 |
- <?php
- /**
- * @file
- * The Views Send module.
- *
- * Views Send allow mass mailing using Views.
- *
- * @ingroup views_send
- */
- /**
- * e-mail priorities.
- */
- define('VIEWS_SEND_PRIORITY_NONE', 0);
- define('VIEWS_SEND_PRIORITY_HIGHEST', 1);
- define('VIEWS_SEND_PRIORITY_HIGH', 2);
- define('VIEWS_SEND_PRIORITY_NORMAL', 3);
- define('VIEWS_SEND_PRIORITY_LOW', 4);
- define('VIEWS_SEND_PRIORITY_LOWEST', 5);
- /**
- * Capture PHP max_execution_time before drupal_cron_run().
- * Workaround for Drupal 6.14. See http://drupal.org/node/584334
- */
- define('VIEWS_SEND_MAX_EXECUTION_TIME', ini_get('max_execution_time'));
- /**
- * Token pattern.
- */
- define('VIEWS_SEND_TOKEN_PATTERN', 'views-send:%s');
- define('VIEWS_SEND_TOKEN_PREFIX', '[');
- define('VIEWS_SEND_TOKEN_POSTFIX', ']');
- /**
- * Detect if there is MIME support (thorough modules like Mime Mail or Mandrill).
- */
- define('VIEWS_SEND_MIMEMAIL', module_exists('mimemail') || module_exists('mandrill'));
- /**
- * Sets the mailsystem for Views Send (if not already set).
- */
- function _views_send_mailsystem_set($key) {
- $mailsystem = mailsystem_get();
- $mailsystem_key = "views_send_$key";
- if (empty($mailsystem[$mailsystem_key])) {
- mailsystem_set(array(
- $mailsystem_key => $mailsystem['default-system']
- ));
- }
- }
- /**
- * Gets the selector field if it exists on the passed-in view.
- *
- * @return
- * The field object if found. Otherwise, FALSE.
- */
- function _views_send_get_field_selector($view) {
- foreach ($view->field as $field_name => $field) {
- if ($field instanceof views_send_handler_field_selector) {
- // Add in the view object for convenience.
- $field->view = $view;
- return $field;
- }
- }
- return FALSE;
- }
- /**
- * Gets the field value from a result row in a view - rendered value (default),
- * plain text or array with mail addresses.
- *
- * @return
- * See description.
- */
- function _views_send_get_field_value_from_views_row($view, $row_id, $field_id, $type='') {
- if (strpos($field_id, 'custom_text') === 0) {
- // Handle the special case for custom text fields.
- $field_id = str_replace('custom_text', 'nothing', $field_id);
- }
- $rendered_field = $view->style_plugin->get_field($row_id, $field_id);
- if ($type == 'plain_text') {
- // Removing HTML tags. Used for names in headers, not body.
- $result = strip_tags($rendered_field);
- }
- elseif ($type == 'mail') {
- // Removing HTML tags and entities. Used for e-mail addresses in headers, not body.
- $result = explode(',', decode_entities(strip_tags($rendered_field)));
- $result = array_map('trim', $result);
- }
- else {
- $result = $rendered_field;
- }
- return $result;
- }
- /**
- * Implements hook_views_form_substitutions().
- */
- function views_send_views_form_substitutions() {
- // Views check_plains the column label, so do the same here in order for the
- // replace operation to succeed.
- $select_all_placeholder = check_plain('<!--views-send-select-all-->');
- $select_all = array(
- '#type' => 'checkbox',
- '#default_value' => FALSE,
- '#attributes' => array('class' => array('views-send-table-select-all')),
- );
- return array(
- $select_all_placeholder => drupal_render($select_all),
- );
- }
- /**
- * Returns the 'select all' div that gets inserted above the view results
- * for non-table style plugins.
- *
- * The actual insertion is done by JS, matching the degradation behavior
- * of Drupal core (no JS - no select all).
- */
- function theme_views_send_select_all($variables) {
- $form = array();
- $form['select_all'] = array(
- '#type' => 'fieldset',
- '#attributes' => array('class' => array('views-send-fieldset-select-all')),
- );
- $form['select_all']['this_page'] = array(
- '#type' => 'checkbox',
- '#title' => t('Select all items on this page'),
- '#default_value' => '',
- '#attributes' => array('class' => array('views-send-select-this-page')),
- );
- $output = '<div class="views-send-select-all-markup">';
- $output .= drupal_render($form);
- $output .= '</div>';
- return $output;
- }
- /**
- * Implements hook_form_alter().
- */
- function views_send_form_alter(&$form, &$form_state, $form_id) {
- if (strpos($form_id, 'views_form_') === 0) {
- $field = _views_send_get_field_selector($form_state['build_info']['args'][0]);
- }
- // This form isn't used by Views Send.
- if (empty($field)) {
- return;
- }
- // Allow Views Send to work when embedded using views_embed_view(), or in a block.
- if (empty($field->view->override_path)) {
- if (!empty($field->view->preview) || $field->view->display_handler instanceof views_plugin_display_block) {
- $field->view->override_path = $_GET['q'];
- }
- }
- $query = drupal_get_query_parameters($_GET, array('q'));
- $form['#action'] = url($field->view->get_url(), array('query' => $query));
- // Cache the built form to prevent it from being rebuilt prior to validation
- // and submission, which could lead to data being processed incorrectly,
- // because the views rows (and thus, the form elements as well) have changed
- // in the meantime. Matching views issue: http://drupal.org/node/1473276.
- $form_state['cache'] = TRUE;
- // Add the custom CSS for all steps of the form.
- $form['#attached']['css'][] = drupal_get_path('module', 'views_send') . '/views_send.css';
- if ($form_state['step'] == 'views_form_views_form') {
- $form['actions']['submit']['#value'] = t('Send e-mail');
- $form['actions']['submit']['#submit'] = array('views_send_form_submit');
- if (isset($form['#prefix']) && ($form['#prefix'] == '<div class="vbo-views-form">')) {
- $form['#prefix'] = '<div class="vbo-views-form views-send-selection-form">';
- }
- else {
- $form['#prefix'] = '<div class="views-send-selection-form">';
- }
- $form['#suffix'] = '</div>';
- // Add the custom JS for this step of the form.
- $form['#attached']['js'][] = drupal_get_path('module', 'views_send') . '/views_send.js';
- // Adds the "select all" functionality for non-table style plugins
- // if the view has results.
- if (!empty($field->view->result) && !($field->view->style_plugin instanceof views_plugin_style_table)) {
- $form['select_all_markup'] = array(
- '#type' => 'markup',
- '#markup' => theme('views_send_select_all'),
- );
- }
- }
- }
- /**
- * Multistep form callback for the "configure" step.
- *
- @TODO: Hide "Sender" (from) if Mandrill is used.
- */
- function views_send_config_form($form, &$form_state, $view, $output) {
- if (!empty($form_state['configuration'])) {
- // Values entered in the "config" step.
- $config = $form_state['configuration'];
- }
- $display = $view->name . ':' . $view->current_display;
- $form['display'] = array(
- '#type' => 'value',
- '#value' => $display,
- );
- $form['from'] = array(
- '#type' => 'fieldset',
- '#title' => t('Sender'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
- $form['from']['views_send_from_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Sender\'s name'),
- '#description' => t("Enter the sender's human readable name."),
- '#default_value' => isset($config['views_send_from_name']) ? $config['views_send_from_name'] : variable_get('views_send_from_name_' . $display, variable_get('site_name', '')),
- '#maxlen' => 255,
- );
- $form['from']['views_send_from_mail'] = array(
- '#type' => 'textfield',
- '#title' => t('Sender\'s e-mail'),
- '#description' => t("Enter the sender's e-mail address."),
- '#required' => TRUE,
- '#default_value' => isset($config['views_send_from_mail']) ? $config['views_send_from_mail'] : variable_get('views_send_from_mail_' . $display, variable_get('site_mail', ini_get('sendmail_from'))),
- '#maxlen' => 255,
- );
- $fields = _views_send_get_fields_and_tokens($view, 'fields');
- $tokens = _views_send_get_fields_and_tokens($view, 'tokens');
- $fields_name_text = _views_send_get_fields_and_tokens($view, 'fields_name_text');
- $fields_options = array_merge(array('' => '<' . t('select') . '>'), $fields);
- $form['views_send_tokens'] = array(
- '#type' => 'value',
- '#value' => $tokens,
- );
- $form['to'] = array(
- '#type' => 'fieldset',
- '#title' => t('Recipients'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
- $form['to']['views_send_to_name'] = array(
- '#type' => 'select',
- '#title' => t('Field used for recipient\'s name'),
- '#description' => t('Select which field from the current view will be used as recipient\'s name.'),
- '#options' => $fields_options,
- '#default_value' => isset($config['views_send_to_name']) ? $config['views_send_to_name'] : variable_get('views_send_to_name_' . $display, ''),
- );
- $form['to']['views_send_to_mail'] = array(
- '#type' => 'select',
- '#title' => t('Field used for recipient\'s e-mail'),
- '#description' => t('Select which field from the current view will be used as recipient\'s e-mail.'),
- '#options' => $fields_options,
- '#default_value' => isset($config['views_send_to_mail']) ? $config['views_send_to_mail'] : variable_get('views_send_to_mail_' . $display, ''),
- '#required' => TRUE,
- );
- $form['mail'] = array(
- '#type' => 'fieldset',
- '#title' => t('E-mail content'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
- $form['mail']['views_send_subject'] = array(
- '#type' => 'textfield',
- '#title' => t('Subject'),
- '#description' => t('Enter the e-mail\'s subject. You can use tokens in the subject.'),
- '#maxlen' => 255,
- '#required' => TRUE,
- '#default_value' => isset($config['views_send_subject']) ? $config['views_send_subject'] : variable_get('views_send_subject_' . $display, ''),
- );
- $form['mail']['views_send_message'] = array(
- '#type' => 'text_format',
- '#title' => t('Message'),
- '#description' => t('Enter the body of the message. You can use tokens in the message.'),
- '#required' => TRUE,
- '#rows' => 10,
- );
- if (isset($config['views_send_message']['value'])) {
- $form['mail']['views_send_message'] += array(
- '#format' => $config['views_send_message']['format'],
- '#default_value' => $config['views_send_message']['value'],
- );
- }
- else {
- $saved_message = variable_get('views_send_message_' . $display);
- $form['mail']['views_send_message'] += array(
- '#format' => isset($saved_message['format']) ? $saved_message['format'] : filter_fallback_format(),
- '#default_value' => isset($saved_message['value']) ? $saved_message['value'] : '',
- );
- }
- $form['mail']['token'] = array(
- '#type' => 'fieldset',
- '#title' => t('Tokens'),
- '#description' => t('You can use the following tokens in the subject or message.'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
- if (!module_exists('token')) {
- $form['mail']['token']['tokens'] = array(
- '#markup' => theme('views_send_token_help', $fields_name_text)
- );
- }
- else {
- $form['mail']['token']['views_send'] = array(
- '#type' => 'fieldset',
- '#title' => t('Views Send specific tokens'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
- $form['mail']['token']['views_send']['tokens'] = array(
- '#markup' => theme('views_send_token_help', $fields_name_text)
- );
- $form['mail']['token']['general'] = array(
- '#type' => 'fieldset',
- '#title' => t('General tokens'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
- $token_types = array('site', 'user', 'node', 'current-date');
- $form['mail']['token']['general']['tokens'] = array(
- '#markup' => theme('token_tree', array('token_types' => $token_types))
- );
- }
- if (VIEWS_SEND_MIMEMAIL && user_access('attachments with views_send')) {
- // set the form encoding type
- $form['#attributes']['enctype'] = "multipart/form-data";
- // add a file upload file
- $form['mail']['views_send_attachments'] = array(
- '#type' => 'file',
- '#title' => t('Attachment'),
- '#description' => t('NB! The attached file is stored once per recipient in the database if you aren\'t sending the message directly.'),
- );
- }
- $form['additional'] = array(
- '#type' => 'fieldset',
- '#title' => t('Additional e-mail options'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
- $form['additional']['views_send_priority'] = array(
- '#type' => 'select',
- '#title' => t('Priority'),
- '#options' => array(
- VIEWS_SEND_PRIORITY_NONE => t('none'),
- VIEWS_SEND_PRIORITY_HIGHEST => t('highest'),
- VIEWS_SEND_PRIORITY_HIGH => t('high'),
- VIEWS_SEND_PRIORITY_NORMAL => t('normal'),
- VIEWS_SEND_PRIORITY_LOW => t('low'),
- VIEWS_SEND_PRIORITY_LOWEST => t('lowest')
- ),
- '#description' => t('Note that e-mail priority is ignored by a lot of e-mail programs.'),
- '#default_value' => isset($config['views_send_priority']) ? $config['views_send_priority'] : variable_get('views_send_priority_' . $display, 0),
- );
- $form['additional']['views_send_receipt'] = array(
- '#type' => 'checkbox',
- '#title' => t('Request receipt'),
- '#default_value' => isset($config['views_send_receipt']) ? $config['views_send_receipt'] : variable_get('views_send_receipt_' . $display, 0),
- '#description' => t('Request a Read Receipt from your e-mails. A lot of e-mail programs ignore these so it is not a definitive indication of how many people have read your message.'),
- );
- $form['additional']['views_send_headers'] = array(
- '#type' => 'textarea',
- '#title' => t('Additional headers'),
- '#description' => t("Additional headers to be send with the message. You'll have to enter one per line. Example:<pre>Reply-To: noreply@example.com\nX-MyCustomHeader: Whatever</pre>"),
- '#rows' => 4,
- '#default_value' => isset($config['views_send_headers']) ? $config['views_send_headers'] : variable_get('views_send_headers_' . $display, ''),
- );
- $form['views_send_direct'] = array(
- '#type' => 'checkbox',
- '#title' => t('Send the message directly using the Batch API.'),
- '#default_value' => isset($config['views_send_direct']) ? $config['views_send_direct'] : variable_get('views_send_direct_'. $display, TRUE),
- );
- $form['views_send_carbon_copy'] = array(
- '#type' => 'checkbox',
- '#title' => t('Send a copy of the message to the sender.'),
- '#default_value' => isset($config['views_send_carbon_copy']) ? $config['views_send_carbon_copy'] : variable_get('views_send_carbon_copy_' . $display, TRUE),
- );
- $form['views_send_remember'] = array(
- '#type' => 'checkbox',
- '#title' => t('Remember these values for the next time a mass mail is sent. (The values are not stored per user.)'),
- '#default_value' => variable_get('views_send_remember_' . $display, FALSE),
- );
- $query = drupal_get_query_parameters($_GET, array('q'));
- $form['actions'] = array(
- '#type' => 'container',
- '#attributes' => array('class' => array('form-actions')),
- '#weight' => 999,
- );
- $form['actions']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Next'),
- '#validate' => array('views_send_config_form_validate'),
- '#submit' => array('views_send_form_submit'),
- '#suffix' => l(t('Cancel'), $view->get_url(), array('query' => $query)),
- );
- return $form;
- }
- /**
- * Validation callback for the "configure" step.
- */
- function views_send_config_form_validate($form, &$form_state) {
- $values =& $form_state['values'];
- $view = $form_state['build_info']['args'][0];
- $formats = filter_formats();
- if (!filter_access($formats[$values['views_send_message']['format']])) {
- form_set_error('views_send_message', t('Illegale format selected'));
- }
- // Check if sender's e-mail is a valid one.
- if (!valid_email_address(trim($values['views_send_from_mail']))) {
- form_set_error('views_send_from_mail',
- t('The sender\'s e-mail is not a valid e-mail address: %mail',
- array('%mail' => $values['views_send_from_mail'])
- )
- );
- }
- // Check in the column selected as e-mail contain valid e-mail values.
- if (!empty($values['views_send_to_mail'])) {
- $wrong_addresses = array();
- $to_mail_field = $values['views_send_tokens'][$values['views_send_to_mail']];
- foreach ($form_state['selection'] as $row_id) {
- $mail_addresses = _views_send_get_field_value_from_views_row($view, $row_id, $to_mail_field, 'mail');
- foreach ($mail_addresses as $mail_address) {
- if (!valid_email_address($mail_address)) {
- $wrong_addresses[$row_id] = $mail_address;
- break;
- }
- }
- }
- if (count($wrong_addresses) > 0) {
- if (count($wrong_addresses) == count($form_state['selection'])) {
- $error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in all selected rows. Maybe choose another field to act as recipient's e-mail?");
- }
- else {
- $error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in @wrong of @total selected rows. Choose another field to act as recipient's e-mail or return to the view and narrow the selection to a subset containing only valid addresses. Bad addresses:",
- array('@wrong' => count($wrong_addresses), '@total' => count($form_state['selection']))
- );
- $error_message .= sprintf('<table><tr><th>%s</th><th>%s</th></tr>',
- t('Row'), t('E-mail address'));
- foreach ($wrong_addresses as $rowid => $wrong_address) {
- $error_message .= sprintf('<tr><td>%s</td><td>%s</td></tr>',
- $rowid, check_plain($wrong_address));
- }
- $error_message .= '</table>';
- }
- form_set_error('views_send_to_mail', $error_message);
- }
- }
- }
- /**
- * Multistep form callback for the "confirm" step.
- * Allows the user to preview the whole message before sending it.
- */
- function views_send_confirm_form($form, &$form_state, $view, $output) {
- drupal_set_title(t('Review and confirm the message that is about to be sent'));
- // Values entered in the "config" step.
- $configuration = $form_state['configuration'];
- if (!VIEWS_SEND_MIMEMAIL && ($configuration['views_send_message']['format'] != 'plain_text')) {
- drupal_set_message(
- t("Only plain text is supported in the message. Any HTML will be converted to text. If you want to format the message with HTML, you'll have to install and enable the !mimemail or !mandrill module.",
- array(
- '!mimemail' => '<a href="http://drupal.org/project/mimemail">Mime Mail</a>',
- '!mandrill' => '<a href="http://drupal.org/project/mandrill">Mandrill</a>'
- )
- )
- );
- }
- // From: parts.
- $from_mail = trim($configuration['views_send_from_mail']);
- $from_name = trim($configuration['views_send_from_name']);
- $form['#attributes']['class'] = array('views-send-preview');
- $form['from'] = array(
- '#type' => 'item',
- '#title' => t('From'),
- '#markup' => '<div class="views-send-preview-value">' .
- check_plain(_views_send_format_address($from_mail, $from_name, FALSE)) .
- '</div>',
- );
- // To: parts. (Mail is mandatory, name is optional.)
- $recipients = array();
- if (!empty($configuration['views_send_to_name'])) {
- $to_name_field = $configuration['views_send_tokens'][$configuration['views_send_to_name']];
- }
- else {
- $to_name_field = false;
- $to_name = '';
- }
- $to_mail_field = $configuration['views_send_tokens'][$configuration['views_send_to_mail']];
- foreach ($form_state['selection'] as $row_id) {
- if ($to_name_field) {
- $to_name = _views_send_get_field_value_from_views_row($view, $row_id, $to_name_field, 'plain_text');
- }
- $mail_addresses = _views_send_get_field_value_from_views_row($view, $row_id, $to_mail_field, 'mail');
- foreach ($mail_addresses as $mail_address) {
- $recipients[] = check_plain(_views_send_format_address($mail_address, $to_name, FALSE));
- }
- }
- $form['to'] = array(
- '#type' => 'item',
- '#title' => t('To'),
- '#markup' => '<div id="views-send-preview-to" class="views-send-preview-value">' . implode(', ', $recipients) . '</div>',
- );
- $form['subject'] = array(
- '#type' => 'item',
- '#title' => t('Subject'),
- '#markup' => '<div class="views-send-preview-value">' . check_plain($configuration['views_send_subject']) . '</div>',
- );
- $form['message'] = array(
- '#type' => 'item',
- '#title' => t('Message'),
- '#markup' => '<div id="views-send-preview-message" class="views-send-preview-value">' . check_markup($configuration['views_send_message']['value'], $configuration['views_send_message']['format']) . '</div>',
- );
- $headers = array();
- foreach (_views_send_headers($configuration['views_send_receipt'], $configuration['views_send_priority'], $configuration['views_send_from_mail'], $configuration['views_send_headers']) as $key => $value) {
- $headers[] = check_plain($key . ': ' . $value);
- }
- $form['headers'] = array(
- '#type' => 'item',
- '#title' => t('Headers'),
- '#markup' => '<div id="views-send-preview-headers" class="views-send-preview-value">' . implode('<br />', $headers) . '</div>',
- );
- if (VIEWS_SEND_MIMEMAIL && !empty($configuration['views_send_attachments']) && user_access('attachments with views_send')) {
- foreach ($configuration['views_send_attachments'] as $attachment) {
- $attachments[] = $attachment['filename'];
- }
- $form['attachments'] = array(
- '#type' => 'item',
- '#title' => t('Attachments'),
- '#markup' => '<div id="views-send-preview-attachments" class="views-send-preview-value">'. implode('<br />', $attachments) .'</div>',
- );
- }
- $query = drupal_get_query_parameters($_GET, array('q'));
- $form['actions'] = array(
- '#type' => 'container',
- '#attributes' => array('class' => array('form-actions')),
- '#weight' => 999,
- );
- $form['actions']['back'] = array(
- '#type' => 'submit',
- '#value' => t('Go back'),
- '#submit' => array('views_send_form_back_submit'),
- );
- $form['actions']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Send'),
- '#submit' => array('views_send_form_submit'),
- '#suffix' => l(t('Cancel'), $view->get_url(), array('query' => $query)),
- );
- return $form;
- }
- /**
- * Submit handler for all steps of the Views Send multistep form.
- */
- function views_send_form_submit($form, &$form_state) {
- $field = _views_send_get_field_selector($form_state['build_info']['args'][0]);
- switch ($form_state['step']) {
- case 'views_form_views_form':
- $field_name = $field->options['id'];
- $selection = array_filter($form_state['values'][$field_name]);
- $form_state['selection'] = array_keys($selection);
- $form_state['step'] = 'views_send_config_form';
- $form_state['rebuild'] = TRUE;
- break;
- case 'views_send_config_form':
- $display = $form['display']['#value'];
- foreach ($form_state['values'] as $key => $value) {
- $key = ($key == 'format') ? 'views_send_message_format' : $key;
- if (substr($key, 0, 11) == 'views_send_') {
- if ($form_state['values']['views_send_remember']) {
- variable_set($key . '_' . $display, $value);
- }
- else {
- variable_del($key . '_' . $display);
- }
- }
- }
- $form_state['configuration'] = $form_state['values'];
- // If a file was uploaded, process it.
- if (VIEWS_SEND_MIMEMAIL && user_access('attachments with views_send') && isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['views_send_attachments'])) {
- // attempt to save the uploaded file
- $dir = file_default_scheme() . '://views_send_attachments';
- file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
- $file_extensions = variable_get('views_send_attachment_valid_extensions', FALSE);
- if ($file_extensions) {
- $file_validators['file_validate_extensions'] = array();
- $file_validators['file_validate_extensions'][0] = $file_extensions;
- }
- else {
- $file_validators = array();
- }
- $file = file_save_upload('views_send_attachments', $file_validators, $dir);
- // set error if file was not uploaded
- if (!$file) {
- //form_set_error('views_send_attachment', 'Error uploading file.');
- }
- else {
- // set files to form_state, to process when form is submitted
- // @todo: when we add a multifile formfield then loop through to add each file to attachments array
- $form_state['configuration']['views_send_attachments'][] = (array)$file;
- }
- }
- $form_state['step'] = 'views_send_confirm_form';
- $form_state['rebuild'] = TRUE;
- break;
- case 'views_send_confirm_form':
- // Queue the email for sending.
- views_send_queue_mail($form_state['configuration'], $form_state['selection'], $field->view);
- // Redirect.
- $query = drupal_get_query_parameters($_GET, array('q'));
- $form_state['redirect'] = array($field->view->get_url(), array('query' => $query));
- break;
- }
- }
- /**
- * Submit handler that handles back buttons.
- */
- function views_send_form_back_submit($form, &$form_state) {
- switch ($form_state['step']) {
- case 'views_send_confirm_form':
- $form_state['step'] = 'views_send_config_form';
- $form_state['rebuild'] = TRUE;
- break;
- }
- }
- /**
- * Assembles the email and queues it for sending.
- *
- * @param $params
- * Data entered in the "config" step of the form.
- * @param $selected_rows
- * An array with the indexes of the selected views rows.
- * @param $view
- * The actual view object.
- */
- function views_send_queue_mail($params, $selected_rows, $view) {
- global $user;
- if (!user_access('mass mailing with views_send')) {
- drupal_set_message(
- t('No mails sent since you aren\'t allowed to send mass mail with Views. (<a href="@permurl">Edit the permission.</a>)',
- array('@permurl' => url('admin/people/permissions', array('fragment' => 'module-views_send')))),
- 'error'
- );
- return;
- }
- $formats = filter_formats();
- // From: parts.
- $from_mail = trim($params['views_send_from_mail']);
- $from_name = $params['views_send_from_name'];
- // To: parts. (Mail is mandatory, name is optional.)
- $to_mail_key = $params['views_send_tokens'][$params['views_send_to_mail']];
- if (!empty($params['views_send_to_name'])) {
- $to_name_key = $params['views_send_tokens'][$params['views_send_to_name']];
- }
- else {
- $to_name_key = false;
- $to_name = '';
- }
- foreach ($selected_rows as $selected_rows_key => $row_id) {
- // To: parts.
- $to_mail = implode(',', _views_send_get_field_value_from_views_row($view, $row_id, $to_mail_key, 'mail'));
- if ($to_name_key) {
- $to_name = _views_send_get_field_value_from_views_row($view, $row_id, $to_name_key, 'plain_text');
- }
- $subject = $params['views_send_subject'];
- $body = $params['views_send_message']['value'];
- $params['format'] = $params['views_send_message']['format'];
- // This shouldn't happen, but better be 100% sure.
- if (!filter_access($formats[$params['format']])) {
- drupal_set_message(t('No mails sent since an illegale format is selected for the message.'));
- return;
- }
- $body = check_markup($body, $params['format']);
- // Populate row/context tokens.
- $token_keys = $token_values = array();
- foreach ($params['views_send_tokens'] as $field_key => $field_name) {
- $token_keys[] = VIEWS_SEND_TOKEN_PREFIX . sprintf(VIEWS_SEND_TOKEN_PATTERN, $field_name) . VIEWS_SEND_TOKEN_POSTFIX;
- $token_values[] = _views_send_get_field_value_from_views_row($view, $row_id, $field_name);
- }
- // Views Send specific token replacements
- $subject = str_replace($token_keys, $token_values, $subject);
- $body = str_replace($token_keys, $token_values, $body);
- // Global token replacement, and node/user token replacements
- // if a nid/uid is found in the views result row.
- $data = array();
- if (property_exists($view->result[$row_id], 'uid')) {
- $data['user'] = user_load($view->result[$row_id]->uid);
- }
- if (property_exists($view->result[$row_id], 'nid')) {
- $data['node'] = node_load($view->result[$row_id]->nid);
- }
- $subject = token_replace($subject, $data);
- $body = token_replace($body, $data);
- if (!VIEWS_SEND_MIMEMAIL || (variable_get('mimemail_format', 'plain_text') == 'plain_text')) {
- $body = drupal_html_to_text($body);
- }
- if ($params['format'] == 'plain_text') {
- $plain_format = TRUE;
- }
- else {
- $plain_format = FALSE;
- }
- // We transform receipt, priority in headers,
- // merging them to the user defined headers.
- $headers = _views_send_headers($params['views_send_receipt'], $params['views_send_priority'], $from_mail, $params['views_send_headers']);
- $attachments = isset($params['views_send_attachments']) ? $params['views_send_attachments'] : array();
- $message = array(
- 'uid' => $user->uid,
- 'timestamp' => time(),
- 'from_name' => trim($from_name),
- 'from_mail' => trim($from_mail),
- 'to_name' => trim($to_name),
- 'to_mail' => trim($to_mail),
- 'subject' => strip_tags($subject),
- 'body' => $body,
- 'headers' => $headers,
- );
- // Enable other modules to alter the actual message before queueing it
- // by providing the hook 'views_send_mail_alter'.
- drupal_alter('views_send_mail', $message);
- if ($params['views_send_direct']) {
- $operations[] = array('views_send_batch_deliver', array($message, $plain_format, $attachments));
- }
- else {
- _views_send_prepare_mail($message, $plain_format, $attachments);
- // Only queue the message if it hasn't been cancelled by another module.
- if ($message['send']) {
- unset($message['send']);
- db_insert('views_send_spool')->fields($message)->execute();
- if (module_exists('rules')) {
- rules_invoke_event('views_send_email_added_to_spool', $message);
- }
- // Enabled other modules to act just after a message is queued
- // by providing the hook 'views_send_mail_queued'.
- module_invoke_all('views_send_mail_queued', $message, $view, $row_id);
- }
- else {
- unset($selected_rows[$selected_rows_key]);
- }
- }
- }
- if ($params['views_send_direct']) {
- if ($params['views_send_carbon_copy']) {
- $message['to_name'] = $from_name;
- $message['to_mail'] = $from_mail;
- $operations[] = array('views_send_batch_deliver', array($message, $plain_format, $attachments));
- }
- $batch = array(
- 'operations' => $operations,
- 'finished' => 'views_send_batch_deliver_finished',
- 'progress_message' => t('Sent @current of @total messages.'),
- );
- batch_set($batch);
- drupal_set_message(
- format_plural(count($selected_rows), '1 message processed.', '@count messages processed.')
- );
- }
- else {
- if ($params['views_send_carbon_copy']) {
- $message['to_name'] = $from_name;
- $message['to_mail'] = $from_mail;
- db_insert('views_send_spool')->fields($message)->execute();
- }
- drupal_set_message(
- format_plural(count($selected_rows), '1 message added to the spool.', '@count messages added to the spool.')
- );
- if (module_exists('rules')) {
- rules_invoke_event('views_send_all_email_added_to_spool', count($selected_rows));
- }
- }
- }
- // === Hook implementations ====================================================
- /**
- * Implements hook_menu().
- */
- function views_send_menu() {
- $items = array();
- $items['admin/config/system/views_send'] = array(
- 'type' => MENU_NORMAL_ITEM,
- 'title' => 'Views Send',
- 'description' => 'Configure Views Send general options.',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('views_send_settings'),
- 'access arguments' => array('administer views_send'),
- 'file' => 'views_send.admin.inc',
- );
- return $items;
- }
- /**
- * Implements hook_permission().
- */
- function views_send_permission() {
- $perms = array(
- 'administer views_send' => array(
- 'title' => t('Administer mass mail with Views'),
- 'description' => t('Configure sending of e-mails to a list created with Views.'),
- ),
- 'mass mailing with views_send' => array(
- 'title' => t('Send mass mail with Views'),
- 'description' => t('Send e-mails to a list created with Views.'),
- ),
- );
- if (VIEWS_SEND_MIMEMAIL) {
- $perms['attachments with views_send'] = array(
- 'title' => t('Use attachments with Views Send'),
- 'description' => t('Attach files to e-mails sent with Views Send.'),
- );
- }
- return $perms;
- }
- /**
- * Implements hook_theme().
- */
- function views_send_theme($existing, $type, $theme, $path) {
- return array(
- 'views_send_select_all' => array(
- 'variables' => array(),
- ),
- 'views_send_token_help' => array(
- 'arguments' => array('tokens' => array()),
- ),
- );
- }
- /**
- * Implements hook_views_api().
- */
- function views_send_views_api() {
- return array(
- 'api' => 3,
- 'path' => drupal_get_path('module', 'views_send') . '/views',
- );
- }
- /**
- * Implements hook_cron().
- */
- function views_send_cron() {
- // Load cron functions.
- module_load_include('cron.inc', 'views_send');
- // Send pending messages from spool.
- views_send_send_from_spool();
- // Clear successful sent messages.
- views_send_clear_spool();
- }
- /**
- * Implements hook_mail().
- */
- function views_send_mail($key, &$message, $params) {
- // This is a simple message send. User inputs the content directly.
- if ($key == 'direct') {
- // Set the subject.
- $message['subject'] = $params['subject'];
- // Set the body.
- $message['body'][] = $params['body'];
- // Add additional headers.
- $message['headers'] += $params['headers'];
- }
- // TODO: Implement node message parsing.
- elseif ($key == 'node') {
- // Translations, theming, etc...
- }
- }
- // === Helper functions ========================================================
- /**
- * Build header array with priority and receipt confirmation settings.
- *
- * @param $receipt
- * Boolean: If a receipt is requested.
- * @param $priority
- * Integer: The message priority.
- * @param $from
- * String: The sender's e-mail address.
- *
- * @return Header array with priority and receipt confirmation info
- */
- function _views_send_headers($receipt, $priority, $from, $additional_headers) {
- $headers = array();
- // If receipt is requested, add headers.
- if ($receipt) {
- $headers['Disposition-Notification-To'] = $from;
- $headers['X-Confirm-Reading-To'] = $from;
- }
- // Add priority if set.
- switch ($priority) {
- case VIEWS_SEND_PRIORITY_HIGHEST:
- $headers['Priority'] = 'High';
- $headers['X-Priority'] = '1';
- $headers['X-MSMail-Priority'] = 'Highest';
- break;
- case VIEWS_SEND_PRIORITY_HIGH:
- $headers['Priority'] = 'urgent';
- $headers['X-Priority'] = '2';
- $headers['X-MSMail-Priority'] = 'High';
- break;
- case VIEWS_SEND_PRIORITY_NORMAL:
- $headers['Priority'] = 'normal';
- $headers['X-Priority'] = '3';
- $headers['X-MSMail-Priority'] = 'Normal';
- break;
- case VIEWS_SEND_PRIORITY_LOW:
- $headers['Priority'] = 'non-urgent';
- $headers['X-Priority'] = '4';
- $headers['X-MSMail-Priority'] = 'Low';
- break;
- case VIEWS_SEND_PRIORITY_LOWEST:
- $headers['Priority'] = 'non-urgent';
- $headers['X-Priority'] = '5';
- $headers['X-MSMail-Priority'] = 'Lowest';
- break;
- }
- // Add general headers.
- $headers['Precedence'] = 'bulk';
- // Add additional headers.
- $additional_headers = trim($additional_headers);
- $additional_headers = str_replace("\r", "\n", $additional_headers);
- $additional_headers = explode("\n", $additional_headers);
- foreach ($additional_headers as $header) {
- $header = trim($header);
- if (!empty($header)) {
- list($key, $value) = explode(': ', $header, 2);
- $headers[$key] = trim($value);
- }
- }
- return $headers;
- }
- /**
- * Build a formatted e-mail address.
- */
- function _views_send_format_address($mail, $name, $encode = TRUE) {
- // Do not format addres on Windows based PHP systems or when $name is empty.
- if ((substr(PHP_OS, 0, 3) == 'WIN') || empty($name)) {
- return $mail;
- }
- else {
- $name = ($encode ? _views_send_mime_header_encode($name) : $name);
- return sprintf('"%s" <%s>', $name, $mail);
- }
- }
- /**
- * Returns a mime-encoded string for strings that contain UTF-8.
- *
- * Simplified and correct version of mime_header_decode.
- */
- function _views_send_mime_header_encode($string) {
- if (preg_match('/[^\x20-\x7E]/', $string)) {
- $string = '=?UTF-8?B?' . base64_encode($string) . '?=';
- }
- return $string;
- }
- /**
- * Prepare the mail message before sending or spooling.
- *
- * @param array $message
- * which contains the following keys:
- * from_name
- * String holding the Sender's name.
- * from_mail
- * String holding the Sender's e-mail.
- * to_name
- * String holding the Recipient's name.
- * to_mail
- * String holding the Recipient's e-mail.
- * subject
- * String with the e-mail subject. This argument can be altered here.
- * body
- * Text with the e-mail body. This argument can be altered here.
- * headers
- * Associative array with e-mail headers. This argument can be altered here.
- * @param boolean $plain_format
- * Whether the e-mail should be sent in plain format.
- * @param array $attachments
- * An array with file information objects (as returned by file_save_upload).
- */
- function _views_send_prepare_mail(&$message, $plain_format=TRUE, $attachments=array()) {
- // Extract all variables/keys from the message.
- extract($message);
- /**
- * TODO: In the future, this module will be able to send an existing node.
- * $key will have to make the difference. A value when we pickup a node, other
- * when user inputs the subject & body of the message.
- */
- $key = 'direct';
- // Build message parameters.
- $params = array();
- $params['from_name'] = $from_name;
- $params['from_mail'] = $from_mail;
- $params['from_formatted'] = _views_send_format_address($from_mail, $from_name);
- $params['to_name'] = $to_name;
- $params['to_mail'] = $to_mail;
- $to_mail_formatted = array();
- foreach (explode(',', $to_mail) as $addr) {
- $to_mail_formatted[] = _views_send_format_address($addr, $to_name);
- }
- $params['to_formatted'] = implode(', ', $to_mail_formatted);
- $params['subject'] = $subject;
- $params['body'] = $body;
- $params['headers'] = $headers;
- if (VIEWS_SEND_MIMEMAIL) {
- _views_send_mailsystem_set($key);
- $params['attachments'] = $attachments;
- if ($plain_format) {
- $params['plain'] = TRUE;
- }
- }
- // Call Drupal standard mail function, but without sending.
- $mail = drupal_mail('views_send', $key, $params['to_formatted'], language_default(), $params, $params['from_formatted'], FALSE);
- // Add additional Mime Mail post processing.
- if (VIEWS_SEND_MIMEMAIL) {
- // We want to spool the Subject decoded.
- $mail['subject'] = mime_header_decode($mail['subject']);
- }
- // Updating message with data from generated mail
- $message['to_mail'] = $mail['to'];
- $message['from_mail'] = $mail['from'];
- $message['subject'] = $mail['subject'];
- $message['body'] = $mail['body'];
- $message['send'] = $mail['send'];
- $message['headers'] = serialize($mail['headers']);
- }
- /**
- * Sending a prepared message.
- *
- * @return
- * Boolean indicating if the message was sent successfully.
- */
- function views_send_deliver($message) {
- if (is_array($message)) {
- $message = (object) $message;
- }
- $key = 'direct';
- $headers = unserialize($message->headers);
- $mail = array(
- 'id' => 'views_send_' . $key,
- 'module' => 'views_send',
- 'key' => $key,
- 'to' => $message->to_mail,
- 'from' => $message->from_mail,
- 'subject' => $message->subject,
- 'body' => $message->body,
- 'headers' => $headers,
- );
- if (VIEWS_SEND_MIMEMAIL) {
- _views_send_mailsystem_set($key);
- }
- // Mime encode the subject before passing to the mail function
- // to work around a bug in Drupal's mime_header_encode.
- $mail['subject'] = _views_send_mime_header_encode($message->subject);
-
- $system = drupal_mail_system('views_send', $key);
- return $system->mail($mail);
- }
- /**
- * Preparing and sending a message (coming from a batch job).
- */
- function views_send_batch_deliver($message, $plain_format, $attachments, &$context) {
- _views_send_prepare_mail($message, $plain_format, $attachments);
- if (!$message['send']) {
- $context['results'][] = t('Skipping sending message to %mail.',
- array('%mail' => $message['to_mail']));
- return;
- }
- else {
- unset($message['send']);
- }
-
- $status = views_send_deliver($message);
- if ($status) {
- if (variable_get('views_send_debug', FALSE)) {
- watchdog('views_send', 'Message sent to %mail.', array('%mail' => $message['to_mail']));
- }
- if (module_exists('rules')) {
- rules_invoke_event('views_send_email_sent', $message);
- }
- }
- else {
- $context['results'][] = t('Failed sending message to %mail - spooling it.',
- array('%mail' => $message['to_mail']));
- // Queue the message to the spool table.
- db_insert('views_send_spool')->fields($message)->execute();
- if (module_exists('rules')) {
- rules_invoke_event('views_send_email_added_to_spool', $message);
- }
- }
- }
- /**
- * Displays status after sending messages as a batch job.
- */
- function views_send_batch_deliver_finished($success, $results, $operations) {
- if ($success) {
- foreach ($results as $result) {
- drupal_set_message($result);
- }
- }
- }
- // === Theming functions =======================================================
- /**
- * Theme the replacement tokens.
- *
- * @param $tokens:
- * Keyed array with tokens as keys and description as values.
- *
- * @return
- * A themed table wirh all tokens.
- *
- * @todo: Add help for other tokens
- */
- function theme_views_send_token_help($fields) {
- $header = array(t('Token'), t('Replacement value'));
- $rows = array();
- foreach ($fields as $field => $title) {
- $rows[] = array(VIEWS_SEND_TOKEN_PREFIX . sprintf(VIEWS_SEND_TOKEN_PATTERN, $field) . VIEWS_SEND_TOKEN_POSTFIX, $title);
- }
- $output = theme('table', array('header' => $header, 'rows' => $rows));
- return $output;
- }
- if (module_exists('token')) {
- /**
- * Implements hook_token_info().
- *
- * These token are used by Rules and not in the Views form.
- */
- function views_send_token_info() {
- $data = array();
- foreach (_views_send_email_message_property_info() as $key => $info) {
- $data[$key] = array(
- 'name' => $info['label'],
- 'description' => ''
- );
- }
- $type = array(
- 'name' => t('Views Send e-mail message'),
- 'description' => t('Tokens for Views Send e-mail message.'),
- 'needs-data' => 'views_send_email_message',
- );
- return array(
- 'types' => array('views_send_email_message' => $type),
- 'tokens' => array('views_send_email_message' => $data),
- );
- }
- /**
- * Implementation hook_tokens().
- *
- * These token replacements are used by Rules and not in the Views form.
- */
- function views_send_tokens($type, $tokens, array $data = array(), array $options = array()) {
- $replacements = array();
- if ($type == 'views_send_email_message' && !empty($data['views_send_email_message'])) {
- foreach ($tokens as $name => $original) {
- $replacements[$original] = $data['views_send_email_message']->{$name};
- }
- }
- return $replacements;
- }
- }
- /**
- * Generates and returns fields and tokens.
- */
- function _views_send_get_fields_and_tokens($view, $type) {
- static $return;
- if (isset($return[$type])) {
- return $return[$type];
- }
- if (!in_array($type, array('fields', 'tokens', 'fields_name_text')) || !$view) {
- return FALSE;
- }
- $fields = array();
- $tokens = array();
- $fields_name_text = array();
- foreach ($view->field as $field_name => $field) {
- // Ignore Views Form fields.
- if (property_exists($field, 'views_form_callback') || method_exists($field, 'views_form')) {
- continue;
- }
- if ($field instanceof views_handler_field_custom) {
- $field_key = $field_name;
- // Using a nice field name (for tokens) for custom text fields.
- $field_name = str_replace('nothing', 'custom_text', $field_name);;
- }
- elseif (!empty($field->field_info)) {
- $field_key = $field->field_info['field_name'];
- }
- elseif (property_exists($field, 'field_alias')) {
- $field_key = $field->field_alias;
- if ($field_key == 'unknown') {
- $field_key = $field_name;
- }
- }
- else {
- $field_key = $field_name;
- }
- // Add field position to ensure unique keys.
- $field_key .= '_pos_' . $field->position;
- $field_text = $field->label() . ' (' . $field_name . ')';
- $fields[$field_key] = $field_text;
- $tokens[$field_key] = $field_name;
- $fields_name_text[$field_name] = $field_text;
- }
- $return = array();
- $return['fields'] = $fields;
- $return['tokens'] = $tokens;
- $return['fields_name_text'] = $fields_name_text;
- return $return[$type];
- }
- /**
- * Returns property info for Views Send Email Message
- */
- function _views_send_email_message_property_info() {
- $propertyinfo = array(
- 'uid' => array(
- 'type' => 'integer',
- 'label' => t('User ID'),
- ),
- 'timestamp' => array(
- 'type' => 'integer',
- 'label' => t('Timestamp'),
- ),
- 'from_name' => array(
- 'type' => 'text',
- 'label' => t('Sender\'s name'),
- ),
- 'from_mail' => array(
- 'type' => 'text',
- 'label' => t('Sender\'s e-mail'),
- ),
- 'to_name' => array(
- 'type' => 'text',
- 'label' => t('Recipient\'s name'),
- ),
- 'to_mail' => array(
- 'type' => 'text',
- 'label' => t('Recipient\'s e-mail'),
- ),
- 'subject' => array(
- 'type' => 'text',
- 'label' => t('E-mail subject'),
- ),
- 'body' => array(
- 'type' => 'text',
- 'label' => t('E-mail body'),
- ),
- 'headers' => array(
- 'type' => 'text',
- 'label' => t('E-mail headers (serialized)'),
- ),
- );
- return $propertyinfo;
- }
|