Projet

Général

Profil

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

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

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

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

    
197
  $form['#attached']['library'][] = array('webform', 'admin');
198
  $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');
199

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

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

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

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

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

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

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

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

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

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

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

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

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

    
369
  $form['template']['components'] = array(
370
    '#type' => 'select',
371
    '#title' => t('Included e-mail values'),
372
    '#options' => webform_component_list($node, 'email', TRUE),
373
    '#default_value' => array_diff(array_keys($node->webform['components']), $email['excluded_components']),
374
    '#multiple' => TRUE,
375
    '#size' => 10,
376
    '#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.'),
377
    '#process' => array('webform_component_select'),
378
  );
379

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

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

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

    
406
  $form['#validate'] = array('webform_email_address_validate', 'webform_email_edit_form_validate');
407

    
408
  return $form;
409
}
410

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

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

    
431
  $details = '';
432
  $details .= drupal_render($form['subject_option']);
433
  $details .= drupal_render($form['from_address_option']);
434
  $details .= drupal_render($form['from_address_mapping']);
435
  $details .= drupal_render($form['from_name_option']);
436

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

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

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

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

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

    
477
  $empty = t('This component has no options defined yet.');
478
  $table = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'empty' => $empty));
479
  $description = t('The selected component %name has multiple options. You may enter an e-mail address for each choice.', array('%name' => $element['#title']));
480
  if ($element['#webform_allow_empty']) {
481
    $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.');
482
  }
483
  else {
484
    $description .= ' ' . t('When that choice is selected, an e-mail will be sent from the corresponding address.');
485
  }
486

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

    
495
  return render($wrapper_element);
496
}
497

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

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

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

    
529
}
530

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

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

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

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

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

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

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

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

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

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

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

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

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

    
608
  $form_state['redirect'] = array('node/' . $node->nid . '/webform/emails');
609
}
610

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

    
617
  $form['node'] = array(
618
    '#type' => 'value',
619
    '#value' => $node,
620
  );
621
  $form['email'] = array(
622
    '#type' => 'value',
623
    '#value' => $email,
624
  );
625

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

    
634
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform/emails', $description, t('Delete'));
635
}
636

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

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

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

    
654
  $form_state['redirect'] = 'node/' . $node->nid . '/webform/emails';
655
}
656

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

    
684
  return $email;
685
}
686

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

    
704
  $email['excluded_components'] = implode(',', $email['excluded_components']);
705
  $email['extra'] = empty($email['extra']) ? '' : serialize($email['extra']);
706
  $success = drupal_write_record('webform_emails', $email);
707

    
708
  return $success ? $email['eid'] : FALSE;
709
}
710

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

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

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