Projet

Général

Profil

Paste
Télécharger (68,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / includes / webform.report.inc @ a6e869e4

1
<?php
2

    
3
/**
4
 * @file
5
 * This file includes helper functions for creating reports for webform.module
6
 *
7
 * @author Nathan Haug <nate@lullabot.com>
8
 */
9

    
10
// All functions within this file need the webform.submissions.inc.
11
module_load_include('inc', 'webform', 'includes/webform.submissions');
12

    
13
/**
14
 * Retrieve lists of submissions for a given webform.
15
 */
16
function webform_results_submissions($node, $user_filter, $pager_count) {
17
  global $user;
18

    
19
  // Determine whether views or hard-coded tables should be used for the
20
  // submissions table.
21
  if (!webform_variable_get('webform_table')) {
22
    // Load the submissions view
23
    $view = webform_get_view($node, 'webform_submissions');
24
    if ($user_filter) {
25
      if ($user->uid) {
26
        drupal_set_title(t('Submissions for %user', array('%user' => $user->name)), PASS_THROUGH);
27
      }
28
      else {
29
        drupal_set_title(t('Your submissions'));
30
        webform_disable_page_cache();
31
      }
32
      return $view->preview('default', array($node->nid, $user->uid));
33
    }
34
    else {
35
      return $view->preview('default', array($node->nid));
36
    }
37
  }
38

    
39
  if (isset($_GET['results']) && is_numeric($_GET['results'])) {
40
    $pager_count = $_GET['results'];
41
  }
42

    
43
  $header = theme('webform_results_submissions_header', array('node' => $node));
44
  if ($user_filter) {
45
    if ($user->uid) {
46
      drupal_set_title(t('Submissions for %user', array('%user' => $user->name)), PASS_THROUGH);
47
    }
48
    else {
49
      drupal_set_title(t('Your submissions'));
50
      webform_disable_page_cache();
51
    }
52
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid), $header, $pager_count);
53
    $count = webform_get_submission_count($node->nid, $user->uid, NULL);
54
  }
55
  else {
56
    $submissions = webform_get_submissions($node->nid, $header, $pager_count);
57
    $count = webform_get_submission_count($node->nid, NULL, NULL);
58
  }
59

    
60
  $operation_column = end($header);
61
  $operation_total = $operation_column['colspan'];
62

    
63
  $rows = array();
64
  foreach ($submissions as $sid => $submission) {
65
    $row = array(
66
      $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial,
67
      format_date($submission->submitted, 'short'),
68
    );
69
    if (webform_results_access($node, $user)) {
70
      $row[] = theme('username', array('account' => $submission));
71
      $row[] = $submission->remote_addr;
72
    }
73
    $row[] = l(t('View'), "node/$node->nid/submission/$sid");
74
    $operation_count = 1;
75
    // No need to call this multiple times, just reference this in a variable.
76
    $destination = drupal_get_destination();
77
    if (webform_submission_access($node, $submission, 'edit', $user)) {
78
      $row[] = l(t('Edit'), "node/$node->nid/submission/$sid/edit", array('query' => $destination));
79
      $operation_count++;
80
    }
81
    if (webform_submission_access($node, $submission, 'delete', $user)) {
82
      $row[] = l(t('Delete'), "node/$node->nid/submission/$sid/delete", array('query' => $destination));
83
      $operation_count++;
84
    }
85
    if ($operation_count < $operation_total) {
86
      $row[count($row) - 1] = array('data' => $row[count($row) - 1], 'colspan' => $operation_total - $operation_count + 1);
87
    }
88
    $rows[] = $row;
89
  }
90

    
91
  $element['#theme'] = 'webform_results_submissions';
92
  $element['#node'] = $node;
93
  $element['#submissions'] = $submissions;
94
  $element['#total_count'] = $count;
95
  $element['#pager_count'] = $pager_count;
96
  $element['#attached']['library'][] = array('webform', 'admin');
97

    
98
  $element['table']['#theme'] = 'table';
99
  $element['table']['#header'] = $header;
100
  $element['table']['#rows'] = $rows;
101
  $element['table']['#operation_total'] = $operation_total;
102

    
103
  return drupal_render($element);
104

    
105
}
106

    
107
/**
108
 * Returns the most appropriate view for this webform node.
109
 *
110
 * Site builders can customize the view that webform uses by webform node id or
111
 * by webform content type. For example, use webform_results_123 to for node
112
 * id 123 or webform_results_my_content_type for a node of type my_content_type.
113
 *
114
 * @param object $node
115
 *   Loaded webform node.
116
 * @param string $view_id
117
 *   machine_id of the view, such as webform_results or webform_submissions.
118
 * @return object|NULL
119
 *   The loaded view.
120
 */
121
function webform_get_view($node, $view_id) {
122
  foreach (array("{$view_id}_{$node->nid}", "{$view_id}_{$node->type}", $view_id) as $id) {
123
    $view = views_get_view($id);
124
    if ($view) {
125
      return $view;
126
    }
127
  }
128
}
129

    
130
/**
131
 * Theme the list of links for selecting the number of results per page.
132
 *
133
 * @param $total_count
134
 *   The total number of results available.
135
 * @param $pager_count
136
 *   The current number of results displayed per page.
137
 */
138
function theme_webform_results_per_page($variables) {
139
  $total_count = $variables['total_count'];
140
  $pager_count = $variables['pager_count'];
141
  $output = '';
142

    
143
  // Create a list of results-per-page options.
144
  $counts = array(
145
    '20' => '20',
146
    '50' => '50',
147
    '100' => '100',
148
    '200' => '200',
149
    '500' => '500',
150
    '1000' => '1000',
151
    '0' => t('All'),
152
  );
153

    
154
  $count_links = array();
155

    
156
  foreach ($counts as $number => $text) {
157
    if ($number < $total_count) {
158
      $count_links[] = l($text, $_GET['q'], array('query' => array('results' => $number), 'attributes' => array('class' => array($pager_count == $number ? 'selected' : ''))));
159
    }
160
  }
161

    
162
  $output .= '<div class="webform-results-per-page">';
163
  if (count($count_links) > 1) {
164
    $output .= t('Show !count results per page.', array('!count' => implode(' | ', $count_links)));
165
  }
166
  else {
167
    $output .= t('Showing all results.');
168
  }
169
  if ($total_count > 1) {
170
    $output .= ' ' . t('@total results total.', array('@total' => $total_count));
171
  }
172
  $output .= '</div>';
173

    
174
  return $output;
175
}
176

    
177
/**
178
 * Theme the header of the submissions table.
179
 *
180
 * This is done in it's own function so that webform can retrieve the header and
181
 * use it for sorting the results.
182
 */
183
function theme_webform_results_submissions_header($variables) {
184
  $node = $variables['node'];
185

    
186
  $columns = array(
187
    array('data' => t('#'), 'field' => 'sid', 'sort' => 'desc'),
188
    array('data' => t('Submitted'), 'field' => 'submitted'),
189
  );
190
  if (webform_results_access($node)) {
191
    $columns[] = array('data' => t('User'), 'field' => 'name');
192
    $columns[] = array('data' => t('IP Address'), 'field' => 'remote_addr');
193
  }
194
  $columns[] = array('data' => t('Operations'), 'colspan' => module_exists('print') ? 5 : 3);
195

    
196
  return $columns;
197
}
198

    
199
/**
200
 * Preprocess function for webform-results-submissions.tpl.php
201
 */
202
function template_preprocess_webform_results_submissions(&$vars) {
203
  $vars['node'] = $vars['element']['#node'];
204
  $vars['submissions'] = $vars['element']['#submissions'];
205
  $vars['table'] = $vars['element']['table'];
206
  $vars['total_count'] = $vars['element']['#total_count'];
207
  $vars['pager_count'] = $vars['element']['#pager_count'];
208
  $vars['is_submissions'] = (arg(2) == 'submissions')? 1 : 0;
209

    
210
  unset($vars['element']);
211
}
212

    
213
/**
214
 * Create a table containing all submitted values for a webform node.
215
 */
216
function webform_results_table($node, $pager_count = 0) {
217

    
218
  // Determine whether views or hard-coded tables should be used for the
219
  // submissions table.
220
  if (!webform_variable_get('webform_table')) {
221
    // Load and preview the results view with a node id argument
222
    $view = webform_get_view($node, 'webform_results');
223
    return $view->preview('default', array($node->nid));
224
  }
225

    
226
  // Get all the submissions for the node
227
  if (isset($_GET['results']) && is_numeric($_GET['results'])) {
228
    $pager_count = $_GET['results'];
229
  }
230

    
231
  // Get all the submissions for the node.
232
  $header = theme('webform_results_table_header', array('node' => $node));
233
  $submissions = webform_get_submissions($node->nid, $header, $pager_count);
234
  $total_count = webform_get_submission_count($node->nid, NULL, NULL);
235

    
236
  $output = theme('webform_results_table', array('node' => $node, 'components' => $node->webform['components'], 'submissions' => $submissions, 'total_count' => $total_count, 'pager_count' => $pager_count));
237
  if ($pager_count) {
238
    $output .= theme('pager');
239
  }
240
  return $output;
241
}
242

    
243
function theme_webform_results_table_header($variables) {
244
  return array(
245
    array('data' => t('#'), 'field' => 'sid', 'sort' => 'desc'),
246
    array('data' => t('Submitted'), 'field' => 'submitted'),
247
    array('data' => t('User'), 'field' => 'name'),
248
    array('data' => t('IP Address'), 'field' => 'remote_addr'),
249
  );
250
}
251

    
252
/**
253
 * Theme the results table displaying all the submissions for a particular node.
254
 *
255
 * @param $node
256
 *   The node whose results are being displayed.
257
 * @param $components
258
 *   An associative array of the components for this webform.
259
 * @param $submissions
260
 *   An array of all submissions for this webform.
261
 * @param $total_count
262
 *   The total number of submissions to this webform.
263
 * @param $pager_count
264
 *   The number of results to be shown per page.
265
 */
266
function theme_webform_results_table($variables) {
267
  drupal_add_library('webform', 'admin');
268

    
269
  $node = $variables['node'];
270
  $components = $variables['components'];
271
  $submissions = $variables['submissions'];
272
  $total_count = $variables['total_count'];
273
  $pager_count = $variables['pager_count'];
274

    
275
  $header = array();
276
  $rows = array();
277
  $cell = array();
278

    
279
  // This header has to be generated separately so we can add the SQL necessary.
280
  // to sort the results.
281
  $header = theme('webform_results_table_header', array('node' => $node));
282

    
283
  // Generate a row for each submission.
284
  foreach ($submissions as $sid => $submission) {
285
    $link_text = $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial;
286
    $cell[] = l($link_text, 'node/' . $node->nid . '/submission/' . $sid);
287
    $cell[] = format_date($submission->submitted, 'short');
288
    $cell[] = theme('username', array('account' => $submission));
289
    $cell[] = $submission->remote_addr;
290
    $component_headers = array();
291

    
292
    // Generate a cell for each component.
293
    foreach ($node->webform['components'] as $component) {
294
      $data = isset($submission->data[$component['cid']]) ? $submission->data[$component['cid']] : NULL;
295
      $submission_output = webform_component_invoke($component['type'], 'table', $component, $data);
296
      if ($submission_output !== NULL) {
297
        $component_headers[] = array('data' => check_plain($component['name']), 'field' => $component['cid']);
298
        $cell[] = $submission_output;
299
      }
300
    }
301

    
302
    $rows[] = $cell;
303
    unset($cell);
304
  }
305
  if (!empty($component_headers)) {
306
    $header = array_merge($header, $component_headers);
307
  }
308

    
309
  if (count($rows) == 0) {
310
    $rows[] = array(array('data' => t('There are no submissions for this form. <a href="!url">View this form</a>.', array('!url' => url('node/' . $node->nid))), 'colspan' => 4));
311
  }
312

    
313

    
314
  $output = '';
315
  $output .= theme('webform_results_per_page', array('total_count' => $total_count, 'pager_count' => $pager_count));
316
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
317
  return $output;
318
}
319

    
320
/**
321
 * Delete all submissions for a node.
322
 *
323
 * @param $nid
324
 *   The node id whose submissions will be deleted.
325
 */
326
function webform_results_clear($nid) {
327
  $node = node_load($nid);
328
  $submissions = webform_get_submissions($nid);
329
  foreach ($submissions as $submission) {
330
    webform_submission_delete($node, $submission);
331
  }
332
}
333

    
334
/**
335
 * Confirmation form to delete all submissions for a node.
336
 *
337
 * @param $nid
338
 *   ID of node for which to clear submissions.
339
 */
340
function webform_results_clear_form($form, $form_state, $node) {
341
  drupal_set_title(t('Clear Form Submissions'));
342

    
343
  $form = array();
344
  $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
345
  $question = t('Are you sure you want to delete all submissions for this form?');
346

    
347
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform-results', NULL, t('Clear'), t('Cancel'));
348
}
349

    
350
function webform_results_clear_form_submit($form, &$form_state) {
351
  webform_results_clear($form_state['values']['nid']);
352
  $node = node_load($form_state['values']['nid']);
353
  $title = $node->title;
354
  drupal_set_message(t('Webform %title entries cleared.', array('%title' => $title)));
355
  watchdog('webform', 'Webform %title entries cleared.', array('%title' => $title));
356
  $form_state['redirect'] = 'node/' . $form_state['values']['nid'] . '/webform-results';
357
}
358

    
359
/**
360
 * Form to configure the download of CSV files.
361
 */
362
function webform_results_download_form($form, &$form_state, $node) {
363
  module_load_include('inc', 'webform', 'includes/webform.export');
364
  module_load_include('inc', 'webform', 'includes/webform.components');
365

    
366
  $form['#attached']['js'][] = drupal_get_path('module', 'webform') . '/js/webform-admin.js';
367

    
368
  // If an export is waiting to be downloaded, redirect the user there after
369
  // the page has finished loading.
370
  if (isset($_SESSION['webform_export_info'])) {
371
    $download_url = url('node/' . $node->nid . '/webform-results/download-file', array('absolute' => TRUE));
372
    $form['#attached']['js'][] = array('data' => array('webformExport' => $download_url), 'type' => 'setting');
373
  }
374

    
375
  $form['node'] = array(
376
    '#type' => 'value',
377
    '#value' => $node,
378
  );
379

    
380
  $form['format'] = array(
381
    '#type' => 'radios',
382
    '#title' => t('Export format'),
383
    '#options' => webform_export_list(),
384
    '#default_value' => webform_variable_get('webform_export_format'),
385
  );
386

    
387
  $form['delimiter'] = array(
388
    '#type' => 'select',
389
    '#title' => t('Delimited text format'),
390
    '#description' => t('This is the delimiter used in the CSV/TSV file when downloading Webform results. Using tabs in the export is the most reliable method for preserving non-latin characters. You may want to change this to another character depending on the program with which you anticipate importing results.'),
391
    '#default_value' => webform_variable_get('webform_csv_delimiter'),
392
    '#options' => array(
393
      ','  => t('Comma (,)'),
394
      '\t' => t('Tab (\t)'),
395
      ';'  => t('Semicolon (;)'),
396
      ':'  => t('Colon (:)'),
397
      '|'  => t('Pipe (|)'),
398
      '.'  => t('Period (.)'),
399
      ' '  => t('Space ( )'),
400
    ),
401
    '#states' => array(
402
      'visible' => array(
403
        ':input[name=format]' => array('value' => 'delimited'),
404
      ),
405
    ),
406
  );
407

    
408
  $form['header_keys'] = array(
409
    '#type' => 'radios',
410
    '#title' => t('Column header format'),
411
    '#options' => array(
412
      -1 => t('None'),
413
      0 => t('Label'),
414
      1 => t('Field Key'),
415
    ),
416
    '#default_value' => 0,
417
    '#description' => t('Choose whether to show the label or field key in each column header.'),
418
  );
419

    
420
  $form['select_options'] = array(
421
    '#type' => 'fieldset',
422
    '#title' => t('Select list options'),
423
    '#collapsible' => TRUE,
424
    '#collapsed' => TRUE,
425
  );
426

    
427
  $form['select_options']['select_keys'] = array(
428
    '#type' => 'radios',
429
    '#title' => t('Select keys'),
430
    '#options' => array(
431
      0 => t('Full, human-readable options (values)'),
432
      1 => t('Short, raw options (keys)'),
433
    ),
434
    '#default_value' => 0,
435
    '#description' => t('Choose which part of options should be displayed from key|value pairs.'),
436
  );
437

    
438
  $form['select_options']['select_format'] = array(
439
    '#type' => 'radios',
440
    '#title' => t('Select list format'),
441
    '#options' => array(
442
      'separate' => t('Separate'),
443
      'compact' => t('Compact'),
444
    ),
445
    '#default_value' => 'separate',
446
    '#attributes' => array('class' => array('webform-select-list-format')),
447
    '#theme' => 'webform_results_download_select_format',
448
  );
449

    
450
  $csv_components = array('info' => t('Submission information'));
451
  // Prepend information fields with "-" to indent.
452
  foreach (webform_results_download_submission_information($node) as $key => $title) {
453
    $csv_components[$key] = '-' . $title;
454
  }
455

    
456
  $csv_components += webform_component_list($node, 'csv', TRUE);
457

    
458
  $form['components'] = array(
459
    '#type' => 'select',
460
    '#title' => t('Included export components'),
461
    '#options' => $csv_components,
462
    '#default_value' => array_keys($csv_components),
463
    '#multiple' => TRUE,
464
    '#size' => 10,
465
    '#description' => t('The selected components will be included in the export.'),
466
    '#process' => array('webform_component_select'),
467
  );
468

    
469
  $form['range'] = array(
470
    '#type' => 'fieldset',
471
    '#title' => t('Download range options'),
472
    '#collapsible' => TRUE,
473
    '#collapsed' => TRUE,
474
    '#tree' => TRUE,
475
    '#theme' => 'webform_results_download_range',
476
    '#element_validate' => array('webform_results_download_range_validate'),
477
    '#after_build' => array('webform_results_download_range_after_build'),
478
  );
479

    
480
  $form['range']['range_type'] = array(
481
    '#type' => 'radios',
482
    '#options' => array(
483
      'all' => t('All submissions'),
484
      'new' => t('Only new submissions since your last download'),
485
      'latest' => t('Only the latest'),
486
      'range_serial' => t('All submissions starting from'),
487
      'range_date' => t('All submissions by date'),
488
    ),
489
    '#default_value' => 'all',
490
  );
491
  $form['range']['latest'] = array(
492
    '#type' => 'textfield',
493
    '#size' => 5,
494
    '#maxlength' => 8,
495
  );
496
  $form['range']['start'] = array(
497
    '#type' => 'textfield',
498
    '#size' => 5,
499
    '#maxlength' => 8,
500
  );
501
  $form['range']['end'] = array(
502
    '#type' => 'textfield',
503
    '#size' => 5,
504
    '#maxlength' => 8,
505
  );
506
  $date_attributes = array('placeholder' => format_date(REQUEST_TIME, 'custom', webform_date_format('short')));
507
  $form['range']['start_date'] = array(
508
    '#type' => 'textfield',
509
    '#size' => 20,
510
    '#attributes' => $date_attributes,
511
  );
512
  $form['range']['end_date'] = array(
513
    '#type' => 'textfield',
514
    '#size' => 20,
515
    '#attributes' => $date_attributes,
516
  );
517

    
518
  // If drafts are allowed, provide options to filter download based on draft
519
  // status.
520
  $form['range']['completion_type'] = array(
521
    '#type' => 'radios',
522
    '#title' => t('Included submissions'),
523
    '#default_value' => 'all',
524
    '#options' => array(
525
      'all' => t('Finished and draft submissions'),
526
      'finished' => t('Finished submissions only'),
527
      'draft' => t('Drafts only'),
528
    ),
529
    '#access' => ($node->webform['allow_draft'] || $node->webform['auto_save']),
530
  );
531

    
532
  // By default results are downloaded. User can override this value if
533
  // programmatically submitting this form.
534
  $form['download'] = array(
535
    '#type' => 'value',
536
    '#default_value' => TRUE
537
  );
538

    
539
  $form['actions'] = array('#type' => 'actions');
540
  $form['actions']['submit'] = array(
541
    '#type' => 'submit',
542
    '#value' => t('Download'),
543
  );
544

    
545
  return $form;
546
}
547

    
548
/**
549
 * FormAPI element validate function for the range fieldset.
550
 */
551
function webform_results_download_range_validate($element, $form_state) {
552
  switch ($element['range_type']['#value']) {
553
    case 'latest':
554
      // Download latest x submissions.
555
      if ($element['latest']['#value'] == '') {
556
        form_error($element['latest'], t('Latest number of submissions field is required.'));
557
      }
558
      else {
559
        if (!is_numeric($element['latest']['#value'])) {
560
          form_error($element['latest'], t('Latest number of submissions must be numeric.'));
561
        }
562
        else {
563
          if ($element['latest']['#value'] <= 0) {
564
            form_error($element['latest'], t('Latest number of submissions must be greater than 0.'));
565
          }
566
        }
567
      }
568
      break;
569
    case 'range_serial':
570
      // Download Start-End range of submissions.
571
      // Start submission number.
572
      if ($element['start']['#value'] == '') {
573
        form_error($element['start'], t('Start submission number is required.'));
574
      }
575
      else {
576
        if (!is_numeric($element['start']['#value'])) {
577
          form_error($element['start'], t('Start submission number must be numeric.'));
578
        }
579
        else {
580
          if ($element['start']['#value'] <= 0) {
581
            form_error($element['start'], t('Start submission number must be greater than 0.'));
582
          }
583
        }
584
      }
585
      // End submission number.
586
      if ($element['end']['#value'] != '') {
587
        if (!is_numeric($element['end']['#value'])) {
588
          form_error($element['end'], t('End submission number must be numeric.'));
589
        }
590
        else {
591
          if ($element['end']['#value'] <= 0) {
592
            form_error($element['end'], t('End submission number must be greater than 0.'));
593
          }
594
          else {
595
            if ($element['end']['#value'] < $element['start']['#value']) {
596
              form_error($element['end'], t('End submission number must not be less than Start submission number.'));
597
            }
598
          }
599
        }
600
      }
601
      break;
602
    case 'range_date':
603
      // Download Start-end range of submissions.
604
      // Start submission time.
605
      $start_date = strtotime($element['start_date']['#value']);
606
      if ($element['start_date']['#value'] == '') {
607
        form_error($element['start_date'], t('Start date range is required.'));
608
      }
609
      elseif ($start_date === FALSE) {
610
        form_error($element['start_date'], t('Start date range is not in a valid format.'));
611
      }
612
      // End submission time.
613
      $end_date = strtotime($element['end_date']['#value']);
614
      if ($element['end_date']['#value'] != '') {
615
        if ($end_date === FALSE) {
616
          form_error($element['end_date'], t('End date range is not in a valid format.'));
617
        }
618
        elseif ($start_date !== FALSE && $start_date > $end_date) {
619
          form_error($element['end_date'], t('End date range must not be before the Start date..'));
620
        }
621
      }
622
      break;
623
  }
624

    
625
  // Check that the range will return something at all.
626
  $range_options = array(
627
    'range_type' => $element['range_type']['#value'],
628
    'start' => $element['start']['#value'],
629
    'end' => $element['end']['#value'],
630
    'latest' => $element['latest']['#value'],
631
    'start_date' => $element['start_date']['#value'],
632
    'end_date' => $element['end_date']['#value'],
633
    'completion_type' => $element['completion_type']['#value'],
634
    'batch_size' => 1,
635
    'batch_number' => 0,
636
  );
637
  if (!form_get_errors() && !webform_download_sids_count($form_state['values']['node']->nid, $range_options)) {
638
    form_error($element['range_type'], t('The specified range will not return any results.'));
639
  }
640

    
641
}
642

    
643
/**
644
 * FormAPI after build function for the download range fieldset.
645
 */
646
function webform_results_download_range_after_build($element, &$form_state) {
647
  $node = $form_state['values']['node'];
648

    
649
  // Build a list of counts of new and total submissions.
650
  $last_download = webform_download_last_download_info($node->nid);
651

    
652
  $element['#webform_download_info']['sid'] = $last_download ? $last_download['sid'] : 0;
653
  $element['#webform_download_info']['serial'] = $last_download ? $last_download['serial'] : NULL;
654
  $element['#webform_download_info']['requested'] = $last_download ? $last_download['requested'] : $node->created;
655
  $element['#webform_download_info']['total'] = webform_get_submission_count($node->nid, NULL, NULL);
656
  $element['#webform_download_info']['new'] = webform_download_sids_count($node->nid, array('range_type' => 'new'));
657

    
658
  return $element;
659
}
660

    
661
/**
662
 * Theme the output of the export range fieldset.
663
 */
664
function theme_webform_results_download_range($variables) {
665
  drupal_add_library('webform', 'admin');
666

    
667
  $element = $variables['element'];
668
  $download_info = $element['#webform_download_info'];
669

    
670
  // Set description for total of all submissions.
671
  $element['range_type']['all']['#theme_wrappers'] = array('webform_inline_radio');
672
  $element['range_type']['all']['#title'] .= ' (' . t('@count total', array('@count' => $download_info['total'])) . ')';
673

    
674
  // Set description for "New submissions since last download".
675
  $format = webform_date_format('short');
676
  $requested_date = format_date($download_info['requested'], 'custom', $format);
677
  $element['range_type']['new']['#theme_wrappers'] = array('webform_inline_radio');
678
  $element['range_type']['new']['#title'] .= ' (' . t('@count new since @date', array('@count' => $download_info['new'], '@date' => $requested_date)) . ')';
679

    
680

    
681
  // Disable option if there are no new submissions.
682
  if ($download_info['new'] == 0) {
683
    $element['range_type']['new']['#attributes']['disabled'] = 'disabled';
684
  }
685

    
686
  // Render latest x submissions option.
687
  $element['latest']['#attributes']['class'][] = 'webform-set-active';
688
  $element['latest']['#theme_wrappers'] = array();
689
  $element['range_type']['latest']['#theme_wrappers'] = array('webform_inline_radio');
690
  $element['range_type']['latest']['#title'] = t('Only the latest !number submissions', array('!number' => drupal_render($element['latest'])));
691

    
692
  // Render Start-End submissions option.
693
  $element['start']['#attributes']['class'][] = 'webform-set-active';
694
  $element['end']['#attributes']['class'][] = 'webform-set-active';
695
  $element['start']['#theme_wrappers'] = array();
696
  $element['end']['#theme_wrappers'] = array();
697
  $element['start_date']['#attributes']['class'] = array('webform-set-active');
698
  $element['end_date']['#attributes']['class'] = array('webform-set-active');
699
  $element['start_date']['#theme_wrappers'] = array();
700
  $element['end_date']['#theme_wrappers'] = array();
701
  $element['range_type']['range_serial']['#theme_wrappers'] = array('webform_inline_radio');
702
  $last_serial = $download_info['serial'] ? $download_info['serial'] : drupal_placeholder(t('none'));
703
  $element['range_type']['range_serial']['#title'] = t('Submissions by number from !start and optionally to: !end &nbsp; (Last downloaded: !serial)',
704
                                                       array('!start' => drupal_render($element['start']), '!end' => drupal_render($element['end']), '!serial' => $last_serial));
705

    
706
  // date range
707
  $element['range_type']['range_date']['#theme_wrappers'] = array('webform_inline_radio');
708
  $element['range_type']['range_date']['#title'] = t('Submissions by date from !start_date and optionally to: !end_date', array('!start_date' => drupal_render($element['start_date']), '!end_date' => drupal_render($element['end_date'])));
709

    
710
  return drupal_render_children($element);
711
}
712

    
713
/**
714
 * Theme the output of the select list format radio buttons.
715
 */
716
function theme_webform_results_download_select_format($variables) {
717
  drupal_add_library('webform', 'admin');
718

    
719
  $element = $variables['element'];
720
  $output = '';
721

    
722
  // Build an example table for the separate option.
723
  $header = array(t('Option A'), t('Option B'), t('Option C'));
724
  $rows = array(
725
    array('X', '', ''),
726
    array('X', '', 'X'),
727
    array('', 'X', 'X'),
728
  );
729

    
730
  $element['separate']['#attributes']['class'] = array();
731
  $element['separate']['#description'] = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE));
732
  $element['separate']['#description'] .= t('Separate options are more suitable for building reports, graphs, and statistics in a spreadsheet application.');
733
  $output .= drupal_render($element['separate']);
734

    
735
  // Build an example table for the compact option.
736
  $header = array(t('My select list'));
737
  $rows = array(
738
    array('Option A'),
739
    array('Option A,Option C'),
740
    array('Option B,Option C'),
741
  );
742

    
743
  $element['compact']['#attributes']['class'] = array();
744
  $element['compact']['#description'] = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE));
745
  $element['compact']['#description'] .= t('Compact options are more suitable for importing data into other systems.');
746
  $output .= drupal_render($element['compact']);
747

    
748
  return $output;
749
}
750

    
751
/**
752
 * Submit handler for webform_results_download_form().
753
 */
754
function webform_results_download_form_submit(&$form, &$form_state) {
755
  $node = $form_state['values']['node'];
756
  $format = $form_state['values']['format'];
757

    
758
  $options = array(
759
    'delimiter' => $form_state['values']['delimiter'],
760
    'components' => array_keys(array_filter($form_state['values']['components'])),
761
    'header_keys' => $form_state['values']['header_keys'],
762
    'select_keys' => $form_state['values']['select_keys'],
763
    'select_format' => $form_state['values']['select_format'],
764
    'range' => $form_state['values']['range'],
765
    'download' => $form_state['values']['download'],
766
  );
767

    
768
  $defaults = webform_results_download_default_options($node, $format);
769
  $options += $defaults;
770
  $options['range'] += $defaults['range'];
771

    
772
  // Determine an appropriate batch size based on the form and server specs.
773
  if (!isset($options['range']['batch_size'])) {
774
    // Start the batch size at 50,000 per batch, but divide by number of
775
    // components in the form. e.g. If a form had 10 components, it would
776
    // export 5,000 submissions at a time.
777
    $batch_size = ceil(50000 / max(1, count($form_state['values']['node']->webform['components'])));
778

    
779
    // Every 32MB of additional memory after 64MB adds a multiplier in size.
780
    $memory_limit = parse_size(ini_get('memory_limit'));
781
    $mb = 1048576;
782
    $memory_modifier = max(1, ($memory_limit - (64 * $mb)) / (32 * $mb));
783
    $batch_size = ceil($batch_size * $memory_modifier);
784

    
785
    // For time reasons, limit the batch size to 5,000.
786
    $batch_size = min($batch_size, 5000);
787

    
788
    // Allow a non-UI configuration to override the batch size.
789
    $batch_size = variable_get('webform_export_batch_size', $batch_size);
790

    
791
    $options['range']['batch_size'] = $batch_size;
792
  }
793

    
794
  $options['file_name'] = _webform_export_tempname();
795

    
796
  // Set up a batch to export the results.
797
  $batch = webform_results_export_batch($node, $format, $options);
798
  batch_set($batch);
799
}
800

    
801
/**
802
 * Returns a temporary export filename.
803
 */
804
function _webform_export_tempname() {
805
  return drupal_tempnam(variable_get('webform_export_path', 'temporary://'), 'webform_');
806
}
807

    
808
/**
809
 * Generate a Excel-readable CSV file containing all submissions for a Webform.
810
 *
811
 * Note that this function is generally no longer utilized. Instead Batch API
812
 * should be used to generate a file over multiple requests.
813
 *
814
 * @see webform_results_export_batch()
815
 *
816
 * @deprecated This function is schedule to be removed in webform 7.x-5.x. Use
817
 * the batch opertions instead.
818
 *
819
 * @return array|null
820
 *   The array of export info or null if the file could not be opened.
821
 */
822
function webform_results_export($node, $format = 'delimited', $options = array()) {
823
  global $user;
824
  module_load_include('inc', 'webform', 'includes/webform.export');
825
  module_load_include('inc', 'webform', 'includes/webform.components');
826

    
827
  $defaults = webform_results_download_default_options($node, $format);
828
  $options += $defaults;
829
  $options['range'] += $defaults['range'];
830

    
831
  // Open a new Webform exporter object.
832
  $exporter = webform_export_create_handler($format, $options);
833

    
834
  $file_name = _webform_export_tempname();
835
  $handle = fopen($file_name, 'w');
836
  if (!$handle) {
837
    return;
838
  }
839

    
840
  // Add the beginning of file marker (little-endian usually for MS Excel).
841
  $exporter->bof($handle);
842

    
843
  // Add headers to the file.
844
  $row_count = 0;
845
  $col_count = 0;
846
  $headers = webform_results_download_headers($node, $options);
847
  foreach ($headers as $row) {
848
    // Output header if header_keys is non-negative. -1 means no headers.
849
    if ($options['header_keys'] >= 0) {
850
      $exporter->add_row($handle, $row, $row_count);
851
      $row_count++;
852
    }
853
    $col_count = count($row) > $col_count ? count($row) : $col_count;
854
  }
855

    
856
  // Write data from submissions. $last_is is non_NULL to trigger returning it
857
  // by reference.
858
  $last_sid = TRUE;
859
  $rows = webform_results_download_rows($node, $options, 0, $last_sid);
860
  foreach ($rows as $row) {
861
    $exporter->add_row($handle, $row, $row_count);
862
    $row_count++;
863
  }
864

    
865
  // Add the closing bytes.
866
  $exporter->eof($handle, $row_count, $col_count);
867

    
868
  // Close the file.
869
  @fclose($handle);
870

    
871
  $export_info['format'] = $format;
872
  $export_info['options'] = $options;
873
  $export_info['file_name'] = $file_name;
874
  $export_info['row_count'] = $row_count;
875
  $export_info['col_count'] = $col_count;
876
  $export_info['last_sid'] = $last_sid;
877
  $export_info['exporter'] = $exporter;
878

    
879
  return $export_info;
880
}
881

    
882
/**
883
 * Return a Batch API array of commands that will generate an export.
884
 *
885
 * @param $node
886
 *   The webform node on which to generate the analysis.
887
 * @param string $format
888
 *   (optional) Delimiter of the exported file.
889
 * @param array $options
890
 *   (optional) An associative array of options that define the output format.
891
 *   These are generally passed through from the GUI interface. Possible options
892
 *   include:
893
 *   - sids: An array of submission IDs to which this export may be filtered.
894
 *     May be used to generate exports that are per-user or other groups of
895
 *     submissions.
896
 *
897
 * @return array
898
 *   A Batch API array suitable to pass to batch_set().
899
 */
900
function webform_results_export_batch($node, $format = 'delimited', $options = array()) {
901
  $defaults = webform_results_download_default_options($node, $format);
902
  $options += $defaults;
903
  $options['range'] += $defaults['range'];
904

    
905
  return array(
906
    'operations' => array(
907
      array('webform_results_batch_bof', array($node, $format, $options)),
908
      array('webform_results_batch_headers', array($node, $format, $options)),
909
      array('webform_results_batch_rows', array($node, $format, $options)),
910
      array('webform_results_batch_eof', array($node, $format, $options)),
911
      array('webform_results_batch_post_process', array($node, $format, $options)),
912
      array('webform_results_batch_results', array($node, $format, $options)),
913
    ),
914
    'finished' => 'webform_results_batch_finished',
915
    'title' => t('Exporting submissions'),
916
    'init_message' => t('Creating export file'),
917
    'error_message' => t('The export file could not be created because an error occurred.'),
918
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
919
  );
920
}
921

    
922
/**
923
 * Print the header rows for the downloadable webform data.
924
 *
925
 * @param $node
926
 *   The webform node on which to generate the analysis.
927
 * @param array $options
928
 *   A list of options that define the output format. These are generally passed
929
 *   through from the GUI interface.
930
 */
931
function webform_results_download_headers($node, $options) {
932
  module_load_include('inc', 'webform', 'includes/webform.components');
933
  $submission_information = webform_results_download_submission_information($node, $options);
934

    
935
  // Fill in the header for the submission information (if any).
936
  $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
937
  if (count($submission_information)) {
938
    $header[0][0] = $node->title;
939

    
940
    if ($options['header_keys']) {
941
      $header[1][0] = t('submission_details');
942
      $submission_information_headers = array_keys($submission_information);
943
    }
944
    else {
945
      $header[1][0] = t('Submission Details');
946
      $submission_information_headers = array_values($submission_information);
947
    }
948
    foreach ($submission_information_headers as $column => $label) {
949
      $header[2][$column] = $label;
950
    }
951
  }
952

    
953
  // Compile header information for components.
954
  foreach ($options['components'] as $cid) {
955
    if (isset($node->webform['components'][$cid])) {
956
      $component = $node->webform['components'][$cid];
957

    
958
      // Let each component determine its headers.
959
      if (webform_component_feature($component['type'], 'csv')) {
960
        $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
961
        // Allow modules to modify the component CSV header.
962
        drupal_alter('webform_csv_header', $component_header, $component);
963

    
964
        // Merge component CSV header to overall CSV header
965
        $header[0] = array_merge($header[0], (array) $component_header[0]);
966
        $header[1] = array_merge($header[1], (array) $component_header[1]);
967
        $header[2] = array_merge($header[2], (array) $component_header[2]);
968
      }
969
    }
970
  }
971

    
972
  return $header;
973
}
974

    
975
/**
976
 * Returns rows of downloadable webform data.
977
 *
978
 * @deprecated This function is scheduled to be removed in webform 7.x-5.x.
979
 *
980
 * @param $node
981
 *   The webform node on which to generate the analysis.
982
 * @param array $options
983
 *   A list of options that define the output format. These are generally passed
984
 *   through from the GUI interface.
985
 * @param $serial_start
986
 *   The starting position for the Serial column in the output.
987
 * @param $last_sid
988
 *   If set to a non-NULL value, the last sid will be returned.
989
 *
990
 * @return $rows
991
 *   An array of rows built according to the provided $serial_start and
992
 *   $pager_count variables. Note that the current page number is determined
993
 *   by the super-global $_GET['page'] variable.
994
 */
995
function webform_results_download_rows($node, $options, $serial_start = 0, $last_sid = NULL) {
996
  // Get all the required submissions for the download.
997
  $filters['nid'] = $node->nid;
998
  if (isset($options['sids'])) {
999
    $filters['sid'] = $options['sids'];
1000
  }
1001
  elseif (!empty($options['completion_type']) && $options['completion_type'] !== 'all') {
1002
    $filters['is_draft'] = (int) ($options['completion_type'] === 'draft');
1003
  }
1004

    
1005
  $submissions = webform_get_submissions($filters, NULL);
1006

    
1007
  if (isset($last_sid)) {
1008
    $last_sid = end($submissions) ? key($submissions) : NULL;
1009
  }
1010

    
1011
  return webform_results_download_rows_process($node, $options, $serial_start, $submissions);
1012
}
1013

    
1014
/**
1015
 * Processes the submissions to be downloaded into exported rows.
1016
 *
1017
 * This is an internal routine and not intended for use by other modules.
1018
 *
1019
 * @param $node
1020
 *   The webform node on which to generate the analysis.
1021
 * @param array $options
1022
 *   A list of options that define the output format. These are generally passed
1023
 *   through from the GUI interface.
1024
 * @param $serial_start
1025
 *   The starting position for the Serial column in the output.
1026
 * @param array $submissions
1027
 *   An associative array of loaded submissions, indexed by sid.
1028
 *
1029
 * @return $rows
1030
 *   An array of rows built according to the provided $serial_start and
1031
 *   $pager_count variables. Note that the current page number is determined
1032
 *   by the super-global $_GET['page'] variable.
1033
 */
1034
function webform_results_download_rows_process($node, $options, $serial_start, $submissions) {
1035
  module_load_include('inc', 'webform', 'includes/webform.components');
1036

    
1037
  $submission_information = webform_results_download_submission_information($node, $options);
1038

    
1039
  // Generate a row for each submission.
1040
  $row_count = 0;
1041
  $rows = array();
1042
  foreach ($submissions as $sid => $submission) {
1043
    $row_count++;
1044

    
1045
    $row = array();
1046
    // Add submission information.
1047
    foreach (array_keys($submission_information) as $token) {
1048
      $cell = module_invoke_all('webform_results_download_submission_information_data', $token, $submission, $options, $serial_start, $row_count);
1049
      $context = array('token' => $token, 'submission' => $submission, 'options' => $options, 'serial_start' => $serial_start, 'row_count' => $row_count);
1050
      drupal_alter('webform_results_download_submission_information_data', $cell, $context);
1051
      // implode() to ensure everything from a single value goes into one
1052
      // column, even if more than one module responds to this item.
1053
      $row[] = implode(', ', $cell);
1054
    }
1055

    
1056
    foreach ($options['components'] as $cid) {
1057
      if (isset($node->webform['components'][$cid])) {
1058
        $component = $node->webform['components'][$cid];
1059
        // Let each component add its data.
1060
        $raw_data = isset($submission->data[$cid]) ? $submission->data[$cid] : NULL;
1061
        if (webform_component_feature($component['type'], 'csv')) {
1062
          $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);
1063

    
1064
          // Allow modules to modify the CSV data.
1065
          drupal_alter('webform_csv_data', $data, $component, $submission);
1066

    
1067
          if (is_array($data)) {
1068
            $row = array_merge($row, array_values($data));
1069
          }
1070
          else {
1071
            $row[] = isset($data) ? $data : '';
1072
          }
1073
        }
1074
      }
1075
    }
1076

    
1077
    $rows[$serial_start + $row_count] = $row;
1078
  }
1079

    
1080
  return $rows;
1081
}
1082

    
1083
/**
1084
 * Default columns for submission information.
1085
 *
1086
 * By default all exports have several columns of generic information that
1087
 * applies to all submissions. This function returns the list of generic columns
1088
 * plus columns added by other modules.
1089
 *
1090
 * @param $options
1091
 *   Filter down the list of columns based on a provided column list.
1092
 */
1093
function webform_results_download_submission_information($node, $options = array()) {
1094
  $submission_information = module_invoke_all('webform_results_download_submission_information_info');
1095
  drupal_alter('webform_results_download_submission_information_info', $submission_information);
1096

    
1097
  if (isset($options['components'])) {
1098
    foreach ($submission_information as $key => $label) {
1099
      if (!in_array($key, $options['components'])) {
1100
        unset($submission_information[$key]);
1101
      }
1102
    }
1103
  }
1104

    
1105
  return $submission_information;
1106
}
1107

    
1108
/**
1109
 * Implements hook_webform_results_download_submission_information_info().
1110
 */
1111
function webform_webform_results_download_submission_information_info() {
1112
  return array(
1113
    'webform_serial' => t('Serial'),
1114
    'webform_sid' => t('SID'),
1115
    'webform_time' => t('Submitted Time'),
1116
    'webform_completed_time' => t('Completed Time'),
1117
    'webform_modified_time' => t('Modified Time'),
1118
    'webform_draft' => t('Draft'),
1119
    'webform_ip_address' => t('IP Address'),
1120
    'webform_uid' => t('UID'),
1121
    'webform_username' => t('Username'),
1122
  );
1123
}
1124

    
1125
/**
1126
 * Implements hook_webform_results_download_submission_information_data().
1127
 */
1128
function webform_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
1129
  switch ($token) {
1130
    case 'webform_serial':
1131
      return $submission->serial;
1132
    case 'webform_sid':
1133
      return $submission->sid;
1134
    case 'webform_time':
1135
      // Return timestamp in local time (not UTC).
1136
      if (!empty($options['iso8601_date'])) {
1137
        return format_date($submission->submitted, 'custom', 'Y-m-d\TH:i:s');
1138
      }
1139
      else {
1140
        return format_date($submission->submitted, 'short');
1141
      }
1142
    case 'webform_completed_time':
1143
      if (!$submission->completed) {
1144
        return '';
1145
      }
1146
      // Return timestamp in local time (not UTC).
1147
      elseif (!empty($options['iso8601_date'])) {
1148
        return format_date($submission->completed, 'custom', 'Y-m-d\TH:i:s');
1149
      }
1150
      else {
1151
        return format_date($submission->completed, 'short');
1152
      }
1153
    case 'webform_modified_time':
1154
      // Return timestamp in local time (not UTC).
1155
      if (!empty($options['iso8601_date'])) {
1156
        return format_date($submission->modified, 'custom', 'Y-m-d\TH:i:s');
1157
      }
1158
      else {
1159
        return format_date($submission->modified, 'short');
1160
      }
1161
    case 'webform_draft':
1162
      return $submission->is_draft;
1163
    case 'webform_ip_address':
1164
      return $submission->remote_addr;
1165
    case 'webform_uid':
1166
      return $submission->uid;
1167
    case 'webform_username':
1168
      return $submission->name;
1169
  }
1170
}
1171

    
1172
/**
1173
 * Get options for creating downloadable versions of the webform data.
1174
 *
1175
 * @param $node
1176
 *   The webform node on which to generate the analysis.
1177
 * @param string $format
1178
 *   The export format being used.
1179
 * @param array $options
1180
 *   A list of options that define the output format. These are generally passed
1181
 *   through from the GUI interface.
1182
 */
1183
function webform_results_download_default_options($node, $format) {
1184
  $submission_information = webform_results_download_submission_information($node);
1185

    
1186
  $options = array(
1187
    'delimiter' => webform_variable_get('webform_csv_delimiter'),
1188
    'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
1189
    'header_keys' => 0,
1190
    'select_keys' => 0,
1191
    'select_format' => 'separate',
1192
    'range' => array(
1193
      'range_type' => 'all',
1194
      'completion_type' => 'all',
1195
    ),
1196
  );
1197

    
1198
  // Allow exporters to merge in additional options.
1199
  $exporter_information = webform_export_fetch_definition($format);
1200
  if (isset($exporter_information['options'])) {
1201
    $options = array_merge($options, $exporter_information['options']);
1202
  }
1203

    
1204
  return $options;
1205
}
1206

    
1207
/**
1208
 * Send a generated webform results file to the user's browser.
1209
 *
1210
 * @param $node
1211
 *   The webform node.
1212
 * @param $export_info
1213
 *   Export information array retrieved from webform_results_export().
1214
 */
1215
function webform_results_download($node, $export_info) {
1216
  global $user;
1217

    
1218
  // If the exporter provides a custom download method, use that.
1219
  if (method_exists($export_info['exporter'], 'download')) {
1220
    $export_info['exporter']->download($node);
1221
  }
1222
  // Otherwise use the set_headers() method to set headers and then read in the
1223
  // file directly. Delete it when complete.
1224
  else {
1225
    $export_name = _webform_safe_name($node->title);
1226
    if (!strlen($export_name)) {
1227
      $export_name  = t('Untitled');
1228
    }
1229
    $export_info['exporter']->set_headers($export_name);
1230
    @readfile($export_info['file_name']);  // The @ makes it silent.
1231
    @unlink($export_info['file_name']);  // Clean up, the @ makes it silent.
1232
  }
1233

    
1234
  // Update user last downloaded sid if required.
1235
  if (!in_array($export_info['options']['range']['range_type'], array('range', 'range_serial', 'range_date')) && !empty($export_info['last_sid'])) {
1236
    // Insert a new record or update an existing record.
1237
    db_merge('webform_last_download')
1238
      ->key(array(
1239
        'nid' => $node->nid,
1240
        'uid' => $user->uid,
1241
      ))
1242
      ->fields(array(
1243
        'sid' => $export_info['last_sid'],
1244
        'requested' => REQUEST_TIME,
1245
      ))
1246
      ->execute();
1247
  }
1248

    
1249
  exit();
1250
}
1251

    
1252
/**
1253
 * Menu callback; Download an exported file.
1254
 *
1255
 * This callabck requires that an export file be already generated by a batch
1256
 * process. The $_SESSION settings are usually put in place by the
1257
 * webform_results_export_results() function.
1258
 *
1259
 * @param $node
1260
 *   The webform $node whose export file is being downloaded.
1261
 *
1262
 * @return
1263
 *   Either an export file is downloaded with the appropriate HTTP headers set,
1264
 *   or an error page is shown if now export is available to download.
1265
 */
1266
function webform_results_download_callback($node) {
1267
  if (isset($_SESSION['webform_export_info'])) {
1268
    module_load_include('inc', 'webform', 'includes/webform.export');
1269

    
1270
    $export_info = $_SESSION['webform_export_info'];
1271
    $export_info['exporter'] = webform_export_create_handler($export_info['format'], $export_info['options']);
1272

    
1273
    unset($_SESSION['webform_export_info']);
1274
    if (isset($_COOKIE['webform_export_info'])) {
1275
      unset($_COOKIE['webform_export_info']);
1276
      $params = session_get_cookie_params();
1277
      setcookie('webform_export_info', '', -1, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1278
    }
1279

    
1280
    webform_results_download($node, $export_info);
1281
  }
1282
  else {
1283
    return t('No export file ready for download. The file may have already been downloaded by your browser. Visit the <a href="!href">download export form</a> to create a new export.', array('!href' => url('node/' . $node->nid . '/webform-results/download')));
1284
  }
1285
}
1286

    
1287
/**
1288
 * Batch API callback; Write the opening byte in the export file.
1289
 */
1290
function webform_results_batch_bof($node, $format = 'delimited', $options = array(), &$context) {
1291
  module_load_include('inc', 'webform', 'includes/webform.export');
1292

    
1293
  $exporter = webform_export_create_handler($format, $options);
1294
  $handle = fopen($options['file_name'], 'w');
1295
  if (!$handle) {
1296
    return;
1297
  }
1298
  $exporter->bof($handle);
1299
  @fclose($handle);
1300
}
1301

    
1302
/**
1303
 * Batch API callback; Write the headers of the export to the export file.
1304
 */
1305
function webform_results_batch_headers($node, $format = 'delimited', $options = array(), &$context) {
1306
  module_load_include('inc', 'webform', 'includes/webform.export');
1307

    
1308
  $exporter = webform_export_create_handler($format, $options);
1309
  $handle = fopen($options['file_name'], 'a');
1310
  if (!$handle) {
1311
    return;
1312
  }
1313
  $headers = webform_results_download_headers($node, $options);
1314
  $row_count = 0;
1315
  $col_count = 0;
1316
  foreach ($headers as $row) {
1317
    // Output header if header_keys is non-negative. -1 means no headers.
1318
    if ($options['header_keys'] >= 0) {
1319
      $exporter->add_row($handle, $row, $row_count);
1320
      $row_count++;
1321
    }
1322
    $col_count = count($row) > $col_count ? count($row) : $col_count;
1323
  }
1324
  $context['results']['row_count'] = $row_count;
1325
  $context['results']['col_count'] = $col_count;
1326
  @fclose($handle);
1327
}
1328

    
1329
/**
1330
 * Batch API callback; Write the rows of the export to the export file.
1331
 */
1332
function webform_results_batch_rows($node, $format = 'delimited', $options = array(), &$context) {
1333
  module_load_include('inc', 'webform', 'includes/webform.export');
1334

    
1335
  // Initialize the sandbox if this is the first execution of the batch
1336
  // operation.
1337
  if (!isset($context['sandbox']['batch_number'])) {
1338
    $context['sandbox']['batch_number'] = 0;
1339
    $context['sandbox']['sid_count'] = webform_download_sids_count($node->nid, $options['range']);
1340
    $context['sandbox']['batch_max'] = max(1, ceil($context['sandbox']['sid_count'] / $options['range']['batch_size']));
1341
    $context['sandbox']['serial'] = 0;
1342
    $context['sandbox']['last_sid'] = 0;
1343
  }
1344

    
1345
  // Retrieve the submissions for this batch process.
1346
  $options['range']['batch_number'] = $context['sandbox']['batch_number'];
1347

    
1348
  $query = webform_download_sids_query($node->nid, $options['range']);
1349

    
1350
  // Join to the users table to include user name in results, as required by
1351
  // webform_results_download_rows_process.
1352
  $query->leftJoin('users', 'u', 'u.uid = ws.uid');
1353
  $query->fields('u', array('name'));
1354
  $query->fields('ws');
1355

    
1356
  $submissions = webform_get_submissions_load($query);
1357

    
1358
  $rows = webform_results_download_rows_process($node, $options, $context['sandbox']['serial'], $submissions);
1359

    
1360
  // Write these submissions to the file.
1361
  $exporter = webform_export_create_handler($format, $options);
1362
  $handle = fopen($options['file_name'], 'a');
1363
  if (!$handle) {
1364
    return;
1365
  }
1366
  foreach ($rows as $row) {
1367
    $exporter->add_row($handle, $row, $context['results']['row_count']);
1368
    $context['results']['row_count']++;
1369
  }
1370

    
1371
  $context['sandbox']['serial'] += count($submissions);
1372
  $context['sandbox']['last_sid'] = end($submissions) ? key($submissions) : NULL;
1373
  $context['sandbox']['batch_number']++;
1374

    
1375
  @fclose($handle);
1376

    
1377
  // Display status message
1378
  $context['message'] = t('Exported @count of @total submissions...', array('@count' => $context['sandbox']['serial'], '@total' => $context['sandbox']['sid_count']));
1379
  $context['finished'] = $context['sandbox']['batch_number'] < $context['sandbox']['batch_max']
1380
                            ? $context['sandbox']['batch_number'] / $context['sandbox']['batch_max']
1381
                            : 1.0;
1382
  $context['results']['last_sid'] = $context['sandbox']['last_sid'];
1383
}
1384

    
1385
/**
1386
 * Batch API callback; Write the closing bytes in the export file.
1387
 */
1388
function webform_results_batch_eof($node, $format = 'delimited', $options = array(), &$context) {
1389
  module_load_include('inc', 'webform', 'includes/webform.export');
1390

    
1391
  $exporter = webform_export_create_handler($format, $options);
1392

    
1393
  // We open the file for reading and writing, rather than just appending for
1394
  // exporters that need to adjust the beginning of the files as well as the
1395
  // end, i.e. webform_exporter_excel_xlsx::eof().
1396
  $handle = fopen($options['file_name'], 'r+');
1397
  if (!$handle) {
1398
    return;
1399
  }
1400
  fseek($handle, 0, SEEK_END); // Move pointer to the end of the file.
1401
  $exporter->eof($handle, $context['results']['row_count'], $context['results']['col_count']);
1402
  @fclose($handle);
1403
}
1404

    
1405
/**
1406
 * Batch API callback; Do any last processing on the finished export.
1407
 */
1408
function webform_results_batch_post_process($node, $format = 'delimited', $options = array(), &$context) {
1409
  module_load_include('inc', 'webform', 'includes/webform.export');
1410

    
1411
  $context['results']['node'] = $node;
1412
  $context['results']['file_name'] = $options['file_name'];
1413

    
1414
  $exporter = webform_export_create_handler($format, $options);
1415
  $exporter->post_process($context['results']);
1416
}
1417

    
1418
/**
1419
 * Batch API callback; Set the $_SESSION variables used to download the file.
1420
 *
1421
 * Because we want the user to be returned to the main form first, we have to
1422
 * temporarily store information about the created file, send the user to the
1423
 * form, then use JavaScript to request node/x/webform-results/download-file,
1424
 * which will execute webform_results_download_file().
1425
 */
1426
function webform_results_batch_results($node, $format, $options, &$context) {
1427

    
1428
  $export_info = array(
1429
    'format' => $format,
1430
    'options' => $options,
1431
    'file_name' => $context['results']['file_name'],
1432
    'row_count' => $context['results']['row_count'],
1433
    'last_sid' => $context['results']['last_sid'],
1434
  );
1435

    
1436
  // Set a session variable containing the information referencing the exported
1437
  // file. A cookie is also set to allow the browser to ensure the redirect
1438
  // to the file only happens one time.
1439
  $_SESSION['webform_export_info'] = $export_info;
1440
  $params = session_get_cookie_params();
1441
  setcookie('webform_export_info', '1', REQUEST_TIME + 120, $params['path'], $params['domain'], $params['secure'], FALSE);
1442
}
1443

    
1444
/**
1445
 * Batch API completion callback; Display completion message and cleanup.
1446
 */
1447
function webform_results_batch_finished($success, $results, $operations) {
1448
  if ($success) {
1449
    $download_url = url('node/' . $results['node']->nid . '/webform-results/download-file');
1450
    drupal_set_message(t('Export creation complete. Your download should begin now. If it does not start, <a href="!href">download the file here</a>. This file may only be downloaded once.', array('!href' => $download_url)));
1451
  }
1452
  else {
1453
    drupal_set_message(t('An error occurred while generating the export file.'));
1454
    if (isset($results['file_name']) && is_file($results['file_name'])) {
1455
      @unlink($results['file_name']);
1456
    }
1457
  }
1458
}
1459

    
1460
/**
1461
 * Provides a simple analysis of all submissions to a webform.
1462
 *
1463
 * @param $node
1464
 *   The webform node on which to generate the analysis.
1465
 * @param $sids
1466
 *   An array of submission IDs to which this analysis may be filtered. May be
1467
 *   used to generate results that are per-user or other groups of submissions.
1468
 * @param $analysis_component
1469
 *   A webform component. If passed in, additional information may be returned
1470
 *   relating specifically to that component's analysis, such as a list of
1471
 *   "Other" values within a select list.
1472
 */
1473
function webform_results_analysis($node, $sids = array(), $analysis_component = NULL) {
1474
  if (!is_array($sids)) {
1475
    $sids = array();
1476
  }
1477

    
1478
  // Build a renderable for the content of this page.
1479
  $analysis = array(
1480
    '#theme' => array('webform_analysis__' . $node->nid, 'webform_analysis'),
1481
    '#node' => $node,
1482
    '#component' => $analysis_component,
1483
  );
1484

    
1485
  // See if a query (possibly with exposed filter) needs to restrict the
1486
  // submissions that are being analyzed.
1487
  $query = NULL;
1488
  if (empty($sids)) {
1489
    $view = webform_get_view($node, 'webform_analysis');
1490
    if ($view->type != t('Default') || $view->name != 'webform_analysis') {
1491
      // The view has been customized from the no-op built-in view. Use it.
1492
      $view->set_display();
1493
      $view->init_handlers();
1494
      $view->override_url = $_GET['q'];
1495
      $view->preview = TRUE;
1496
      $view->pre_execute(array($node->nid));
1497
      $view->build();
1498
      // Let modules modify the view just prior to executing it.
1499
      foreach (module_implements('views_pre_execute') as $module) {
1500
        $function = $module . '_views_pre_execute';
1501
        $function($view);
1502
      }
1503
      // If the view is already executed, there was an error in generating it.
1504
      $query = $view->executed ? NULL : $view->query->query();
1505
      $view->post_execute();
1506

    
1507
      if (isset($view->exposed_widgets)) {
1508
        $analysis['exposed_filter']['#markup'] = $view->exposed_widgets;
1509
      }
1510
    }
1511
  }
1512

    
1513
  // If showing all components, display selection form.
1514
  if (!$analysis_component) {
1515
    $analysis['form'] = drupal_get_form('webform_analysis_components_form', $node);
1516
  }
1517

    
1518
  // Add all the components to the analysis renderable array.
1519
  $components = isset($analysis_component) ? array($analysis_component['cid']) : webform_analysis_enabled_components($node);
1520
  foreach ($components as $cid) {
1521
    // Do component specific call.
1522
    $component = $node->webform['components'][$cid];
1523
    if ($data = webform_component_invoke($component['type'], 'analysis', $component, $sids, isset($analysis_component), $query)) {
1524
      drupal_alter('webform_analysis_component_data', $data, $node, $component);
1525
      $analysis['data'][$cid] = array(
1526
        '#theme' => array('webform_analysis_component__' . $node->nid . '__' . $cid, 'webform_analysis_component__' . $node->nid, 'webform_analysis_component'),
1527
        '#node' => $node,
1528
        '#component' => $component,
1529
        '#data' => $data,
1530
      );
1531
      $analysis['data'][$cid]['basic'] = array(
1532
        '#theme' => array('webform_analysis_component_basic__' . $node->nid . '__' . $cid, 'webform_analysis_component_basic__' . $node->nid, 'webform_analysis_component_basic'),
1533
        '#component' => $component,
1534
        '#data' => $data,
1535
      );
1536
    }
1537
  }
1538

    
1539
  drupal_alter('webform_analysis', $analysis);
1540
  return drupal_render($analysis);
1541
}
1542

    
1543
/**
1544
 * Prerender function for webform-analysis.tpl.php.
1545
 */
1546
function template_preprocess_webform_analysis(&$variables) {
1547
  $analysis = $variables['analysis'];
1548
  $variables['node'] = $analysis['#node'];
1549
  $variables['component'] = $analysis['#component'];
1550
}
1551

    
1552
/**
1553
 * Prerender function for webform-analysis-component.tpl.php.
1554
 */
1555
function template_preprocess_webform_analysis_component(&$variables) {
1556
  $component_analysis = $variables['component_analysis'];
1557
  $variables['node'] = $component_analysis['#node'];
1558
  $variables['component'] = $component_analysis['#component'];
1559

    
1560
  // Ensure defaults.
1561
  $variables['component_analysis']['#data'] += array(
1562
    'table_header' => NULL,
1563
    'table_rows' => array(),
1564
    'other_data' => array(),
1565
  );
1566
  $variables['classes_array'][] = 'webform-analysis-component-' . $variables['component']['type'];
1567
  $variables['classes_array'][] = 'webform-analysis-component--' . str_replace('_', '-', implode('--', webform_component_parent_keys($variables['node'], $variables['component'])));
1568
}
1569

    
1570
/**
1571
 * Render an individual component's analysis data in a table.
1572
 *
1573
 * @param $variables
1574
 *   An array of theming variables for this theme function. Included keys:
1575
 *   - $component: The component whose analysis is being rendered.
1576
 *   - $data: An array of array containing the analysis data. Contains the keys:
1577
 *     - table_header: If this table has more than a single column, an array
1578
 *       of header labels.
1579
 *     - table_rows: If this component has a table that should be rendered, an
1580
 *       array of values
1581
 */
1582
function theme_webform_analysis_component_basic($variables) {
1583
  $data = $variables['data'];
1584

    
1585
  // Ensure defaults.
1586
  $data += array(
1587
    'table_header' => NULL,
1588
    'table_rows' => array(),
1589
    'other_data' => array(),
1590
  );
1591

    
1592
  // Combine the "other data" into the table rows by default.
1593
  if (is_array($data['other_data'])) {
1594
    foreach ($data['other_data'] as $other_data) {
1595
      if (is_array($other_data)) {
1596
        $data['table_rows'][] = $other_data;
1597
      }
1598
      else {
1599
        $data['table_rows'][] = array(array(
1600
          'colspan' => 2,
1601
          'data' => $other_data,
1602
        ));
1603
      }
1604
    }
1605
  }
1606
  elseif (strlen($data['other_data'])) {
1607
    $data['table_rows'][] = array(
1608
      'colspan' => 2,
1609
      'data' => $data['other_data'],
1610
    );
1611
  }
1612

    
1613
  return theme('table', array(
1614
    'header' => $data['table_header'],
1615
    'rows' => $data['table_rows'],
1616
    'sticky' => FALSE,
1617
    'attributes' => array('class' => array('webform-analysis-table')),
1618
  ));
1619
}
1620

    
1621
/**
1622
 * Return a list of components that should be displayed for analysis.
1623
 *
1624
 * @param $node
1625
 *   The node whose components' data is being analyzed.
1626
 * @return array
1627
 *   An array of component IDs.
1628
 */
1629
function webform_analysis_enabled_components($node) {
1630
  $cids = array();
1631
  foreach ($node->webform['components'] as $cid => $component) {
1632
    if (!empty($component['extra']['analysis'])) {
1633
      $cids[] = $cid;
1634
    }
1635
  }
1636
  return $cids;
1637
}
1638

    
1639
/**
1640
 * Form for selecting which components should be shown on the analysis page.
1641
 */
1642
function webform_analysis_components_form($form, &$form_state, $node) {
1643
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1644
  $form['#node'] = $node;
1645

    
1646
  $component_list = webform_component_list($node, 'analysis', TRUE);
1647
  $enabled_components = webform_analysis_enabled_components($node);
1648
  if (empty($component_list)) {
1649
    $help = t('No components have added that support analysis. <a href="!url">Add components to your form</a> to see calculated data.', array('!url' => url('node/' . $node->nid . '/webform')));
1650
  }
1651
  elseif (empty($enabled_components)) {
1652
    $help = t('No components have analysis enabled in this form. Enable analysis under the "Add analysis components" fieldset.');
1653
  }
1654
  else {
1655
    $help = t('This page shows analysis of submitted data, such as the number of submissions per component value, calculations, and averages. Additional components may be added under the "Add analysis components" fieldset.');
1656
  }
1657

    
1658
  $form['help'] = array(
1659
    '#markup' => '<p>' . $help . '</p>',
1660
    '#access' => !empty($help),
1661
    '#weight' => -100,
1662
  );
1663

    
1664
  $form['components'] = array(
1665
    '#type' => 'select',
1666
    '#title' => t('Add analysis components'),
1667
    '#options' => $component_list,
1668
    '#default_value' => $enabled_components,
1669
    '#multiple' => TRUE,
1670
    '#size' => 10,
1671
    '#description' => t('The selected components will be included on the analysis page.'),
1672
    '#process' => array('webform_component_select'),
1673
    '#access' => count($component_list),
1674
  );
1675

    
1676
  $form['actions'] = array(
1677
    '#type' => 'actions',
1678
    '#access' => count($component_list),
1679
  );
1680
  $form['actions']['submit'] = array(
1681
    '#type' => 'submit',
1682
    '#value' => t('Update analysis display'),
1683
  );
1684

    
1685
  return $form;
1686
}
1687

    
1688
/**
1689
 * Submit handler for webform_analysis_components_form().
1690
 */
1691
function webform_analysis_components_form_submit($form, $form_state) {
1692
  $node = $form['#node'];
1693
  foreach ($form_state['values']['components'] as $cid => $enabled) {
1694
    $node->webform['components'][$cid]['extra']['analysis'] = (bool) $enabled;
1695
  }
1696
  node_save($node);
1697
}
1698

    
1699
/**
1700
 * Output the content of the Analysis page.
1701
 *
1702
 * @see webform_results_analysis()
1703
 */
1704
function theme_webform_results_analysis($variables) {
1705
  $node = $variables['node'];
1706
  $data = $variables['data'];
1707
  $sids = $variables['sids'];
1708
  $analysis_component = $variables['component'];
1709

    
1710
  $rows = array();
1711
  $question_number = 0;
1712
  $single = isset($analysis_component);
1713

    
1714
  $header = array(
1715
    $single ? $analysis_component['name'] : t('Q'),
1716
    array('data' => $single ? '&nbsp;' : t('responses'), 'colspan' => '10')
1717
  );
1718

    
1719
  foreach ($data as $cid => $row_data) {
1720
    $question_number++;
1721

    
1722
    if (is_array($row_data)) {
1723
      $row = array();
1724
      if (!$single) {
1725
        $row['data'][] = array('data' => '<strong>' . $question_number . '</strong>', 'rowspan' => count($row_data) + 1, 'valign' => 'top');
1726
        $row['data'][] = array('data' => '<strong>' . check_plain($node->webform['components'][$cid]['name']) . '</strong>', 'colspan' => '10');
1727
        $row['class'][] = 'webform-results-question';
1728
      }
1729
      $rows = array_merge($rows, array_merge(array($row), $row_data));
1730
    }
1731
  }
1732

    
1733
  if (count($rows) == 0) {
1734
    $rows[] = array(array('data' => t('There are no submissions for this form. <a href="!url">View this form</a>.', array('!url' => url('node/' . $node->nid))), 'colspan' => 20));
1735
  }
1736

    
1737
  return theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('class' => array('webform-results-analysis'))));
1738
}
1739

    
1740
/**
1741
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1742
 *
1743
 * @deprecated This function is scheduled to be removed int webform 7.x-5.x.
1744
 * Use webform_download_sids_query() instead.
1745
 *
1746
 */
1747
function webform_download_sids($nid, $range_options, $uid = NULL) {
1748
  return webform_download_sids_query($nid, $range_options, $uid)
1749
    ->fields('ws', array('sid'))
1750
    ->execute()
1751
    ->fetchCol();
1752
}
1753

    
1754
/**
1755
 * Retrieves a count the number of matching submissions.
1756
 *
1757
 */
1758
function webform_download_sids_count($nid, $range_options, $uid = NULL) {
1759
  return webform_download_sids_query($nid, $range_options, $uid)
1760
    ->countQuery()
1761
    ->execute()
1762
    ->fetchField();
1763
}
1764

    
1765
/**
1766
 * Given a set of range options, return an unexecuted select query.
1767
 *
1768
 * The query will have no fields as they should be added by the caller as
1769
 * desired.
1770
 *
1771
 * @param integer $nid
1772
 *   The node id of the webform.
1773
 * @param array $range_options
1774
 *   Associate array of range options.
1775
 * @param integer $uid
1776
 *   The user id of the user whose last download information should be used,
1777
 *   or the current user if NULL. This is unrelated to which user submitted
1778
 *   the submissions.
1779
 */
1780
function webform_download_sids_query($nid, $range_options, $uid = NULL) {
1781
  $query = db_select('webform_submissions', 'ws')
1782
    ->condition('nid', $nid)
1783
    ->addTag('webform_download_sids');
1784

    
1785
  switch ($range_options['range_type']) {
1786
    case 'all':
1787
      // All Submissions.
1788
      $query->orderBy('ws.sid', 'ASC');
1789
      break;
1790
    case 'new':
1791
      // All Since Last Download.
1792
      $download_info = webform_download_last_download_info($nid, $uid);
1793
      $last_sid = $download_info ? $download_info['sid'] : 0;
1794
      $query
1795
        ->condition('ws.sid', $last_sid, '>')
1796
        ->orderBy('ws.sid', 'ASC');
1797
      break;
1798
    case 'latest':
1799
      // Last x Submissions.
1800
      $start_sid = webform_download_latest_start_sid($nid, $range_options['latest'], $range_options['completion_type']);
1801
      $query->condition('ws.sid', $start_sid, '>=');
1802
      break;
1803
    case 'range':
1804
      // Submissions Start-End.
1805
      $query->condition('ws.sid', $range_options['start'], '>=');
1806
      if ($range_options['end']) {
1807
        $query->condition('ws.sid', $range_options['end'], '<=');
1808
      }
1809
      $query->orderBy('ws.sid', 'ASC');
1810
      break;
1811
    case 'range_serial':
1812
      // Submissions Start-End, using serial numbers.
1813
      $query->condition('ws.serial', $range_options['start'], '>=');
1814
      if ($range_options['end']) {
1815
        $query->condition('ws.serial', $range_options['end'], '<=');
1816
      }
1817
      $query->orderBy('ws.serial', 'ASC');
1818
      break;
1819
    case 'range_date':
1820
      $date_field = $range_options['completion_type'] == 'finished' ? 'ws.completed' : 'ws.submitted';
1821
      $query->condition($date_field, strtotime($range_options['start_date']), '>=');
1822
      if ($range_options['end_date'] != '' && ($end_time = strtotime($range_options['end_date'])) !== FALSE) {
1823
        if ($end_time == strtotime('midnight', $end_time)) {
1824
          // Full day specified
1825
          $end_time += 86399; // 86400 is a full day of seconds.
1826
        }
1827
        $query->condition($date_field, $end_time, '<=');
1828
      }
1829
      ;
1830
      $query->orderBy($date_field, 'ASC');
1831
      break;
1832
  }
1833

    
1834
  // Filter down to draft or finished submissions.
1835
  if (!empty($range_options['completion_type']) && $range_options['completion_type'] !== 'all') {
1836
    $query->condition('is_draft', (int) ($range_options['completion_type'] === 'draft'));
1837
  }
1838

    
1839
  if (isset($range_options['batch_number']) && !empty($range_options['batch_size'])) {
1840
    $query->range($range_options['batch_number'] * $range_options['batch_size'], $range_options['batch_size']);
1841
  }
1842
  return $query;
1843
}
1844

    
1845
/**
1846
 * Get this user's last download information, including the SID and timestamp.
1847
 *
1848
 * This function provides an array of information about the last download that
1849
 * a user had for a particular Webform node. Currently it only returns an array
1850
 * with two keys:
1851
 *  - sid: The last submission ID that was downloaded.
1852
 *  - requested: The timestamp of the last download request.
1853
 *
1854
 * @param $nid
1855
 *   The Webform NID.
1856
 * @param $uid
1857
 *   The user account ID for which to retrieve download information.
1858
 * @return
1859
 *   An array of download information or FALSE if this user has never downloaded
1860
 *   results for this particular node.
1861
 */
1862
function webform_download_last_download_info($nid, $uid = NULL) {
1863
  $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
1864

    
1865
  $query = db_select('webform_last_download', 'wld');
1866
  $query->leftJoin('webform_submissions', 'wfs', 'wld.sid = wfs.sid');
1867
  $info = $query
1868
    ->fields('wld')
1869
    ->fields('wfs', array('serial'))
1870
    ->condition('wld.nid', $nid)
1871
    ->condition('wld.uid', $uid)
1872
    ->execute()
1873
    ->fetchAssoc();
1874

    
1875
  return $info;
1876
}
1877

    
1878
/**
1879
 * Get an SID based a requested latest count.
1880
 *
1881
 * @param int $nid
1882
 *   The webform NID.
1883
 * @param int $latest_count
1884
 *   The latest count on which the SID will be retrieved.
1885
 * @param string $completion_type
1886
 *   The completion type, either "finished", "draft", or "all".
1887
 * @return
1888
 *   The submission ID that starts the latest sequence of submissions.
1889
 */
1890
function webform_download_latest_start_sid($nid, $latest_count, $completion_type = 'all') {
1891
  // TODO: Find a more efficient DBTNG query to retrieve this number.
1892
  $query = db_select('webform_submissions', 'ws')
1893
    ->fields('ws', array('sid'))
1894
    ->condition('nid', $nid)
1895
    ->orderBy('ws.sid', 'DESC')
1896
    ->range(0, $latest_count)
1897
    ->addTag('webform_download_latest_start_sid');
1898

    
1899
  if ($completion_type !== 'all') {
1900
    $query->condition('is_draft', (int) ($completion_type === 'draft'));
1901
  }
1902

    
1903
  $latest_sids = $query->execute()->fetchCol();
1904
  return $latest_sids ? min($latest_sids) : 1;
1905
}