Projet

Général

Profil

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

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

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 array $variables
98
 *   Array with key "form" containing the form array.
99
 *
100
 * @return string
101
 *   Formatted HTML form, ready for display.
102
 *
103
 * @throws Exception
104
 */
105
function theme_webform_emails_form($variables) {
106
  $form = $variables['form'];
107
  $node = $form['#node'];
108

    
109
  $header = array(t('Send'), t('E-mail to'), t('Subject'), t('From'), array('data' => t('Operations'), 'colspan' => 3));
110
  $rows = array();
111

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

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

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

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

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

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

    
164
  return drupal_render_children($form);
165
}
166

    
167
/**
168
 * Submit handler for webform_emails_form().
169
 */
170
function webform_emails_form_submit($form, &$form_state) {
171
  if ($form_state['values']['email_option'] == 'custom') {
172
    $email = $form_state['values']['email_custom'];
173
  }
174
  else {
175
    $email = $form_state['values']['email_component'];
176
  }
177
  $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))));
178
}
179

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
412
  $form['#validate'] = array('webform_email_address_validate', 'webform_email_edit_form_validate');
413

    
414
  return $form;
415
}
416

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

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

    
437
  $details = '';
438
  $details .= drupal_render($form['subject_option']);
439
  $details .= drupal_render($form['from_address_option']);
440
  $details .= drupal_render($form['from_address_mapping']);
441
  $details .= drupal_render($form['from_name_option']);
442

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

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

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

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

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

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

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

    
501
  return render($wrapper_element);
502
}
503

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

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

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

    
535
}
536

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

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

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

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

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

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

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

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

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

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

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

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

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

    
614
  $form_state['redirect'] = array('node/' . $node->nid . '/webform/emails');
615
}
616

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

    
623
  $form['node'] = array(
624
    '#type' => 'value',
625
    '#value' => $node,
626
  );
627
  $form['email'] = array(
628
    '#type' => 'value',
629
    '#value' => $email,
630
  );
631

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

    
640
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform/emails', $description, t('Delete'));
641
}
642

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

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

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

    
660
  $form_state['redirect'] = 'node/' . $node->nid . '/webform/emails';
661
}
662

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

    
690
  return $email;
691
}
692

    
693
/**
694
 * Insert a new e-mail setting into the database.
695
 *
696
 * @param $email
697
 *   An array of settings for sending an e-mail.
698
 *
699
 * @return int|false
700
 *   The e-mail identifier for this row's settings on success else false.
701
 */
702
function webform_email_insert($email) {
703
  // TODO: This is not race-condition safe. Switch to using transactions?
704
  if (!isset($email['eid'])) {
705
    $next_id_query = db_select('webform_emails')->condition('nid', $email['nid']);
706
    $next_id_query->addExpression('MAX(eid) + 1', 'eid');
707
    $email['eid'] = $next_id_query->execute()->fetchField();
708
    if ($email['eid'] == NULL) {
709
      $email['eid'] = 1;
710
    }
711
  }
712

    
713
  $email['excluded_components'] = implode(',', $email['excluded_components']);
714
  $email['extra'] = empty($email['extra']) ? '' : serialize($email['extra']);
715
  $success = drupal_write_record('webform_emails', $email);
716

    
717
  return $success ? $email['eid'] : FALSE;
718
}
719

    
720
/**
721
 * Clone an existing e-mail setting.
722
 *
723
 * @param $email
724
 *   An array of settings for sending an e-mail.
725
 *
726
 * @return false|int
727
 *   The e-mail identifier for this row's settings on success else false.
728
 */
729
function webform_email_clone($email) {
730
  $email['eid'] = NULL;
731
  return webform_email_insert($email);
732
}
733

    
734
/**
735
 * Update an existing e-mail setting with new values.
736
 *
737
 * @param $email
738
 *   An array of settings for sending an e-mail containing a nid, eid, and all
739
 *   other fields from the e-mail form.
740
 *
741
 * @return false|int
742
 *   On success SAVED_NEW or SAVED_UPDATED, depending on the operation performed,
743
 *   false on failure.
744
 */
745
function webform_email_update($email) {
746
  $email['excluded_components'] = implode(',', $email['excluded_components']);
747
  $email['extra'] = empty($email['extra']) ? '' : serialize($email['extra']);
748
  return drupal_write_record('webform_emails', $email, array('nid', 'eid'));
749
}
750

    
751
/**
752
 * Delete an e-mail setting.
753
 */
754
function webform_email_delete($node, $email) {
755
  db_delete('webform_emails')
756
    ->condition('nid', $node->nid)
757
    ->condition('eid', $email['eid'])
758
    ->execute();
759
}