Projet

Général

Profil

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

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

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
        if (!isset($data[0]) || $data[0] == '') {
648
          unset($components[$cid]);
649
        }
650
      }
651
    }
652
  }
653

    
654
  module_load_include('inc', 'webform', 'includes/webform.components');
655
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
656

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

    
669
  drupal_alter('webform_submission_render', $renderable);
670
  return $renderable;
671
}
672

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

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

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

    
719
  // If the sid is specified, but there are none, force the query to fail
720
  // rather than query on an empty array
721
  if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
722
    $filters['ws.sid'] = 0;
723
  }
724

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

    
733
  // Add each filter.
734
  foreach ($filters as $column => $value) {
735
    $pager_query->condition($column, $value);
736
  }
737

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

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

    
780
  if ($pager_count) {
781
    // Extending the query instantiates a new query object.
782
    $pager_query = $pager_query->extend('PagerDefault');
783
    $pager_query->limit($pager_count);
784
  }
785
  return $pager_query;
786
}
787

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

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

    
818
  $result = $pager_query->execute();
819
  $submissions = $result->fetchAllAssoc('sid');
820

    
821
  // If there are no submissions being retrieved, return an empty array.
822
  if (!$submissions) {
823
    return $submissions;
824
  }
825

    
826
  foreach ($submissions as $sid => $submission) {
827
    $submissions[$sid]->preview = FALSE;
828
    $submissions[$sid]->data = array();
829
  }
830

    
831
  // Query the required submission data.
832
  $query = db_select('webform_submitted_data', 'sd');
833
  $query
834
    ->addTag('webform_get_submissions_data')
835
    ->fields('sd', array('sid', 'cid', 'no', 'data'))
836
    ->orderBy('sd.sid', 'ASC')
837
    ->orderBy('sd.cid', 'ASC')
838
    ->orderBy('sd.no', 'ASC');
839

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

    
850
  // By adding the NID to this query we allow MySQL to use the primary key on
851
  // in webform_submitted_data for sorting (nid_sid_cid_no).
852
  if (isset($nid)) {
853
    $query->condition('sd.nid', $nid);
854
  }
855

    
856
  $result = $query->execute();
857

    
858
  // Convert the queried rows into submission data.
859
  foreach ($result as $row) {
860
    $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
861
  }
862

    
863
  foreach (module_implements('webform_submission_load') as $module) {
864
    $function = $module . '_webform_submission_load';
865
    $function($submissions);
866
  }
867

    
868
  return $submissions;
869
}
870

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

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

    
909
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
910
  }
911
  return $counts[$nid][$uid];
912
}
913

    
914
/**
915
 * Fetch a specified submission for a webform node.
916
 */
917
function webform_get_submission($nid, $sid) {
918
  $submissions = &drupal_static(__FUNCTION__, array());
919

    
920
  // Load the submission if needed.
921
  if (!isset($submissions[$sid])) {
922
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
923
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
924
  }
925

    
926
  return $submissions[$sid];
927
}
928

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

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

    
954
  if (!isset($account)) {
955
    $account = $user;
956
  }
957

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

    
964
  // Check if submission limiting is enabled.
965
  if ($node->webform['submit_limit'] == '-1') {
966
    return FALSE; // No check enabled.
967
  }
968

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

    
979
    if ($node->webform['submit_interval'] != -1) {
980
      $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
981
    }
982

    
983
    if ($account->uid) {
984
      $query->condition('uid', $account->uid);
985
    }
986
    else {
987
      $query->condition('remote_addr', ip_address());
988
    }
989
    $num_submissions_database = $query->countQuery()->execute()->fetchField();
990
  }
991

    
992
  // Double check the submission history from the users machine using cookies.
993
  $num_submissions_cookie = 0;
994
  if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
995
    $cookie_name = 'webform-' . $node->nid;
996

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

    
1010
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
1011
    // Limit exceeded.
1012
    return TRUE;
1013
  }
1014

    
1015
  // Limit not exceeded.
1016
  return FALSE;
1017
}
1018

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

    
1029
  // Check if submission limiting is enabled.
1030
  if ($node->webform['total_submit_limit'] == '-1') {
1031
    return FALSE; // No check enabled.
1032
  }
1033

    
1034
  // Retrieve submission data from the database.
1035
  $query = db_select('webform_submissions')
1036
    ->addTag('webform_submission_total_limit_check')
1037
    ->condition('nid', $node->nid)
1038
    ->condition('is_draft', 0);
1039

    
1040
  if ($node->webform['total_submit_interval'] != -1) {
1041
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
1042
  }
1043

    
1044
  // Fetch all the entries from the database within the submit interval.
1045
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
1046

    
1047
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
1048
    // Limit exceeded.
1049
    return TRUE;
1050
  }
1051

    
1052
  // Limit not exceeded.
1053
  return FALSE;
1054
}
1055

    
1056
/**
1057
 * Preprocess function for webform-submission.tpl.php.
1058
 */
1059
function template_preprocess_webform_submission(&$vars) {
1060
  $vars['node'] = $vars['renderable']['#node'];
1061
  $vars['submission'] = $vars['renderable']['#submission'];
1062
  $vars['email'] = $vars['renderable']['#email'];
1063
  $vars['format'] = $vars['renderable']['#format'];
1064
}
1065

    
1066
/**
1067
 * Preprocess function for webform-submission-navigation.tpl.php.
1068
 */
1069
function template_preprocess_webform_submission_navigation(&$vars) {
1070
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
1071

    
1072
  $previous_query = db_select('webform_submissions')
1073
    ->condition('nid', $vars['node']->nid)
1074
    ->condition('sid', $vars['submission']->sid, '<');
1075
  $previous_query->addExpression('MAX(sid)');
1076

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

    
1082
  $vars['previous'] = $previous_query->execute()->fetchField();
1083
  $vars['next'] = $next_query->execute()->fetchField();
1084
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
1085
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
1086
}
1087

    
1088
/**
1089
 * Preprocess function for webform-submission-navigation.tpl.php.
1090
 */
1091
function template_preprocess_webform_submission_information(&$vars) {
1092
  $vars['account'] = user_load($vars['submission']->uid);
1093
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
1094
}