Projet

Général

Profil

Paste
Télécharger (38,6 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

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

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

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

    
30
    if (is_array($values)) {
31
      $data[$cid] = $values;
32
    }
33
    else {
34
      $data[$cid][0] = $values;
35
    }
36
  }
37

    
38
  return $data;
39
}
40

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

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

    
99
  $submission->completed = empty($submission->completed) && !$submission->is_draft ? REQUEST_TIME : $submission->completed;
100
  $submission->modified = REQUEST_TIME;
101

    
102
  // Update the main submission info.
103
  drupal_write_record('webform_submissions', $submission, 'sid');
104

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

    
122
  // Then re-add submission data to the database.
123
  $submission->is_new = FALSE;
124
  webform_submission_insert($node, $submission);
125

    
126
  module_invoke_all('webform_submission_update', $node, $submission);
127

    
128
  return $submission->sid;
129
}
130

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

    
158
  foreach ($submission->data as $cid => $values) {
159
    foreach ($values as $delta => $value) {
160
      $data = array(
161
        'nid' => $node->webform['nid'],
162
        'sid' => $submission->sid,
163
        'cid' => $cid,
164
        'no' => $delta,
165
        'data' => is_null($value) ? '' : $value,
166
      );
167
      drupal_write_record('webform_submitted_data', $data);
168
    }
169
  }
170

    
171
  // Invoke the insert hook after saving all the data.
172
  if (isset($is_new)) {
173
    module_invoke_all('webform_submission_insert', $node, $submission);
174
  }
175

    
176
  return $submission->sid;
177
}
178

    
179
/**
180
 * Delete a single submission.
181
 *
182
 * @param $node
183
 *   The node object containing the current webform.
184
 * @param $submission
185
 *   The webform submission object to be deleted from the database.
186
 */
187
function webform_submission_delete($node, $submission) {
188
  // Iterate through all components and let each do cleanup if necessary.
189
  foreach ($node->webform['components'] as $cid => $component) {
190
    if (isset($submission->data[$cid])) {
191
      webform_component_invoke($component['type'], 'delete', $component, $submission->data[$cid]);
192
    }
193
  }
194

    
195
  // Delete any anonymous session information.
196
  if (isset($_SESSION['webform_submission'][$submission->sid])) {
197
    unset($_SESSION['webform_submission'][$submission->sid]);
198
  }
199

    
200
  db_delete('webform_submitted_data')
201
    ->condition('nid', $node->nid)
202
    ->condition('sid', $submission->sid)
203
    ->execute();
204
  db_delete('webform_submissions')
205
    ->condition('nid', $node->nid)
206
    ->condition('sid', $submission->sid)
207
    ->execute();
208

    
209
  module_invoke_all('webform_submission_delete', $node, $submission);
210
}
211

    
212
/**
213
 * Send related e-mails related to a submission.
214
 *
215
 * This function is usually invoked when a submission is completed, but may be
216
 * called any time e-mails should be redelivered.
217
 *
218
 * @param $node
219
 *   The node object containing the current webform.
220
 * @param $submission
221
 *   The webform submission object to be used in sending e-mails.
222
 * @param $emails
223
 *   (optional) An array of specific e-mail settings to be used. If omitted, all
224
 *   e-mails in $node->webform['emails'] will be sent.
225
 */
226
function webform_submission_send_mail($node, $submission, $emails = NULL) {
227
  global $user;
228

    
229
  // Get the list of e-mails we'll be sending.
230
  $emails = isset($emails) ? $emails : $node->webform['emails'];
231

    
232
  // Create a themed message for mailing.
233
  $send_count = 0;
234
  foreach ($emails as $eid => $email) {
235
    // Continue with next email recipients array if disabled for current.
236
    if (!$email['status'])
237
      continue;
238

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

    
242
    // Pass through the theme layer if using the default template.
243
    if ($email['template'] == 'default') {
244
      $email['message'] = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'submission' => $submission, 'email' => $email));
245
    }
246
    else {
247
      $email['message'] = $email['template'];
248
    }
249

    
250
    // Replace tokens in the message.
251
    $email['message'] = webform_replace_tokens($email['message'], $node, $submission, $email, (boolean)$email['html']);
252

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

    
256
    // Assemble the From string.
257
    if (isset($email['headers']['From'])) {
258
      // If a header From is already set, don't override it.
259
      $email['from'] = $email['headers']['From'];
260
      unset($email['headers']['From']);
261
    }
262
    else {
263
      // Format the From address.
264
      $mapping = isset($email['extra']['from_address_mapping']) ?  $email['extra']['from_address_mapping'] : NULL;
265
      $email['from'] = webform_format_email_address($email['from_address'], $email['from_name'], $node, $submission, TRUE, TRUE, NULL, $mapping);
266
    }
267

    
268
    // If requested and not already set, set Reply-To to the From and re-format From address.
269
    if (webform_variable_get('webform_email_replyto') &&
270
        empty($email['headers']['Reply-To']) &&
271
        ($default_from_name = webform_variable_get('webform_default_from_name')) &&
272
        ($default_from_address = webform_variable_get('webform_default_from_address')) &&
273
        ($default_from_parts = explode('@', $default_from_address)) &&
274
        count($default_from_parts) == 2 &&
275
        $default_from_parts[1] &&
276
        stripos($email['from'], '@' . $default_from_parts[1]) === FALSE) {
277
      // Message is not already being sent from the domain of the default
278
      // webform from address.
279
      $email['headers']['Reply-To'] = $email['from'];
280
      $email['from'] = $default_from_address;
281
      if (webform_variable_get('webform_email_address_format') == 'long') {
282
        $email_parts = webform_parse_email_address($email['headers']['Reply-To']);
283
        $from_name = t('!name via !site_name',
284
                        array('!name' => strlen($email_parts['name']) ? $email_parts['name'] : $email_parts['address'],
285
                              '!site_name' => $default_from_name));
286
        $from_name = implode(' ', array_map('mime_header_encode', explode(' ', $from_name)));
287
        $email['from'] = '"' . $from_name . '" <' . $email['from'] . '>';
288
      }
289
    }
290

    
291
    // Update the subject if set in the themed headers.
292
    if (isset($email['headers']['Subject'])) {
293
      $email['subject'] = $email['headers']['Subject'];
294
      unset($email['headers']['Subject']);
295
    }
296
    else {
297
      $email['subject'] = webform_format_email_subject($email['subject'], $node, $submission);
298
    }
299

    
300
    // Update the to e-mail if set in the themed headers.
301
    if (isset($email['headers']['To'])) {
302
      $email['email'] = $email['headers']['To'];
303
      unset($email['headers']['To']);
304
      $addresses = array_filter(explode(',', $email['email']));
305
    }
306
    else {
307
      // Format the To address(es).
308
      $mapping = isset($email['extra']['email_mapping']) ?  $email['extra']['email_mapping'] : NULL;
309
      $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, TRUE, FALSE, NULL, $mapping);
310
      $email['email'] = implode(',', $addresses);
311
    }
312

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

    
316
    if (!$addresses_final) {
317
      continue;
318
    }
319

    
320
    // Verify that this submission is not attempting to send any spam hacks.
321
    foreach ($addresses_final as $address) {
322
      if (_webform_submission_spam_check($address, $email['subject'], $email['from'], $email['headers'])) {
323
        watchdog('webform', 'Possible spam attempt from @remote !message',
324
                 array('@remote' => ip_address(), '!message'=> "<br />\n" . nl2br(htmlentities($email['message']))));
325
        drupal_set_message(t('Illegal information. Data not submitted.'), 'error');
326
        return FALSE;
327
      }
328
    }
329

    
330
    // Consolidate addressees into one message if permitted by configuration.
331
    $send_increment = 1;
332
    if (!webform_variable_get('webform_email_address_individual')) {
333
      $send_increment = count($addresses_final);
334
      $addresses_final = array(implode(', ', $addresses_final));
335
    }
336

    
337
    // Mail the webform results.
338
    foreach ($addresses_final as $address) {
339

    
340
      $language = $user->uid ? user_preferred_language($user) : language_default();
341
      $mail_params = array(
342
        'message' => $email['message'],
343
        'subject' => $email['subject'],
344
        'headers' => $email['headers'],
345
        'node' => $node,
346
        'submission' => $submission,
347
        'email' => $email,
348
      );
349

    
350
      if (webform_variable_get('webform_email_html_capable')) {
351
        // Load attachments for the e-mail.
352
        $attachments = array();
353
        if ($email['attachments']) {
354
          webform_component_include('file');
355
          foreach ($node->webform['components'] as $component) {
356
            if (webform_component_feature($component['type'], 'attachment') && !empty($submission->data[$component['cid']][0])) {
357
              if (webform_component_implements($component['type'], 'attachments')) {
358
                $files = webform_component_invoke($component['type'], 'attachments', $component, $submission->data[$component['cid']]);
359
                if ($files) {
360
                  $attachments = array_merge($attachments, $files);
361
                }
362
              }
363
            }
364
          }
365
        }
366

    
367
        // Add the attachments to the mail parameters.
368
        $mail_params['attachments'] = $attachments;
369

    
370
        // Set all other properties for HTML e-mail handling.
371
        $mail_params['plain'] = !$email['html'];
372
        $mail_params['plaintext'] = $email['html'] ? NULL : $email['message'];
373
        $mail_params['headers'] = $email['headers'];
374
        if ($email['html']) {
375
          // MIME Mail requires this header or it will filter all text.
376
          $mail_params['headers']['Content-Type'] = 'text/html; charset=UTF-8';
377
        }
378
      }
379

    
380
      // Mail the submission.
381
      $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
382
      if ($message['result']) {
383
        $send_count += $send_increment;
384
      }
385
    }
386
  }
387

    
388
  return $send_count;
389
}
390

    
391
/**
392
 * Confirm form to delete a single form submission.
393
 *
394
 * @param $form
395
 *   The new form array.
396
 * @param $form_state
397
 *   The current form state.
398
 * @param $node
399
 *   The node for which this webform was submitted.
400
 * @param $submission
401
 *   The submission to be deleted (from webform_submitted_data).
402
 */
403
function webform_submission_delete_form($form, $form_state, $node, $submission) {
404
  webform_set_breadcrumb($node, $submission);
405

    
406
  // Set the correct page title.
407
  drupal_set_title(webform_submission_title($node, $submission));
408

    
409
  // Keep the NID and SID in the same location as the webform_client_form().
410
  // This helps mollom identify the same fields when deleting a submission.
411
  $form['#tree'] = TRUE;
412
  $form['details']['nid'] = array(
413
    '#type' => 'value',
414
    '#value' => $node->nid,
415
  );
416
  $form['details']['sid'] = array(
417
    '#type' => 'value',
418
    '#value' => $submission->sid,
419
  );
420

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

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

    
426
function webform_submission_delete_form_submit($form, &$form_state) {
427
  $node = node_load($form_state['values']['details']['nid']);
428
  $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
429
  webform_submission_delete($node, $submission);
430
  drupal_set_message(t('Submission deleted.'));
431

    
432
  // If no destination query was supplied in the URL (e.g. Edit tab), redirect
433
  // to the most-privledged destination.
434
  $form_state['redirect'] = 'node/' . $node->nid .
435
                            (webform_results_access($node) ? '/webform-results' : '/submissions');
436
}
437

    
438
/**
439
 * Menu title callback; Return the submission number as a title.
440
 */
441
function webform_submission_title($node, $submission) {
442
  return t('Submission #@serial', array('@serial' => $submission->serial));
443
}
444

    
445
/**
446
 * Menu callback; Present a Webform submission page for display or editing.
447
 */
448
function webform_submission_page($node, $submission, $format) {
449
  global $user;
450

    
451
  // Render the admin UI breadcrumb.
452
  webform_set_breadcrumb($node, $submission);
453

    
454
  // Set the correct page title.
455
  drupal_set_title(webform_submission_title($node, $submission));
456

    
457
  if ($format == 'form') {
458
    $output = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission);
459
  }
460
  else {
461
    $renderable = webform_submission_render($node, $submission, NULL, $format);
462
    $renderable['#attached']['css'][] = drupal_get_path('module', 'webform') . '/css/webform.css';
463
    $output = drupal_render($renderable);
464
  }
465

    
466
  // Determine the mode in which we're displaying this submission.
467
  $mode = ($format != 'form') ? 'display' : 'form';
468
  if (strpos(request_uri(), 'print/') !== FALSE) {
469
    $mode = 'print';
470
  }
471
  if (strpos(request_uri(), 'printpdf/') !== FALSE) {
472
    $mode = 'pdf';
473
  }
474

    
475
  // Add navigation for administrators.
476
  if (webform_results_access($node)) {
477
    $navigation = theme('webform_submission_navigation', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
478
    $information = theme('webform_submission_information', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
479
  }
480
  else {
481
    $navigation = NULL;
482
    $information = NULL;
483
  }
484

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

    
488
  // Disable the page cache for anonymous users viewing or editing submissions.
489
  if (!$user->uid) {
490
    webform_disable_page_cache();
491
  }
492

    
493
  $page = array(
494
    '#theme' => 'webform_submission_page',
495
    '#node' => $node,
496
    '#mode' => $mode,
497
    '#submission' => $submission,
498
    '#submission_content' => $output,
499
    '#submission_navigation' => $navigation,
500
    '#submission_information' => $information,
501
    '#submission_actions' => $actions,
502
  );
503
  $page['#attached']['library'][] = array('webform', 'admin');
504
  return $page;
505
}
506

    
507
/**
508
 * Form to resend specific e-mails associated with a submission.
509
 */
510
function webform_submission_resend($form, $form_state, $node, $submission) {
511
  // Render the admin UI breadcrumb.
512
  webform_set_breadcrumb($node, $submission);
513

    
514
  $form['#tree'] = TRUE;
515
  $form['#node'] = $node;
516
  $form['#submission'] = $submission;
517

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

    
520
    $mapping = isset($email['extra']['email_mapping']) ?  $email['extra']['email_mapping'] : NULL;
521
    $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, FALSE, FALSE, NULL, $mapping);
522
    $addresses_valid = array_map('webform_valid_email_address', $addresses);
523
    $valid_email = count($addresses) == array_sum($addresses_valid);
524
    
525
    $form['resend'][$eid] = array(
526
      '#type' => 'checkbox',
527
      '#default_value' => $valid_email && $email['status'],
528
      '#disabled' => !$valid_email,
529
    );
530
    $form['emails'][$eid]['email'] = array(
531
      '#markup' => nl2br(check_plain(implode("\n", $addresses))),
532
    );
533
    if (!$valid_email) {
534
      $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty or invalid') . ')';
535
    }
536
    $form['emails'][$eid]['subject'] = array(
537
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
538
    );
539

    
540
    $form['actions'] = array('#type' => 'actions');
541
    $form['actions']['submit'] = array(
542
      '#type' => 'submit',
543
      '#value' => t('Resend e-mails'),
544
    );
545
    $form['actions']['cancel'] = array(
546
      '#type' => 'markup',
547
      '#markup' => l(t('Cancel'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/submission/' . $submission->sid),
548
    );
549
  }
550
  return $form;
551
}
552

    
553
/**
554
 * Validate handler for webform_submission_resend().
555
 */
556
function webform_submission_resend_validate($form, &$form_state) {
557
  if (count(array_filter($form_state['values']['resend'])) == 0) {
558
    form_set_error('emails', t('You must select at least one email address to resend submission.'));
559
  }
560
}
561

    
562
/**
563
 * Submit handler for webform_submission_resend().
564
 */
565
function webform_submission_resend_submit($form, &$form_state) {
566
  $node = $form['#node'];
567
  $submission = $form['#submission'];
568

    
569
  $emails = array();
570
  foreach ($form_state['values']['resend'] as $eid => $checked) {
571
    if ($checked) {
572
      $emails[] = $form['#node']->webform['emails'][$eid];
573
    }
574
  }
575
  $sent_count = webform_submission_send_mail($node, $submission, $emails);
576
  if ($sent_count) {
577
    drupal_set_message(format_plural($sent_count,
578
      'Successfully re-sent submission #@sid to 1 recipient.',
579
      'Successfully re-sent submission #@sid to @count recipients.',
580
      array('@sid' => $submission->sid)
581
    ));
582
  }
583
  else {
584
    drupal_set_message(t('No e-mails were able to be sent due to a server error.'), 'error');
585
  }
586
}
587

    
588
/**
589
 * Theme the node components form. Use a table to organize the components.
590
 *
591
 * @param $form
592
 *   The form array.
593
 * @return
594
 *   Formatted HTML form, ready for display.
595
 */
596
function theme_webform_submission_resend($variables) {
597
  $form = $variables['form'];
598

    
599
  $header = array(t('Send'), t('E-mail to'), t('Subject'));
600
  $rows = array();
601
  if (!empty($form['emails'])) {
602
    foreach (element_children($form['emails']) as $eid) {
603
      // Add each component to a table row.
604
      $rows[] = array(
605
        drupal_render($form['resend'][$eid]),
606
        drupal_render($form['emails'][$eid]['email']),
607
        drupal_render($form['emails'][$eid]['subject']),
608
      );
609
    }
610
  }
611
  else {
612
    $rows[] = array(array('data' => t('This webform is currently not setup to send emails.'), 'colspan' => 3));
613
  }
614
  $output = '';
615
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('id' => 'webform-emails')));
616
  $output .= drupal_render_children($form);
617
  return $output;
618
}
619

    
620
/**
621
 * Print a Webform submission for display on a page or in an e-mail.
622
 */
623
function webform_submission_render($node, $submission, $email, $format, $excluded_components = NULL) {
624
  $component_tree = array();
625
  $renderable = array();
626
  $page_count = 1;
627

    
628
  // Meta data that may be useful for modules implementing
629
  // hook_webform_submission_render_alter().
630
  $renderable['#node'] = $node;
631
  $renderable['#submission'] = $submission;
632
  $renderable['#email'] = $email;
633
  $renderable['#format'] = $format;
634

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

    
638
  $components = $node->webform['components'];
639
  
640
  // Remove excluded components.
641
  if (is_array($excluded_components)) {
642
    foreach ($excluded_components as $cid) {
643
      unset($components[$cid]);
644
    }
645
    if ($email && $email['exclude_empty']) {
646
      foreach ($submission->data as $cid => $data) {
647
        // Caution. Grids store their data in an array index by question key.
648
        foreach ($data as $value) {
649
          if ($value != '') {
650
            // This component has a non-empty value. Continue the outer loop.
651
            continue 2;
652
          }
653
        }
654
        unset($components[$cid]);
655
      }
656
    }
657
  }
658

    
659
  module_load_include('inc', 'webform', 'includes/webform.components');
660
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
661

    
662
  // Make sure at least one field is available
663
  if (isset($component_tree['children'])) {
664
    // Recursively add components to the form.
665
    $sorter = webform_get_conditional_sorter($node);
666
    $input_values = $sorter->executeConditionals($submission->data);
667
    foreach ($component_tree['children'] as $cid => $component) {
668
      if ($sorter->componentVisibility($cid, $component['page_num']) == webformConditionals::componentShown) {
669
        _webform_client_form_add_component($node, $component, NULL, $renderable, $renderable, $input_values, $format);
670
      }
671
    }
672
  }
673

    
674
  drupal_alter('webform_submission_render', $renderable);
675
  return $renderable;
676
}
677

    
678
/**
679
 * Return all the submissions for a particular node.
680
 *
681
 * @param $filters
682
 *   An array of filters to apply to this query. Usually in the format
683
 *   array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
684
 *   in, which will be equivalent to specifying a $nid filter.
685
 * @param $header
686
 *   If the results of this fetch will be used in a sortable
687
 *   table, pass the array header of the table.
688
 * @param $pager_count
689
 *   Optional. The number of submissions to include in the results.
690
 */
691
function webform_get_submissions($filters = array(), $header = NULL, $pager_count = 0) {
692
  return webform_get_submissions_load(webform_get_submissions_query($filters, $header, $pager_count));
693
}
694

    
695
/**
696
 * Returns an unexecuted webform_submissions query on for the arguments.
697
 *
698
 * This is an internal routine and not intended for use by other modules.
699
 *
700
 * @param $filters
701
 *   An array of filters to apply to this query. Usually in the format
702
 *   array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
703
 *   in, which will be equivalent to specifying a $nid filter. 'sid' may also
704
 *   be included, either as a single sid or an array of sid's.
705
 * @param $header
706
 *   If the results of this fetch will be used in a sortable
707
 *   table, pass the array header of the table.
708
 * @param $pager_count
709
 *   Optional. The number of submissions to include in the results.
710
 */
711
function webform_get_submissions_query($filters = array(), $header = NULL, $pager_count = 0) {
712
  if (!is_array($filters)) {
713
    $filters = array('ws.nid' => $filters);
714
  }
715

    
716
  // Qualify all filters with a table alias. ws.* is assumed, except for u.uid.
717
  foreach ($filters as $column => $value) {
718
    if (strpos($column, '.') === FALSE) {
719
      $filters[($column == 'uid' ? 'u.' : 'ws.') . $column] = $value;
720
      unset($filters[$column]);
721
    }
722
  }
723

    
724
  // If the sid is specified, but there are none, force the query to fail
725
  // rather than query on an empty array
726
  if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
727
    $filters['ws.sid'] = 0;
728
  }
729

    
730
  // Build the list of submissions and load their basic information.
731
  $pager_query = db_select('webform_submissions', 'ws')
732
    // Ensure only one row per submission is returned. Could be more than one if
733
    // sorting on a column that uses multiple rows for its data.
734
    ->distinct()
735
    ->addTag('webform_get_submissions_sids')
736
    ->fields('ws');
737

    
738
  // Add each filter.
739
  foreach ($filters as $column => $value) {
740
    $pager_query->condition($column, $value);
741
  }
742

    
743
  // Join to the users table to include user name in results.
744
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
745
  $pager_query->fields('u', array('name'));
746
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
747
    if (!empty($_SESSION['webform_submission'])) {
748
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
749
      $pager_query->condition('ws.sid', $anonymous_sids, 'IN');
750
    }
751
    else {
752
      $pager_query->condition('ws.sid', 0);
753
    }
754
  }
755

    
756
  if (is_array($header)) {
757
    $metadata_columns = array();
758
    foreach ($header as $header_item) {
759
      $metadata_columns[] = $header_item['data'];
760
    }
761
    $sort = drupal_get_query_parameters();
762
    // Sort by submitted data column if order is set but not in
763
    // $metadata_columns.
764
    if (isset($sort['order']) && !in_array($sort['order'], $metadata_columns, TRUE)) {
765
      // Default if sort is unset or invalid.
766
      if (!isset($sort['sort']) || !in_array($sort['sort'], array('asc', 'desc'), TRUE)) {
767
        $sort['sort'] = '';
768
      }
769
      $pager_query->leftJoin('webform_component', 'wc', 'ws.nid = wc.nid AND wc.name = :form_key', array('form_key' => $sort['order']));
770
      $pager_query->leftJoin('webform_submitted_data', 'wsd', 'wc.nid = wsd.nid AND ws.sid = wsd.sid AND wc.cid = wsd.cid');
771
      $pager_query->orderBy('wsd.data', $sort['sort']);
772
      $pager_query->orderBy('ws.sid', 'ASC');
773
    }
774
    // Sort by metadata column.
775
    else {
776
      // Extending the query instantiates a new query object.
777
      $pager_query = $pager_query->extend('TableSort');
778
      $pager_query->orderByHeader($header);
779
    }
780
  }
781
  else {
782
    $pager_query->orderBy('ws.sid', 'ASC');
783
  }
784

    
785
  if ($pager_count) {
786
    // Extending the query instantiates a new query object.
787
    $pager_query = $pager_query->extend('PagerDefault');
788
    $pager_query->limit($pager_count);
789
  }
790
  return $pager_query;
791
}
792

    
793
/**
794
 * Retrieve and load the submissions for the specified submissions query.
795
 *
796
 * This is an internal routine and not intended for use by other modules.
797
 *
798
 * @params object $pager_query
799
 *   A select or extended select query containing the needed fields:
800
 *     webform_submissions: all fields
801
 *     user: name
802
 * @return array
803
 *   An array of loaded webform submissions.
804
 */
805
function webform_get_submissions_load($pager_query) {
806
  // If the "$pager_query" is actually an unextended select query, then instead
807
  // of querying the webform_submissions_data table with a pontentially huge
808
  // array of sids in an IN clause, use the select query directy as this will
809
  // be much faster. Extended queries don't work in join clauses. The query
810
  // is assumed to include the sid.
811
  if ($pager_query instanceof SelectQuery) {
812
    $submissions_query = clone $pager_query;
813
  }
814

    
815
  // Extract any filter on node id to use in an optimization below
816
  foreach ($pager_query->conditions() as $index => $condition) {
817
    if ($index !== '#conjunction' && $condition['operator'] === '=' && ($condition['field'] === 'nid' || $condition['field'] === 'ws.nid')) {
818
      $nid = $condition['value'];
819
      break;
820
    }
821
  }
822

    
823
  $result = $pager_query->execute();
824
  $submissions = $result->fetchAllAssoc('sid');
825

    
826
  // If there are no submissions being retrieved, return an empty array.
827
  if (!$submissions) {
828
    return $submissions;
829
  }
830

    
831
  foreach ($submissions as $sid => $submission) {
832
    $submissions[$sid]->preview = FALSE;
833
    $submissions[$sid]->data = array();
834
  }
835

    
836
  // Query the required submission data.
837
  $query = db_select('webform_submitted_data', 'sd');
838
  $query
839
    ->addTag('webform_get_submissions_data')
840
    ->fields('sd', array('sid', 'cid', 'no', 'data'))
841
    ->orderBy('sd.sid', 'ASC')
842
    ->orderBy('sd.cid', 'ASC')
843
    ->orderBy('sd.no', 'ASC');
844

    
845
  if (isset($submissions_query)) {
846
    // If available, prefer joining on the subquery as it is much faster than an
847
    // IN clause on a large array. A subquery with the IN operator doesn't work
848
    // when the subquery has a LIMIT clause, requiring an inner join instead.
849
    $query->innerJoin($submissions_query, 'ws2', 'sd.sid = ws2.sid');
850
  }
851
  else {
852
    $query->condition('sd.sid',  array_keys($submissions), 'IN');
853
  }
854

    
855
  // By adding the NID to this query we allow MySQL to use the primary key on
856
  // in webform_submitted_data for sorting (nid_sid_cid_no).
857
  if (isset($nid)) {
858
    $query->condition('sd.nid', $nid);
859
  }
860

    
861
  $result = $query->execute();
862

    
863
  // Convert the queried rows into submission data.
864
  foreach ($result as $row) {
865
    $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
866
  }
867

    
868
  foreach (module_implements('webform_submission_load') as $module) {
869
    $function = $module . '_webform_submission_load';
870
    $function($submissions);
871
  }
872

    
873
  return $submissions;
874
}
875

    
876
/**
877
 * Return a count of the total number of submissions for a node.
878
 *
879
 * @param $nid
880
 *   The node ID for which submissions are being fetched.
881
 * @param $uid
882
 *   Optional; the user ID to filter the submissions by.
883
 * @param $is_draft
884
 *   Optional; NULL for all, truthy for drafts only, falsy for completed only.
885
 *   The default is completed submissions only.
886
 * @return
887
 *   An integer value of the number of submissions.
888
 */
889
function webform_get_submission_count($nid, $uid = NULL, $is_draft = 0) {
890
  $counts = &drupal_static(__FUNCTION__);
891

    
892
  if (!isset($counts[$nid][$uid])) {
893
    $query = db_select('webform_submissions', 'ws')
894
      ->addTag('webform_get_submission_count')
895
      ->condition('ws.nid', $nid);
896
    if ($uid !== NULL) {
897
      $query->condition('ws.uid', $uid);
898
    }
899
    if ($uid === 0) {
900
      $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
901
      if ($submissions) {
902
        $query->condition('ws.sid', $submissions, 'IN');
903
      }
904
      else {
905
        // Intentionally never match anything if the anonymous user has no
906
        // submissions.
907
        $query->condition('ws.sid', 0);
908
      }
909
    }
910
    if (isset($is_draft)) {
911
      $query->condition('ws.is_draft', $is_draft);
912
    }
913

    
914
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
915
  }
916
  return $counts[$nid][$uid];
917
}
918

    
919
/**
920
 * Fetch a specified submission for a webform node.
921
 */
922
function webform_get_submission($nid, $sid) {
923
  $submissions = &drupal_static(__FUNCTION__, array());
924

    
925
  // Load the submission if needed.
926
  if (!isset($submissions[$sid])) {
927
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
928
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
929
  }
930

    
931
  return $submissions[$sid];
932
}
933

    
934
function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
935
  $headers = implode('\n', (array)$headers);
936
  // Check if they are attempting to spam using a bcc or content type hack.
937
  if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
938
    return TRUE; // Possible spam attempt.
939
  }
940
  return FALSE; // Not spam.
941
}
942

    
943
/**
944
 * Check if the current user has exceeded the limit on this form.
945
 *
946
 * @param $node
947
 *   The webform node to be checked.
948
 * @param $account
949
 *   Optional parameter. Specify the account you want to check the limit
950
 *   against.
951
 *
952
 * @return
953
 *   Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
954
 */
955
function webform_submission_user_limit_check($node, $account = NULL) {
956
  global $user;
957
  $tracking_mode = webform_variable_get('webform_tracking_mode');
958

    
959
  if (!isset($account)) {
960
    $account = $user;
961
  }
962

    
963
  // We can only check access for anonymous users through their cookies.
964
  if ($user->uid !== 0 && $account->uid === 0) {
965
    watchdog('webform', 'Unable to check anonymous user submission limit when logged in as user @uid.', array('@uid' => $user->uid), WATCHDOG_WARNING);
966
    return FALSE;
967
  }
968

    
969
  // Check if submission limiting is enabled.
970
  if ($node->webform['submit_limit'] == '-1') {
971
    return FALSE; // No check enabled.
972
  }
973

    
974
  // Fetch all the entries from the database within the submit interval with
975
  // this username and IP.
976
  $num_submissions_database = 0;
977
  if (!$node->webform['confidential'] &&
978
      ($account->uid !== 0 || $tracking_mode === 'ip_address' || $tracking_mode === 'strict')) {
979
    $query = db_select('webform_submissions')
980
      ->addTag('webform_submission_user_limit_check')
981
      ->condition('nid', $node->nid)
982
      ->condition('is_draft', 0);
983

    
984
    if ($node->webform['submit_interval'] != -1) {
985
      $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
986
    }
987

    
988
    if ($account->uid) {
989
      $query->condition('uid', $account->uid);
990
    }
991
    else {
992
      $query->condition('remote_addr', ip_address());
993
    }
994
    $num_submissions_database = $query->countQuery()->execute()->fetchField();
995
  }
996

    
997
  // Double check the submission history from the users machine using cookies.
998
  $num_submissions_cookie = 0;
999
  if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
1000
    $cookie_name = 'webform-' . $node->nid;
1001

    
1002
    if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
1003
      foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
1004
        if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
1005
          // Remove the cookie if past the required time interval.
1006
          $params = session_get_cookie_params();
1007
          setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1008
        }
1009
      }
1010
      // Count the number of submissions recorded in cookies.
1011
      $num_submissions_cookie = count($_COOKIE[$cookie_name]);
1012
    }
1013
  }
1014

    
1015
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
1016
    // Limit exceeded.
1017
    return TRUE;
1018
  }
1019

    
1020
  // Limit not exceeded.
1021
  return FALSE;
1022
}
1023

    
1024
/**
1025
 * Check if the total number of submissions has exceeded the limit on this form.
1026
 *
1027
 * @param $node
1028
 *   The webform node to be checked.
1029
 * @return
1030
 *   Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
1031
 */
1032
function webform_submission_total_limit_check($node) {
1033

    
1034
  // Check if submission limiting is enabled.
1035
  if ($node->webform['total_submit_limit'] == '-1') {
1036
    return FALSE; // No check enabled.
1037
  }
1038

    
1039
  // Retrieve submission data from the database.
1040
  $query = db_select('webform_submissions')
1041
    ->addTag('webform_submission_total_limit_check')
1042
    ->condition('nid', $node->nid)
1043
    ->condition('is_draft', 0);
1044

    
1045
  if ($node->webform['total_submit_interval'] != -1) {
1046
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
1047
  }
1048

    
1049
  // Fetch all the entries from the database within the submit interval.
1050
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
1051

    
1052
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
1053
    // Limit exceeded.
1054
    return TRUE;
1055
  }
1056

    
1057
  // Limit not exceeded.
1058
  return FALSE;
1059
}
1060

    
1061
/**
1062
 * Preprocess function for webform-submission.tpl.php.
1063
 */
1064
function template_preprocess_webform_submission(&$vars) {
1065
  $vars['node'] = $vars['renderable']['#node'];
1066
  $vars['submission'] = $vars['renderable']['#submission'];
1067
  $vars['email'] = $vars['renderable']['#email'];
1068
  $vars['format'] = $vars['renderable']['#format'];
1069
}
1070

    
1071
/**
1072
 * Preprocess function for webform-submission-navigation.tpl.php.
1073
 */
1074
function template_preprocess_webform_submission_navigation(&$vars) {
1075
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
1076

    
1077
  $previous_query = db_select('webform_submissions')
1078
    ->condition('nid', $vars['node']->nid)
1079
    ->condition('sid', $vars['submission']->sid, '<');
1080
  $previous_query->addExpression('MAX(sid)');
1081

    
1082
  $next_query = db_select('webform_submissions')
1083
    ->condition('nid', $vars['node']->nid)
1084
    ->condition('sid', $vars['submission']->sid, '>');
1085
  $next_query->addExpression('MIN(sid)');
1086

    
1087
  $vars['previous'] = $previous_query->execute()->fetchField();
1088
  $vars['next'] = $next_query->execute()->fetchField();
1089
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
1090
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
1091
}
1092

    
1093
/**
1094
 * Preprocess function for webform-submission-navigation.tpl.php.
1095
 */
1096
function template_preprocess_webform_submission_information(&$vars) {
1097
  $vars['account'] = user_load($vars['submission']->uid);
1098
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
1099
}