Projet

Général

Profil

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

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

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
  // Allow other modules to modify the submission before saving.
99
  foreach (module_implements('webform_submission_presave') as $module) {
100
    $function = $module . '_webform_submission_presave';
101
    $function($node, $submission);
102
  }
103

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

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

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

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

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

    
133
  return $submission->sid;
134
}
135

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

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

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

    
182
  return $submission->sid;
183
}
184

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

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

    
206
  db_delete('webform_submitted_data')
207
    ->condition('nid', $node->nid)
208
    ->condition('sid', $submission->sid)
209
    ->execute();
210
  db_delete('webform_submissions')
211
    ->condition('nid', $node->nid)
212
    ->condition('sid', $submission->sid)
213
    ->execute();
214

    
215
  module_invoke_all('webform_submission_delete', $node, $submission);
216
}
217

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

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

    
241
  // Create a themed message for mailing.
242
  $send_count = 0;
243
  foreach ($emails as $eid => $email) {
244
    // Continue with next email recipients array if disabled for current.
245
    if (!$email['status']) {
246
      continue;
247
    }
248

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

    
252
    // Pass through the theme layer if using the default template.
253
    if ($email['template'] == 'default') {
254
      $email['message'] = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'submission' => $submission, 'email' => $email));
255
    }
256
    else {
257
      $email['message'] = $email['template'];
258
    }
259

    
260
    // Replace tokens in the message.
261
    $email['message'] = webform_replace_tokens($email['message'], $node, $submission, $email, (boolean) $email['html']);
262

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

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

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

    
303
    // Update the subject if set in the themed headers.
304
    if (isset($email['headers']['Subject'])) {
305
      $email['subject'] = $email['headers']['Subject'];
306
      unset($email['headers']['Subject']);
307
    }
308
    else {
309
      $email['subject'] = webform_format_email_subject($email['subject'], $node, $submission);
310
    }
311

    
312
    // Update the to e-mail if set in the themed headers.
313
    if (isset($email['headers']['To'])) {
314
      $email['email'] = $email['headers']['To'];
315
      unset($email['headers']['To']);
316
      $addresses = array_filter(explode(',', $email['email']));
317
    }
318
    else {
319
      // Format the To address(es).
320
      $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
321
      $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, TRUE, FALSE, NULL, $mapping);
322
      $email['email'] = implode(',', $addresses);
323
    }
324

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

    
328
    if (!$addresses_final) {
329
      continue;
330
    }
331

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

    
342
    // Consolidate addressees into one message if permitted by configuration.
343
    $send_increment = 1;
344
    if (!webform_variable_get('webform_email_address_individual')) {
345
      $send_increment = count($addresses_final);
346
      $addresses_final = array(implode(', ', $addresses_final));
347
    }
348

    
349
    // Mail the webform results.
350
    foreach ($addresses_final as $address) {
351

    
352
      $language = $user->uid ? user_preferred_language($user) : language_default();
353
      $mail_params = array(
354
        'message' => $email['message'],
355
        'subject' => $email['subject'],
356
        'headers' => $email['headers'],
357
        'node' => $node,
358
        'submission' => $submission,
359
        'email' => $email,
360
      );
361

    
362
      if (webform_variable_get('webform_email_html_capable')) {
363
        // Load attachments for the e-mail.
364
        $attachments = array();
365
        if ($email['attachments']) {
366
          webform_component_include('file');
367
          foreach ($node->webform['components'] as $component) {
368
            if (webform_component_feature($component['type'], 'attachment') && !empty($submission->data[$component['cid']][0])) {
369
              if (webform_component_implements($component['type'], 'attachments')) {
370
                $files = webform_component_invoke($component['type'], 'attachments', $component, $submission->data[$component['cid']]);
371
                if ($files) {
372
                  $attachments = array_merge($attachments, $files);
373
                }
374
              }
375
            }
376
          }
377
        }
378

    
379
        // Add the attachments to the mail parameters.
380
        $mail_params['attachments'] = $attachments;
381

    
382
        // Set all other properties for HTML e-mail handling.
383
        $mail_params['plain'] = !$email['html'];
384
        $mail_params['plaintext'] = $email['html'] ? NULL : $email['message'];
385
        $mail_params['headers'] = $email['headers'];
386
        if ($email['html']) {
387
          // MIME Mail requires this header or it will filter all text.
388
          $mail_params['headers']['Content-Type'] = 'text/html; charset=UTF-8';
389
        }
390
      }
391

    
392
      // Mail the submission.
393
      $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
394
      if ($message['result']) {
395
        $send_count += $send_increment;
396
      }
397
    }
398
  }
399

    
400
  return $send_count;
401
}
402

    
403
/**
404
 * Confirm form to delete a single form submission.
405
 *
406
 * @param $form
407
 *   The new form array.
408
 * @param $form_state
409
 *   The current form state.
410
 * @param $node
411
 *   The node for which this webform was submitted.
412
 * @param $submission
413
 *   The submission to be deleted (from webform_submitted_data).
414
 */
415
function webform_submission_delete_form($form, $form_state, $node, $submission) {
416
  webform_set_breadcrumb($node, $submission);
417

    
418
  // Set the correct page title.
419
  drupal_set_title(webform_submission_title($node, $submission));
420

    
421
  // Keep the NID and SID in the same location as the webform_client_form().
422
  $form['#tree'] = TRUE;
423
  $form['details']['nid'] = array(
424
    '#type' => 'value',
425
    '#value' => $node->nid,
426
  );
427
  $form['details']['sid'] = array(
428
    '#type' => 'value',
429
    '#value' => $submission->sid,
430
  );
431

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

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

    
437
/**
438
 *
439
 */
440
function webform_submission_delete_form_submit($form, &$form_state) {
441
  $node = node_load($form_state['values']['details']['nid']);
442
  $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
443
  webform_submission_delete($node, $submission);
444
  drupal_set_message(t('Submission deleted.'));
445

    
446
  // If no destination query was supplied in the URL (for example, Edit tab),
447
  // redirect to the most-privledged destination.
448
  $form_state['redirect'] = 'node/' . $node->nid .
449
                            (webform_results_access($node) ? '/webform-results' : '/submissions');
450
}
451

    
452
/**
453
 * Menu title callback; Return the submission number as a title.
454
 */
455
function webform_submission_title($node, $submission) {
456
  return t('Submission #@serial', array('@serial' => $submission->serial));
457
}
458

    
459
/**
460
 * Menu callback; Present a Webform submission page for display or editing.
461
 */
462
function webform_submission_page($node, $submission, $format) {
463
  global $user;
464

    
465
  // Render the admin UI breadcrumb.
466
  webform_set_breadcrumb($node, $submission);
467

    
468
  // Set the correct page title.
469
  drupal_set_title(webform_submission_title($node, $submission));
470

    
471
  if ($format == 'form') {
472
    $output = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission);
473
  }
474
  else {
475
    $renderable = webform_submission_render($node, $submission, NULL, $format);
476
    $renderable['#attached']['css'][] = drupal_get_path('module', 'webform') . '/css/webform.css';
477
    $output = drupal_render($renderable);
478
  }
479

    
480
  // Determine the mode in which we're displaying this submission.
481
  $mode = ($format != 'form') ? 'display' : 'form';
482
  if (strpos(request_uri(), 'print/') !== FALSE) {
483
    $mode = 'print';
484
  }
485
  if (strpos(request_uri(), 'printpdf/') !== FALSE) {
486
    $mode = 'pdf';
487
  }
488

    
489
  // Add navigation for administrators.
490
  if (webform_results_access($node)) {
491
    $navigation = theme('webform_submission_navigation', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
492
    $information = theme('webform_submission_information', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
493
  }
494
  else {
495
    $navigation = NULL;
496
    $information = NULL;
497
  }
498

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

    
502
  // Disable the page cache for anonymous users viewing or editing submissions.
503
  if (!$user->uid) {
504
    webform_disable_page_cache();
505
  }
506

    
507
  $page = array(
508
    '#theme' => 'webform_submission_page',
509
    '#node' => $node,
510
    '#mode' => $mode,
511
    '#submission' => $submission,
512
    '#submission_content' => $output,
513
    '#submission_navigation' => $navigation,
514
    '#submission_information' => $information,
515
    '#submission_actions' => $actions,
516
  );
517
  $page['#attached']['library'][] = array('webform', 'admin');
518
  return $page;
519
}
520

    
521
/**
522
 * Form to resend specific e-mails associated with a submission.
523
 */
524
function webform_submission_resend($form, $form_state, $node, $submission) {
525
  // Render the admin UI breadcrumb.
526
  webform_set_breadcrumb($node, $submission);
527

    
528
  $form['#tree'] = TRUE;
529
  $form['#node'] = $node;
530
  $form['#submission'] = $submission;
531

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

    
534
    $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
535
    $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, FALSE, FALSE, NULL, $mapping);
536
    $addresses_valid = array_map('webform_valid_email_address', $addresses);
537
    $valid_email = count($addresses) == array_sum($addresses_valid);
538

    
539
    $form['resend'][$eid] = array(
540
      '#type' => 'checkbox',
541
      '#default_value' => $valid_email && $email['status'],
542
      '#disabled' => !$valid_email,
543
    );
544
    $form['emails'][$eid]['email'] = array(
545
      '#markup' => nl2br(check_plain(implode("\n", $addresses))),
546
    );
547
    if (!$valid_email) {
548
      $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty or invalid') . ')';
549
    }
550
    $form['emails'][$eid]['subject'] = array(
551
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
552
    );
553

    
554
    $form['actions'] = array('#type' => 'actions');
555
    $form['actions']['submit'] = array(
556
      '#type' => 'submit',
557
      '#value' => t('Resend e-mails'),
558
    );
559
    $form['actions']['cancel'] = array(
560
      '#type' => 'markup',
561
      '#markup' => l(t('Cancel'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/submission/' . $submission->sid),
562
    );
563
  }
564
  return $form;
565
}
566

    
567
/**
568
 * Validate handler for webform_submission_resend().
569
 */
570
function webform_submission_resend_validate($form, &$form_state) {
571
  if (count(array_filter($form_state['values']['resend'])) == 0) {
572
    form_set_error('emails', t('You must select at least one email address to resend submission.'));
573
  }
574
}
575

    
576
/**
577
 * Submit handler for webform_submission_resend().
578
 */
579
function webform_submission_resend_submit($form, &$form_state) {
580
  $node = $form['#node'];
581
  $submission = $form['#submission'];
582

    
583
  $emails = array();
584
  foreach ($form_state['values']['resend'] as $eid => $checked) {
585
    if ($checked) {
586
      $emails[] = $form['#node']->webform['emails'][$eid];
587
    }
588
  }
589
  $sent_count = webform_submission_send_mail($node, $submission, $emails);
590
  if ($sent_count) {
591
    drupal_set_message(format_plural($sent_count,
592
      'Successfully re-sent submission #@sid to 1 recipient.',
593
      'Successfully re-sent submission #@sid to @count recipients.',
594
      array('@sid' => $submission->sid)
595
    ));
596
  }
597
  else {
598
    drupal_set_message(t('No e-mails were able to be sent due to a server error.'), 'error');
599
  }
600
}
601

    
602
/**
603
 * Theme the node components form. Use a table to organize the components.
604
 *
605
 * @param array $variables
606
 *   Array with key "form" containing the form array.
607
 *
608
 * @return string
609
 *   Formatted HTML form, ready for display.
610
 *
611
 * @throws Exception
612
 */
613
function theme_webform_submission_resend(array $variables) {
614
  $form = $variables['form'];
615

    
616
  $header = array(t('Send'), t('E-mail to'), t('Subject'));
617
  $rows = array();
618
  if (!empty($form['emails'])) {
619
    foreach (element_children($form['emails']) as $eid) {
620
      // Add each component to a table row.
621
      $rows[] = array(
622
        drupal_render($form['resend'][$eid]),
623
        drupal_render($form['emails'][$eid]['email']),
624
        drupal_render($form['emails'][$eid]['subject']),
625
      );
626
    }
627
  }
628
  else {
629
    $rows[] = array(array('data' => t('This webform is currently not setup to send emails.'), 'colspan' => 3));
630
  }
631
  $output = '';
632
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('id' => 'webform-emails')));
633
  $output .= drupal_render_children($form);
634
  return $output;
635
}
636

    
637
/**
638
 * Print a Webform submission for display on a page or in an e-mail.
639
 */
640
function webform_submission_render($node, $submission, $email, $format, $excluded_components = NULL) {
641
  $component_tree = array();
642
  $renderable = array();
643
  $page_count = 1;
644

    
645
  // Meta data that may be useful for modules implementing
646
  // hook_webform_submission_render_alter().
647
  $renderable['#node'] = $node;
648
  $renderable['#submission'] = $submission;
649
  $renderable['#email'] = $email;
650
  $renderable['#format'] = $format;
651

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

    
655
  $components = $node->webform['components'];
656

    
657
  // Remove excluded components.
658
  if (is_array($excluded_components)) {
659
    foreach ($excluded_components as $cid) {
660
      unset($components[$cid]);
661
    }
662
    if (!empty($email['exclude_empty'])) {
663
      foreach ($submission->data as $cid => $data) {
664
        // Caution. Grids store their data in an array index by question key.
665
        if (implode($data) == '') {
666
          unset($components[$cid]);
667
        }
668
      }
669
    }
670
  }
671

    
672
  module_load_include('inc', 'webform', 'includes/webform.components');
673
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
674

    
675
  // Make sure at least one field is available.
676
  if (isset($component_tree['children'])) {
677
    // Recursively add components to the form.
678
    $sorter = webform_get_conditional_sorter($node);
679
    $input_values = $sorter->executeConditionals($submission->data);
680
    foreach ($component_tree['children'] as $cid => $component) {
681
      if ($sorter->componentVisibility($cid, $component['page_num']) == webformConditionals::componentShown) {
682
        _webform_client_form_add_component($node, $component, NULL, $renderable, $renderable, $input_values, $format);
683
      }
684
    }
685
  }
686

    
687
  drupal_alter('webform_submission_render', $renderable);
688
  return $renderable;
689
}
690

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

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

    
735
  // Qualify all filters with a table alias. ws.* is assumed, except for u.uid.
736
  foreach ($filters as $column => $value) {
737
    if (strpos($column, '.') === FALSE) {
738
      $filters[($column == 'uid' ? 'u.' : 'ws.') . $column] = $value;
739
      unset($filters[$column]);
740
    }
741
  }
742

    
743
  // If the sid is specified, but there are none, force the query to fail
744
  // rather than query on an empty array.
745
  if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
746
    $filters['ws.sid'] = 0;
747
  }
748

    
749
  // Build the list of submissions and load their basic information.
750
  $pager_query = db_select('webform_submissions', 'ws')
751
    // Ensure only one row per submission is returned. Could be more than one if
752
    // sorting on a column that uses multiple rows for its data.
753
    ->distinct()
754
    ->addTag('webform_get_submissions_sids')
755
    ->fields('ws');
756

    
757
  // Add each filter.
758
  foreach ($filters as $column => $value) {
759
    $pager_query->condition($column, $value);
760
  }
761

    
762
  // Join to the users table to include user name in results.
763
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
764
  $pager_query->fields('u', array('name'));
765
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
766
    if (!empty($_SESSION['webform_submission'])) {
767
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
768
      $pager_query->condition('ws.sid', $anonymous_sids, 'IN');
769
    }
770
    else {
771
      $pager_query->condition('ws.sid', 0);
772
    }
773
  }
774

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

    
804
  if ($pager_count) {
805
    // Extending the query instantiates a new query object.
806
    $pager_query = $pager_query->extend('PagerDefault');
807
    $pager_query->limit($pager_count);
808
  }
809
  return $pager_query;
810
}
811

    
812
/**
813
 * Retrieve and load the submissions for the specified submissions query.
814
 *
815
 * This is an internal routine and not intended for use by other modules.
816
 *
817
 * @params object $pager_query
818
 *   A select or extended select query containing the needed fields:
819
 *     webform_submissions: all fields
820
 *     user: name
821
 *
822
 * @return array
823
 *   An array of loaded webform submissions.
824
 */
825
function webform_get_submissions_load($pager_query) {
826
  // If the "$pager_query" is actually an unextended select query, then instead
827
  // of querying the webform_submissions_data table with a potentially huge
828
  // array of sids in an IN clause, use the select query directly as this will
829
  // be much faster. Extended queries don't work in join clauses. The query
830
  // is assumed to include the sid.
831
  if ($pager_query instanceof SelectQuery) {
832
    $submissions_query = clone $pager_query;
833
  }
834

    
835
  // Extract any filter on node id to use in an optimization below.
836
  foreach ($pager_query->conditions() as $index => $condition) {
837
    if ($index !== '#conjunction' && $condition['operator'] === '=' && ($condition['field'] === 'nid' || $condition['field'] === 'ws.nid')) {
838
      $nid = $condition['value'];
839
      break;
840
    }
841
  }
842

    
843
  $result = $pager_query->execute();
844
  $submissions = $result->fetchAllAssoc('sid');
845

    
846
  // If there are no submissions being retrieved, return an empty array.
847
  if (!$submissions) {
848
    return $submissions;
849
  }
850

    
851
  foreach ($submissions as $sid => $submission) {
852
    $submissions[$sid]->preview = FALSE;
853
    $submissions[$sid]->data = array();
854
  }
855

    
856
  // Query the required submission data.
857
  $query = db_select('webform_submitted_data', 'sd');
858
  $query
859
    ->addTag('webform_get_submissions_data')
860
    ->fields('sd', array('sid', 'cid', 'no', 'data'))
861
    ->orderBy('sd.sid', 'ASC')
862
    ->orderBy('sd.cid', 'ASC')
863
    ->orderBy('sd.no', 'ASC');
864

    
865
  if (isset($submissions_query)) {
866
    // If available, prefer joining on the subquery as it is much faster than an
867
    // IN clause on a large array. A subquery with the IN operator doesn't work
868
    // when the subquery has a LIMIT clause, requiring an inner join instead.
869
    $query->innerJoin($submissions_query, 'ws2', 'sd.sid = ws2.sid');
870
  }
871
  else {
872
    $query->condition('sd.sid', array_keys($submissions), 'IN');
873
  }
874

    
875
  // By adding the NID to this query we allow MySQL to use the primary key on
876
  // in webform_submitted_data for sorting (nid_sid_cid_no).
877
  if (isset($nid)) {
878
    $query->condition('sd.nid', $nid);
879
  }
880

    
881
  $result = $query->execute();
882

    
883
  // Convert the queried rows into submission data.
884
  foreach ($result as $row) {
885
    $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
886
  }
887

    
888
  foreach (module_implements('webform_submission_load') as $module) {
889
    $function = $module . '_webform_submission_load';
890
    $function($submissions);
891
  }
892

    
893
  return $submissions;
894
}
895

    
896
/**
897
 * Return a count of the total number of submissions for a node.
898
 *
899
 * @param $nid
900
 *   The node ID for which submissions are being fetched.
901
 * @param $uid
902
 *   Optional; the user ID to filter the submissions by.
903
 * @param $is_draft
904
 *   Optional; NULL for all, truthy for drafts only, falsy for completed only.
905
 *   The default is completed submissions only.
906
 *
907
 * @return int
908
 *   The number of submissions.
909
 */
910
function webform_get_submission_count($nid, $uid = NULL, $is_draft = 0) {
911
  $counts = &drupal_static(__FUNCTION__);
912

    
913
  if (!isset($counts[$nid][$uid])) {
914
    $query = db_select('webform_submissions', 'ws')
915
      ->addTag('webform_get_submission_count')
916
      ->condition('ws.nid', $nid);
917
    if ($uid !== NULL) {
918
      $query->condition('ws.uid', $uid);
919
    }
920
    if ($uid === 0) {
921
      $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
922
      if ($submissions) {
923
        $query->condition('ws.sid', $submissions, 'IN');
924
      }
925
      else {
926
        // Intentionally never match anything if the anonymous user has no
927
        // submissions.
928
        $query->condition('ws.sid', 0);
929
      }
930
    }
931
    if (isset($is_draft)) {
932
      $query->condition('ws.is_draft', $is_draft);
933
    }
934

    
935
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
936
  }
937
  return $counts[$nid][$uid];
938
}
939

    
940
/**
941
 * Fetch a specified submission for a webform node.
942
 */
943
function webform_get_submission($nid, $sid) {
944
  $submissions = &drupal_static(__FUNCTION__, array());
945

    
946
  // Load the submission if needed.
947
  if (!isset($submissions[$sid])) {
948
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
949
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
950
  }
951

    
952
  return $submissions[$sid];
953
}
954

    
955
/**
956
 *
957
 */
958
function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
959
  $headers = implode('\n', (array) $headers);
960
  // Check if they are attempting to spam using a bcc or content type hack.
961
  if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
962
    // Possible spam attempt.
963
    return TRUE;
964
  }
965
  // Not spam.
966
  return FALSE;
967
}
968

    
969
/**
970
 * Check if the current user has exceeded the limit on this form.
971
 *
972
 * @param $node
973
 *   The webform node to be checked.
974
 * @param $account
975
 *   Optional parameter. Specify the account you want to check the limit
976
 *   against.
977
 *
978
 * @return bool
979
 *   Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
980
 */
981
function webform_submission_user_limit_check($node, $account = NULL) {
982
  global $user;
983
  $tracking_mode = webform_variable_get('webform_tracking_mode');
984

    
985
  if (!isset($account)) {
986
    $account = $user;
987
  }
988

    
989
  // We can only check access for anonymous users through their cookies.
990
  if ($user->uid !== 0 && $account->uid === 0) {
991
    watchdog('webform', 'Unable to check anonymous user submission limit when logged in as user @uid.', array('@uid' => $user->uid), WATCHDOG_WARNING);
992
    return FALSE;
993
  }
994

    
995
  // Check if submission limiting is enabled.
996
  if ($node->webform['submit_limit'] == '-1') {
997
    // No check enabled.
998
    return FALSE;
999
  }
1000

    
1001
  // Fetch all the entries from the database within the submit interval with
1002
  // this username and IP.
1003
  $num_submissions_database = 0;
1004
  if (!$node->webform['confidential'] &&
1005
      ($account->uid !== 0 || $tracking_mode === 'ip_address' || $tracking_mode === 'strict')) {
1006
    $query = db_select('webform_submissions')
1007
      ->addTag('webform_submission_user_limit_check')
1008
      ->condition('nid', $node->nid)
1009
      ->condition('is_draft', 0);
1010

    
1011
    if ($node->webform['submit_interval'] != -1) {
1012
      $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
1013
    }
1014

    
1015
    if ($account->uid) {
1016
      $query->condition('uid', $account->uid);
1017
    }
1018
    else {
1019
      $query->condition('remote_addr', ip_address());
1020
    }
1021
    $num_submissions_database = $query->countQuery()->execute()->fetchField();
1022
  }
1023

    
1024
  // Double check the submission history from the users machine using cookies.
1025
  $num_submissions_cookie = 0;
1026
  if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
1027
    $cookie_name = 'webform-' . $node->nid;
1028

    
1029
    if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
1030
      foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
1031
        if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
1032
          // Remove the cookie if past the required time interval.
1033
          $params = session_get_cookie_params();
1034
          setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1035
        }
1036
      }
1037
      // Count the number of submissions recorded in cookies.
1038
      $num_submissions_cookie = count($_COOKIE[$cookie_name]);
1039
    }
1040
  }
1041

    
1042
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
1043
    // Limit exceeded.
1044
    return TRUE;
1045
  }
1046

    
1047
  // Limit not exceeded.
1048
  return FALSE;
1049
}
1050

    
1051
/**
1052
 * Check if the total number of submissions has exceeded the limit on this form.
1053
 *
1054
 * @param $node
1055
 *   The webform node to be checked.
1056
 *
1057
 * @return bool
1058
 *   Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
1059
 */
1060
function webform_submission_total_limit_check($node) {
1061

    
1062
  // Check if submission limiting is enabled.
1063
  if ($node->webform['total_submit_limit'] == '-1') {
1064
    // No check enabled.
1065
    return FALSE;
1066
  }
1067

    
1068
  // Retrieve submission data from the database.
1069
  $query = db_select('webform_submissions')
1070
    ->addTag('webform_submission_total_limit_check')
1071
    ->condition('nid', $node->nid)
1072
    ->condition('is_draft', 0);
1073

    
1074
  if ($node->webform['total_submit_interval'] != -1) {
1075
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
1076
  }
1077

    
1078
  // Fetch all the entries from the database within the submit interval.
1079
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
1080

    
1081
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
1082
    // Limit exceeded.
1083
    return TRUE;
1084
  }
1085

    
1086
  // Limit not exceeded.
1087
  return FALSE;
1088
}
1089

    
1090
/**
1091
 * Preprocess function for webform-submission.tpl.php.
1092
 */
1093
function template_preprocess_webform_submission(&$vars) {
1094
  $vars['node'] = $vars['renderable']['#node'];
1095
  $vars['submission'] = $vars['renderable']['#submission'];
1096
  $vars['email'] = $vars['renderable']['#email'];
1097
  $vars['format'] = $vars['renderable']['#format'];
1098
}
1099

    
1100
/**
1101
 * Preprocess function for webform-submission-navigation.tpl.php.
1102
 */
1103
function template_preprocess_webform_submission_navigation(&$vars) {
1104
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
1105

    
1106
  $previous_query = db_select('webform_submissions')
1107
    ->condition('nid', $vars['node']->nid)
1108
    ->condition('sid', $vars['submission']->sid, '<');
1109
  $previous_query->addExpression('MAX(sid)');
1110

    
1111
  $next_query = db_select('webform_submissions')
1112
    ->condition('nid', $vars['node']->nid)
1113
    ->condition('sid', $vars['submission']->sid, '>');
1114
  $next_query->addExpression('MIN(sid)');
1115

    
1116
  $vars['previous'] = $previous_query->execute()->fetchField();
1117
  $vars['next'] = $next_query->execute()->fetchField();
1118
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
1119
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
1120
}
1121

    
1122
/**
1123
 * Preprocess function for webform-submission-navigation.tpl.php.
1124
 */
1125
function template_preprocess_webform_submission_information(&$vars) {
1126
  $vars['account'] = user_load($vars['submission']->uid);
1127
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
1128
}