Projet

Général

Profil

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

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

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
 * @param $batch_size
326
 *   The number of submissions to be processed. NULL means all submissions.
327
 * @return
328
 *   The number of submissions processed.
329
 */
330
function webform_results_clear($nid, $batch_size = NULL) {
331
  $node = node_load($nid);
332
  $submissions = webform_get_submissions($nid, NULL, $batch_size);
333
  $count = 0;
334
  foreach ($submissions as $submission) {
335
    webform_submission_delete($node, $submission);
336
    $count++;
337
  }
338
  return $count;
339
}
340

    
341
/**
342
 * Confirmation form to delete all submissions for a node.
343
 *
344
 * @param $nid
345
 *   ID of node for which to clear submissions.
346
 */
347
function webform_results_clear_form($form, $form_state, $node) {
348
  drupal_set_title(t('Clear Form Submissions'));
349

    
350
  $form = array();
351
  $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
352
  $question = t('Are you sure you want to delete all submissions for this form?');
353

    
354
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform-results', NULL, t('Clear'), t('Cancel'));
355
}
356

    
357
function webform_results_clear_form_submit($form, &$form_state) {
358
  $nid = $form_state['values']['nid'];
359
  $node = node_load($nid);
360
  // Set a modest batch size, due to the inefficiency of the hooks invoked when
361
  // submissions are deleted.
362
  $batch_size = min(webform_export_batch_size($node), 500);
363

    
364
  // Set up a batch to clear the results.
365
  $batch = array(
366
    'operations' => array(
367
      array('webform_clear_batch_rows', array($node, $batch_size)),
368
    ),
369
    'finished' => 'webform_clear_batch_finished',
370
    'title' => t('Clear submissions'),
371
    'init_message' => t('Clearing submission data'),
372
    'error_message' => t('The submissions could not be cleared because an error occurred.'),
373
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
374
  );
375
  batch_set($batch);
376
  $form_state['redirect'] = 'node/' . $nid . '/webform-results';
377
}
378

    
379
/**
380
 * Batch API callback; Write the rows of the export to the export file.
381
 */
382
function webform_clear_batch_rows($node, $batch_size, &$context) {
383
  // Initialize the results if this is the first execution of the batch
384
  // operation.
385
  if (!isset($context['results']['count'])) {
386
    $context['results'] = array(
387
      'count' => 0,
388
      'total' => webform_get_submission_count($node->nid),
389
      'node' => $node,
390
    );
391
  }
392

    
393
  // Clear a batch of submissions.
394
  $count = webform_results_clear($node->nid, $batch_size);
395
  $context['results']['count'] += $count;
396

    
397
  // Display status message
398
  $context['message'] = t('Cleared @count of @total submissions...', array('@count' => $context['results']['count'], '@total' => $context['results']['total']));
399
  $context['finished'] = $count > 0
400
                            ? $context['results']['count'] / $context['results']['total']
401
                            : 1.0;
402
}
403

    
404
/**
405
 * Batch API completion callback; Finish clearing submissions.
406
 */
407
function webform_clear_batch_finished($success, $results, $operations) {
408
  if ($success) {
409
    $title = $results['node']->title;
410
    drupal_set_message(t('Webform %title entries cleared.', array('%title' => $title)));
411
    watchdog('webform', 'Webform %title entries cleared.', array('%title' => $title));
412
  }
413
}
414

    
415
/**
416
 * Form to configure the download of CSV files.
417
 */
418
function webform_results_download_form($form, &$form_state, $node) {
419
  module_load_include('inc', 'webform', 'includes/webform.export');
420
  module_load_include('inc', 'webform', 'includes/webform.components');
421

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

    
424
  // If an export is waiting to be downloaded, redirect the user there after
425
  // the page has finished loading.
426
  if (isset($_SESSION['webform_export_info'])) {
427
    $download_url = url('node/' . $node->nid . '/webform-results/download-file', array('absolute' => TRUE));
428
    $form['#attached']['js'][] = array('data' => array('webformExport' => $download_url), 'type' => 'setting');
429
  }
430

    
431
  $form['node'] = array(
432
    '#type' => 'value',
433
    '#value' => $node,
434
  );
435

    
436
  $form['format'] = array(
437
    '#type' => 'radios',
438
    '#title' => t('Export format'),
439
    '#options' => webform_export_list(),
440
    '#default_value' => webform_variable_get('webform_export_format'),
441
  );
442

    
443
  $form['delimiter'] = array(
444
    '#type' => 'select',
445
    '#title' => t('Delimited text format'),
446
    '#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.'),
447
    '#default_value' => webform_variable_get('webform_csv_delimiter'),
448
    '#options' => array(
449
      ','  => t('Comma (,)'),
450
      '\t' => t('Tab (\t)'),
451
      ';'  => t('Semicolon (;)'),
452
      ':'  => t('Colon (:)'),
453
      '|'  => t('Pipe (|)'),
454
      '.'  => t('Period (.)'),
455
      ' '  => t('Space ( )'),
456
    ),
457
    '#states' => array(
458
      'visible' => array(
459
        ':input[name=format]' => array('value' => 'delimited'),
460
      ),
461
    ),
462
  );
463

    
464
  $form['header_keys'] = array(
465
    '#type' => 'radios',
466
    '#title' => t('Column header format'),
467
    '#options' => array(
468
      -1 => t('None'),
469
      0 => t('Label'),
470
      1 => t('Field Key'),
471
    ),
472
    '#default_value' => 0,
473
    '#description' => t('Choose whether to show the label or field key in each column header.'),
474
  );
475

    
476
  $form['select_options'] = array(
477
    '#type' => 'fieldset',
478
    '#title' => t('Select list options'),
479
    '#collapsible' => TRUE,
480
    '#collapsed' => TRUE,
481
  );
482

    
483
  $form['select_options']['select_keys'] = array(
484
    '#type' => 'radios',
485
    '#title' => t('Select keys'),
486
    '#options' => array(
487
      0 => t('Full, human-readable options (values)'),
488
      1 => t('Short, raw options (keys)'),
489
    ),
490
    '#default_value' => 0,
491
    '#description' => t('Choose which part of options should be displayed from key|value pairs.'),
492
  );
493

    
494
  $form['select_options']['select_format'] = array(
495
    '#type' => 'radios',
496
    '#title' => t('Select list format'),
497
    '#options' => array(
498
      'separate' => t('Separate'),
499
      'compact' => t('Compact'),
500
    ),
501
    '#default_value' => 'separate',
502
    '#attributes' => array('class' => array('webform-select-list-format')),
503
    '#theme' => 'webform_results_download_select_format',
504
  );
505

    
506
  $csv_components = array('info' => t('Submission information'));
507
  // Prepend information fields with "-" to indent.
508
  foreach (webform_results_download_submission_information($node) as $key => $title) {
509
    $csv_components[$key] = '-' . $title;
510
  }
511

    
512
  $csv_components += webform_component_list($node, 'csv', TRUE);
513

    
514
  $form['components'] = array(
515
    '#type' => 'select',
516
    '#title' => t('Included export components'),
517
    '#options' => $csv_components,
518
    '#default_value' => array_keys($csv_components),
519
    '#multiple' => TRUE,
520
    '#size' => 10,
521
    '#description' => t('The selected components will be included in the export.'),
522
    '#process' => array('webform_component_select'),
523
  );
524

    
525
  $form['range'] = array(
526
    '#type' => 'fieldset',
527
    '#title' => t('Download range options'),
528
    '#collapsible' => TRUE,
529
    '#collapsed' => TRUE,
530
    '#tree' => TRUE,
531
    '#theme' => 'webform_results_download_range',
532
    '#element_validate' => array('webform_results_download_range_validate'),
533
    '#after_build' => array('webform_results_download_range_after_build'),
534
  );
535

    
536
  $form['range']['range_type'] = array(
537
    '#type' => 'radios',
538
    '#options' => array(
539
      'all' => t('All submissions'),
540
      'new' => t('Only new submissions since your last download'),
541
      'latest' => t('Only the latest'),
542
      'range_serial' => t('All submissions starting from'),
543
      'range_date' => t('All submissions by date'),
544
    ),
545
    '#default_value' => 'all',
546
  );
547
  $form['range']['latest'] = array(
548
    '#type' => 'textfield',
549
    '#size' => 5,
550
    '#maxlength' => 8,
551
  );
552
  $form['range']['start'] = array(
553
    '#type' => 'textfield',
554
    '#size' => 5,
555
    '#maxlength' => 8,
556
  );
557
  $form['range']['end'] = array(
558
    '#type' => 'textfield',
559
    '#size' => 5,
560
    '#maxlength' => 8,
561
  );
562
  $date_attributes = array('placeholder' => format_date(REQUEST_TIME, 'custom', webform_date_format('short')));
563
  $form['range']['start_date'] = array(
564
    '#type' => 'textfield',
565
    '#size' => 20,
566
    '#attributes' => $date_attributes,
567
  );
568
  $form['range']['end_date'] = array(
569
    '#type' => 'textfield',
570
    '#size' => 20,
571
    '#attributes' => $date_attributes,
572
  );
573

    
574
  // If drafts are allowed, provide options to filter download based on draft
575
  // status.
576
  $form['range']['completion_type'] = array(
577
    '#type' => 'radios',
578
    '#title' => t('Included submissions'),
579
    '#default_value' => 'all',
580
    '#options' => array(
581
      'all' => t('Finished and draft submissions'),
582
      'finished' => t('Finished submissions only'),
583
      'draft' => t('Drafts only'),
584
    ),
585
    '#access' => ($node->webform['allow_draft'] || $node->webform['auto_save']),
586
  );
587

    
588
  // By default results are downloaded. User can override this value if
589
  // programmatically submitting this form.
590
  $form['download'] = array(
591
    '#type' => 'value',
592
    '#default_value' => TRUE
593
  );
594

    
595
  $form['actions'] = array('#type' => 'actions');
596
  $form['actions']['submit'] = array(
597
    '#type' => 'submit',
598
    '#value' => t('Download'),
599
  );
600

    
601
  return $form;
602
}
603

    
604
/**
605
 * FormAPI element validate function for the range fieldset.
606
 */
607
function webform_results_download_range_validate($element, $form_state) {
608
  switch ($element['range_type']['#value']) {
609
    case 'latest':
610
      // Download latest x submissions.
611
      if ($element['latest']['#value'] == '') {
612
        form_error($element['latest'], t('Latest number of submissions field is required.'));
613
      }
614
      else {
615
        if (!is_numeric($element['latest']['#value'])) {
616
          form_error($element['latest'], t('Latest number of submissions must be numeric.'));
617
        }
618
        else {
619
          if ($element['latest']['#value'] <= 0) {
620
            form_error($element['latest'], t('Latest number of submissions must be greater than 0.'));
621
          }
622
        }
623
      }
624
      break;
625
    case 'range_serial':
626
      // Download Start-End range of submissions.
627
      // Start submission number.
628
      if ($element['start']['#value'] == '') {
629
        form_error($element['start'], t('Start submission number is required.'));
630
      }
631
      else {
632
        if (!is_numeric($element['start']['#value'])) {
633
          form_error($element['start'], t('Start submission number must be numeric.'));
634
        }
635
        else {
636
          if ($element['start']['#value'] <= 0) {
637
            form_error($element['start'], t('Start submission number must be greater than 0.'));
638
          }
639
        }
640
      }
641
      // End submission number.
642
      if ($element['end']['#value'] != '') {
643
        if (!is_numeric($element['end']['#value'])) {
644
          form_error($element['end'], t('End submission number must be numeric.'));
645
        }
646
        else {
647
          if ($element['end']['#value'] <= 0) {
648
            form_error($element['end'], t('End submission number must be greater than 0.'));
649
          }
650
          else {
651
            if ($element['end']['#value'] < $element['start']['#value']) {
652
              form_error($element['end'], t('End submission number must not be less than Start submission number.'));
653
            }
654
          }
655
        }
656
      }
657
      break;
658
    case 'range_date':
659
      // Download Start-end range of submissions.
660
      // Start submission time.
661
      $start_date = strtotime($element['start_date']['#value']);
662
      if ($element['start_date']['#value'] == '') {
663
        form_error($element['start_date'], t('Start date range is required.'));
664
      }
665
      elseif ($start_date === FALSE) {
666
        form_error($element['start_date'], t('Start date range is not in a valid format.'));
667
      }
668
      // End submission time.
669
      $end_date = strtotime($element['end_date']['#value']);
670
      if ($element['end_date']['#value'] != '') {
671
        if ($end_date === FALSE) {
672
          form_error($element['end_date'], t('End date range is not in a valid format.'));
673
        }
674
        elseif ($start_date !== FALSE && $start_date > $end_date) {
675
          form_error($element['end_date'], t('End date range must not be before the Start date..'));
676
        }
677
      }
678
      break;
679
  }
680

    
681
  // Check that the range will return something at all.
682
  $range_options = array(
683
    'range_type' => $element['range_type']['#value'],
684
    'start' => $element['start']['#value'],
685
    'end' => $element['end']['#value'],
686
    'latest' => $element['latest']['#value'],
687
    'start_date' => $element['start_date']['#value'],
688
    'end_date' => $element['end_date']['#value'],
689
    'completion_type' => $element['completion_type']['#value'],
690
    'batch_size' => 1,
691
    'batch_number' => 0,
692
  );
693
  if (!form_get_errors() && !webform_download_sids_count($form_state['values']['node']->nid, $range_options)) {
694
    form_error($element['range_type'], t('The specified range will not return any results.'));
695
  }
696

    
697
}
698

    
699
/**
700
 * FormAPI after build function for the download range fieldset.
701
 */
702
function webform_results_download_range_after_build($element, &$form_state) {
703
  $node = $form_state['values']['node'];
704

    
705
  // Build a list of counts of new and total submissions.
706
  $last_download = webform_download_last_download_info($node->nid);
707

    
708
  $element['#webform_download_info']['sid'] = $last_download ? $last_download['sid'] : 0;
709
  $element['#webform_download_info']['serial'] = $last_download ? $last_download['serial'] : NULL;
710
  $element['#webform_download_info']['requested'] = $last_download ? $last_download['requested'] : $node->created;
711
  $element['#webform_download_info']['total'] = webform_get_submission_count($node->nid, NULL, NULL);
712
  $element['#webform_download_info']['new'] = webform_download_sids_count($node->nid, array('range_type' => 'new'));
713

    
714
  return $element;
715
}
716

    
717
/**
718
 * Theme the output of the export range fieldset.
719
 */
720
function theme_webform_results_download_range($variables) {
721
  drupal_add_library('webform', 'admin');
722

    
723
  $element = $variables['element'];
724
  $download_info = $element['#webform_download_info'];
725

    
726
  // Set description for total of all submissions.
727
  $element['range_type']['all']['#theme_wrappers'] = array('webform_inline_radio');
728
  $element['range_type']['all']['#title'] .= ' (' . t('@count total', array('@count' => $download_info['total'])) . ')';
729

    
730
  // Set description for "New submissions since last download".
731
  $format = webform_date_format('short');
732
  $requested_date = format_date($download_info['requested'], 'custom', $format);
733
  $element['range_type']['new']['#theme_wrappers'] = array('webform_inline_radio');
734
  $element['range_type']['new']['#title'] .= ' (' . t('@count new since @date', array('@count' => $download_info['new'], '@date' => $requested_date)) . ')';
735

    
736

    
737
  // Disable option if there are no new submissions.
738
  if ($download_info['new'] == 0) {
739
    $element['range_type']['new']['#attributes']['disabled'] = 'disabled';
740
  }
741

    
742
  // Render latest x submissions option.
743
  $element['latest']['#attributes']['class'][] = 'webform-set-active';
744
  $element['latest']['#theme_wrappers'] = array();
745
  $element['range_type']['latest']['#theme_wrappers'] = array('webform_inline_radio');
746
  $element['range_type']['latest']['#title'] = t('Only the latest !number submissions', array('!number' => drupal_render($element['latest'])));
747

    
748
  // Render Start-End submissions option.
749
  $element['start']['#attributes']['class'][] = 'webform-set-active';
750
  $element['end']['#attributes']['class'][] = 'webform-set-active';
751
  $element['start']['#theme_wrappers'] = array();
752
  $element['end']['#theme_wrappers'] = array();
753
  $element['start_date']['#attributes']['class'] = array('webform-set-active');
754
  $element['end_date']['#attributes']['class'] = array('webform-set-active');
755
  $element['start_date']['#theme_wrappers'] = array();
756
  $element['end_date']['#theme_wrappers'] = array();
757
  $element['range_type']['range_serial']['#theme_wrappers'] = array('webform_inline_radio');
758
  $last_serial = $download_info['serial'] ? $download_info['serial'] : drupal_placeholder(t('none'));
759
  $element['range_type']['range_serial']['#title'] = t('Submissions by number from !start and optionally to: !end &nbsp; (Last downloaded: !serial)',
760
                                                       array('!start' => drupal_render($element['start']), '!end' => drupal_render($element['end']), '!serial' => $last_serial));
761

    
762
  // date range
763
  $element['range_type']['range_date']['#theme_wrappers'] = array('webform_inline_radio');
764
  $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'])));
765

    
766
  return drupal_render_children($element);
767
}
768

    
769
/**
770
 * Theme the output of the select list format radio buttons.
771
 */
772
function theme_webform_results_download_select_format($variables) {
773
  drupal_add_library('webform', 'admin');
774

    
775
  $element = $variables['element'];
776
  $output = '';
777

    
778
  // Build an example table for the separate option.
779
  $header = array(t('Option A'), t('Option B'), t('Option C'));
780
  $rows = array(
781
    array('X', '', ''),
782
    array('X', '', 'X'),
783
    array('', 'X', 'X'),
784
  );
785

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

    
791
  // Build an example table for the compact option.
792
  $header = array(t('My select list'));
793
  $rows = array(
794
    array('Option A'),
795
    array('Option A,Option C'),
796
    array('Option B,Option C'),
797
  );
798

    
799
  $element['compact']['#attributes']['class'] = array();
800
  $element['compact']['#description'] = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE));
801
  $element['compact']['#description'] .= t('Compact options are more suitable for importing data into other systems.');
802
  $output .= drupal_render($element['compact']);
803

    
804
  return $output;
805
}
806

    
807
/**
808
 * Submit handler for webform_results_download_form().
809
 */
810
function webform_results_download_form_submit(&$form, &$form_state) {
811
  $node = $form_state['values']['node'];
812
  $format = $form_state['values']['format'];
813

    
814
  $options = array(
815
    'delimiter' => $form_state['values']['delimiter'],
816
    'components' => array_keys(array_filter($form_state['values']['components'])),
817
    'header_keys' => $form_state['values']['header_keys'],
818
    'select_keys' => $form_state['values']['select_keys'],
819
    'select_format' => $form_state['values']['select_format'],
820
    'range' => $form_state['values']['range'],
821
    'download' => $form_state['values']['download'],
822
  );
823

    
824
  $defaults = webform_results_download_default_options($node, $format);
825
  $options += $defaults;
826
  $options['range'] += $defaults['range'];
827

    
828
  // Determine an appropriate batch size based on the form and server specs.
829
  if (!isset($options['range']['batch_size'])) {
830
    $options['range']['batch_size'] = webform_export_batch_size($node);
831
  }
832

    
833
  $options['file_name'] = _webform_export_tempname();
834

    
835
  // Set up a batch to export the results.
836
  $batch = webform_results_export_batch($node, $format, $options);
837
  batch_set($batch);
838
}
839

    
840
/**
841
 * Calculate an appropriate batch size for bulk submission operations.
842
 *
843
 * @param object $node
844
 *   The webform node.
845
 * @return integer
846
 *   The number of submissions to be processed at once.
847
 */
848
function webform_export_batch_size($node) {
849
  // Start the batch size at 50,000 per batch, but divide by number of
850
  // components in the form. e.g. If a form had 10 components, it would
851
  // export 5,000 submissions at a time.
852
  $batch_size = ceil(50000 / max(1, count($node->webform['components'])));
853

    
854
  // Every 32MB of additional memory after 64MB adds a multiplier in size.
855
  $memory_limit = parse_size(ini_get('memory_limit'));
856
  $mb = 1048576;
857
  $memory_modifier = max(1, ($memory_limit - (64 * $mb)) / (32 * $mb));
858
  $batch_size = ceil($batch_size * $memory_modifier);
859

    
860
  // For time reasons, limit the batch size to 5,000.
861
  $batch_size = min($batch_size, 5000);
862

    
863
  // Allow a non-UI configuration to override the batch size.
864
  $batch_size = variable_get('webform_export_batch_size', $batch_size);
865

    
866
  return $batch_size;
867
}
868

    
869
/**
870
 * Returns a temporary export filename.
871
 */
872
function _webform_export_tempname() {
873
  return drupal_tempnam(variable_get('webform_export_path', 'temporary://'), 'webform_');
874
}
875

    
876
/**
877
 * Generate a Excel-readable CSV file containing all submissions for a Webform.
878
 *
879
 * Note that this function is generally no longer utilized. Instead Batch API
880
 * should be used to generate a file over multiple requests.
881
 *
882
 * @see webform_results_export_batch()
883
 *
884
 * @deprecated This function is schedule to be removed in webform 7.x-5.x. Use
885
 * the batch opertions instead.
886
 *
887
 * @return array|null
888
 *   The array of export info or null if the file could not be opened.
889
 */
890
function webform_results_export($node, $format = 'delimited', $options = array()) {
891
  module_load_include('inc', 'webform', 'includes/webform.export');
892
  module_load_include('inc', 'webform', 'includes/webform.components');
893

    
894
  $defaults = webform_results_download_default_options($node, $format);
895
  $options += $defaults;
896
  $options['range'] += $defaults['range'];
897

    
898
  // Open a new Webform exporter object.
899
  $exporter = webform_export_create_handler($format, $options);
900

    
901
  $file_name = _webform_export_tempname();
902
  $handle = fopen($file_name, 'w');
903
  if (!$handle) {
904
    return;
905
  }
906

    
907
  // Add the beginning of file marker (little-endian usually for MS Excel).
908
  $exporter->bof($handle);
909

    
910
  // Add headers to the file.
911
  $row_count = 0;
912
  $col_count = 0;
913
  $headers = webform_results_download_headers($node, $options);
914
  foreach ($headers as $row) {
915
    // Output header if header_keys is non-negative. -1 means no headers.
916
    if ($options['header_keys'] >= 0) {
917
      $exporter->add_row($handle, $row, $row_count);
918
      $row_count++;
919
    }
920
    $col_count = count($row) > $col_count ? count($row) : $col_count;
921
  }
922

    
923
  // Write data from submissions. $last_is is non_NULL to trigger returning it
924
  // by reference.
925
  $last_sid = TRUE;
926
  $rows = webform_results_download_rows($node, $options, 0, $last_sid);
927
  foreach ($rows as $row) {
928
    $exporter->add_row($handle, $row, $row_count);
929
    $row_count++;
930
  }
931

    
932
  // Add the closing bytes.
933
  $exporter->eof($handle, $row_count, $col_count);
934

    
935
  // Close the file.
936
  @fclose($handle);
937

    
938
  $export_info['format'] = $format;
939
  $export_info['options'] = $options;
940
  $export_info['file_name'] = $file_name;
941
  $export_info['row_count'] = $row_count;
942
  $export_info['col_count'] = $col_count;
943
  $export_info['last_sid'] = $last_sid;
944
  $export_info['exporter'] = $exporter;
945

    
946
  return $export_info;
947
}
948

    
949
/**
950
 * Return a Batch API array of commands that will generate an export.
951
 *
952
 * @param $node
953
 *   The webform node on which to generate the analysis.
954
 * @param string $format
955
 *   (optional) Delimiter of the exported file.
956
 * @param array $options
957
 *   (optional) An associative array of options that define the output format.
958
 *   These are generally passed through from the GUI interface. Possible options
959
 *   include:
960
 *   - sids: An array of submission IDs to which this export may be filtered.
961
 *     May be used to generate exports that are per-user or other groups of
962
 *     submissions.
963
 *
964
 * @return array
965
 *   A Batch API array suitable to pass to batch_set().
966
 */
967
function webform_results_export_batch($node, $format = 'delimited', $options = array()) {
968
  $defaults = webform_results_download_default_options($node, $format);
969
  $options += $defaults;
970
  $options['range'] += $defaults['range'];
971

    
972
  return array(
973
    'operations' => array(
974
      array('webform_results_batch_bof', array($node, $format, $options)),
975
      array('webform_results_batch_headers', array($node, $format, $options)),
976
      array('webform_results_batch_rows', array($node, $format, $options)),
977
      array('webform_results_batch_eof', array($node, $format, $options)),
978
      array('webform_results_batch_post_process', array($node, $format, $options)),
979
      array('webform_results_batch_results', array($node, $format, $options)),
980
    ),
981
    'finished' => 'webform_results_batch_finished',
982
    'title' => t('Exporting submissions'),
983
    'init_message' => t('Creating export file'),
984
    'error_message' => t('The export file could not be created because an error occurred.'),
985
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
986
  );
987
}
988

    
989
/**
990
 * Print the header rows for the downloadable webform data.
991
 *
992
 * @param $node
993
 *   The webform node on which to generate the analysis.
994
 * @param array $options
995
 *   A list of options that define the output format. These are generally passed
996
 *   through from the GUI interface.
997
 */
998
function webform_results_download_headers($node, $options) {
999
  module_load_include('inc', 'webform', 'includes/webform.components');
1000
  $submission_information = webform_results_download_submission_information($node, $options);
1001

    
1002
  // Fill in the header for the submission information (if any).
1003
  $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
1004
  if (count($submission_information)) {
1005
    $header[0][0] = $node->title;
1006

    
1007
    if ($options['header_keys']) {
1008
      $header[1][0] = t('submission_details');
1009
      $submission_information_headers = array_keys($submission_information);
1010
    }
1011
    else {
1012
      $header[1][0] = t('Submission Details');
1013
      $submission_information_headers = array_values($submission_information);
1014
    }
1015
    foreach ($submission_information_headers as $column => $label) {
1016
      $header[2][$column] = $label;
1017
    }
1018
  }
1019

    
1020
  // Compile header information for components.
1021
  foreach ($options['components'] as $cid) {
1022
    if (isset($node->webform['components'][$cid])) {
1023
      $component = $node->webform['components'][$cid];
1024

    
1025
      // Let each component determine its headers.
1026
      if (webform_component_feature($component['type'], 'csv')) {
1027
        $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
1028
        // Allow modules to modify the component CSV header.
1029
        drupal_alter('webform_csv_header', $component_header, $component);
1030

    
1031
        // Merge component CSV header to overall CSV header
1032
        $header[0] = array_merge($header[0], (array) $component_header[0]);
1033
        $header[1] = array_merge($header[1], (array) $component_header[1]);
1034
        $header[2] = array_merge($header[2], (array) $component_header[2]);
1035
      }
1036
    }
1037
  }
1038

    
1039
  return $header;
1040
}
1041

    
1042
/**
1043
 * Returns rows of downloadable webform data.
1044
 *
1045
 * @deprecated This function is scheduled to be removed in webform 7.x-5.x.
1046
 *
1047
 * @param $node
1048
 *   The webform node on which to generate the analysis.
1049
 * @param array $options
1050
 *   A list of options that define the output format. These are generally passed
1051
 *   through from the GUI interface.
1052
 * @param $serial_start
1053
 *   The starting position for the Serial column in the output.
1054
 * @param $last_sid
1055
 *   If set to a non-NULL value, the last sid will be returned.
1056
 *
1057
 * @return $rows
1058
 *   An array of rows built according to the provided $serial_start and
1059
 *   $pager_count variables. Note that the current page number is determined
1060
 *   by the super-global $_GET['page'] variable.
1061
 */
1062
function webform_results_download_rows($node, $options, $serial_start = 0, $last_sid = NULL) {
1063
  // Get all the required submissions for the download.
1064
  $filters['nid'] = $node->nid;
1065
  if (isset($options['sids'])) {
1066
    $filters['sid'] = $options['sids'];
1067
  }
1068
  elseif (!empty($options['completion_type']) && $options['completion_type'] !== 'all') {
1069
    $filters['is_draft'] = (int) ($options['completion_type'] === 'draft');
1070
  }
1071

    
1072
  $submissions = webform_get_submissions($filters, NULL);
1073

    
1074
  if (isset($last_sid)) {
1075
    $last_sid = end($submissions) ? key($submissions) : NULL;
1076
  }
1077

    
1078
  return webform_results_download_rows_process($node, $options, $serial_start, $submissions);
1079
}
1080

    
1081
/**
1082
 * Processes the submissions to be downloaded into exported rows.
1083
 *
1084
 * This is an internal routine and not intended for use by other modules.
1085
 *
1086
 * @param $node
1087
 *   The webform node on which to generate the analysis.
1088
 * @param array $options
1089
 *   A list of options that define the output format. These are generally passed
1090
 *   through from the GUI interface.
1091
 * @param $serial_start
1092
 *   The starting position for the Serial column in the output.
1093
 * @param array $submissions
1094
 *   An associative array of loaded submissions, indexed by sid.
1095
 *
1096
 * @return $rows
1097
 *   An array of rows built according to the provided $serial_start and
1098
 *   $pager_count variables. Note that the current page number is determined
1099
 *   by the super-global $_GET['page'] variable.
1100
 */
1101
function webform_results_download_rows_process($node, $options, $serial_start, $submissions) {
1102
  module_load_include('inc', 'webform', 'includes/webform.components');
1103

    
1104
  $submission_information = webform_results_download_submission_information($node, $options);
1105

    
1106
  // Generate a row for each submission.
1107
  $row_count = 0;
1108
  $rows = array();
1109
  foreach ($submissions as $sid => $submission) {
1110
    $row_count++;
1111

    
1112
    $row = array();
1113
    // Add submission information.
1114
    foreach (array_keys($submission_information) as $token) {
1115
      $cell = module_invoke_all('webform_results_download_submission_information_data', $token, $submission, $options, $serial_start, $row_count);
1116
      $context = array('token' => $token, 'submission' => $submission, 'options' => $options, 'serial_start' => $serial_start, 'row_count' => $row_count);
1117
      drupal_alter('webform_results_download_submission_information_data', $cell, $context);
1118
      // implode() to ensure everything from a single value goes into one
1119
      // column, even if more than one module responds to this item.
1120
      $row[] = implode(', ', $cell);
1121
    }
1122

    
1123
    foreach ($options['components'] as $cid) {
1124
      if (isset($node->webform['components'][$cid])) {
1125
        $component = $node->webform['components'][$cid];
1126
        // Let each component add its data.
1127
        $raw_data = isset($submission->data[$cid]) ? $submission->data[$cid] : NULL;
1128
        if (webform_component_feature($component['type'], 'csv')) {
1129
          $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);
1130

    
1131
          // Allow modules to modify the CSV data.
1132
          drupal_alter('webform_csv_data', $data, $component, $submission);
1133

    
1134
          if (is_array($data)) {
1135
            $row = array_merge($row, array_values($data));
1136
          }
1137
          else {
1138
            $row[] = isset($data) ? $data : '';
1139
          }
1140
        }
1141
      }
1142
    }
1143

    
1144
    $rows[$serial_start + $row_count] = $row;
1145
  }
1146

    
1147
  return $rows;
1148
}
1149

    
1150
/**
1151
 * Default columns for submission information.
1152
 *
1153
 * By default all exports have several columns of generic information that
1154
 * applies to all submissions. This function returns the list of generic columns
1155
 * plus columns added by other modules.
1156
 *
1157
 * @param $options
1158
 *   Filter down the list of columns based on a provided column list.
1159
 */
1160
function webform_results_download_submission_information($node, $options = array()) {
1161
  $submission_information = module_invoke_all('webform_results_download_submission_information_info');
1162
  drupal_alter('webform_results_download_submission_information_info', $submission_information);
1163

    
1164
  if (isset($options['components'])) {
1165
    foreach ($submission_information as $key => $label) {
1166
      if (!in_array($key, $options['components'])) {
1167
        unset($submission_information[$key]);
1168
      }
1169
    }
1170
  }
1171

    
1172
  return $submission_information;
1173
}
1174

    
1175
/**
1176
 * Implements hook_webform_results_download_submission_information_info().
1177
 */
1178
function webform_webform_results_download_submission_information_info() {
1179
  return array(
1180
    'webform_serial' => t('Serial'),
1181
    'webform_sid' => t('SID'),
1182
    'webform_time' => t('Submitted Time'),
1183
    'webform_completed_time' => t('Completed Time'),
1184
    'webform_modified_time' => t('Modified Time'),
1185
    'webform_draft' => t('Draft'),
1186
    'webform_ip_address' => t('IP Address'),
1187
    'webform_uid' => t('UID'),
1188
    'webform_username' => t('Username'),
1189
  );
1190
}
1191

    
1192
/**
1193
 * Implements hook_webform_results_download_submission_information_data().
1194
 */
1195
function webform_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
1196
  switch ($token) {
1197
    case 'webform_serial':
1198
      return $submission->serial;
1199
    case 'webform_sid':
1200
      return $submission->sid;
1201
    case 'webform_time':
1202
      // Return timestamp in local time (not UTC).
1203
      if (!empty($options['iso8601_date'])) {
1204
        return format_date($submission->submitted, 'custom', 'Y-m-d\TH:i:s');
1205
      }
1206
      else {
1207
        return format_date($submission->submitted, 'short');
1208
      }
1209
    case 'webform_completed_time':
1210
      if (!$submission->completed) {
1211
        return '';
1212
      }
1213
      // Return timestamp in local time (not UTC).
1214
      elseif (!empty($options['iso8601_date'])) {
1215
        return format_date($submission->completed, 'custom', 'Y-m-d\TH:i:s');
1216
      }
1217
      else {
1218
        return format_date($submission->completed, 'short');
1219
      }
1220
    case 'webform_modified_time':
1221
      // Return timestamp in local time (not UTC).
1222
      if (!empty($options['iso8601_date'])) {
1223
        return format_date($submission->modified, 'custom', 'Y-m-d\TH:i:s');
1224
      }
1225
      else {
1226
        return format_date($submission->modified, 'short');
1227
      }
1228
    case 'webform_draft':
1229
      return $submission->is_draft;
1230
    case 'webform_ip_address':
1231
      return $submission->remote_addr;
1232
    case 'webform_uid':
1233
      return $submission->uid;
1234
    case 'webform_username':
1235
      return $submission->name;
1236
  }
1237
}
1238

    
1239
/**
1240
 * Get options for creating downloadable versions of the webform data.
1241
 *
1242
 * @param $node
1243
 *   The webform node on which to generate the analysis.
1244
 * @param string $format
1245
 *   The export format being used.
1246
 * @param array $options
1247
 *   A list of options that define the output format. These are generally passed
1248
 *   through from the GUI interface.
1249
 */
1250
function webform_results_download_default_options($node, $format) {
1251
  $submission_information = webform_results_download_submission_information($node);
1252

    
1253
  $options = array(
1254
    'delimiter' => webform_variable_get('webform_csv_delimiter'),
1255
    'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
1256
    'header_keys' => 0,
1257
    'select_keys' => 0,
1258
    'select_format' => 'separate',
1259
    'range' => array(
1260
      'range_type' => 'all',
1261
      'completion_type' => 'all',
1262
    ),
1263
  );
1264

    
1265
  // Allow exporters to merge in additional options.
1266
  $exporter_information = webform_export_fetch_definition($format);
1267
  if (isset($exporter_information['options'])) {
1268
    $options = array_merge($options, $exporter_information['options']);
1269
  }
1270

    
1271
  return $options;
1272
}
1273

    
1274
/**
1275
 * Send a generated webform results file to the user's browser.
1276
 *
1277
 * @param $node
1278
 *   The webform node.
1279
 * @param $export_info
1280
 *   Export information array retrieved from webform_results_export().
1281
 */
1282
function webform_results_download($node, $export_info) {
1283
  // If the exporter provides a custom download method, use that.
1284
  if (method_exists($export_info['exporter'], 'download')) {
1285
    $export_info['exporter']->download($node);
1286
  }
1287
  // Otherwise use the set_headers() method to set headers and then read in the
1288
  // file directly. Delete it when complete.
1289
  else {
1290
    $export_name = _webform_safe_name($node->title);
1291
    if (!strlen($export_name)) {
1292
      $export_name  = t('Untitled');
1293
    }
1294
    $export_info['exporter']->set_headers($export_name);
1295
    @readfile($export_info['file_name']);  // The @ makes it silent.
1296
    @unlink($export_info['file_name']);  // Clean up, the @ makes it silent.
1297
  }
1298

    
1299
  // Save the last exported sid for new-only exports.
1300
  webform_results_export_success($node, $export_info);
1301

    
1302
  exit();
1303
}
1304

    
1305
/**
1306
 * Save the last-exported sid for new-only exports.
1307
 *
1308
 * @param $node
1309
 *   The webform node.
1310
 * @param $export_info
1311
 *   Export information array retrieved from webform_results_export().
1312
 */
1313
function webform_results_export_success($node, $export_info) {
1314
  if (!in_array($export_info['options']['range']['range_type'], array('range', 'range_serial', 'range_date')) && !empty($export_info['last_sid'])) {
1315
    // Insert a new record or update an existing record.
1316
    db_merge('webform_last_download')
1317
      ->key(array(
1318
        'nid' => $node->nid,
1319
        'uid' => $GLOBALS['user']->uid,
1320
      ))
1321
      ->fields(array(
1322
        'sid' => $export_info['last_sid'],
1323
        'requested' => REQUEST_TIME,
1324
      ))
1325
      ->execute();
1326
  }
1327
}
1328

    
1329
/**
1330
 * Menu callback; Download an exported file.
1331
 *
1332
 * This callabck requires that an export file be already generated by a batch
1333
 * process. The $_SESSION settings are usually put in place by the
1334
 * webform_results_export_results() function.
1335
 *
1336
 * @param $node
1337
 *   The webform $node whose export file is being downloaded.
1338
 *
1339
 * @return
1340
 *   Either an export file is downloaded with the appropriate HTTP headers set,
1341
 *   or an error page is shown if now export is available to download.
1342
 */
1343
function webform_results_download_callback($node) {
1344
  if (isset($_SESSION['webform_export_info'])) {
1345
    module_load_include('inc', 'webform', 'includes/webform.export');
1346

    
1347
    $export_info = $_SESSION['webform_export_info'];
1348
    $export_info['exporter'] = webform_export_create_handler($export_info['format'], $export_info['options']);
1349

    
1350
    unset($_SESSION['webform_export_info']);
1351
    if (isset($_COOKIE['webform_export_info'])) {
1352
      unset($_COOKIE['webform_export_info']);
1353
      $params = session_get_cookie_params();
1354
      setcookie('webform_export_info', '', -1, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1355
    }
1356

    
1357
    webform_results_download($node, $export_info);
1358
  }
1359
  else {
1360
    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')));
1361
  }
1362
}
1363

    
1364
/**
1365
 * Batch API callback; Write the opening byte in the export file.
1366
 */
1367
function webform_results_batch_bof($node, $format = 'delimited', $options = array(), &$context) {
1368
  module_load_include('inc', 'webform', 'includes/webform.export');
1369

    
1370
  $exporter = webform_export_create_handler($format, $options);
1371
  $handle = fopen($options['file_name'], 'w');
1372
  if (!$handle) {
1373
    return;
1374
  }
1375
  $exporter->bof($handle);
1376
  @fclose($handle);
1377
}
1378

    
1379
/**
1380
 * Batch API callback; Write the headers of the export to the export file.
1381
 */
1382
function webform_results_batch_headers($node, $format = 'delimited', $options = array(), &$context) {
1383
  module_load_include('inc', 'webform', 'includes/webform.export');
1384

    
1385
  $exporter = webform_export_create_handler($format, $options);
1386
  $handle = fopen($options['file_name'], 'a');
1387
  if (!$handle) {
1388
    return;
1389
  }
1390
  $headers = webform_results_download_headers($node, $options);
1391
  $row_count = 0;
1392
  $col_count = 0;
1393
  foreach ($headers as $row) {
1394
    // Output header if header_keys is non-negative. -1 means no headers.
1395
    if ($options['header_keys'] >= 0) {
1396
      $exporter->add_row($handle, $row, $row_count);
1397
      $row_count++;
1398
    }
1399
    $col_count = count($row) > $col_count ? count($row) : $col_count;
1400
  }
1401
  $context['results']['row_count'] = $row_count;
1402
  $context['results']['col_count'] = $col_count;
1403
  @fclose($handle);
1404
}
1405

    
1406
/**
1407
 * Batch API callback; Write the rows of the export to the export file.
1408
 */
1409
function webform_results_batch_rows($node, $format = 'delimited', $options = array(), &$context) {
1410
  module_load_include('inc', 'webform', 'includes/webform.export');
1411

    
1412
  // Initialize the sandbox if this is the first execution of the batch
1413
  // operation.
1414
  if (!isset($context['sandbox']['batch_number'])) {
1415
    $context['sandbox']['batch_number'] = 0;
1416
    $context['sandbox']['sid_count'] = webform_download_sids_count($node->nid, $options['range']);
1417
    $context['sandbox']['batch_max'] = max(1, ceil($context['sandbox']['sid_count'] / $options['range']['batch_size']));
1418
    $context['sandbox']['serial'] = 0;
1419
    $context['sandbox']['last_sid'] = 0;
1420
  }
1421

    
1422
  // Retrieve the submissions for this batch process.
1423
  $options['range']['batch_number'] = $context['sandbox']['batch_number'];
1424

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

    
1427
  // Join to the users table to include user name in results, as required by
1428
  // webform_results_download_rows_process.
1429
  $query->leftJoin('users', 'u', 'u.uid = ws.uid');
1430
  $query->fields('u', array('name'));
1431
  $query->fields('ws');
1432

    
1433
  $submissions = webform_get_submissions_load($query);
1434

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

    
1437
  // Write these submissions to the file.
1438
  $exporter = webform_export_create_handler($format, $options);
1439
  $handle = fopen($options['file_name'], 'a');
1440
  if (!$handle) {
1441
    return;
1442
  }
1443
  foreach ($rows as $row) {
1444
    $exporter->add_row($handle, $row, $context['results']['row_count']);
1445
    $context['results']['row_count']++;
1446
  }
1447

    
1448
  $context['sandbox']['serial'] += count($submissions);
1449
  $context['sandbox']['last_sid'] = end($submissions) ? key($submissions) : NULL;
1450
  $context['sandbox']['batch_number']++;
1451

    
1452
  @fclose($handle);
1453

    
1454
  // Display status message
1455
  $context['message'] = t('Exported @count of @total submissions...', array('@count' => $context['sandbox']['serial'], '@total' => $context['sandbox']['sid_count']));
1456
  $context['finished'] = $context['sandbox']['batch_number'] < $context['sandbox']['batch_max']
1457
                            ? $context['sandbox']['batch_number'] / $context['sandbox']['batch_max']
1458
                            : 1.0;
1459
  $context['results']['last_sid'] = $context['sandbox']['last_sid'];
1460
}
1461

    
1462
/**
1463
 * Batch API callback; Write the closing bytes in the export file.
1464
 */
1465
function webform_results_batch_eof($node, $format = 'delimited', $options = array(), &$context) {
1466
  module_load_include('inc', 'webform', 'includes/webform.export');
1467

    
1468
  $exporter = webform_export_create_handler($format, $options);
1469

    
1470
  // We open the file for reading and writing, rather than just appending for
1471
  // exporters that need to adjust the beginning of the files as well as the
1472
  // end, i.e. webform_exporter_excel_xlsx::eof().
1473
  $handle = fopen($options['file_name'], 'r+');
1474
  if (!$handle) {
1475
    return;
1476
  }
1477
  fseek($handle, 0, SEEK_END); // Move pointer to the end of the file.
1478
  $exporter->eof($handle, $context['results']['row_count'], $context['results']['col_count']);
1479
  @fclose($handle);
1480
}
1481

    
1482
/**
1483
 * Batch API callback; Do any last processing on the finished export.
1484
 */
1485
function webform_results_batch_post_process($node, $format = 'delimited', $options = array(), &$context) {
1486
  module_load_include('inc', 'webform', 'includes/webform.export');
1487

    
1488
  $context['results']['node'] = $node;
1489
  $context['results']['file_name'] = $options['file_name'];
1490

    
1491
  $exporter = webform_export_create_handler($format, $options);
1492
  $exporter->post_process($context['results']);
1493
}
1494

    
1495
/**
1496
 * Batch API callback; Set the $_SESSION variables used to download the file.
1497
 *
1498
 * Because we want the user to be returned to the main form first, we have to
1499
 * temporarily store information about the created file, send the user to the
1500
 * form, then use JavaScript to request node/x/webform-results/download-file,
1501
 * which will execute webform_results_download_file().
1502
 */
1503
function webform_results_batch_results($node, $format, $options, &$context) {
1504

    
1505
  $export_info = array(
1506
    'format' => $format,
1507
    'options' => $options,
1508
    'file_name' => $context['results']['file_name'],
1509
    'row_count' => $context['results']['row_count'],
1510
    'last_sid' => $context['results']['last_sid'],
1511
  );
1512

    
1513
  if (isset($_SESSION)) {
1514
    // UI exection. Defer resetting last-downloaded sid until download page.
1515
    // Set a session variable containing the information referencing the exported
1516
    // file. A cookie is also set to allow the browser to ensure the redirect
1517
    // to the file only happens one time.
1518
    $_SESSION['webform_export_info'] = $export_info;
1519
    $params = session_get_cookie_params();
1520
    setcookie('webform_export_info', '1', REQUEST_TIME + 120, $params['path'], $params['domain'], $params['secure'], FALSE);
1521
  }
1522
  else {
1523
    // Drush execution of wfx command. Reset last-downloaded sid now. $_SESSION
1524
    // is not supported for command line execution.
1525
    webform_results_export_success($node, $export_info);
1526
  }
1527
}
1528

    
1529
/**
1530
 * Batch API completion callback; Display completion message and cleanup.
1531
 */
1532
function webform_results_batch_finished($success, $results, $operations) {
1533
  if ($success) {
1534
    $download_url = url('node/' . $results['node']->nid . '/webform-results/download-file');
1535
    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)));
1536
  }
1537
  else {
1538
    drupal_set_message(t('An error occurred while generating the export file.'));
1539
    if (isset($results['file_name']) && is_file($results['file_name'])) {
1540
      @unlink($results['file_name']);
1541
    }
1542
  }
1543
}
1544

    
1545
/**
1546
 * Provides a simple analysis of all submissions to a webform.
1547
 *
1548
 * @param $node
1549
 *   The webform node on which to generate the analysis.
1550
 * @param $sids
1551
 *   An array of submission IDs to which this analysis may be filtered. May be
1552
 *   used to generate results that are per-user or other groups of submissions.
1553
 * @param $analysis_component
1554
 *   A webform component. If passed in, additional information may be returned
1555
 *   relating specifically to that component's analysis, such as a list of
1556
 *   "Other" values within a select list.
1557
 */
1558
function webform_results_analysis($node, $sids = array(), $analysis_component = NULL) {
1559
  if (!is_array($sids)) {
1560
    $sids = array();
1561
  }
1562

    
1563
  // Build a renderable for the content of this page.
1564
  $analysis = array(
1565
    '#theme' => array('webform_analysis__' . $node->nid, 'webform_analysis'),
1566
    '#node' => $node,
1567
    '#component' => $analysis_component,
1568
  );
1569

    
1570
  // See if a query (possibly with exposed filter) needs to restrict the
1571
  // submissions that are being analyzed.
1572
  $query = NULL;
1573
  if (empty($sids)) {
1574
    $view = webform_get_view($node, 'webform_analysis');
1575
    if ($view->type != t('Default') || $view->name != 'webform_analysis') {
1576
      // The view has been customized from the no-op built-in view. Use it.
1577
      $view->set_display();
1578
      $view->init_handlers();
1579
      $view->override_url = $_GET['q'];
1580
      $view->preview = TRUE;
1581
      $view->pre_execute(array($node->nid));
1582
      $view->build();
1583
      // Let modules modify the view just prior to executing it.
1584
      foreach (module_implements('views_pre_execute') as $module) {
1585
        $function = $module . '_views_pre_execute';
1586
        $function($view);
1587
      }
1588
      // If the view is already executed, there was an error in generating it.
1589
      $query = $view->executed ? NULL : $view->query->query();
1590
      $view->post_execute();
1591

    
1592
      if (isset($view->exposed_widgets)) {
1593
        $analysis['exposed_filter']['#markup'] = $view->exposed_widgets;
1594
      }
1595
    }
1596
  }
1597

    
1598
  // If showing all components, display selection form.
1599
  if (!$analysis_component) {
1600
    $analysis['form'] = drupal_get_form('webform_analysis_components_form', $node);
1601
  }
1602

    
1603
  // Add all the components to the analysis renderable array.
1604
  $components = isset($analysis_component) ? array($analysis_component['cid']) : webform_analysis_enabled_components($node);
1605
  foreach ($components as $cid) {
1606
    // Do component specific call.
1607
    $component = $node->webform['components'][$cid];
1608
    if ($data = webform_component_invoke($component['type'], 'analysis', $component, $sids, isset($analysis_component), $query)) {
1609
      drupal_alter('webform_analysis_component_data', $data, $node, $component);
1610
      $analysis['data'][$cid] = array(
1611
        '#theme' => array('webform_analysis_component__' . $node->nid . '__' . $cid, 'webform_analysis_component__' . $node->nid, 'webform_analysis_component'),
1612
        '#node' => $node,
1613
        '#component' => $component,
1614
        '#data' => $data,
1615
      );
1616
      $analysis['data'][$cid]['basic'] = array(
1617
        '#theme' => array('webform_analysis_component_basic__' . $node->nid . '__' . $cid, 'webform_analysis_component_basic__' . $node->nid, 'webform_analysis_component_basic'),
1618
        '#component' => $component,
1619
        '#data' => $data,
1620
      );
1621
    }
1622
  }
1623

    
1624
  drupal_alter('webform_analysis', $analysis);
1625
  return drupal_render($analysis);
1626
}
1627

    
1628
/**
1629
 * Prerender function for webform-analysis.tpl.php.
1630
 */
1631
function template_preprocess_webform_analysis(&$variables) {
1632
  $analysis = $variables['analysis'];
1633
  $variables['node'] = $analysis['#node'];
1634
  $variables['component'] = $analysis['#component'];
1635
}
1636

    
1637
/**
1638
 * Prerender function for webform-analysis-component.tpl.php.
1639
 */
1640
function template_preprocess_webform_analysis_component(&$variables) {
1641
  $component_analysis = $variables['component_analysis'];
1642
  $variables['node'] = $component_analysis['#node'];
1643
  $variables['component'] = $component_analysis['#component'];
1644

    
1645
  // Ensure defaults.
1646
  $variables['component_analysis']['#data'] += array(
1647
    'table_header' => NULL,
1648
    'table_rows' => array(),
1649
    'other_data' => array(),
1650
  );
1651
  $variables['classes_array'][] = 'webform-analysis-component-' . $variables['component']['type'];
1652
  $variables['classes_array'][] = 'webform-analysis-component--' . str_replace('_', '-', implode('--', webform_component_parent_keys($variables['node'], $variables['component'])));
1653
}
1654

    
1655
/**
1656
 * Render an individual component's analysis data in a table.
1657
 *
1658
 * @param $variables
1659
 *   An array of theming variables for this theme function. Included keys:
1660
 *   - $component: The component whose analysis is being rendered.
1661
 *   - $data: An array of array containing the analysis data. Contains the keys:
1662
 *     - table_header: If this table has more than a single column, an array
1663
 *       of header labels.
1664
 *     - table_rows: If this component has a table that should be rendered, an
1665
 *       array of values
1666
 */
1667
function theme_webform_analysis_component_basic($variables) {
1668
  $data = $variables['data'];
1669

    
1670
  // Ensure defaults.
1671
  $data += array(
1672
    'table_header' => NULL,
1673
    'table_rows' => array(),
1674
    'other_data' => array(),
1675
  );
1676

    
1677
  // Combine the "other data" into the table rows by default.
1678
  if (is_array($data['other_data'])) {
1679
    foreach ($data['other_data'] as $other_data) {
1680
      if (is_array($other_data)) {
1681
        $data['table_rows'][] = $other_data;
1682
      }
1683
      else {
1684
        $data['table_rows'][] = array(array(
1685
          'colspan' => 2,
1686
          'data' => $other_data,
1687
        ));
1688
      }
1689
    }
1690
  }
1691
  elseif (strlen($data['other_data'])) {
1692
    $data['table_rows'][] = array(
1693
      'colspan' => 2,
1694
      'data' => $data['other_data'],
1695
    );
1696
  }
1697

    
1698
  return theme('table', array(
1699
    'header' => $data['table_header'],
1700
    'rows' => $data['table_rows'],
1701
    'sticky' => FALSE,
1702
    'attributes' => array('class' => array('webform-analysis-table')),
1703
  ));
1704
}
1705

    
1706
/**
1707
 * Return a list of components that should be displayed for analysis.
1708
 *
1709
 * @param $node
1710
 *   The node whose components' data is being analyzed.
1711
 * @return array
1712
 *   An array of component IDs.
1713
 */
1714
function webform_analysis_enabled_components($node) {
1715
  $cids = array();
1716
  foreach ($node->webform['components'] as $cid => $component) {
1717
    if (!empty($component['extra']['analysis'])) {
1718
      $cids[] = $cid;
1719
    }
1720
  }
1721
  return $cids;
1722
}
1723

    
1724
/**
1725
 * Form for selecting which components should be shown on the analysis page.
1726
 */
1727
function webform_analysis_components_form($form, &$form_state, $node) {
1728
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1729
  $form['#node'] = $node;
1730

    
1731
  $component_list = webform_component_list($node, 'analysis', TRUE);
1732
  $enabled_components = webform_analysis_enabled_components($node);
1733
  if (empty($component_list)) {
1734
    $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')));
1735
  }
1736
  elseif (empty($enabled_components)) {
1737
    $help = t('No components have analysis enabled in this form. Enable analysis under the "Add analysis components" fieldset.');
1738
  }
1739
  else {
1740
    $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.');
1741
  }
1742

    
1743
  $form['help'] = array(
1744
    '#markup' => '<p>' . $help . '</p>',
1745
    '#access' => !empty($help),
1746
    '#weight' => -100,
1747
  );
1748

    
1749
  $form['components'] = array(
1750
    '#type' => 'select',
1751
    '#title' => t('Add analysis components'),
1752
    '#options' => $component_list,
1753
    '#default_value' => $enabled_components,
1754
    '#multiple' => TRUE,
1755
    '#size' => 10,
1756
    '#description' => t('The selected components will be included on the analysis page.'),
1757
    '#process' => array('webform_component_select'),
1758
    '#access' => count($component_list),
1759
  );
1760

    
1761
  $form['actions'] = array(
1762
    '#type' => 'actions',
1763
    '#access' => count($component_list),
1764
  );
1765
  $form['actions']['submit'] = array(
1766
    '#type' => 'submit',
1767
    '#value' => t('Update analysis display'),
1768
  );
1769

    
1770
  return $form;
1771
}
1772

    
1773
/**
1774
 * Submit handler for webform_analysis_components_form().
1775
 */
1776
function webform_analysis_components_form_submit($form, $form_state) {
1777
  $node = $form['#node'];
1778
  foreach ($form_state['values']['components'] as $cid => $enabled) {
1779
    $node->webform['components'][$cid]['extra']['analysis'] = (bool) $enabled;
1780
  }
1781
  node_save($node);
1782
}
1783

    
1784
/**
1785
 * Output the content of the Analysis page.
1786
 *
1787
 * @see webform_results_analysis()
1788
 */
1789
function theme_webform_results_analysis($variables) {
1790
  $node = $variables['node'];
1791
  $data = $variables['data'];
1792
  $sids = $variables['sids'];
1793
  $analysis_component = $variables['component'];
1794

    
1795
  $rows = array();
1796
  $question_number = 0;
1797
  $single = isset($analysis_component);
1798

    
1799
  $header = array(
1800
    $single ? $analysis_component['name'] : t('Q'),
1801
    array('data' => $single ? '&nbsp;' : t('responses'), 'colspan' => '10')
1802
  );
1803

    
1804
  foreach ($data as $cid => $row_data) {
1805
    $question_number++;
1806

    
1807
    if (is_array($row_data)) {
1808
      $row = array();
1809
      if (!$single) {
1810
        $row['data'][] = array('data' => '<strong>' . $question_number . '</strong>', 'rowspan' => count($row_data) + 1, 'valign' => 'top');
1811
        $row['data'][] = array('data' => '<strong>' . check_plain($node->webform['components'][$cid]['name']) . '</strong>', 'colspan' => '10');
1812
        $row['class'][] = 'webform-results-question';
1813
      }
1814
      $rows = array_merge($rows, array_merge(array($row), $row_data));
1815
    }
1816
  }
1817

    
1818
  if (count($rows) == 0) {
1819
    $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));
1820
  }
1821

    
1822
  return theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('class' => array('webform-results-analysis'))));
1823
}
1824

    
1825
/**
1826
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1827
 *
1828
 * @deprecated This function is scheduled to be removed int webform 7.x-5.x.
1829
 * Use webform_download_sids_query() instead.
1830
 *
1831
 */
1832
function webform_download_sids($nid, $range_options, $uid = NULL) {
1833
  return webform_download_sids_query($nid, $range_options, $uid)
1834
    ->fields('ws', array('sid'))
1835
    ->execute()
1836
    ->fetchCol();
1837
}
1838

    
1839
/**
1840
 * Retrieves a count the number of matching submissions.
1841
 *
1842
 */
1843
function webform_download_sids_count($nid, $range_options, $uid = NULL) {
1844
  return webform_download_sids_query($nid, $range_options, $uid)
1845
    ->countQuery()
1846
    ->execute()
1847
    ->fetchField();
1848
}
1849

    
1850
/**
1851
 * Given a set of range options, return an unexecuted select query.
1852
 *
1853
 * The query will have no fields as they should be added by the caller as
1854
 * desired.
1855
 *
1856
 * @param integer $nid
1857
 *   The node id of the webform.
1858
 * @param array $range_options
1859
 *   Associate array of range options.
1860
 * @param integer $uid
1861
 *   The user id of the user whose last download information should be used,
1862
 *   or the current user if NULL. This is unrelated to which user submitted
1863
 *   the submissions.
1864
 */
1865
function webform_download_sids_query($nid, $range_options, $uid = NULL) {
1866
  $query = db_select('webform_submissions', 'ws')
1867
    ->condition('nid', $nid)
1868
    ->addTag('webform_download_sids');
1869

    
1870
  switch ($range_options['range_type']) {
1871
    case 'all':
1872
      // All Submissions.
1873
      $query->orderBy('ws.sid', 'ASC');
1874
      break;
1875
    case 'new':
1876
      // All Since Last Download.
1877
      $download_info = webform_download_last_download_info($nid, $uid);
1878
      $last_sid = $download_info ? $download_info['sid'] : 0;
1879
      $query
1880
        ->condition('ws.sid', $last_sid, '>')
1881
        ->orderBy('ws.sid', 'ASC');
1882
      break;
1883
    case 'latest':
1884
      // Last x Submissions.
1885
      $start_sid = webform_download_latest_start_sid($nid, $range_options['latest'], $range_options['completion_type']);
1886
      $query->condition('ws.sid', $start_sid, '>=');
1887
      break;
1888
    case 'range':
1889
      // Submissions Start-End.
1890
      $query->condition('ws.sid', $range_options['start'], '>=');
1891
      if ($range_options['end']) {
1892
        $query->condition('ws.sid', $range_options['end'], '<=');
1893
      }
1894
      $query->orderBy('ws.sid', 'ASC');
1895
      break;
1896
    case 'range_serial':
1897
      // Submissions Start-End, using serial numbers.
1898
      $query->condition('ws.serial', $range_options['start'], '>=');
1899
      if ($range_options['end']) {
1900
        $query->condition('ws.serial', $range_options['end'], '<=');
1901
      }
1902
      $query->orderBy('ws.serial', 'ASC');
1903
      break;
1904
    case 'range_date':
1905
      $date_field = $range_options['completion_type'] == 'finished' ? 'ws.completed' : 'ws.submitted';
1906
      $query->condition($date_field, strtotime($range_options['start_date']), '>=');
1907
      if ($range_options['end_date'] != '' && ($end_time = strtotime($range_options['end_date'])) !== FALSE) {
1908
        if ($end_time == strtotime('midnight', $end_time)) {
1909
          // Full day specified
1910
          $end_time += 86399; // 86400 is a full day of seconds.
1911
        }
1912
        $query->condition($date_field, $end_time, '<=');
1913
      }
1914
      ;
1915
      $query->orderBy($date_field, 'ASC');
1916
      break;
1917
  }
1918

    
1919
  // Filter down to draft or finished submissions.
1920
  if (!empty($range_options['completion_type']) && $range_options['completion_type'] !== 'all') {
1921
    $query->condition('is_draft', (int) ($range_options['completion_type'] === 'draft'));
1922
  }
1923

    
1924
  if (isset($range_options['batch_number']) && !empty($range_options['batch_size'])) {
1925
    $query->range($range_options['batch_number'] * $range_options['batch_size'], $range_options['batch_size']);
1926
  }
1927
  return $query;
1928
}
1929

    
1930
/**
1931
 * Get this user's last download information, including the SID and timestamp.
1932
 *
1933
 * This function provides an array of information about the last download that
1934
 * a user had for a particular Webform node. Currently it only returns an array
1935
 * with two keys:
1936
 *  - sid: The last submission ID that was downloaded.
1937
 *  - requested: The timestamp of the last download request.
1938
 *
1939
 * @param $nid
1940
 *   The Webform NID.
1941
 * @param $uid
1942
 *   The user account ID for which to retrieve download information.
1943
 * @return
1944
 *   An array of download information or FALSE if this user has never downloaded
1945
 *   results for this particular node.
1946
 */
1947
function webform_download_last_download_info($nid, $uid = NULL) {
1948
  $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
1949

    
1950
  $query = db_select('webform_last_download', 'wld');
1951
  $query->leftJoin('webform_submissions', 'wfs', 'wld.sid = wfs.sid');
1952
  $info = $query
1953
    ->fields('wld')
1954
    ->fields('wfs', array('serial'))
1955
    ->condition('wld.nid', $nid)
1956
    ->condition('wld.uid', $uid)
1957
    ->execute()
1958
    ->fetchAssoc();
1959

    
1960
  return $info;
1961
}
1962

    
1963
/**
1964
 * Get an SID based a requested latest count.
1965
 *
1966
 * @param int $nid
1967
 *   The webform NID.
1968
 * @param int $latest_count
1969
 *   The latest count on which the SID will be retrieved.
1970
 * @param string $completion_type
1971
 *   The completion type, either "finished", "draft", or "all".
1972
 * @return
1973
 *   The submission ID that starts the latest sequence of submissions.
1974
 */
1975
function webform_download_latest_start_sid($nid, $latest_count, $completion_type = 'all') {
1976
  // TODO: Find a more efficient DBTNG query to retrieve this number.
1977
  $query = db_select('webform_submissions', 'ws')
1978
    ->fields('ws', array('sid'))
1979
    ->condition('nid', $nid)
1980
    ->orderBy('ws.sid', 'DESC')
1981
    ->range(0, $latest_count)
1982
    ->addTag('webform_download_latest_start_sid');
1983

    
1984
  if ($completion_type !== 'all') {
1985
    $query->condition('is_draft', (int) ($completion_type === 'draft'));
1986
  }
1987

    
1988
  $latest_sids = $query->execute()->fetchCol();
1989
  return $latest_sids ? min($latest_sids) : 1;
1990
}