Projet

Général

Profil

Paste
Télécharger (27,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / includes / webform.emails.inc @ 024de6ea

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides interface and database handling for e-mail settings of a webform.
6
 *
7
 * @author Nathan Haug <nate@lullabot.com>
8
 */
9

    
10
/**
11
 * Overview form of all components for this webform.
12
 */
13
function webform_emails_form($form, $form_state, $node) {
14
  module_load_include('inc', 'webform', 'includes/webform.components');
15

    
16
  $form['#attached']['library'][] = array('webform', 'admin');
17

    
18
  $form['#tree'] = TRUE;
19
  $form['#node'] = $node;
20
  $form['components'] = array();
21

    
22
  foreach ($node->webform['emails'] as $eid => $email) {
23
    $form['emails'][$eid]['status'] = array(
24
      '#type' => 'checkbox',
25
      '#default_value' => $email['status'],
26
    );
27
    $form['emails'][$eid]['email'] = array(
28
      '#markup' => nl2br(check_plain(implode("\n", webform_format_email_address($email['email'], NULL, $node, NULL, FALSE, FALSE)))),
29
    );
30
    $form['emails'][$eid]['subject'] = array(
31
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node)),
32
    );
33
    $form['emails'][$eid]['from'] = array(
34
      '#markup' => check_plain(webform_format_email_address($email['from_address'], $email['from_name'], $node, NULL, FALSE)),
35
    );
36
  }
37

    
38
  $form['add'] = array(
39
    '#theme' => 'webform_email_add_form',
40
    '#tree' => FALSE,
41
  );
42

    
43
  $form['add']['status'] = array(
44
    '#type' => 'checkbox',
45
    '#default_value' => TRUE,
46
  );
47

    
48
  $form['add']['email_option'] = array(
49
    '#type' => 'radios',
50
    '#options' => array(
51
      'custom' => t('Address'),
52
      'component' => t('Component value'),
53
    ),
54
    '#default_value' => 'custom',
55
  );
56

    
57
  $form['add']['email_custom'] = array(
58
    '#type' => 'textfield',
59
    '#size' => 24,
60
    '#maxlength' => 500,
61
  );
62

    
63
  $form['add']['email_component'] = array(
64
    '#type' => 'select',
65
    '#options' => webform_component_list($node, 'email_address', FALSE),
66
  );
67

    
68
  if (empty($form['add']['email_component']['#options'])) {
69
    $form['add']['email_component']['#options'][''] = t('No available components');
70
    $form['add']['email_component']['#disabled'] = TRUE;
71
  }
72

    
73
  $form['add']['add'] = array(
74
    '#type' => 'submit',
75
    '#value' => t('Add'),
76
    '#validate' => array('webform_email_address_validate'),
77
    '#submit' => array('webform_emails_form_submit'),
78
  );
79

    
80
  $form['actions'] = array(
81
    '#type' => 'actions',
82
    '#weight' => 45,
83
  );
84
  $form['actions']['save'] = array(
85
    '#type' => 'submit',
86
    '#value' => t('Save'),
87
    '#submit' => array('webform_emails_form_status_save'),
88
    '#access' => count($node->webform['emails']) > 0,
89
  );
90

    
91
  return $form;
92
}
93

    
94
/**
95
 * Theme the node components form. Use a table to organize the components.
96
 *
97
 * @param $form
98
 *   The form array.
99
 * @return
100
 *   Formatted HTML form, ready for display.
101
 */
102
function theme_webform_emails_form($variables) {
103
  $form = $variables['form'];
104
  $node = $form['#node'];
105

    
106
  $header = array(t('Send'), t('E-mail to'), t('Subject'), t('From'), array('data' => t('Operations'), 'colspan' => 3));
107
  $rows = array();
108

    
109
  if (!empty($form['emails'])) {
110
    foreach (element_children($form['emails']) as $eid) {
111
      // Add each component to a table row.
112
      $rows[] = array(
113
        array('data' => drupal_render($form['emails'][$eid]['status']), 'class' => array('webform-email-status', 'checkbox')),
114
        drupal_render($form['emails'][$eid]['email']),
115
        drupal_render($form['emails'][$eid]['subject']),
116
        drupal_render($form['emails'][$eid]['from']),
117
        l(t('Edit'), 'node/' . $node->nid . '/webform/emails/' . $eid),
118
        l(t('Clone'), 'node/' . $node->nid . '/webform/emails/' . $eid . '/clone'),
119
        l(t('Delete'), 'node/' . $node->nid . '/webform/emails/' . $eid . '/delete'),
120
      );
121
    }
122
  }
123
  else {
124
    $rows[] = array(array('data' => t('Currently not sending e-mails, add an e-mail recipient below.'), 'colspan' => 7));
125
  }
126

    
127
  // Add a row containing form elements for a new item.
128
  $add_button = drupal_render($form['add']['add']);
129
  $row_data = array(
130
    array('data' => drupal_render($form['add']['status']), 'class' => array('webform-email-status', 'checkbox')),
131
    array('colspan' => 3, 'data' => drupal_render($form['add'])),
132
    array('colspan' => 3, 'data' => $add_button),
133
  );
134
  $rows[] = array('data' => $row_data, 'class' => array('webform-add-form'));
135

    
136
  $output = '';
137
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('id' => 'webform-emails')));
138
  $output .= drupal_render_children($form);
139
  return $output;
140
}
141

    
142
/**
143
 * Theme the add new e-mail settings form on the node/x/webform/emails page.
144
 */
145
function theme_webform_email_add_form($variables) {
146
  $form = $variables['form'];
147

    
148
  // Add a default value to the custom e-mail textfield.
149
  $form['email_custom']['#attributes']['placeholder'] = t('email@example.com');
150
  $form['email_custom']['#attributes']['class'][] = 'webform-set-active';
151
  $form['email_custom']['#theme_wrappers'] = array();
152
  $form['email_option']['custom']['#theme_wrappers'] = array('webform_inline_radio');
153
  $form['email_option']['custom']['#title'] = t('Address: !email', array('!email' => drupal_render($form['email_custom'])));
154

    
155
  // Render the component value.
156
  $form['email_component']['#theme_wrappers'] = array();
157
  $form['email_component']['#attributes']['class'][] = 'webform-set-active';
158
  $form['email_option']['component']['#theme_wrappers'] = array('webform_inline_radio');
159
  $form['email_option']['component']['#title'] = t('Component value: !component', array('!component' => drupal_render($form['email_component'])));
160

    
161
  return drupal_render_children($form);
162
}
163

    
164
/**
165
 * Submit handler for webform_emails_form().
166
 */
167
function webform_emails_form_submit($form, &$form_state) {
168
  if ($form_state['values']['email_option'] == 'custom') {
169
    $email = $form_state['values']['email_custom'];
170
  }
171
  else {
172
    $email = $form_state['values']['email_component'];
173
  }
174
  $form_state['redirect'] = array('node/' . $form['#node']->nid . '/webform/emails/new', array('query' => array('status' => $form_state['values']['status'], 'option' => $form_state['values']['email_option'], 'email' => trim($email))));
175
}
176

    
177
/**
178
 * Submit handler for status update.
179
 */
180
function webform_emails_form_status_save($form, &$form_state) {
181
  foreach ($form_state['values']['emails'] as $eid => $status) {
182
    db_update('webform_emails')->fields(array(
183
      'status' => $status['status']
184
    ))
185
    ->condition('eid', $eid)
186
    ->condition('nid', $form['#node']->nid)
187
    ->execute();
188
  }
189

    
190
  // Refresh the entity cache, should it be cached in persistent storage.
191
  entity_get_controller('node')->resetCache(array($form['#node']->nid));
192
}
193

    
194
/**
195
 * Form for configuring an e-mail setting and template.
196
 */
197
function webform_email_edit_form($form, $form_state, $node, $email = array(), $clone = FALSE) {
198
  module_load_include('inc', 'webform', 'includes/webform.components');
199

    
200
  $form['#attached']['library'][] = array('webform', 'admin');
201
  $form['#attached']['js'][] = array('data' => array('webform' => array('revertConfirm' => t('Are you sure you want to revert any changes to your template back to the default?'))), 'type' => 'setting');
202

    
203
  $form['#tree'] = TRUE;
204
  $form['#node'] = $node;
205
  $form['eid'] = array(
206
    '#type' => 'value',
207
    '#value' => isset($email['eid']) ? $email['eid'] : NULL,
208
  );
209
  $form['clone'] = array(
210
    '#type' => 'value',
211
    '#value' => $clone,
212
  );
213

    
214
  // All these fields work essentially the same, with a radio button set,
215
  // a textfield for custom values, and a select list for a component.
216
  foreach (array('email', 'subject', 'from_address', 'from_name') as $field) {
217
    switch ($field) {
218
      case 'email':
219
        $default_value = NULL;
220
        $title = t('E-mail to address');
221
        $description = t('Form submissions will be e-mailed to this address. Any email, select, or hidden form element may be selected as the recipient address. Multiple e-mail addresses may be separated by commas.');
222
        break;
223
      case 'subject':
224
        $default_value = webform_replace_tokens(webform_variable_get('webform_default_subject'), $node);
225
        $title = t('E-mail subject');
226
        $description = t('Any textfield, select, or hidden form element may be selected as the subject for e-mails.');
227
        break;
228
      case 'from_address':
229
        $default_value = webform_replace_tokens(webform_variable_get('webform_default_from_address'), $node);
230
        $title = t('E-mail from address');
231
        $description = t('Any email, select, or hidden form element may be selected as the sender\'s e-mail address.');
232
        break;
233
      case 'from_name':
234
        $default_value = webform_replace_tokens(webform_variable_get('webform_default_from_name'), $node);
235
        $title = t('E-mail from name');
236
        $description = t('Any textfield, select, or hidden form element may be selected as the sender\'s name for e-mails.');
237
        break;
238
    }
239

    
240
    $form[$field . '_option'] = array(
241
      '#title' => $title,
242
      '#type' => 'radios',
243
      '#default_value' => is_numeric($email[$field]) ? 'component' : ((empty($default_value) || ($email[$field] != 'default' && isset($email[$field]))) ? 'custom' : 'default'),
244
      '#description' => $description,
245
    );
246
    if (!empty($default_value)) {
247
      $form[$field . '_option']['#options']['default'] = t('Default: %value', array('%value' => $default_value));
248
    }
249
    $form[$field . '_option']['#options']['custom'] = t('Custom');
250
    $form[$field . '_option']['#options']['component'] = t('Component');
251

    
252
    $form[$field . '_custom'] = array(
253
      '#type' => 'textfield',
254
      '#size' => 40,
255
      '#default_value' => (!is_numeric($email[$field]) && $email[$field] != 'default') ? $email[$field] : NULL,
256
      '#maxlength' => 500,
257
    );
258
    $field_type = $field === 'from_address' || $field === 'email' ? 'email_address' : 'email_name';
259
    $component_options = webform_component_list($node, $field_type, FALSE);
260
    $form[$field . '_component'] = array(
261
      '#type' => 'select',
262
      '#default_value' =>  is_numeric($email[$field]) ? $email[$field] : NULL,
263
      '#options' => empty($component_options) ? array('' => t('No available components')) : $component_options,
264
      '#disabled' => empty($component_options) ? TRUE : FALSE,
265
      '#weight' => 6,
266
    );
267

    
268
    // If this component is being used as an e-mail address and has multiple
269
    // options (such as a select list or checkboxes), we provide text fields to
270
    // map each option to a user-defined e-mail.
271
    if ($field_type === 'email_address') {
272
      foreach ($component_options as $cid => $component_label) {
273
        $component = $node->webform['components'][$cid];
274
        $options = webform_component_invoke($component['type'], 'options', $component, TRUE);
275
        // For components that don't provide multiple options (hidden or email).
276
        if (empty($options)) {
277
          continue;
278
        }
279

    
280
        // To avoid flooding the form with hundreds of textfields, skip select
281
        // lists that have huge numbers of options.
282
        if (count($options) > webform_variable_get('webform_email_select_max')) {
283
          unset($form[$field . '_component']['#options'][$cid]);
284
          continue;
285
        }
286
        $form[$field . '_mapping'][$cid] = array(
287
          '#title' => check_plain($component['name']),
288
          '#theme' => 'webform_email_component_mapping',
289
          '#attributes' => array('class' => array('webform-email-mapping')),
290
          '#webform_allow_empty' => $field === 'email',
291
          '#type' => 'container',
292
          '#states' => array(
293
            'visible' => array(
294
              'input[name=' . $field . '_option' . ']' => array('value' => 'component'),
295
              'select[name=' . $field . '_component' . ']' => array('value' => (string) $cid),
296
            ),
297
          ),
298
        );
299
        foreach ($options as $key => $label) {
300
          $form[$field . '_mapping'][$cid][$key] = array(
301
            '#type' => 'textfield',
302
            '#title' => $label,
303
            '#default_value' => is_numeric($email[$field]) && $email[$field] == $cid && is_array($email['extra']) && isset($email['extra'][$field . '_mapping'][$key]) ? $email['extra'][$field . '_mapping'][$key] : '',
304
            '#attributes' => array('placeholder' => t('email@example.com')),
305
            '#maxlength' => 500,
306
          );
307
        }
308
      }
309
    }
310
  }
311

    
312
  // Do not show the "E-mail from name" if using the short e-mail format.
313
  if (webform_variable_get('webform_email_address_format') == 'short') {
314
    $form['from_name_option']['#access'] = FALSE;
315
    $form['from_name_custom']['#access'] = FALSE;
316
    $form['from_name_component']['#access'] = FALSE;
317
  }
318

    
319
  // Add the checkbox to disable the email for current recipients.
320
  $form['status'] = array(
321
    '#title' => t('Enable sending'),
322
    '#description' => t('Uncheck to disable sending this email.'),
323
    '#type' => 'checkbox',
324
    '#default_value' => $email['status'],
325
  );
326

    
327
  // Add the template fieldset.
328
  $form['template'] = array(
329
    '#type' => 'fieldset',
330
    '#title' => t('E-mail template'),
331
    '#collapsible' => TRUE,
332
    '#collapsed' => !empty($email['cid']) && empty($email['template']),
333
    '#description' => t('An e-mail template can customize the display of e-mails.'),
334
    '#weight' => 15,
335
    '#tree' => FALSE,
336
    '#attributes' => array('id' => 'webform-template-fieldset'),
337
  );
338

    
339
  $form['template']['template_option'] = array(
340
    '#type' => 'select',
341
    '#options' => array(
342
      'default' => t('Default template'),
343
      'custom' => t('Custom template'),
344
    ),
345
    '#default_value' => $email['template'] == 'default' ? 'default' : 'custom',
346
  );
347

    
348
  $default_template = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'email' => $email));
349
  $template = $email['template'] == 'default' ? $default_template : $email['template'];
350
  $form['template']['template'] = array(
351
    '#type' => 'textarea',
352
    '#rows' => max(10, min(20, count(explode("\n", $template)))),
353
    '#default_value' => $template,
354
    '#wysiwyg' => webform_variable_get('webform_email_html_capable') ? NULL : FALSE,
355
    '#description' => theme('webform_token_help', array('groups' => array('node', 'submission'))),
356
  );
357

    
358
  $form['template']['html'] = array(
359
    '#type' => 'checkbox',
360
    '#title' => t('Send e-mail as HTML'),
361
    '#default_value' => $email['html'],
362
    '#access' => webform_variable_get('webform_email_html_capable') && !webform_variable_get('webform_format_override'),
363
  );
364

    
365
  $form['template']['attachments'] = array(
366
    '#type' => 'checkbox',
367
    '#title' => t('Include files as attachments'),
368
    '#default_value' => $email['attachments'],
369
    '#access' => webform_variable_get('webform_email_html_capable'),
370
  );
371

    
372
  $form['template']['components'] = array(
373
    '#type' => 'select',
374
    '#title' => t('Included e-mail values'),
375
    '#options' => webform_component_list($node, 'email', TRUE),
376
    '#default_value' => array_diff(array_keys($node->webform['components']), $email['excluded_components']),
377
    '#multiple' => TRUE,
378
    '#size' => 10,
379
    '#description' => t('The selected components will be included in the [submission:values] token. Individual values may still be printed if explicitly specified as a [submission:values:?] in the template.'),
380
    '#process' => array('webform_component_select'),
381
  );
382

    
383
  $form['template']['components']['suffix']['exclude_empty'] = array(
384
    '#type' => 'checkbox',
385
    '#title' => t('Exclude empty components'),
386
    '#default_value' => $email['exclude_empty'],
387
  );
388

    
389
  // TODO: Allow easy re-use of existing templates.
390
  $form['templates']['#tree'] = TRUE;
391
  $form['templates']['default'] = array(
392
    '#type' => 'textarea',
393
    '#value' => $default_template,
394
    '#resizable' => FALSE,
395
    '#weight' => 19,
396
    '#wysiwyg' => FALSE,
397
  );
398

    
399
  // Add the submit button.
400
  $form['actions'] = array(
401
    '#type' => 'actions',
402
    '#weight' => 20,
403
  );
404
  $form['actions']['submit'] = array(
405
    '#type' => 'submit',
406
    '#value' => t('Save e-mail settings'),
407
  );
408

    
409
  $form['#validate'] = array('webform_email_address_validate', 'webform_email_edit_form_validate');
410

    
411
  return $form;
412
}
413

    
414
/**
415
 * Theme the Webform mail settings section of the node form.
416
 */
417
function theme_webform_email_edit_form($variables) {
418
  $form = $variables['form'];
419

    
420
  // Loop through fields, rendering them into radio button options.
421
  foreach (array('email', 'subject', 'from_address', 'from_name') as $field) {
422
    foreach (array('custom', 'component') as $option) {
423
      $form[$field . '_' . $option]['#attributes']['class'][] = 'webform-set-active';
424
      $form[$field . '_' . $option]['#theme_wrappers'] = array();
425
      $form[$field . '_option'][$option]['#theme_wrappers'] = array('webform_inline_radio');
426
      $form[$field . '_option'][$option]['#title'] = t('!title: !field', array('!title' => $form[$field . '_option'][$option]['#title'], '!field' => drupal_render($form[$field . '_' . $option])));
427
    }
428
    if (isset($form[$field . '_option']['#options']['default'])) {
429
      $form[$field]['#theme_wrappers'] = array();
430
      $form[$field . '_option']['default']['#theme_wrappers'] = array('webform_inline_radio');
431
    }
432
  }
433

    
434
  $details = '';
435
  $details .= drupal_render($form['subject_option']);
436
  $details .= drupal_render($form['from_address_option']);
437
  $details .= drupal_render($form['from_address_mapping']);
438
  $details .= drupal_render($form['from_name_option']);
439

    
440
  $form['details'] = array(
441
    '#type' => 'fieldset',
442
    '#title' => t('E-mail header details'),
443
    '#weight' => 10,
444
    '#children' => $details,
445
    '#collapsible' => FALSE,
446
    '#parents' => array('details'),
447
    '#groups' => array('details' => array()),
448
    '#attributes' => array(),
449
  );
450

    
451
  // Ensure templates are completely hidden.
452
  $form['templates']['#prefix'] = '<div id="webform-email-templates" style="display: none">';
453
  $form['templates']['#suffix'] = '</div>';
454

    
455
  // Re-sort the elements since we added the details fieldset.
456
  $form['#sorted'] = FALSE;
457
  $children = element_children($form, TRUE);
458
  return drupal_render_children($form, $children);
459
}
460

    
461
/**
462
 * Theme the presentation of select list option to e-mail address mappings.
463
 */
464
function theme_webform_email_component_mapping($variables) {
465
  $element = $variables['element'];
466

    
467
  $header = array(t('Option'), t('E-mail address'));
468
  $rows = array();
469
  foreach (element_children($element) as $key) {
470
    $element[$key]['#theme_wrappers'] = array();
471
    $row = array();
472
    $row[] = array(
473
      'data' => theme('form_element_label', array('element' => $element[$key])),
474
      'class' => array('webform-email-option'),
475
    );
476
    $row[] = drupal_render($element[$key]);
477
    $rows[] = $row;
478
  }
479

    
480
  $empty = t('This component has no options defined yet.');
481
  $table = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'empty' => $empty));
482
  $description = t('The selected component %name has multiple options. You may enter an e-mail address for each choice.', array('%name' => $element['#title']));
483
  if ($element['#webform_allow_empty']) {
484
    $description .= ' ' . t('When that choice is selected, an e-mail will be sent to the corresponding address. If a field is left blank, no e-mail will be sent for that option.');
485
  }
486
  else {
487
    $description .= ' ' . t('When that choice is selected, an e-mail will be sent from the corresponding address.');
488
  }
489

    
490
  $wrapper_element = array(
491
    '#title' => t('Component e-mail options'),
492
    '#children' => $table,
493
    '#description' => $description,
494
    '#theme_wrappers' => array('form_element'),
495
    '#id' => NULL,
496
  );
497

    
498
  return render($wrapper_element);
499
}
500

    
501
/**
502
 * Validate handler for webform_email_edit_form() and webform_emails_form().
503
 */
504
function webform_email_address_validate($form, &$form_state) {
505
  if ($form_state['values']['email_option'] == 'custom') {
506
    webform_email_validate($form_state['values']['email_custom'], 'email_custom', FALSE, TRUE, TRUE);
507
  }
508
}
509

    
510
/**
511
 * Validate handler for webform_email_edit_form().
512
 */
513
function webform_email_edit_form_validate($form, &$form_state) {
514
  if ($form_state['values']['from_address_option'] == 'custom') {
515
    webform_email_validate($form_state['values']['from_address_custom'], 'from_address_custom', FALSE, FALSE, TRUE);
516
  }
517

    
518
  // Validate component-based values for the TO and FROM address.
519
  foreach (array('email', 'from_address') as $field_name) {
520
    if ($form_state['values'][$field_name . '_option'] == 'component') {
521
      $cid = $form_state['values'][$field_name . '_component'];
522
      if (isset($form_state['values'][$field_name . '_mapping'][$cid])) {
523
        $empty_allowed = $field_name === 'email';
524
        $multiple_allowed = $field_name === 'email';
525
        foreach ($form_state['values'][$field_name . '_mapping'][$cid] as $key => &$value) {
526
          webform_email_validate($value, "{$field_name}_mapping][$cid][$key", $empty_allowed, $multiple_allowed, TRUE);
527
        }
528
      }
529
    }
530
  }
531

    
532
}
533

    
534
/**
535
 * Submit handler for webform_email_edit_form().
536
 */
537
function webform_email_edit_form_submit($form, &$form_state) {
538
  // Ensure a webform record exists.
539
  $node = $form['#node'];
540
  webform_ensure_record($node);
541

    
542
  // Remove duplicate email To: addresses.
543
  $form_state['values']['email_custom'] = implode(',', array_unique(array_map('trim', explode(',', $form_state['values']['email_custom']))));
544

    
545
  // Merge the e-mail, name, address, and subject options into single values.
546
  $email = array(
547
    'eid' => $form_state['values']['eid'],
548
    'nid' => $node->nid,
549
  );
550

    
551
  foreach (array('email', 'from_name', 'from_address', 'subject') as $field) {
552
    $option = $form_state['values'][$field . '_option'];
553
    if ($option == 'default') {
554
      $email[$field] = 'default';
555
    }
556
    else {
557
      $email[$field] = $form_state['values'][$field . '_' . $option];
558

    
559
      // Merge the email mapping(s) into single value(s)
560
      $cid = $form_state['values'][$field . '_' . $option];
561
      if (is_numeric($cid) && isset($form_state['values'][$field . '_mapping'][$cid])) {
562
        $email['extra'][$field . '_mapping'] = $form_state['values'][$field . '_mapping'][$cid];
563
      }
564
    }
565
  }
566

    
567
  // Ensure templates are unaffected by differences in line breaks.
568
  $form_state['values']['template'] = str_replace(array("\r", "\n"), array('', "\n"), $form_state['values']['template']);
569
  $form_state['values']['templates']['default'] = str_replace(array("\r", "\n"), array('', "\n"), $form_state['values']['templates']['default']);
570

    
571
  // Set the template value.
572
  // TODO: Support reuse of templates.
573
  if (strcmp(trim($form_state['values']['templates']['default']), trim($form_state['values']['template'])) == 0) {
574
    $email['template'] = 'default';
575
  }
576
  else {
577
    $email['template'] = $form_state['values']['template'];
578
  }
579

    
580
  // Save the attachment and HTML options provided by MIME mail.
581
  $email['html'] = empty($form_state['values']['html']) ? 0 : 1;
582
  $email['attachments'] = empty($form_state['values']['attachments']) ? 0 : 1;
583

    
584
  // Save the list of included components.
585
  // We actually maintain an *exclusion* list, so any new components will
586
  // default to being included in the [submission:values] token until unchecked.
587
  $included = array_keys(array_filter((array) $form_state['values']['components']));
588
  $excluded = array_diff(array_keys($node->webform['components']), $included);
589
  $email['excluded_components'] = $excluded;
590

    
591
  $email['exclude_empty'] = empty($form_state['values']['exclude_empty']) ? 0 : 1;
592

    
593
  $email['status'] = empty($form_state['values']['status']) ? 0 : 1;
594

    
595
  if ($form_state['values']['clone']) {
596
    drupal_set_message(t('Email settings cloned.'));
597
    $form_state['values']['eid'] = webform_email_clone($email);
598
  }
599
  elseif (empty($form_state['values']['eid'])) {
600
    drupal_set_message(t('Email settings added.'));
601
    $form_state['values']['eid'] = webform_email_insert($email);
602
  }
603
  else {
604
    drupal_set_message(t('Email settings updated.'));
605
    webform_email_update($email);
606
  }
607

    
608
  // Refresh the entity cache, should it be cached in persistent storage.
609
  entity_get_controller('node')->resetCache(array($node->nid));
610

    
611
  $form_state['redirect'] = array('node/' . $node->nid . '/webform/emails');
612
}
613

    
614
/**
615
 * Form for deleting an e-mail setting.
616
 */
617
function webform_email_delete_form($form, $form_state, $node, $email) {
618
  $eid = $email['eid'];
619

    
620
  $form['node'] = array(
621
    '#type' => 'value',
622
    '#value' => $node,
623
  );
624
  $form['email'] = array(
625
    '#type' => 'value',
626
    '#value' => $email,
627
  );
628

    
629
  $question = t('Delete e-mail settings?');
630
  if (is_numeric($email['email'])) {
631
    $description = t('This will immediately delete the e-mail settings based on the @component component.', array('@component' => $email['email']));
632
  }
633
  else {
634
    $description = t('This will immediately delete the e-mail settings sending to the @address address.', array('@address' => $email['email']));
635
  }
636

    
637
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform/emails', $description, t('Delete'));
638
}
639

    
640
/**
641
 * Submit handler for webform_email_delete_form().
642
 */
643
function webform_email_delete_form_submit($form, &$form_state) {
644
  // Delete the e-mail settings.
645
  $node = $form_state['values']['node'];
646
  $email = $form_state['values']['email'];
647
  webform_email_delete($node, $email);
648
  drupal_set_message(t('E-mail settings deleted.'));
649

    
650
  // Check if this webform still contains any information.
651
  unset($node->webform['emails'][$email['eid']]);
652
  webform_check_record($node);
653

    
654
  // Refresh the entity cache, should it be cached in persistent storage.
655
  entity_get_controller('node')->resetCache(array($node->nid));
656

    
657
  $form_state['redirect'] = 'node/' . $node->nid . '/webform/emails';
658
}
659

    
660
/**
661
 * Load an e-mail setting from the database or initialize a new e-mail.
662
 */
663
function webform_email_load($eid, $nid) {
664
  $node = node_load($nid);
665
  if ($eid == 'new') {
666
    $email = array(
667
      'email' => '',
668
      'subject' => 'default',
669
      'from_name' => 'default',
670
      'from_address' => 'default',
671
      'template' => 'default',
672
      'excluded_components' => array(),
673
      'exclude_empty' => 0,
674
      'html' => webform_variable_get('webform_default_format'),
675
      'attachments' => 0,
676
      'extra' => '',
677
      'status' => 1,
678
    );
679
  }
680
  else {
681
    $email = isset($node->webform['emails'][$eid]) ? $node->webform['emails'][$eid] : FALSE;
682
    if ($email && webform_variable_get('webform_format_override')) {
683
      $email['html'] = webform_variable_get('webform_default_format');
684
    }
685
  }
686

    
687
  return $email;
688
}
689

    
690
/**
691
 * Insert a new e-mail setting into the database.
692
 *
693
 * @param $email
694
 *   An array of settings for sending an e-mail.
695
 */
696
function webform_email_insert($email) {
697
  // TODO: This is not race-condition safe. Switch to using transactions?
698
  if (!isset($email['eid'])) {
699
    $next_id_query = db_select('webform_emails')->condition('nid', $email['nid']);
700
    $next_id_query->addExpression('MAX(eid) + 1', 'eid');
701
    $email['eid'] = $next_id_query->execute()->fetchField();
702
    if ($email['eid'] == NULL) {
703
      $email['eid'] = 1;
704
    }
705
  }
706

    
707
  $email['excluded_components'] = implode(',', $email['excluded_components']);
708
  $email['extra'] = empty($email['extra']) ? '' : serialize($email['extra']);
709
  $success = drupal_write_record('webform_emails', $email);
710

    
711
  return $success ? $email['eid'] : FALSE;
712
}
713

    
714
/**
715
 * Clone an existing e-mail setting.
716
 *
717
 * @param $email
718
 *   An array of settings for sending an e-mail.
719
 */
720
function webform_email_clone($email) {
721
  $email['eid'] = NULL;
722
  return webform_email_insert($email);
723
}
724

    
725
/**
726
 * Update an existing e-mail setting with new values.
727
 *
728
 * @param $email
729
 *   An array of settings for sending an e-mail containing a nid, eid, and all
730
 *   other fields from the e-mail form.
731
 */
732
function webform_email_update($email) {
733
  $email['excluded_components'] = implode(',', $email['excluded_components']);
734
  $email['extra'] = empty($email['extra']) ? '' : serialize($email['extra']);
735
  return drupal_write_record('webform_emails', $email, array('nid', 'eid'));
736
}
737

    
738
/**
739
 * Delete an e-mail setting.
740
 */
741
function webform_email_delete($node, $email) {
742
  db_delete('webform_emails')
743
    ->condition('nid', $node->nid)
744
    ->condition('eid', $email['eid'])
745
    ->execute();
746
}