Projet

Général

Profil

Paste
Télécharger (40,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / includes / webform.submissions.inc @ 8d02775b

1
<?php
2

    
3
/**
4
 * @file
5
 * Submission handling functions.
6
 *
7
 * This file is loaded when handling submissions, either submitting new,
8
 * editing, or viewing. It also contains all CRUD functions for submissions.
9
 *
10
 * @author Nathan Haug <nate@lullabot.com>
11
 */
12

    
13
/**
14
 * Given an array of submitted values, flatten it into data for a submission.
15
 *
16
 * @param $node
17
 *   The node object containing the current webform.
18
 * @param $submitted
19
 *   The submitted user values from the webform.
20
 *
21
 * @return array
22
 *   An array suitable for use in the 'data' property of a $submission object.
23
 */
24
function webform_submission_data($node, $submitted) {
25
  $data = array();
26

    
27
  foreach ($submitted as $cid => $values) {
28
    // Don't save pseudo-fields or pagebreaks as submitted data.
29
    if (!isset($node->webform['components'][$cid]) || $node->webform['components'][$cid]['type'] == 'pagebreak') {
30
      continue;
31
    }
32

    
33
    if (is_array($values)) {
34
      $data[$cid] = $values;
35
    }
36
    else {
37
      $data[$cid][0] = $values;
38
    }
39
  }
40

    
41
  return $data;
42
}
43

    
44
/**
45
 * Given set of $form_state values, prepare a psuedo-submission.
46
 *
47
 * @param object $node
48
 *   The webform node object.
49
 * @param object $account
50
 *   The user account that is creating this submission.
51
 * @param array $form_state
52
 *   The form_state containing the values for the submission.
53
 * @param object $prototype
54
 *   An existing submission that is being previewed, if any.
55
 *
56
 * @return object
57
 *   A new submission object, possibly for preview
58
 */
59
function webform_submission_create($node, $account, array $form_state, $is_preview = FALSE, $prototype = NULL) {
60
  $data = webform_submission_data($node, $form_state['values']['submitted']);
61
  if (is_object($prototype)) {
62
    $submission = clone $prototype;
63
    $submission->preview = $is_preview;
64
    $submission->data = $data;
65
  }
66
  else {
67
    $submission = (object) array(
68
      'nid' => $node->nid,
69
      'uid' => $account->uid,
70
      'sid' => NULL,
71
      'submitted' => REQUEST_TIME,
72
      'completed' => 0,
73
      'modified' => REQUEST_TIME,
74
      'remote_addr' => webform_ip_address($node),
75
      'is_draft' => TRUE,
76
      'highest_valid_page' => 0,
77
      'preview' => $is_preview,
78
      'serial' => NULL,
79
      'data' => $data,
80
    );
81
    drupal_alter('webform_submission_create', $submission, $node, $account, $form_state);
82
  }
83
  return $submission;
84
}
85

    
86
/**
87
 * Update a webform submission entry in the database.
88
 *
89
 * @param $node
90
 *   The node object containing the current webform.
91
 * @param $submission
92
 *   The webform submission object to be saved into the database.
93
 *
94
 * @return int
95
 *   The existing submission SID.
96
 */
97
function webform_submission_update($node, $submission) {
98
  $transaction = db_transaction();
99
  // Allow other modules to modify the submission before saving.
100
  foreach (module_implements('webform_submission_presave') as $module) {
101
    $function = $module . '_webform_submission_presave';
102
    $function($node, $submission);
103
  }
104

    
105
  $submission->completed = empty($submission->completed) && !$submission->is_draft ? REQUEST_TIME : $submission->completed;
106
  $submission->modified = REQUEST_TIME;
107

    
108
  // Update the main submission info.
109
  drupal_write_record('webform_submissions', $submission, 'sid');
110

    
111
  // If is draft, only delete data for components submitted, to
112
  // preserve any data from form pages not visited in this submission.
113
  if ($submission->is_draft) {
114
    $submitted_cids = array_keys($submission->data);
115
    if ($submitted_cids) {
116
      db_delete('webform_submitted_data')
117
        ->condition('sid', $submission->sid)
118
        ->condition('cid', $submitted_cids, 'IN')
119
        ->execute();
120
    }
121
  }
122
  else {
123
    db_delete('webform_submitted_data')
124
      ->condition('sid', $submission->sid)
125
      ->execute();
126
  }
127

    
128
  // Then re-add submission data to the database.
129
  $submission->is_new = FALSE;
130
  webform_submission_insert($node, $submission);
131

    
132
  module_invoke_all('webform_submission_update', $node, $submission);
133

    
134
  return $submission->sid;
135
}
136

    
137
/**
138
 * Insert a webform submission entry in the database.
139
 *
140
 * @param $node
141
 *   The node object containing the current webform.
142
 * @param $submission
143
 *   The webform submission object to be saved into the database.
144
 *
145
 * @return int
146
 *   The new submission SID.
147
 */
148
function webform_submission_insert($node, $submission) {
149
  $transaction = db_transaction();
150
  // The submission ID may already be set if being called as an update.
151
  if (!isset($submission->sid) && (!isset($submission->is_new) || $submission->is_new == FALSE)) {
152
    // Allow other modules to modify the submission before saving.
153
    foreach (module_implements('webform_submission_presave') as $module) {
154
      $function = $module . '_webform_submission_presave';
155
      $function($node, $submission);
156
    }
157
    $submission->nid = $node->webform['nid'];
158
    if (empty($submission->serial)) {
159
      $submission->serial = _webform_submission_serial_next_value($node->nid);
160
    }
161
    $submission->completed = empty($submission->completed) && !$submission->is_draft ? REQUEST_TIME : $submission->completed;
162
    drupal_write_record('webform_submissions', $submission);
163
    $is_new = TRUE;
164
  }
165

    
166
  foreach ($submission->data as $cid => $values) {
167
    foreach ($values as $delta => $value) {
168
      $data = array(
169
        'nid' => $node->webform['nid'],
170
        'sid' => $submission->sid,
171
        'cid' => $cid,
172
        'no' => $delta,
173
        'data' => is_null($value) ? '' : $value,
174
      );
175
      drupal_write_record('webform_submitted_data', $data);
176
    }
177
  }
178

    
179
  // Invoke the insert hook after saving all the data.
180
  if (isset($is_new)) {
181
    module_invoke_all('webform_submission_insert', $node, $submission);
182
  }
183

    
184
  return $submission->sid;
185
}
186

    
187
/**
188
 * Delete a single submission.
189
 *
190
 * @param $node
191
 *   The node object containing the current webform.
192
 * @param $submission
193
 *   The webform submission object to be deleted from the database.
194
 */
195
function webform_submission_delete($node, $submission) {
196
  $transaction = db_transaction();
197
  // Iterate through all components and let each do cleanup if necessary.
198
  foreach ($node->webform['components'] as $cid => $component) {
199
    if (isset($submission->data[$cid])) {
200
      webform_component_invoke($component['type'], 'delete', $component, $submission->data[$cid]);
201
    }
202
  }
203

    
204
  // Delete any anonymous session information.
205
  if (isset($_SESSION['webform_submission'][$submission->sid])) {
206
    unset($_SESSION['webform_submission'][$submission->sid]);
207
  }
208

    
209
  db_delete('webform_submitted_data')
210
    ->condition('nid', $node->nid)
211
    ->condition('sid', $submission->sid)
212
    ->execute();
213
  db_delete('webform_submissions')
214
    ->condition('nid', $node->nid)
215
    ->condition('sid', $submission->sid)
216
    ->execute();
217

    
218
  module_invoke_all('webform_submission_delete', $node, $submission);
219
}
220

    
221
/**
222
 * Send related e-mails related to a submission.
223
 *
224
 * This function is usually invoked when a submission is completed, but may be
225
 * called any time e-mails should be redelivered.
226
 *
227
 * @param $node
228
 *   The node object containing the current webform.
229
 * @param $submission
230
 *   The webform submission object to be used in sending e-mails.
231
 * @param $emails
232
 *   (optional) An array of specific e-mail settings to be used. If omitted, all
233
 *   e-mails in $node->webform['emails'] will be sent.
234
 * @param bool $send_disabled
235
 *   (optional) When TRUE, send all emails, even those that are disabled.
236
 *
237
 * @return int
238
 *   Number of mail sent.
239
 */
240
function webform_submission_send_mail($node, $submission, $emails = NULL, $send_disabled = FALSE) {
241
  // Get the list of e-mails we'll be sending.
242
  $emails = isset($emails) ? $emails : $node->webform['emails'];
243

    
244
  // Create a themed message for mailing.
245
  $send_count = 0;
246
  foreach ($emails as $eid => $email) {
247
    if (!$send_disabled && !$email['status']) {
248
      continue;
249
    }
250
    $mail = _webform_submission_prepare_mail($node, $submission, $email);
251
    if (!$mail) {
252
      continue;
253
    }
254

    
255
    $addresses_final = $mail['addresses_final'];
256
    $send_increment = $mail['send_increment'];
257
    $language = $mail['language'];
258
    $mail_params = $mail['mail_params'];
259

    
260
    // Mail the webform results.
261
    foreach ($addresses_final as $address) {
262
      $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
263
      if ($message['result']) {
264
        $send_count += $send_increment;
265
      }
266
    }
267
  }
268

    
269
  return $send_count;
270
}
271

    
272
/**
273
 * Prepare a submission email for use by webform_submission_send_mail()
274
 *
275
 * @param $node
276
 *   The node object containing the current webform.
277
 * @param $submission
278
 *   The webform submission object to be used in sending e-mails.
279
 * @param $email
280
 *   The e-mail settings to be used. This will have some of its values adjusted.
281
 *
282
 * @return array|null
283
 *   An array of the information about the email needed by drupal_mail().
284
 */
285
function _webform_submission_prepare_mail($node, $submission, &$email) {
286
  global $user;
287

    
288
  // Set the HTML property based on availablity of MIME Mail.
289
  $email['html'] = ($email['html'] && webform_variable_get('webform_email_html_capable'));
290

    
291
  // Pass through the theme layer if using the default template.
292
  if ($email['template'] == 'default') {
293
    $email['message'] = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'submission' => $submission, 'email' => $email));
294
  }
295
  else {
296
    $email['message'] = $email['template'];
297
  }
298

    
299
  // Replace tokens in the message.
300
  $email['message'] = webform_replace_tokens($email['message'], $node, $submission, $email, (boolean) $email['html']);
301

    
302
  // Build the e-mail headers.
303
  $email['headers'] = theme(array('webform_mail_headers_' . $node->nid, 'webform_mail_headers'), array('node' => $node, 'submission' => $submission, 'email' => $email));
304

    
305
  // Assemble the From string.
306
  if (isset($email['headers']['From'])) {
307
    // If a header From is already set, don't override it.
308
    $email['from'] = $email['headers']['From'];
309
    unset($email['headers']['From']);
310
  }
311
  else {
312
    // Format the From address.
313
    $mapping = isset($email['extra']['from_address_mapping']) ? $email['extra']['from_address_mapping'] : NULL;
314
    $email['from'] = webform_format_email_address($email['from_address'], $email['from_name'], $node, $submission, TRUE, TRUE, NULL, $mapping);
315
  }
316

    
317
  // If "Use Reply-To header" is set in Webform settings and the Reply-To
318
  // header is not already set, set Reply-To to the From and set From address
319
  // to webform_default_from_name and webform_default_from_address.
320
  if (webform_variable_get('webform_email_replyto') &&
321
      empty($email['headers']['Reply-To']) &&
322
      ($default_from_name = webform_variable_get('webform_default_from_name')) &&
323
      ($default_from_address = webform_variable_get('webform_default_from_address')) &&
324
      $email['from'] !== $default_from_name) {
325
    $email['headers']['Reply-To'] = $email['from'];
326
    $email['from'] = $default_from_address;
327
    if (webform_variable_get('webform_email_address_format') == 'long') {
328
      $email_parts = webform_parse_email_address($email['headers']['Reply-To']);
329
      $from_name = t('!name via !site_name',
330
                      array(
331
                        '!name' => strlen($email_parts['name']) ? $email_parts['name'] : $email_parts['address'],
332
                        '!site_name' => $default_from_name,
333
                      ));
334
      $from_name = str_replace('"', "'", $from_name);
335
      $from_name = implode(' ', array_map('mime_header_encode', explode(' ', $from_name)));
336
      $email['from'] = '"' . $from_name . '" <' . $email['from'] . '>';
337
    }
338
  }
339

    
340
  // Update the subject if set in the themed headers.
341
  if (isset($email['headers']['Subject'])) {
342
    $email['subject'] = $email['headers']['Subject'];
343
    unset($email['headers']['Subject']);
344
  }
345
  else {
346
    $email['subject'] = webform_format_email_subject($email['subject'], $node, $submission);
347
  }
348

    
349
  // Update the to e-mail if set in the themed headers.
350
  if (isset($email['headers']['To'])) {
351
    $email['email'] = $email['headers']['To'];
352
    unset($email['headers']['To']);
353
    $addresses = array_filter(explode(',', $email['email']));
354
  }
355
  else {
356
    // Format the To address(es).
357
    $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
358
    $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, TRUE, FALSE, NULL, $mapping);
359
    $email['email'] = implode(',', $addresses);
360
  }
361

    
362
  // Generate the list of addresses that this e-mail will be sent to.
363
  $addresses_final = array_filter($addresses, 'webform_valid_email_address');
364

    
365
  if (!$addresses_final) {
366
    return;
367
  }
368

    
369
  // Verify that this submission is not attempting to send any spam hacks.
370
  foreach ($addresses_final as $address) {
371
    if (_webform_submission_spam_check($address, $email['subject'], $email['from'], $email['headers'])) {
372
      watchdog('webform', 'Possible spam attempt from @remote !message',
373
        array('@remote' => ip_address(), '!message' => "<br />\n" . nl2br(htmlentities($email['message']))));
374
      drupal_set_message(t('Illegal information. Data not submitted.'), 'error');
375
      return;
376
    }
377
  }
378

    
379
  // Consolidate addressees into one message if permitted by configuration.
380
  $send_increment = 1;
381
  if (!webform_variable_get('webform_email_address_individual')) {
382
    $send_increment = count($addresses_final);
383
    $addresses_final = array(implode(', ', $addresses_final));
384
  }
385

    
386
  // Prepare the variables used by drupal_mail().
387
  $language = $user->uid ? user_preferred_language($user) : language_default();
388
  $mail_params = array(
389
    'message' => $email['message'],
390
    'subject' => $email['subject'],
391
    'headers' => $email['headers'],
392
    'node' => $node,
393
    'submission' => $submission,
394
    'email' => $email,
395
  );
396

    
397
  if (webform_variable_get('webform_email_html_capable')) {
398
    // Load attachments for the e-mail.
399
    $attachments = array();
400
    if ($email['attachments']) {
401
      webform_component_include('file');
402
      foreach ($node->webform['components'] as $component) {
403
        if (webform_component_feature($component['type'], 'attachment') && !empty($submission->data[$component['cid']][0])) {
404
          if (webform_component_implements($component['type'], 'attachments')) {
405
            $files = webform_component_invoke($component['type'], 'attachments', $component, $submission->data[$component['cid']]);
406
            if ($files) {
407
              $attachments = array_merge($attachments, $files);
408
            }
409
          }
410
        }
411
      }
412
    }
413

    
414
    // Add the attachments to the mail parameters.
415
    $mail_params['attachments'] = $attachments;
416

    
417
    // Set all other properties for HTML e-mail handling.
418
    $mail_params['plain'] = !$email['html'];
419
    $mail_params['plaintext'] = $email['html'] ? NULL : $email['message'];
420
    $mail_params['headers'] = $email['headers'];
421
    if ($email['html']) {
422
      // MIME Mail requires this header or it will filter all text.
423
      $mail_params['headers']['Content-Type'] = 'text/html; charset=UTF-8';
424
    }
425
  }
426

    
427
  return array(
428
    'addresses_final' => $addresses_final,
429
    'send_increment' => $send_increment,
430
    'language' => $language,
431
    'mail_params' => $mail_params,
432
  );
433
}
434

    
435
/**
436
 * Confirm form to delete a single form submission.
437
 *
438
 * @param $form
439
 *   The new form array.
440
 * @param $form_state
441
 *   The current form state.
442
 * @param $node
443
 *   The node for which this webform was submitted.
444
 * @param $submission
445
 *   The submission to be deleted (from webform_submitted_data).
446
 */
447
function webform_submission_delete_form($form, $form_state, $node, $submission) {
448
  webform_set_breadcrumb($node, $submission);
449

    
450
  // Set the correct page title.
451
  drupal_set_title(webform_submission_title($node, $submission));
452

    
453
  // Keep the NID and SID in the same location as the webform_client_form().
454
  $form['#tree'] = TRUE;
455
  $form['details']['nid'] = array(
456
    '#type' => 'value',
457
    '#value' => $node->nid,
458
  );
459
  $form['details']['sid'] = array(
460
    '#type' => 'value',
461
    '#value' => $submission->sid,
462
  );
463

    
464
  $question = t('Are you sure you want to delete this submission?');
465

    
466
  return confirm_form($form, NULL, "node/{$node->nid}/submission/{$submission->sid}", $question, t('Delete'), t('Cancel'));
467
}
468

    
469
/**
470
 * Form submit handler.
471
 */
472
function webform_submission_delete_form_submit($form, &$form_state) {
473
  $node = node_load($form_state['values']['details']['nid']);
474
  $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
475
  webform_submission_delete($node, $submission);
476
  drupal_set_message(t('Submission deleted.'));
477

    
478
  // If no destination query was supplied in the URL (for example, Edit tab),
479
  // redirect to the most-privledged destination.
480
  $form_state['redirect'] = 'node/' . $node->nid .
481
                            (webform_results_access($node) ? '/webform-results' : '/submissions');
482
}
483

    
484
/**
485
 * Menu title callback; Return the submission number as a title.
486
 */
487
function webform_submission_title($node, $submission) {
488
  return t('Submission #@serial', array('@serial' => $submission->serial));
489
}
490

    
491
/**
492
 * Menu callback; Present a Webform submission page for display or editing.
493
 */
494
function webform_submission_page($node, $submission, $format) {
495
  global $user;
496

    
497
  // Render the admin UI breadcrumb.
498
  webform_set_breadcrumb($node, $submission);
499

    
500
  // Set the correct page title.
501
  drupal_set_title(webform_submission_title($node, $submission));
502

    
503
  if ($format == 'form') {
504
    $output = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission);
505
  }
506
  else {
507
    $renderable = webform_submission_render($node, $submission, NULL, $format);
508
    $renderable['#attached']['css'][] = drupal_get_path('module', 'webform') . '/css/webform.css';
509
    $output = drupal_render($renderable);
510
  }
511

    
512
  // Determine the mode in which we're displaying this submission.
513
  $mode = ($format != 'form') ? 'display' : 'form';
514
  if (strpos(request_path(), 'print/') !== FALSE) {
515
    $mode = 'print';
516
  }
517
  if (strpos(request_path(), 'printpdf/') !== FALSE) {
518
    $mode = 'pdf';
519
  }
520

    
521
  // Add navigation for administrators.
522
  if (webform_results_access($node)) {
523
    $navigation = theme('webform_submission_navigation', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
524
    $information = theme('webform_submission_information', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
525
  }
526
  else {
527
    $navigation = NULL;
528
    $information = NULL;
529
  }
530

    
531
  // Actions may be shown to all users.
532
  $actions = theme('links', array('links' => module_invoke_all('webform_submission_actions', $node, $submission), 'attributes' => array('class' => array('links', 'inline', 'webform-submission-actions'))));
533

    
534
  // Disable the page cache for anonymous users viewing or editing submissions.
535
  if (!$user->uid) {
536
    webform_disable_page_cache();
537
  }
538

    
539
  $page = array(
540
    '#theme' => 'webform_submission_page',
541
    '#node' => $node,
542
    '#mode' => $mode,
543
    '#submission' => $submission,
544
    '#submission_content' => $output,
545
    '#submission_navigation' => $navigation,
546
    '#submission_information' => $information,
547
    '#submission_actions' => $actions,
548
  );
549
  $page['#attached']['library'][] = array('webform', 'admin');
550
  return $page;
551
}
552

    
553
/**
554
 * Form to resend specific e-mails associated with a submission.
555
 */
556
function webform_submission_resend($form, $form_state, $node, $submission) {
557
  // Render the admin UI breadcrumb.
558
  webform_set_breadcrumb($node, $submission);
559

    
560
  $form['#tree'] = TRUE;
561
  $form['#node'] = $node;
562
  $form['#submission'] = $submission;
563

    
564
  foreach ($node->webform['emails'] as $eid => $email) {
565

    
566
    $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
567
    $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, FALSE, FALSE, NULL, $mapping);
568
    $addresses_valid = array_map('webform_valid_email_address', $addresses);
569
    $valid_email = count($addresses) == array_sum($addresses_valid);
570

    
571
    $form['resend'][$eid] = array(
572
      '#type' => 'checkbox',
573
      '#default_value' => $valid_email && $email['status'],
574
      '#disabled' => !$valid_email,
575
    );
576
    $form['emails'][$eid]['email'] = array(
577
      '#markup' => nl2br(check_plain(implode("\n", $addresses))),
578
    );
579
    if (!$valid_email) {
580
      $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty or invalid') . ')';
581
    }
582
    $form['emails'][$eid]['subject'] = array(
583
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
584
    );
585

    
586
    $form['actions'] = array('#type' => 'actions');
587
    $form['actions']['submit'] = array(
588
      '#type' => 'submit',
589
      '#value' => t('Resend e-mails'),
590
    );
591
    $form['actions']['cancel'] = array(
592
      '#type' => 'markup',
593
      '#markup' => l(t('Cancel'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/submission/' . $submission->sid),
594
    );
595
  }
596
  return $form;
597
}
598

    
599
/**
600
 * Validate handler for webform_submission_resend().
601
 */
602
function webform_submission_resend_validate($form, &$form_state) {
603
  if (count(array_filter($form_state['values']['resend'])) == 0) {
604
    form_set_error('emails', t('You must select at least one email address to resend submission.'));
605
  }
606
}
607

    
608
/**
609
 * Submit handler for webform_submission_resend().
610
 */
611
function webform_submission_resend_submit($form, &$form_state) {
612
  $node = $form['#node'];
613
  $submission = $form['#submission'];
614

    
615
  $emails = array();
616
  foreach ($form_state['values']['resend'] as $eid => $checked) {
617
    if ($checked) {
618
      $emails[] = $form['#node']->webform['emails'][$eid];
619
    }
620
  }
621
  $sent_count = webform_submission_send_mail($node, $submission, $emails, TRUE);
622
  if ($sent_count) {
623
    drupal_set_message(format_plural($sent_count,
624
      'Successfully re-sent submission #@sid to 1 recipient.',
625
      'Successfully re-sent submission #@sid to @count recipients.',
626
      array('@sid' => $submission->sid)
627
    ));
628
  }
629
  else {
630
    drupal_set_message(t('No e-mails were able to be sent due to a server error.'), 'error');
631
  }
632
}
633

    
634
/**
635
 * Theme the node components form. Use a table to organize the components.
636
 *
637
 * @param array $variables
638
 *   Array with key "form" containing the form array.
639
 *
640
 * @return string
641
 *   Formatted HTML form, ready for display.
642
 *
643
 * @throws Exception
644
 */
645
function theme_webform_submission_resend(array $variables) {
646
  $form = $variables['form'];
647

    
648
  $header = array(t('Send'), t('E-mail to'), t('Subject'));
649
  $rows = array();
650
  if (!empty($form['emails'])) {
651
    foreach (element_children($form['emails']) as $eid) {
652
      // Add each component to a table row.
653
      $rows[] = array(
654
        drupal_render($form['resend'][$eid]),
655
        drupal_render($form['emails'][$eid]['email']),
656
        drupal_render($form['emails'][$eid]['subject']),
657
      );
658
    }
659
  }
660
  else {
661
    $rows[] = array(array('data' => t('This webform is currently not setup to send emails.'), 'colspan' => 3));
662
  }
663
  $output = '';
664
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('id' => 'webform-emails')));
665
  $output .= drupal_render_children($form);
666
  return $output;
667
}
668

    
669
/**
670
 * Prepare a Webform submission for display on a page or in an e-mail.
671
 *
672
 * @param object $node
673
 *   The node object.
674
 * @param object $submission
675
 *   The submission object.
676
 * @param array $email
677
 *   The email configuration array.
678
 * @param string $format
679
 *   The format the form should be displayed as. May be one of the following:
680
 *   - form: Show as an editable form.
681
 *   - html: Show as HTML results.
682
 *   - text: Show as plain text.
683
 * @param array $excluded_components
684
 *   An array of components to exclude as cid.
685
 *
686
 * @return array
687
 *   A renderable array of the submission.
688
 */
689
function webform_submission_render($node, $submission, $email, $format, $excluded_components = NULL) {
690
  $component_tree = array();
691
  $renderable = array();
692
  $page_count = 1;
693

    
694
  // Meta data that may be useful for modules implementing
695
  // hook_webform_submission_render_alter().
696
  $renderable['#node'] = $node;
697
  $renderable['#submission'] = $submission;
698
  $renderable['#email'] = $email;
699
  $renderable['#format'] = $format;
700

    
701
  // Set the theme function for submissions.
702
  $renderable['#theme'] = array('webform_submission_' . $node->nid, 'webform_submission');
703

    
704
  $components = $node->webform['components'];
705

    
706
  // Remove excluded components.
707
  if (is_array($excluded_components)) {
708
    foreach ($excluded_components as $cid) {
709
      unset($components[$cid]);
710
    }
711
    if (!empty($email['exclude_empty'])) {
712
      foreach ($submission->data as $cid => $data) {
713
        // Caution. Grids store their data in an array index by question key.
714
        if (implode($data) == '') {
715
          unset($components[$cid]);
716
        }
717
      }
718
    }
719
  }
720

    
721
  module_load_include('inc', 'webform', 'includes/webform.components');
722
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
723

    
724
  // Make sure at least one field is available.
725
  if (isset($component_tree['children'])) {
726
    // Recursively add components to the form.
727
    $sorter = webform_get_conditional_sorter($node);
728
    $input_values = $sorter->executeConditionals($submission->data);
729
    foreach ($component_tree['children'] as $cid => $component) {
730
      if ($sorter->componentVisibility($cid, $component['page_num']) == webformConditionals::componentShown) {
731
        _webform_client_form_add_component($node, $component, NULL, $renderable, $renderable, $input_values, $format);
732
      }
733
    }
734
  }
735

    
736
  drupal_alter('webform_submission_render', $renderable);
737
  return $renderable;
738
}
739

    
740
/**
741
 * Return all the submissions for a particular node.
742
 *
743
 * @param $filters
744
 *   An array of filters to apply to this query. Usually in the format
745
 *   array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
746
 *   in, which will be equivalent to specifying a $nid filter.
747
 * @param $header
748
 *   If the results of this fetch will be used in a sortable
749
 *   table, pass the array header of the table.
750
 * @param $pager_count
751
 *   Optional. The number of submissions to include in the results.
752
 *
753
 * @return array
754
 *   Array of submission data for a particular node.
755
 */
756
function webform_get_submissions($filters = array(), $header = NULL, $pager_count = 0) {
757
  return webform_get_submissions_load(webform_get_submissions_query($filters, $header, $pager_count));
758
}
759

    
760
/**
761
 * Returns an unexecuted webform_submissions query on for the arguments.
762
 *
763
 * This is an internal routine and not intended for use by other modules.
764
 *
765
 * @param $filters
766
 *   An array of filters to apply to this query. Usually in the format
767
 *   array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
768
 *   in, which will be equivalent to specifying a $nid filter. 'sid' may also
769
 *   be included, either as a single sid or an array of sid's.
770
 * @param $header
771
 *   If the results of this fetch will be used in a sortable
772
 *   table, pass the array header of the table.
773
 * @param $pager_count
774
 *   Optional. The number of submissions to include in the results.
775
 *
776
 * @return QueryExtendableInterface|SelectQueryInterface
777
 *   The query object.
778
 */
779
function webform_get_submissions_query($filters = array(), $header = NULL, $pager_count = 0) {
780
  if (!is_array($filters)) {
781
    $filters = array('ws.nid' => $filters);
782
  }
783

    
784
  // Qualify all filters with a table alias. ws.* is assumed, except for u.uid.
785
  foreach ($filters as $column => $value) {
786
    if (strpos($column, '.') === FALSE) {
787
      $filters[($column == 'uid' ? 'u.' : 'ws.') . $column] = $value;
788
      unset($filters[$column]);
789
    }
790
  }
791

    
792
  // If the sid is specified, but there are none, force the query to fail
793
  // rather than query on an empty array.
794
  if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
795
    $filters['ws.sid'] = 0;
796
  }
797

    
798
  // Build the list of submissions and load their basic information.
799
  $pager_query = db_select('webform_submissions', 'ws')
800
    // Ensure only one row per submission is returned. Could be more than one if
801
    // sorting on a column that uses multiple rows for its data.
802
    ->distinct()
803
    ->addTag('webform_get_submissions_sids')
804
    ->fields('ws');
805

    
806
  // Add each filter.
807
  foreach ($filters as $column => $value) {
808
    $pager_query->condition($column, $value);
809
  }
810

    
811
  // Join to the users table to include user name in results.
812
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
813
  $pager_query->fields('u', array('name'));
814
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
815
    if (!empty($_SESSION['webform_submission'])) {
816
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
817
      $pager_query->condition('ws.sid', $anonymous_sids, 'IN');
818
    }
819
    else {
820
      $pager_query->condition('ws.sid', 0);
821
    }
822
  }
823

    
824
  if (is_array($header)) {
825
    $metadata_columns = array();
826
    foreach ($header as $header_item) {
827
      $metadata_columns[] = $header_item['data'];
828
    }
829
    $sort = drupal_get_query_parameters();
830
    // Sort by submitted data column if order is set but not in
831
    // $metadata_columns.
832
    if (isset($sort['order']) && !in_array($sort['order'], $metadata_columns, TRUE)) {
833
      // Default if sort is unset or invalid.
834
      if (!isset($sort['sort']) || !in_array($sort['sort'], array('asc', 'desc'), TRUE)) {
835
        $sort['sort'] = '';
836
      }
837
      $pager_query->leftJoin('webform_component', 'wc', 'ws.nid = wc.nid AND wc.name = :form_key', array('form_key' => $sort['order']));
838
      $pager_query->leftJoin('webform_submitted_data', 'wsd', 'wc.nid = wsd.nid AND ws.sid = wsd.sid AND wc.cid = wsd.cid');
839
      $pager_query->orderBy('wsd.data', $sort['sort']);
840
      $pager_query->orderBy('ws.sid', 'ASC');
841
    }
842
    // Sort by metadata column.
843
    else {
844
      // Extending the query instantiates a new query object.
845
      $pager_query = $pager_query->extend('TableSort');
846
      $pager_query->orderByHeader($header);
847
    }
848
  }
849
  else {
850
    $pager_query->orderBy('ws.sid', 'ASC');
851
  }
852

    
853
  if ($pager_count) {
854
    // Extending the query instantiates a new query object.
855
    $pager_query = $pager_query->extend('PagerDefault');
856
    $pager_query->limit($pager_count);
857
  }
858
  return $pager_query;
859
}
860

    
861
/**
862
 * Retrieve and load the submissions for the specified submissions query.
863
 *
864
 * This is an internal routine and not intended for use by other modules.
865
 *
866
 * @params object $pager_query
867
 *   A select or extended select query containing the needed fields:
868
 *     webform_submissions: all fields
869
 *     user: name
870
 *
871
 * @return array
872
 *   An array of loaded webform submissions.
873
 */
874
function webform_get_submissions_load($pager_query) {
875
  // If the "$pager_query" is actually an unextended select query, then instead
876
  // of querying the webform_submissions_data table with a potentially huge
877
  // array of sids in an IN clause, use the select query directly as this will
878
  // be much faster. Extended queries don't work in join clauses. The query
879
  // is assumed to include the sid.
880
  if ($pager_query instanceof SelectQuery) {
881
    $submissions_query = clone $pager_query;
882
  }
883

    
884
  // Extract any filter on node id to use in an optimization below.
885
  foreach ($pager_query->conditions() as $index => $condition) {
886
    if ($index !== '#conjunction' && $condition['operator'] === '=' && ($condition['field'] === 'nid' || $condition['field'] === 'ws.nid')) {
887
      $nid = $condition['value'];
888
      break;
889
    }
890
  }
891

    
892
  $result = $pager_query->execute();
893
  $submissions = $result->fetchAllAssoc('sid');
894

    
895
  // If there are no submissions being retrieved, return an empty array.
896
  if (!$submissions) {
897
    return $submissions;
898
  }
899

    
900
  foreach ($submissions as $sid => $submission) {
901
    $submissions[$sid]->preview = FALSE;
902
    $submissions[$sid]->data = array();
903
  }
904

    
905
  // Query the required submission data.
906
  $query = db_select('webform_submitted_data', 'sd');
907
  $query
908
    ->addTag('webform_get_submissions_data')
909
    ->fields('sd', array('sid', 'cid', 'no', 'data'))
910
    ->orderBy('sd.sid', 'ASC')
911
    ->orderBy('sd.cid', 'ASC')
912
    ->orderBy('sd.no', 'ASC');
913

    
914
  if (isset($submissions_query)) {
915
    // If available, prefer joining on the subquery as it is much faster than an
916
    // IN clause on a large array. A subquery with the IN operator doesn't work
917
    // when the subquery has a LIMIT clause, requiring an inner join instead.
918
    $query->innerJoin($submissions_query, 'ws2', 'sd.sid = ws2.sid');
919
  }
920
  else {
921
    $query->condition('sd.sid', array_keys($submissions), 'IN');
922
  }
923

    
924
  // By adding the NID to this query we allow MySQL to use the primary key on
925
  // in webform_submitted_data for sorting (nid_sid_cid_no).
926
  if (isset($nid)) {
927
    $query->condition('sd.nid', $nid);
928
  }
929

    
930
  $result = $query->execute();
931

    
932
  // Convert the queried rows into submission data.
933
  foreach ($result as $row) {
934
    $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
935
  }
936

    
937
  foreach (module_implements('webform_submission_load') as $module) {
938
    $function = $module . '_webform_submission_load';
939
    $function($submissions);
940
  }
941

    
942
  return $submissions;
943
}
944

    
945
/**
946
 * Return a count of the total number of submissions for a node.
947
 *
948
 * @param $nid
949
 *   The node ID for which submissions are being fetched.
950
 * @param $uid
951
 *   Optional; the user ID to filter the submissions by.
952
 * @param $is_draft
953
 *   Optional; NULL for all, truthy for drafts only, falsy for completed only.
954
 *   The default is completed submissions only.
955
 *
956
 * @return int
957
 *   The number of submissions.
958
 */
959
function webform_get_submission_count($nid, $uid = NULL, $is_draft = 0) {
960
  $counts = &drupal_static(__FUNCTION__);
961

    
962
  if (!isset($counts[$nid][$uid])) {
963
    $query = db_select('webform_submissions', 'ws')
964
      ->addTag('webform_get_submission_count')
965
      ->condition('ws.nid', $nid);
966
    if ($uid !== NULL) {
967
      $query->condition('ws.uid', $uid);
968
    }
969
    if ($uid === 0) {
970
      $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
971
      if ($submissions) {
972
        $query->condition('ws.sid', array_keys($submissions), 'IN');
973
      }
974
      else {
975
        // Intentionally never match anything if the anonymous user has no
976
        // submissions.
977
        $query->condition('ws.sid', 0);
978
      }
979
    }
980
    if (isset($is_draft)) {
981
      $query->condition('ws.is_draft', $is_draft);
982
    }
983

    
984
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
985
  }
986
  return $counts[$nid][$uid];
987
}
988

    
989
/**
990
 * Fetch a specified submission for a webform node.
991
 */
992
function webform_get_submission($nid, $sid) {
993
  $submissions = &drupal_static(__FUNCTION__, array());
994

    
995
  // Load the submission if needed.
996
  if (!isset($submissions[$sid])) {
997
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
998
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
999
  }
1000

    
1001
  return $submissions[$sid];
1002
}
1003

    
1004
/**
1005
 * Verify that an email is not attempting to send any spam.
1006
 */
1007
function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
1008
  $headers = implode('\n', (array) $headers);
1009
  // Check if they are attempting to spam using a bcc or content type hack.
1010
  if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
1011
    // Possible spam attempt.
1012
    return TRUE;
1013
  }
1014
  // Not spam.
1015
  return FALSE;
1016
}
1017

    
1018
/**
1019
 * Check if the current user has exceeded the limit on this form.
1020
 *
1021
 * @param $node
1022
 *   The webform node to be checked.
1023
 * @param $account
1024
 *   Optional parameter. Specify the account you want to check the limit
1025
 *   against.
1026
 *
1027
 * @return bool
1028
 *   Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
1029
 */
1030
function webform_submission_user_limit_check($node, $account = NULL) {
1031
  global $user;
1032
  $tracking_mode = webform_variable_get('webform_tracking_mode');
1033

    
1034
  if (!isset($account)) {
1035
    $account = $user;
1036
  }
1037

    
1038
  // We can only check access for anonymous users through their cookies.
1039
  if ($user->uid !== 0 && $account->uid === 0) {
1040
    watchdog('webform', 'Unable to check anonymous user submission limit when logged in as user @uid.', array('@uid' => $user->uid), WATCHDOG_WARNING);
1041
    return FALSE;
1042
  }
1043

    
1044
  // Check if submission limiting is enabled.
1045
  if ($node->webform['submit_limit'] == '-1') {
1046
    // No check enabled.
1047
    return FALSE;
1048
  }
1049

    
1050
  // Fetch all the entries from the database within the submit interval with
1051
  // this username and IP.
1052
  $num_submissions_database = 0;
1053
  if (!$node->webform['confidential'] &&
1054
      ($account->uid !== 0 || $tracking_mode === 'ip_address' || $tracking_mode === 'strict')) {
1055
    $query = db_select('webform_submissions')
1056
      ->addTag('webform_submission_user_limit_check')
1057
      ->condition('nid', $node->nid)
1058
      ->condition('is_draft', 0);
1059

    
1060
    if ($node->webform['submit_interval'] != -1) {
1061
      $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
1062
    }
1063

    
1064
    if ($account->uid) {
1065
      $query->condition('uid', $account->uid);
1066
    }
1067
    else {
1068
      $query->condition('remote_addr', ip_address());
1069
    }
1070
    $num_submissions_database = $query->countQuery()->execute()->fetchField();
1071
  }
1072

    
1073
  // Double check the submission history from the users machine using cookies.
1074
  $num_submissions_cookie = 0;
1075
  if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
1076
    $cookie_name = 'webform-' . $node->nid;
1077

    
1078
    if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
1079
      foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
1080
        if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
1081
          // Remove the cookie if past the required time interval.
1082
          $params = session_get_cookie_params();
1083
          setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1084
        }
1085
      }
1086
      // Count the number of submissions recorded in cookies.
1087
      $num_submissions_cookie = count($_COOKIE[$cookie_name]);
1088
    }
1089
  }
1090

    
1091
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
1092
    // Limit exceeded.
1093
    return TRUE;
1094
  }
1095

    
1096
  // Limit not exceeded.
1097
  return FALSE;
1098
}
1099

    
1100
/**
1101
 * Check if the total number of submissions has exceeded the limit on this form.
1102
 *
1103
 * @param $node
1104
 *   The webform node to be checked.
1105
 *
1106
 * @return bool
1107
 *   Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
1108
 */
1109
function webform_submission_total_limit_check($node) {
1110

    
1111
  // Check if submission limiting is enabled.
1112
  if ($node->webform['total_submit_limit'] == '-1') {
1113
    // No check enabled.
1114
    return FALSE;
1115
  }
1116

    
1117
  // Retrieve submission data from the database.
1118
  $query = db_select('webform_submissions')
1119
    ->addTag('webform_submission_total_limit_check')
1120
    ->condition('nid', $node->nid)
1121
    ->condition('is_draft', 0);
1122

    
1123
  if ($node->webform['total_submit_interval'] != -1) {
1124
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
1125
  }
1126

    
1127
  // Fetch all the entries from the database within the submit interval.
1128
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
1129

    
1130
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
1131
    // Limit exceeded.
1132
    return TRUE;
1133
  }
1134

    
1135
  // Limit not exceeded.
1136
  return FALSE;
1137
}
1138

    
1139
/**
1140
 * Preprocess function for webform-submission.tpl.php.
1141
 */
1142
function template_preprocess_webform_submission(&$vars) {
1143
  $vars['node'] = $vars['renderable']['#node'];
1144
  $vars['submission'] = $vars['renderable']['#submission'];
1145
  $vars['email'] = $vars['renderable']['#email'];
1146
  $vars['format'] = $vars['renderable']['#format'];
1147
}
1148

    
1149
/**
1150
 * Preprocess function for webform-submission-navigation.tpl.php.
1151
 */
1152
function template_preprocess_webform_submission_navigation(&$vars) {
1153
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
1154

    
1155
  $previous_query = db_select('webform_submissions')
1156
    ->condition('nid', $vars['node']->nid)
1157
    ->condition('sid', $vars['submission']->sid, '<');
1158
  $previous_query->addExpression('MAX(sid)');
1159

    
1160
  $next_query = db_select('webform_submissions')
1161
    ->condition('nid', $vars['node']->nid)
1162
    ->condition('sid', $vars['submission']->sid, '>');
1163
  $next_query->addExpression('MIN(sid)');
1164

    
1165
  $vars['previous'] = $previous_query->execute()->fetchField();
1166
  $vars['next'] = $next_query->execute()->fetchField();
1167
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
1168
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
1169
}
1170

    
1171
/**
1172
 * Preprocess function for webform-submission-navigation.tpl.php.
1173
 */
1174
function template_preprocess_webform_submission_information(&$vars) {
1175
  $vars['account'] = user_load($vars['submission']->uid);
1176
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
1177
}