Projet

Général

Profil

Paste
Télécharger (30,6 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

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

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

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

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

    
38
  return $data;
39
}
40

    
41
/**
42
 * Update a webform submission entry in the database.
43
 *
44
 * @param $node
45
 *   The node object containing the current webform.
46
 * @param $submission
47
 *   The webform submission object to be saved into the database.
48
 * @return
49
 *   The existing submission SID.
50
 */
51
function webform_submission_update($node, $submission) {
52
  // Allow other modules to modify the submission before saving.
53
  foreach (module_implements('webform_submission_presave') as $module) {
54
    $function = $module . '_webform_submission_presave';
55
    $function($node, $submission);
56
  }
57

    
58
  // Update the main submission info.
59
  drupal_write_record('webform_submissions', $submission, 'sid');
60

    
61
  // If is draft, only delete data for components submitted, to
62
  // preserve any data from form pages not visited in this submission.
63
  if ($submission->is_draft) {
64
    $submitted_cids = array_keys($submission->data);
65
    if ($submitted_cids) {
66
      db_delete('webform_submitted_data')
67
        ->condition('sid', $submission->sid)
68
        ->condition('cid', $submitted_cids, 'IN')
69
        ->execute();
70
    }
71
  }
72
  else {
73
    db_delete('webform_submitted_data')
74
      ->condition('sid', $submission->sid)
75
      ->execute();
76
  }
77

    
78
  // Then re-add submission data to the database.
79
  $submission->is_new = FALSE;
80
  webform_submission_insert($node, $submission);
81

    
82
  module_invoke_all('webform_submission_update', $node, $submission);
83

    
84
  return $submission->sid;
85
}
86

    
87
/**
88
 * Insert a webform submission entry in the database.
89
 *
90
 * @param $node
91
 *   The node object containing the current webform.
92
 * @param $submission
93
 *   The webform submission object to be saved into the database.
94
 * @return
95
 *   The new submission SID.
96
 */
97
function webform_submission_insert($node, $submission) {
98
  // The submission ID may already be set if being called as an update.
99
  if (!isset($submission->sid) && (!isset($submission->is_new) || $submission->is_new == FALSE)) {
100
    // Allow other modules to modify the submission before saving.
101
    foreach (module_implements('webform_submission_presave') as $module) {
102
      $function = $module . '_webform_submission_presave';
103
      $function($node, $submission);
104
    }
105
    $submission->nid = $node->webform['nid'];
106
    drupal_write_record('webform_submissions', $submission);
107
    $is_new = TRUE;
108
  }
109

    
110
  foreach ($submission->data as $cid => $values) {
111
    foreach ($values['value'] as $delta => $value) {
112
      $data = array(
113
        'nid' => $node->webform['nid'],
114
        'sid' => $submission->sid,
115
        'cid' => $cid,
116
        'no' => $delta,
117
        'data' => is_null($value) ? '' : $value,
118
      );
119
      drupal_write_record('webform_submitted_data', $data);
120
    }
121
  }
122

    
123
  // Invoke the insert hook after saving all the data.
124
  if (isset($is_new)) {
125
    module_invoke_all('webform_submission_insert', $node, $submission);
126
  }
127

    
128
  return $submission->sid;
129
}
130

    
131
/**
132
 * Delete a single submission.
133
 *
134
 * @param $node
135
 *   The node object containing the current webform.
136
 * @param $submission
137
 *   The webform submission object to be deleted from the database.
138
 */
139
function webform_submission_delete($node, $submission) {
140
  // Iterate through all components and let each do cleanup if necessary.
141
  foreach ($node->webform['components'] as $cid => $component) {
142
    if (isset($submission->data[$cid])) {
143
      webform_component_invoke($component['type'], 'delete', $component, $submission->data[$cid]['value']);
144
    }
145
  }
146

    
147
  // Delete any anonymous session information.
148
  if (isset($_SESSION['webform_submission'][$submission->sid])) {
149
    unset($_SESSION['webform_submission'][$submission->sid]);
150
  }
151

    
152
  db_delete('webform_submitted_data')
153
    ->condition('nid', $node->nid)
154
    ->condition('sid', $submission->sid)
155
    ->execute();
156
  db_delete('webform_submissions')
157
    ->condition('nid', $node->nid)
158
    ->condition('sid', $submission->sid)
159
    ->execute();
160

    
161
  module_invoke_all('webform_submission_delete', $node, $submission);
162
}
163

    
164
/**
165
 * Send related e-mails related to a submission.
166
 *
167
 * This function is usually invoked when a submission is completed, but may be
168
 * called any time e-mails should be redelivered.
169
 *
170
 * @param $node
171
 *   The node object containing the current webform.
172
 * @param $submission
173
 *   The webform submission object to be used in sending e-mails.
174
 * @param $emails
175
 *   (optional) An array of specific e-mail settings to be used. If omitted, all
176
 *   e-mails in $node->webform['emails'] will be sent.
177
 */
178
function webform_submission_send_mail($node, $submission, $emails = NULL) {
179
  global $user;
180

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

    
184
  // Create a themed message for mailing.
185
  $send_count = 0;
186
  foreach ($emails as $eid => $email) {
187
    // Set the HTML property based on availablity of MIME Mail.
188
    $email['html'] = ($email['html'] && webform_email_html_capable());
189

    
190
    // Pass through the theme layer if using the default template.
191
    if ($email['template'] == 'default') {
192
      $email['message'] = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'submission' => $submission, 'email' => $email));
193
    }
194
    else {
195
      $email['message'] = $email['template'];
196
    }
197

    
198
    // Replace tokens in the message.
199
    $email['message'] = _webform_filter_values($email['message'], $node, $submission, $email, FALSE, TRUE);
200

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

    
204
    // Assemble the From string.
205
    if (isset($email['headers']['From'])) {
206
      // If a header From is already set, don't override it.
207
      $email['from'] = $email['headers']['From'];
208
      unset($email['headers']['From']);
209
    }
210
    else {
211
      $email['from'] = webform_format_email_address($email['from_address'], $email['from_name'], $node, $submission);
212
    }
213

    
214
    // Update the subject if set in the themed headers.
215
    if (isset($email['headers']['Subject'])) {
216
      $email['subject'] = $email['headers']['Subject'];
217
      unset($email['headers']['Subject']);
218
    }
219
    else {
220
      $email['subject'] = webform_format_email_subject($email['subject'], $node, $submission);
221
    }
222

    
223
    // Update the to e-mail if set in the themed headers.
224
    if (isset($email['headers']['To'])) {
225
      $email['email'] = $email['headers']['To'];
226
      unset($email['headers']['To']);
227
    }
228

    
229
    // Generate the list of addresses that this e-mail will be sent to.
230
    $addresses = array_filter(explode(',', $email['email']));
231
    $addresses_final = array();
232
    foreach ($addresses as $address) {
233
      $address = trim($address);
234

    
235
      // After filtering e-mail addresses with component values, a single value
236
      // might contain multiple addresses (such as from checkboxes or selects).
237
      $address = webform_format_email_address($address, NULL, $node, $submission, TRUE, FALSE, 'short');
238

    
239
      if (is_array($address)) {
240
        foreach ($address as $new_address) {
241
          $new_address = trim($new_address);
242
          if (valid_email_address($new_address)) {
243
            $addresses_final[] = $new_address;
244
          }
245
        }
246
      }
247
      elseif (valid_email_address($address)) {
248
        $addresses_final[] = $address;
249
      }
250
    }
251

    
252
    // Mail the webform results.
253
    foreach ($addresses_final as $address) {
254
      // Verify that this submission is not attempting to send any spam hacks.
255
      if (_webform_submission_spam_check($address, $email['subject'], $email['from'], $email['headers'])) {
256
        watchdog('webform', 'Possible spam attempt from @remote_addr' . "<br />\n" . nl2br(htmlentities($email['message'])), array('@remote_add' => ip_address()));
257
        drupal_set_message(t('Illegal information. Data not submitted.'), 'error');
258
        return FALSE;
259
      }
260

    
261
      $language = $user->uid ? user_preferred_language($user) : language_default();
262
      $mail_params = array(
263
        'message' => $email['message'],
264
        'subject' => $email['subject'],
265
        'headers' => $email['headers'],
266
        'node' => $node,
267
        'submission' => $submission,
268
        'email' => $email,
269
      );
270

    
271
      if (webform_email_html_capable()) {
272
        // Load attachments for the e-mail.
273
        $attachments = array();
274
        if ($email['attachments']) {
275
          webform_component_include('file');
276
          foreach ($node->webform['components'] as $component) {
277
            if (webform_component_feature($component['type'], 'attachment') && !empty($submission->data[$component['cid']]['value'][0])) {
278
              if (webform_component_implements($component['type'], 'attachments')) {
279
                $files = webform_component_invoke($component['type'], 'attachments', $component, $submission->data[$component['cid']]['value']);
280
                if ($files) {
281
                  $attachments = array_merge($attachments, $files);
282
                }
283
              }
284
            }
285
          }
286
        }
287

    
288
        // Add the attachments to the mail parameters.
289
        $mail_params['attachments'] = $attachments;
290

    
291
        // Set all other properties for HTML e-mail handling.
292
        $mail_params['plain'] = !$email['html'];
293
        $mail_params['plaintext'] = $email['html'] ? NULL : $email['message'];
294
        $mail_params['headers'] = $email['headers'];
295
        if ($email['html']) {
296
          // MIME Mail requires this header or it will filter all text.
297
          $mail_params['headers']['Content-Type'] = 'text/html; charset=UTF-8';
298
        }
299
      }
300

    
301
      // Mail the submission.
302
      $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
303
      if ($message['result']) {
304
        $send_count++;
305
      }
306
    }
307
  }
308

    
309
  return $send_count;
310
}
311

    
312
/**
313
 * Confirm form to delete a single form submission.
314
 *
315
 * @param $form
316
 *   The new form array.
317
 * @param $form_state
318
 *   The current form state.
319
 * @param $node
320
 *   The node for which this webform was submitted.
321
 * @param $submission
322
 *   The submission to be deleted (from webform_submitted_data).
323
 */
324
function webform_submission_delete_form($form, $form_state, $node, $submission) {
325
  webform_set_breadcrumb($node, $submission);
326

    
327
  // Set the correct page title.
328
  drupal_set_title(webform_submission_title($node, $submission));
329

    
330
  // Keep the NID and SID in the same location as the webform_client_form().
331
  // This helps mollom identify the same fields when deleting a submission.
332
  $form['#tree'] = TRUE;
333
  $form['details']['nid'] = array(
334
    '#type' => 'value',
335
    '#value' => $node->nid,
336
  );
337
  $form['details']['sid'] = array(
338
    '#type' => 'value',
339
    '#value' => $submission->sid,
340
  );
341

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

    
344
  if (isset($_GET['destination'])) {
345
    $destination = $_GET['destination'];
346
  }
347
  elseif (webform_results_access($node)) {
348
    $destination = 'node/' . $node->nid . '/webform-results';
349
  }
350
  else {
351
    $destination = 'node/' . $node->nid . '/submissions';
352
  }
353

    
354
  return confirm_form($form, NULL, $destination, $question, t('Delete'), t('Cancel'));
355
}
356

    
357
function webform_submission_delete_form_submit($form, &$form_state) {
358
  $node = node_load($form_state['values']['details']['nid']);
359
  $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
360
  webform_submission_delete($node, $submission);
361
  drupal_set_message(t('Submission deleted.'));
362

    
363
  $form_state['redirect'] = 'node/' . $node->nid . '/webform-results';
364
}
365

    
366
/**
367
 * Menu title callback; Return the submission number as a title.
368
 */
369
function webform_submission_title($node, $submission) {
370
  return t('Submission #@sid', array('@sid' => $submission->sid));
371
}
372

    
373
/**
374
 * Menu callback; Present a Webform submission page for display or editing.
375
 */
376
function webform_submission_page($node, $submission, $format) {
377
  global $user;
378

    
379
  // Render the admin UI breadcrumb.
380
  webform_set_breadcrumb($node, $submission);
381

    
382
  // Set the correct page title.
383
  drupal_set_title(webform_submission_title($node, $submission));
384

    
385
  if ($format == 'form') {
386
    $output = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission);
387
  }
388
  else {
389
    $output = webform_submission_render($node, $submission, NULL, $format);
390
  }
391

    
392
  // Determine the mode in which we're displaying this submission.
393
  $mode = ($format != 'form') ? 'display' : 'form';
394
  if (strpos(request_uri(), 'print/') !== FALSE) {
395
    $mode = 'print';
396
  }
397
  if (strpos(request_uri(), 'printpdf/') !== FALSE) {
398
    $mode = 'pdf';
399
  }
400

    
401
  // Add navigation for administrators.
402
  if (webform_results_access($node)) {
403
    $navigation = theme('webform_submission_navigation', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
404
    $information = theme('webform_submission_information', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
405
  }
406
  else {
407
    $navigation = NULL;
408
    $information = NULL;
409
  }
410

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

    
414
  // Disable the page cache for anonymous users viewing or editing submissions.
415
  if (!$user->uid) {
416
    webform_disable_page_cache();
417
  }
418

    
419
  $page = array(
420
    '#theme' => 'webform_submission_page',
421
    '#node' => $node,
422
    '#mode' => $mode,
423
    '#submission' => $submission,
424
    '#submission_content' => $output,
425
    '#submission_navigation' => $navigation,
426
    '#submission_information' => $information,
427
    '#submission_actions' => $actions,
428
  );
429
  $page['#attached']['library'][] = array('webform', 'admin');
430
  return $page;
431
}
432

    
433
/**
434
 * Form to resend specific e-mails associated with a submission.
435
 */
436
function webform_submission_resend($form, $form_state, $node, $submission) {
437
  // Render the admin UI breadcrumb.
438
  webform_set_breadcrumb($node, $submission);
439

    
440
  $form['#tree'] = TRUE;
441
  $form['#node'] = $node;
442
  $form['#submission'] = $submission;
443

    
444
  foreach ($node->webform['emails'] as $eid => $email) {
445
    $email_addresses = array_filter(explode(',', check_plain($email['email'])));
446
    foreach ($email_addresses as $key => $email_address) {
447
      $email_addresses[$key] = webform_format_email_address($email_address, NULL, $node, $submission, FALSE);
448
    }
449
    $valid_email = !empty($email_addresses[0]) && valid_email_address($email_addresses[0]);
450
    $form['resend'][$eid] = array(
451
      '#type' => 'checkbox',
452
      '#default_value' => $valid_email ? TRUE : FALSE,
453
      '#disabled' => $valid_email ? FALSE : TRUE,
454
    );
455
    $form['emails'][$eid]['email'] = array(
456
      '#markup' => implode('<br />', $email_addresses),
457
    );
458
    if (!$valid_email) {
459
      $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty') . ')';
460
    }
461
    $form['emails'][$eid]['subject'] = array(
462
      '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
463
    );
464

    
465
    $form['actions'] = array('#type' => 'actions');
466
    $form['actions']['submit'] = array(
467
      '#type' => 'submit',
468
      '#value' => t('Resend e-mails'),
469
    );
470
    $form['actions']['cancel'] = array(
471
      '#type' => 'markup',
472
      '#markup' => l(t('Cancel'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/submission/' . $submission->sid),
473
    );
474
  }
475
  return $form;
476
}
477

    
478
/**
479
 * Validate handler for webform_submission_resend().
480
 */
481
function webform_submission_resend_validate($form, &$form_state) {
482
  if (count(array_filter($form_state['values']['resend'])) == 0) {
483
    form_set_error('emails', t('You must select at least one email address to resend submission.'));
484
  }
485
}
486

    
487
/**
488
 * Submit handler for webform_submission_resend().
489
 */
490
function webform_submission_resend_submit($form, &$form_state) {
491
  $node = $form['#node'];
492
  $submission = $form['#submission'];
493

    
494
  $emails = array();
495
  foreach ($form_state['values']['resend'] as $eid => $checked) {
496
    if ($checked) {
497
      $emails[] = $form['#node']->webform['emails'][$eid];
498
    }
499
  }
500
  $sent_count = webform_submission_send_mail($node, $submission, $emails);
501
  if ($sent_count) {
502
    drupal_set_message(format_plural($sent_count,
503
      'Successfully re-sent submission #@sid to 1 recipient.',
504
      'Successfully re-sent submission #@sid to @count recipients.',
505
      array('@sid' => $submission->sid)
506
    ));
507
  }
508
  else {
509
    drupal_set_message(t('No e-mails were able to be sent due to a server error.'), 'error');
510
  }
511
}
512

    
513
/**
514
 * Theme the node components form. Use a table to organize the components.
515
 *
516
 * @param $form
517
 *   The form array.
518
 * @return
519
 *   Formatted HTML form, ready for display.
520
 */
521
function theme_webform_submission_resend($variables) {
522
  $form = $variables['form'];
523

    
524
  $header = array('', t('E-mail to'), t('Subject'));
525
  $rows = array();
526
  if (!empty($form['emails'])) {
527
    foreach (element_children($form['emails']) as $eid) {
528
      // Add each component to a table row.
529
      $rows[] = array(
530
        drupal_render($form['resend'][$eid]),
531
        drupal_render($form['emails'][$eid]['email']),
532
        drupal_render($form['emails'][$eid]['subject']),
533
      );
534
    }
535
  }
536
  else {
537
    $rows[] = array(array('data' => t('This webform is currently not setup to send emails.'), 'colspan' => 3));
538
  }
539
  $output = '';
540
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'webform-emails')));
541
  $output .= drupal_render_children($form);
542
  return $output;
543
}
544

    
545
/**
546
 * Print a Webform submission for display on a page or in an e-mail.
547
 */
548
function webform_submission_render($node, $submission, $email, $format) {
549
  $component_tree = array();
550
  $renderable = array();
551
  $page_count = 1;
552
  $excluded_components = isset($email) ? $email['excluded_components'] : array();
553

    
554
  // Meta data that may be useful for modules implementing
555
  // hook_webform_submission_render_alter().
556
  $renderable['#node'] = $node;
557
  $renderable['#submission'] = $submission;
558
  $renderable['#email'] = $email;
559
  $renderable['#format'] = $format;
560

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

    
564
  // Remove excluded components.
565
  $components = $node->webform['components'];
566
  foreach ($excluded_components as $cid) {
567
    unset($components[$cid]);
568
  }
569

    
570
  _webform_components_tree_build($components, $component_tree, 0, $page_count);
571

    
572
  // Make sure at least one field is available
573
  if (isset($component_tree['children'])) {
574
    // Recursively add components to the form.
575
    foreach ($component_tree['children'] as $cid => $component) {
576
      if (_webform_client_form_rule_check($node, $component, $component['page_num'], NULL, $submission)) {
577
        _webform_client_form_add_component($node, $component, NULL, $renderable, $renderable, NULL, $submission, $format);
578
      }
579
    }
580
  }
581

    
582
  drupal_alter('webform_submission_render', $renderable);
583
  return drupal_render($renderable);
584
}
585

    
586
/**
587
 * Return all the submissions for a particular node.
588
 *
589
 * @param $filters
590
 *   An array of filters to apply to this query. Usually in the format
591
 *   array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
592
 *   in, which will be equivalent to specifying a $nid filter.
593
 * @param $header
594
 *   If the results of this fetch will be used in a sortable
595
 *   table, pass the array header of the table.
596
 * @param $pager_count
597
 *   Optional. The number of submissions to include in the results.
598
 */
599
function webform_get_submissions($filters = array(), $header = NULL, $pager_count = 0) {
600
  $submissions = array();
601

    
602
  if (!is_array($filters)) {
603
    $filters = array('nid' => $filters);
604
  }
605

    
606
  // UID filters need to be against a specific table.
607
  if (isset($filters['uid'])) {
608
    $filters['u.uid'] = $filters['uid'];
609
    unset($filters['uid']);
610
  }
611

    
612
  // No need to find SIDs if it was given to us.
613
  if (isset($filters['sid'])) {
614
    $sids = array($filters['sid']);
615
  }
616
  // Build the list of SIDs that need to be retrieved.
617
  else {
618
    $pager_query = db_select('webform_submissions', 'ws')->fields('ws', array('sid'));
619
    foreach ($filters as $column => $value) {
620
      $pager_query->condition($column, $value);
621
    }
622

    
623
    if (isset($filters['u.uid']) || !empty($header)) {
624
      // Join to the users table for sorting by user name.
625
      $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
626
    }
627

    
628
    if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
629
      if (!empty($_SESSION['webform_submission'])) {
630
        $anonymous_sids = array_keys($_SESSION['webform_submission']);
631
        $pager_query->condition('sid', $anonymous_sids, 'IN');
632
      }
633
      else {
634
        $pager_query->condition('sid', 0);
635
      }
636
    }
637

    
638
    if (is_array($header)) {
639
      // Extending the query instatiates a new query object.
640
      $pager_query = $pager_query->extend('TableSort');
641
      $pager_query->orderByHeader($header);
642
    }
643
    else {
644
      $pager_query->orderBy('sid', 'ASC');
645
    }
646

    
647
    if ($pager_count) {
648
      // Extending the query instatiates a new query object.
649
      $pager_query = $pager_query->extend('PagerDefault');
650
      $pager_query->limit($pager_count);
651
    }
652
    $result = $pager_query->execute();
653

    
654
    $sids = array();
655
    foreach ($result as $row) {
656
      $sids[] = $row->sid;
657
      $submissions[$row->sid] = FALSE;
658
    }
659
  }
660

    
661
  // If there are no submissions being retrieved, return an empty array.
662
  if (empty($sids)) {
663
    return $submissions;
664
  }
665

    
666
  // Query the required submission data.
667
  $query = db_select('webform_submitted_data', 'sd');
668
  $query->leftJoin('webform_submissions', 's', 's.sid = sd.sid');
669
  $query->leftJoin('users', 'u', 'u.uid = s.uid');
670
  $query
671
    ->fields('s')
672
    ->fields('sd', array('cid', 'no', 'data'))
673
    ->fields('u', array('name'))
674
    ->condition('sd.sid', $sids, 'IN')
675
    ->orderBy('sd.sid', 'ASC')
676
    ->orderBy('sd.cid', 'ASC')
677
    ->orderBy('sd.no', 'ASC');
678

    
679
  // By adding the NID to this query we allow MySQL to use the primary key on
680
  // in webform_submitted_data for sorting (nid_sid_cid_no).
681
  if (isset($filters['nid'])) {
682
    $query->condition('sd.nid', $filters['nid']);
683
  }
684

    
685
  $result = $query->execute();
686

    
687
  // Convert the queried rows into submissions.
688
  $previous = 0;
689
  foreach ($result as $row) {
690
    if ($row->sid != $previous) {
691
      $submissions[$row->sid] = new stdClass();
692
      $submissions[$row->sid]->sid = $row->sid;
693
      $submissions[$row->sid]->nid = $row->nid;
694
      $submissions[$row->sid]->submitted = $row->submitted;
695
      $submissions[$row->sid]->remote_addr = $row->remote_addr;
696
      $submissions[$row->sid]->uid = $row->uid;
697
      $submissions[$row->sid]->name = $row->name;
698
      $submissions[$row->sid]->is_draft = $row->is_draft;
699
      $submissions[$row->sid]->data = array();
700
    }
701
    // CID may be NULL if this submission does not actually contain any data.
702
    if ($row->cid) {
703
      $submissions[$row->sid]->data[$row->cid]['value'][$row->no] = $row->data;
704
    }
705
    $previous = $row->sid;
706
  }
707

    
708
  foreach (module_implements('webform_submission_load') as $module) {
709
    $function = $module . '_webform_submission_load';
710
    $function($submissions);
711
  }
712

    
713
  return $submissions;
714
}
715

    
716
/**
717
 * Return a count of the total number of submissions for a node.
718
 *
719
 * @param $nid
720
 *   The node ID for which submissions are being fetched.
721
 * @param $uid
722
 *   Optional; the user ID to filter the submissions by.
723
 * @return
724
 *   An integer value of the number of submissions.
725
 */
726
function webform_get_submission_count($nid, $uid = NULL, $reset = FALSE) {
727
  static $counts;
728

    
729
  if (!isset($counts[$nid][$uid]) || $reset) {
730
    $query = db_select('webform_submissions', 'ws')
731
      ->addTag('webform_get_submission_count')
732
      ->condition('ws.nid', $nid)
733
      ->condition('ws.is_draft', 0);
734
    $arguments = array($nid);
735
    if ($uid !== NULL) {
736
      $query->condition('ws.uid', $uid);
737
    }
738
    if ($uid === 0) {
739
      $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
740
      if ($submissions) {
741
        $query->condition('ws.sid', $submissions, 'IN');
742
      }
743
      else {
744
        // Intentionally never match anything if the anonymous user has no
745
        // submissions.
746
        $query->condition('ws.sid', 0);
747
      }
748
    }
749

    
750
    $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
751
  }
752
  return $counts[$nid][$uid];
753
}
754

    
755
/**
756
 * Fetch a specified submission for a webform node.
757
 */
758
function webform_get_submission($nid, $sid, $reset = FALSE) {
759
  static $submissions = array();
760

    
761
  if ($reset) {
762
    $submissions = array();
763
    if (!isset($sid)) {
764
      return;
765
    }
766
  }
767

    
768
  // Load the submission if needed.
769
  if (!isset($submissions[$sid])) {
770
    $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
771
    $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
772
  }
773

    
774
  return $submissions[$sid];
775
}
776

    
777
function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
778
  $headers = implode('\n', (array)$headers);
779
  // Check if they are attempting to spam using a bcc or content type hack.
780
  if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
781
    return TRUE; // Possible spam attempt.
782
  }
783
  return FALSE; // Not spam.
784
}
785

    
786
/**
787
 * Check if the current user has exceeded the limit on this form.
788
 *
789
 * @param $node
790
 *   The webform node to be checked.
791
 * @return
792
 *   Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
793
 */
794
function _webform_submission_user_limit_check($node) {
795
  global $user;
796

    
797
  // Check if submission limiting is enabled.
798
  if ($node->webform['submit_limit'] == '-1') {
799
    return FALSE; // No check enabled.
800
  }
801

    
802
  // Retrieve submission data for this IP address or username from the database.
803
  $query = db_select('webform_submissions')
804
    ->addTag('webform_submission_user_limit_check')
805
    ->condition('nid', $node->nid)
806
    ->condition('is_draft', 0);
807

    
808
  if ($node->webform['submit_interval'] != -1) {
809
    $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
810
  }
811

    
812
  if ($user->uid) {
813
    $query->condition('uid', $user->uid);
814
  }
815
  else {
816
    $query->condition('remote_addr', ip_address());
817
  }
818

    
819
  // Fetch all the entries from the database within the submit interval with this username and IP.
820
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
821

    
822
  // Double check the submission history from the users machine using cookies.
823
  $num_submissions_cookie = 0;
824
  if ($user->uid == 0 && variable_get('webform_use_cookies', 0)) {
825
    $cookie_name = 'webform-' . $node->nid;
826

    
827
    if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
828
      foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
829
        if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
830
          // Remove the cookie if past the required time interval.
831
          $params = session_get_cookie_params();
832
          setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
833
        }
834
      }
835
      // Count the number of submissions recorded in cookies.
836
      $num_submissions_cookie = count($_COOKIE[$cookie_name]);
837
    }
838
    else {
839
      $num_submissions_cookie = 0;
840
    }
841
  }
842

    
843
  if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
844
    // Limit exceeded.
845
    return TRUE;
846
  }
847

    
848
  // Limit not exceeded.
849
  return FALSE;
850
}
851

    
852
/**
853
 * Check if the total number of submissions has exceeded the limit on this form.
854
 *
855
 * @param $node
856
 *   The webform node to be checked.
857
 * @return
858
 *   Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
859
 */
860
function _webform_submission_total_limit_check($node) {
861

    
862
  // Check if submission limiting is enabled.
863
  if ($node->webform['total_submit_limit'] == '-1') {
864
    return FALSE; // No check enabled.
865
  }
866

    
867
  // Retrieve submission data from the database.
868
  $query = db_select('webform_submissions')
869
    ->addTag('webform_submission_total_limit_check')
870
    ->condition('nid', $node->nid)
871
    ->condition('is_draft', 0);
872

    
873
  if ($node->webform['total_submit_interval'] != -1) {
874
    $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
875
  }
876

    
877
  // Fetch all the entries from the database within the submit interval.
878
  $num_submissions_database = $query->countQuery()->execute()->fetchField();
879

    
880
  if ($num_submissions_database >= $node->webform['total_submit_limit']) {
881
    // Limit exceeded.
882
    return TRUE;
883
  }
884

    
885
  // Limit not exceeded.
886
  return FALSE;
887
}
888

    
889
/**
890
 * Preprocess function for webform-submission.tpl.php.
891
 */
892
function template_preprocess_webform_submission(&$vars) {
893
  $vars['node'] = $vars['renderable']['#node'];
894
  $vars['submission'] = $vars['renderable']['#submission'];
895
  $vars['email'] = $vars['renderable']['#email'];
896
  $vars['format'] = $vars['renderable']['#format'];
897
}
898

    
899
/**
900
 * Preprocess function for webform-submission-navigation.tpl.php.
901
 */
902
function template_preprocess_webform_submission_navigation(&$vars) {
903
  $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
904

    
905
  $previous_query = db_select('webform_submissions')
906
    ->condition('nid', $vars['node']->nid)
907
    ->condition('sid', $vars['submission']->sid, '<');
908
  $previous_query->addExpression('MAX(sid)');
909

    
910
  $next_query = db_select('webform_submissions')
911
    ->condition('nid', $vars['node']->nid)
912
    ->condition('sid', $vars['submission']->sid, '>');
913
  $next_query->addExpression('MIN(sid)');
914

    
915
  $vars['previous'] = $previous_query->execute()->fetchField();
916
  $vars['next'] = $next_query->execute()->fetchField();
917
  $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
918
  $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
919
}
920

    
921
/**
922
 * Preprocess function for webform-submission-navigation.tpl.php.
923
 */
924
function template_preprocess_webform_submission_information(&$vars) {
925
  $vars['account'] = user_load($vars['submission']->uid);
926
  $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
927
}