Project

General

Profile

Paste
Download (40.3 KB) Statistics
| Branch: | Revision:

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

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 object $node
17
 *   The node object containing the current webform.
18
 * @param array $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
  require_once __DIR__ . '/webform.components.inc';
26

    
27
  $data = array();
28

    
29
  foreach ($submitted as $cid => $values) {
30
    // Don't save pseudo-fields or components that do not collect data.
31
    if (!isset($node->webform['components'][$cid]) || !webform_component_feature($node->webform['components'][$cid]['type'], 'stores_data')) {
32
      continue;
33
    }
34

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

    
43
  return $data;
44
}
45

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

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

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

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

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

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

    
134
  module_invoke_all('webform_submission_update', $node, $submission);
135

    
136
  return $submission->sid;
137
}
138

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

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

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

    
186
  return $submission->sid;
187
}
188

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

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

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

    
220
  module_invoke_all('webform_submission_delete', $node, $submission);
221
}
222

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

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

    
257
    $addresses_final = $mail['addresses_final'];
258
    $send_increment = $mail['send_increment'];
259
    $language = $mail['language'];
260
    $mail_params = $mail['mail_params'];
261

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

    
271
  return $send_count;
272
}
273

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

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

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

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

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

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

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

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

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

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

    
367
  if (!$addresses_final) {
368
    return;
369
  }
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
562
  $form['#tree'] = TRUE;
563
  $form['#node'] = $node;
564
  $form['#submission'] = $submission;
565

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

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

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

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

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

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

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

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

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

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

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

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

    
706
  $components = $node->webform['components'];
707

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

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

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

    
738
  drupal_alter('webform_submission_render', $renderable);
739
  return $renderable;
740
}
741

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

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

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

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

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

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

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

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

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

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

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

    
894
  $result = $pager_query->execute();
895
  $submissions = $result->fetchAllAssoc('sid');
896

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

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

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

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

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

    
932
  $result = $query->execute();
933

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

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

    
944
  return $submissions;
945
}
946

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

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

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

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

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

    
1003
  return $submissions[$sid];
1004
}
1005

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

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

    
1036
  if (!isset($account)) {
1037
    $account = $user;
1038
  }
1039

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

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

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

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

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

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

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

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

    
1098
  // Limit not exceeded.
1099
  return FALSE;
1100
}
1101

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

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

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

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

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

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

    
1137
  // Limit not exceeded.
1138
  return FALSE;
1139
}
1140

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

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

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

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

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

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