Projet

Général

Profil

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

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

1
<?php
2

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

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

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

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

    
41
  return $data;
42
}
43

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

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

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

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

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

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

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

    
134
  return $submission->sid;
135
}
136

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

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

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

    
184
  return $submission->sid;
185
}
186

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

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

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

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

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

    
242
  // Create a themed message for mailing.
243
  $send_count = 0;
244
  foreach ($emails as $eid => $email) {
245
    $mail = _webform_submission_prepare_mail($node, $submission, $email);
246
    if (!$mail) {
247
      continue;
248
    }
249

    
250
    $addresses_final = $mail['addresses_final'];
251
    $send_increment = $mail['send_increment'];
252
    $language = $mail['language'];
253
    $mail_params = $mail['mail_params'];
254

    
255
    // Mail the webform results.
256
    foreach ($addresses_final as $address) {
257
      $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
258
      if ($message['result']) {
259
        $send_count += $send_increment;
260
      }
261
    }
262
  }
263

    
264
  return $send_count;
265
}
266

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

    
283
  // Don't process disabled emails.
284
  if (!$email['status']) {
285
    return;
286
  }
287

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
941
  return $submissions;
942
}
943

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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