Projet

Général

Profil

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

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

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
 *
19
 * @return array
20
 *   An array suitable for use in the 'data' property of a $submission object.
21
 */
22
function webform_submission_data($node, $submitted) {
23
  $data = array();
24

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

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

    
39
  return $data;
40
}
41

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

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

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

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

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

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

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

    
129
  return $submission->sid;
130
}
131

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

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

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

    
177
  return $submission->sid;
178
}
179

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

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

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

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

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

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

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

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

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

    
254
    // Replace tokens in the message.
255
    $email['message'] = webform_replace_tokens($email['message'], $node, $submission, $email, (boolean)$email['html']);
256

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

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

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

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

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

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

    
320
    if (!$addresses_final) {
321
      continue;
322
    }
323

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

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

    
341
    // Mail the webform results.
342
    foreach ($addresses_final as $address) {
343

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

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

    
371
        // Add the attachments to the mail parameters.
372
        $mail_params['attachments'] = $attachments;
373

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

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

    
392
  return $send_count;
393
}
394

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

    
410
  // Set the correct page title.
411
  drupal_set_title(webform_submission_title($node, $submission));
412

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

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

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

    
430
function webform_submission_delete_form_submit($form, &$form_state) {
431
  $node = node_load($form_state['values']['details']['nid']);
432
  $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
433
  webform_submission_delete($node, $submission);
434
  drupal_set_message(t('Submission deleted.'));
435

    
436
  // If no destination query was supplied in the URL (for example, Edit tab),
437
  // redirect to the most-privledged destination.
438
  $form_state['redirect'] = 'node/' . $node->nid .
439
                            (webform_results_access($node) ? '/webform-results' : '/submissions');
440
}
441

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

    
449
/**
450
 * Menu callback; Present a Webform submission page for display or editing.
451
 */
452
function webform_submission_page($node, $submission, $format) {
453
  global $user;
454

    
455
  // Render the admin UI breadcrumb.
456
  webform_set_breadcrumb($node, $submission);
457

    
458
  // Set the correct page title.
459
  drupal_set_title(webform_submission_title($node, $submission));
460

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

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

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

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

    
492
  // Disable the page cache for anonymous users viewing or editing submissions.
493
  if (!$user->uid) {
494
    webform_disable_page_cache();
495
  }
496

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

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

    
518
  $form['#tree'] = TRUE;
519
  $form['#node'] = $node;
520
  $form['#submission'] = $submission;
521

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

    
524
    $mapping = isset($email['extra']['email_mapping']) ?  $email['extra']['email_mapping'] : NULL;
525
    $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, FALSE, FALSE, NULL, $mapping);
526
    $addresses_valid = array_map('webform_valid_email_address', $addresses);
527
    $valid_email = count($addresses) == array_sum($addresses_valid);
528

    
529
    $form['resend'][$eid] = array(
530
      '#type' => 'checkbox',
531
      '#default_value' => $valid_email && $email['status'],
532
      '#disabled' => !$valid_email,
533
    );
534
    $form['emails'][$eid]['email'] = array(
535
      '#markup' => nl2br(check_plain(implode("\n", $addresses))),
536
    );
537
    if (!$valid_email) {
538
      $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty or invalid') . ')';
539
    }
540
    $form['emails'][$eid]['subject'] = array(
541
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
542
    );
543

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

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

    
566
/**
567
 * Submit handler for webform_submission_resend().
568
 */
569
function webform_submission_resend_submit($form, &$form_state) {
570
  $node = $form['#node'];
571
  $submission = $form['#submission'];
572

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

    
592
/**
593
 * Theme the node components form. Use a table to organize the components.
594
 *
595
 * @param array $variables
596
 *   Array with key "form" containing the form array.
597
 *
598
 * @return string
599
 *   Formatted HTML form, ready for display.
600
 *
601
 * @throws Exception
602
 */
603
function theme_webform_submission_resend($variables) {
604
  $form = $variables['form'];
605

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

    
627
/**
628
 * Print a Webform submission for display on a page or in an e-mail.
629
 */
630
function webform_submission_render($node, $submission, $email, $format, $excluded_components = NULL) {
631
  $component_tree = array();
632
  $renderable = array();
633
  $page_count = 1;
634

    
635
  // Meta data that may be useful for modules implementing
636
  // hook_webform_submission_render_alter().
637
  $renderable['#node'] = $node;
638
  $renderable['#submission'] = $submission;
639
  $renderable['#email'] = $email;
640
  $renderable['#format'] = $format;
641

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

    
645
  $components = $node->webform['components'];
646

    
647
  // Remove excluded components.
648
  if (is_array($excluded_components)) {
649
    foreach ($excluded_components as $cid) {
650
      unset($components[$cid]);
651
    }
652
    if (!empty($email['exclude_empty'])) {
653
      foreach ($submission->data as $cid => $data) {
654
        // Caution. Grids store their data in an array index by question key.
655
        if (implode($data) == '') {
656
          unset($components[$cid]);
657
        }
658
      }
659
    }
660
  }
661

    
662
  module_load_include('inc', 'webform', 'includes/webform.components');
663
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
664

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

    
677
  drupal_alter('webform_submission_render', $renderable);
678
  return $renderable;
679
}
680

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

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

    
724
  // Qualify all filters with a table alias. ws.* is assumed, except for u.uid.
725
  foreach ($filters as $column => $value) {
726
    if (strpos($column, '.') === FALSE) {
727
      $filters[($column == 'uid' ? 'u.' : 'ws.') . $column] = $value;
728
      unset($filters[$column]);
729
    }
730
  }
731

    
732
  // If the sid is specified, but there are none, force the query to fail
733
  // rather than query on an empty array
734
  if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
735
    $filters['ws.sid'] = 0;
736
  }
737

    
738
  // Build the list of submissions and load their basic information.
739
  $pager_query = db_select('webform_submissions', 'ws')
740
    // Ensure only one row per submission is returned. Could be more than one if
741
    // sorting on a column that uses multiple rows for its data.
742
    ->distinct()
743
    ->addTag('webform_get_submissions_sids')
744
    ->fields('ws');
745

    
746
  // Add each filter.
747
  foreach ($filters as $column => $value) {
748
    $pager_query->condition($column, $value);
749
  }
750

    
751
  // Join to the users table to include user name in results.
752
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
753
  $pager_query->fields('u', array('name'));
754
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
755
    if (!empty($_SESSION['webform_submission'])) {
756
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
757
      $pager_query->condition('ws.sid', $anonymous_sids, 'IN');
758
    }
759
    else {
760
      $pager_query->condition('ws.sid', 0);
761
    }
762
  }
763

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

    
793
  if ($pager_count) {
794
    // Extending the query instantiates a new query object.
795
    $pager_query = $pager_query->extend('PagerDefault');
796
    $pager_query->limit($pager_count);
797
  }
798
  return $pager_query;
799
}
800

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

    
823
  // Extract any filter on node id to use in an optimization below
824
  foreach ($pager_query->conditions() as $index => $condition) {
825
    if ($index !== '#conjunction' && $condition['operator'] === '=' && ($condition['field'] === 'nid' || $condition['field'] === 'ws.nid')) {
826
      $nid = $condition['value'];
827
      break;
828
    }
829
  }
830

    
831
  $result = $pager_query->execute();
832
  $submissions = $result->fetchAllAssoc('sid');
833

    
834
  // If there are no submissions being retrieved, return an empty array.
835
  if (!$submissions) {
836
    return $submissions;
837
  }
838

    
839
  foreach ($submissions as $sid => $submission) {
840
    $submissions[$sid]->preview = FALSE;
841
    $submissions[$sid]->data = array();
842
  }
843

    
844
  // Query the required submission data.
845
  $query = db_select('webform_submitted_data', 'sd');
846
  $query
847
    ->addTag('webform_get_submissions_data')
848
    ->fields('sd', array('sid', 'cid', 'no', 'data'))
849
    ->orderBy('sd.sid', 'ASC')
850
    ->orderBy('sd.cid', 'ASC')
851
    ->orderBy('sd.no', 'ASC');
852

    
853
  if (isset($submissions_query)) {
854
    // If available, prefer joining on the subquery as it is much faster than an
855
    // IN clause on a large array. A subquery with the IN operator doesn't work
856
    // when the subquery has a LIMIT clause, requiring an inner join instead.
857
    $query->innerJoin($submissions_query, 'ws2', 'sd.sid = ws2.sid');
858
  }
859
  else {
860
    $query->condition('sd.sid',  array_keys($submissions), 'IN');
861
  }
862

    
863
  // By adding the NID to this query we allow MySQL to use the primary key on
864
  // in webform_submitted_data for sorting (nid_sid_cid_no).
865
  if (isset($nid)) {
866
    $query->condition('sd.nid', $nid);
867
  }
868

    
869
  $result = $query->execute();
870

    
871
  // Convert the queried rows into submission data.
872
  foreach ($result as $row) {
873
    $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
874
  }
875

    
876
  foreach (module_implements('webform_submission_load') as $module) {
877
    $function = $module . '_webform_submission_load';
878
    $function($submissions);
879
  }
880

    
881
  return $submissions;
882
}
883

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

    
900
  if (!isset($counts[$nid][$uid])) {
901
    $query = db_select('webform_submissions', 'ws')
902
      ->addTag('webform_get_submission_count')
903
      ->condition('ws.nid', $nid);
904
    if ($uid !== NULL) {
905
      $query->condition('ws.uid', $uid);
906
    }
907
    if ($uid === 0) {
908
      $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
909
      if ($submissions) {
910
        $query->condition('ws.sid', $submissions, 'IN');
911
      }
912
      else {
913
        // Intentionally never match anything if the anonymous user has no
914
        // submissions.
915
        $query->condition('ws.sid', 0);
916
      }
917
    }
918
    if (isset($is_draft)) {
919
      $query->condition('ws.is_draft', $is_draft);
920
    }
921

    
922
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
923
  }
924
  return $counts[$nid][$uid];
925
}
926

    
927
/**
928
 * Fetch a specified submission for a webform node.
929
 */
930
function webform_get_submission($nid, $sid) {
931
  $submissions = &drupal_static(__FUNCTION__, array());
932

    
933
  // Load the submission if needed.
934
  if (!isset($submissions[$sid])) {
935
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
936
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
937
  }
938

    
939
  return $submissions[$sid];
940
}
941

    
942
function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
943
  $headers = implode('\n', (array)$headers);
944
  // Check if they are attempting to spam using a bcc or content type hack.
945
  if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
946
    return TRUE; // Possible spam attempt.
947
  }
948
  return FALSE; // Not spam.
949
}
950

    
951
/**
952
 * Check if the current user has exceeded the limit on this form.
953
 *
954
 * @param $node
955
 *   The webform node to be checked.
956
 * @param $account
957
 *   Optional parameter. Specify the account you want to check the limit
958
 *   against.
959
 *
960
 * @return bool
961
 *   Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
962
 */
963
function webform_submission_user_limit_check($node, $account = NULL) {
964
  global $user;
965
  $tracking_mode = webform_variable_get('webform_tracking_mode');
966

    
967
  if (!isset($account)) {
968
    $account = $user;
969
  }
970

    
971
  // We can only check access for anonymous users through their cookies.
972
  if ($user->uid !== 0 && $account->uid === 0) {
973
    watchdog('webform', 'Unable to check anonymous user submission limit when logged in as user @uid.', array('@uid' => $user->uid), WATCHDOG_WARNING);
974
    return FALSE;
975
  }
976

    
977
  // Check if submission limiting is enabled.
978
  if ($node->webform['submit_limit'] == '-1') {
979
    return FALSE; // No check enabled.
980
  }
981

    
982
  // Fetch all the entries from the database within the submit interval with
983
  // this username and IP.
984
  $num_submissions_database = 0;
985
  if (!$node->webform['confidential'] &&
986
      ($account->uid !== 0 || $tracking_mode === 'ip_address' || $tracking_mode === 'strict')) {
987
    $query = db_select('webform_submissions')
988
      ->addTag('webform_submission_user_limit_check')
989
      ->condition('nid', $node->nid)
990
      ->condition('is_draft', 0);
991

    
992
    if ($node->webform['submit_interval'] != -1) {
993
      $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
994
    }
995

    
996
    if ($account->uid) {
997
      $query->condition('uid', $account->uid);
998
    }
999
    else {
1000
      $query->condition('remote_addr', ip_address());
1001
    }
1002
    $num_submissions_database = $query->countQuery()->execute()->fetchField();
1003
  }
1004

    
1005
  // Double check the submission history from the users machine using cookies.
1006
  $num_submissions_cookie = 0;
1007
  if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
1008
    $cookie_name = 'webform-' . $node->nid;
1009

    
1010
    if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
1011
      foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
1012
        if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
1013
          // Remove the cookie if past the required time interval.
1014
          $params = session_get_cookie_params();
1015
          setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1016
        }
1017
      }
1018
      // Count the number of submissions recorded in cookies.
1019
      $num_submissions_cookie = count($_COOKIE[$cookie_name]);
1020
    }
1021
  }
1022

    
1023
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
1024
    // Limit exceeded.
1025
    return TRUE;
1026
  }
1027

    
1028
  // Limit not exceeded.
1029
  return FALSE;
1030
}
1031

    
1032
/**
1033
 * Check if the total number of submissions has exceeded the limit on this form.
1034
 *
1035
 * @param $node
1036
 *   The webform node to be checked.
1037
 *
1038
 * @return bool
1039
 *   Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
1040
 */
1041
function webform_submission_total_limit_check($node) {
1042

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

    
1048
  // Retrieve submission data from the database.
1049
  $query = db_select('webform_submissions')
1050
    ->addTag('webform_submission_total_limit_check')
1051
    ->condition('nid', $node->nid)
1052
    ->condition('is_draft', 0);
1053

    
1054
  if ($node->webform['total_submit_interval'] != -1) {
1055
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
1056
  }
1057

    
1058
  // Fetch all the entries from the database within the submit interval.
1059
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
1060

    
1061
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
1062
    // Limit exceeded.
1063
    return TRUE;
1064
  }
1065

    
1066
  // Limit not exceeded.
1067
  return FALSE;
1068
}
1069

    
1070
/**
1071
 * Preprocess function for webform-submission.tpl.php.
1072
 */
1073
function template_preprocess_webform_submission(&$vars) {
1074
  $vars['node'] = $vars['renderable']['#node'];
1075
  $vars['submission'] = $vars['renderable']['#submission'];
1076
  $vars['email'] = $vars['renderable']['#email'];
1077
  $vars['format'] = $vars['renderable']['#format'];
1078
}
1079

    
1080
/**
1081
 * Preprocess function for webform-submission-navigation.tpl.php.
1082
 */
1083
function template_preprocess_webform_submission_navigation(&$vars) {
1084
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
1085

    
1086
  $previous_query = db_select('webform_submissions')
1087
    ->condition('nid', $vars['node']->nid)
1088
    ->condition('sid', $vars['submission']->sid, '<');
1089
  $previous_query->addExpression('MAX(sid)');
1090

    
1091
  $next_query = db_select('webform_submissions')
1092
    ->condition('nid', $vars['node']->nid)
1093
    ->condition('sid', $vars['submission']->sid, '>');
1094
  $next_query->addExpression('MIN(sid)');
1095

    
1096
  $vars['previous'] = $previous_query->execute()->fetchField();
1097
  $vars['next'] = $next_query->execute()->fetchField();
1098
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
1099
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
1100
}
1101

    
1102
/**
1103
 * Preprocess function for webform-submission-navigation.tpl.php.
1104
 */
1105
function template_preprocess_webform_submission_information(&$vars) {
1106
  $vars['account'] = user_load($vars['submission']->uid);
1107
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
1108
}