Project

General

Profile

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

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

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 $element;
104
}
105

    
106
/**
107
 * Returns the most appropriate view for this webform node.
108
 *
109
 * Site builders can customize the view that webform uses by webform node id or
110
 * by webform content type. For example, use webform_results_123 to for node
111
 * id 123 or webform_results_my_content_type for a node of type my_content_type.
112
 *
113
 * @param object $node
114
 *   Loaded webform node.
115
 * @param string $view_id
116
 *   The machine_id of the view, such as webform_results or webform_submissions.
117
 *
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 array $variables
134
 *   Array with keys:
135
 *     - "total_count": The total number of results available.
136
 *     - "pager_count": The current number of results displayed per page.
137
 *
138
 * @return string
139
 *   Pager.
140
 */
141
function theme_webform_results_per_page(array $variables) {
142
  $total_count = $variables['total_count'];
143
  $pager_count = $variables['pager_count'];
144
  $output = '';
145

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

    
157
  $count_links = array();
158

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

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

    
177
  return $output;
178
}
179

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

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

    
199
  return $columns;
200
}
201

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

    
213
  unset($vars['element']);
214
}
215

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

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

    
229
  // Get all the submissions for the node.
230
  if (isset($_GET['results']) && is_numeric($_GET['results'])) {
231
    $pager_count = $_GET['results'];
232
  }
233

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

    
239
  $output[] = array(
240
    '#theme' => 'webform_results_table',
241
    '#node' => $node,
242
    '#components' => $node->webform['components'],
243
    '#submissions' => $submissions,
244
    '#total_count' => $total_count,
245
    '#pager_count' => $pager_count,
246
  );
247
  if ($pager_count) {
248
    $output[] = array('#theme' => 'pager');
249
  }
250
  return $output;
251
}
252

    
253
/**
254
 * Theme function for the Webform results table header.
255
 */
256
function theme_webform_results_table_header($variables) {
257
  return array(
258
    array('data' => t('#'), 'field' => 'sid', 'sort' => 'desc'),
259
    array('data' => t('Submitted'), 'field' => 'submitted'),
260
    array('data' => t('User'), 'field' => 'name'),
261
    array('data' => t('IP Address'), 'field' => 'remote_addr'),
262
  );
263
}
264

    
265
/**
266
 * Theme the results table displaying all the submissions for a particular node.
267
 *
268
 * @param $node
269
 *   The node whose results are being displayed.
270
 * @param $components
271
 *   An associative array of the components for this webform.
272
 * @param $submissions
273
 *   An array of all submissions for this webform.
274
 * @param $total_count
275
 *   The total number of submissions to this webform.
276
 * @param $pager_count
277
 *   The number of results to be shown per page.
278
 *
279
 * @return string
280
 *   HTML string with result data.
281
 */
282
function theme_webform_results_table($variables) {
283
  drupal_add_library('webform', 'admin');
284

    
285
  $node = $variables['node'];
286
  $submissions = $variables['submissions'];
287
  $total_count = $variables['total_count'];
288
  $pager_count = $variables['pager_count'];
289

    
290
  $rows = array();
291
  $cell = array();
292

    
293
  // This header has to be generated separately so we can add the SQL necessary.
294
  // to sort the results.
295
  $header = theme('webform_results_table_header', array('node' => $node));
296

    
297
  // Generate a row for each submission.
298
  foreach ($submissions as $sid => $submission) {
299
    $link_text = $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial;
300
    $cell[] = l($link_text, 'node/' . $node->nid . '/submission/' . $sid);
301
    $cell[] = format_date($submission->submitted, 'short');
302
    $cell[] = theme('username', array('account' => $submission));
303
    $cell[] = $submission->remote_addr;
304
    $component_headers = array();
305

    
306
    // Generate a cell for each component.
307
    foreach ($node->webform['components'] as $component) {
308
      $data = isset($submission->data[$component['cid']]) ? $submission->data[$component['cid']] : NULL;
309
      $submission_output = webform_component_invoke($component['type'], 'table', $component, $data);
310
      if ($submission_output !== NULL) {
311
        $component_headers[] = array('data' => check_plain($component['name']), 'field' => $component['cid']);
312
        $cell[] = $submission_output;
313
      }
314
    }
315

    
316
    $rows[] = $cell;
317
    unset($cell);
318
  }
319
  if (!empty($component_headers)) {
320
    $header = array_merge($header, $component_headers);
321
  }
322

    
323
  if (count($rows) == 0) {
324
    $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));
325
  }
326

    
327
  $output = '';
328
  $output .= theme('webform_results_per_page', array('total_count' => $total_count, 'pager_count' => $pager_count));
329
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
330
  return $output;
331
}
332

    
333
/**
334
 * Delete all submissions for a node.
335
 *
336
 * @param $nid
337
 *   The node id whose submissions will be deleted.
338
 * @param $batch_size
339
 *   The number of submissions to be processed. NULL means all submissions.
340
 *
341
 * @return int
342
 *   The number of submissions processed.
343
 */
344
function webform_results_clear($nid, $batch_size = NULL) {
345
  $node = node_load($nid);
346
  $submissions = webform_get_submissions($nid, NULL, $batch_size);
347
  $count = 0;
348
  foreach ($submissions as $submission) {
349
    webform_submission_delete($node, $submission);
350
    $count++;
351
  }
352
  return $count;
353
}
354

    
355
/**
356
 * Confirmation form to delete all submissions for a node.
357
 *
358
 * @param $nid
359
 *   ID of node for which to clear submissions.
360
 */
361
function webform_results_clear_form($form, $form_state, $node) {
362
  drupal_set_title(t('Clear Form Submissions'));
363

    
364
  $form = array();
365
  $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
366
  $question = t('Are you sure you want to delete all submissions for this form?');
367

    
368
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform-results', NULL, t('Clear'), t('Cancel'));
369
}
370

    
371
/**
372
 * Form submit handler.
373
 */
374
function webform_results_clear_form_submit($form, &$form_state) {
375
  $nid = $form_state['values']['nid'];
376
  $node = node_load($nid);
377
  // Set a modest batch size, due to the inefficiency of the hooks invoked when
378
  // submissions are deleted.
379
  $batch_size = min(webform_export_batch_size($node), 500);
380

    
381
  // Set up a batch to clear the results.
382
  $batch = array(
383
    'operations' => array(
384
      array('webform_clear_batch_rows', array($node, $batch_size)),
385
    ),
386
    'finished' => 'webform_clear_batch_finished',
387
    'title' => t('Clear submissions'),
388
    'init_message' => t('Clearing submission data'),
389
    'error_message' => t('The submissions could not be cleared because an error occurred.'),
390
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
391
  );
392
  batch_set($batch);
393
  $form_state['redirect'] = 'node/' . $nid . '/webform-results';
394
}
395

    
396
/**
397
 * Batch API callback; Write the rows of the export to the export file.
398
 */
399
function webform_clear_batch_rows($node, $batch_size, &$context) {
400
  // Initialize the results if this is the first execution of the batch
401
  // operation.
402
  if (!isset($context['results']['count'])) {
403
    $context['results'] = array(
404
      'count' => 0,
405
      'total' => webform_get_submission_count($node->nid),
406
      'node' => $node,
407
    );
408
  }
409

    
410
  // Clear a batch of submissions.
411
  $count = webform_results_clear($node->nid, $batch_size);
412
  $context['results']['count'] += $count;
413

    
414
  // Display status message.
415
  $context['message'] = t('Cleared @count of @total submissions...', array('@count' => $context['results']['count'], '@total' => $context['results']['total']));
416
  $context['finished'] = $count > 0
417
                            ? $context['results']['count'] / $context['results']['total']
418
                            : 1.0;
419
}
420

    
421
/**
422
 * Batch API completion callback; Finish clearing submissions.
423
 */
424
function webform_clear_batch_finished($success, $results, $operations) {
425
  if ($success) {
426
    $title = $results['node']->title;
427
    drupal_set_message(t('Webform %title entries cleared.', array('%title' => $title)));
428
    watchdog('webform', 'Webform %title entries cleared.', array('%title' => $title));
429
  }
430
}
431

    
432
/**
433
 * Form to configure the download of CSV files.
434
 */
435
function webform_results_download_form($form, &$form_state, $node) {
436
  module_load_include('inc', 'webform', 'includes/webform.export');
437
  module_load_include('inc', 'webform', 'includes/webform.components');
438

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

    
441
  // If an export is waiting to be downloaded, redirect the user there after
442
  // the page has finished loading.
443
  if (isset($_SESSION['webform_export_info'])) {
444
    $download_url = url('node/' . $node->nid . '/webform-results/download-file', array('absolute' => TRUE));
445
    $form['#attached']['js'][] = array('data' => array('webformExport' => $download_url), 'type' => 'setting');
446
  }
447

    
448
  $form['node'] = array(
449
    '#type' => 'value',
450
    '#value' => $node,
451
  );
452

    
453
  $form['format'] = array(
454
    '#type' => 'radios',
455
    '#title' => t('Export format'),
456
    '#options' => webform_export_list(),
457
    '#default_value' => webform_variable_get('webform_export_format'),
458
  );
459

    
460
  $form['delimited_options'] = array(
461
    '#type' => 'container',
462
    'warning' => array(
463
      '#markup' => '<p>' .
464
      t('<strong>Warning:</strong> Opening delimited text files with spreadsheet applications may expose you to <a href="!link">formula injection</a> or other security vulnerabilities. When the submissions contain data from untrusted users and the downloaded file will be used with spreadsheets, use Microsoft Excel format.',
465
        array('!link' => url('https://www.google.com/search?q=spreadsheet+formula+injection'))) .
466
      '</p>',
467
    ),
468
    'delimiter' => array(
469
      '#type' => 'select',
470
      '#title' => t('Delimited text format'),
471
      '#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.'),
472
      '#default_value' => webform_variable_get('webform_csv_delimiter'),
473
      '#options' => array(
474
        ','  => t('Comma (,)'),
475
        '\t' => t('Tab (\t)'),
476
        ';'  => t('Semicolon (;)'),
477
        ':'  => t('Colon (:)'),
478
        '|'  => t('Pipe (|)'),
479
        '.'  => t('Period (.)'),
480
        ' '  => t('Space ( )'),
481
      ),
482
    ),
483
    '#states' => array(
484
      'visible' => array(
485
        ':input[name=format]' => array('value' => 'delimited'),
486
      ),
487
    ),
488
  );
489

    
490
  $form['header_keys'] = array(
491
    '#type' => 'radios',
492
    '#title' => t('Column header format'),
493
    '#options' => array(
494
      -1 => t('None'),
495
      0 => t('Label'),
496
      1 => t('Form Key'),
497
    ),
498
    '#default_value' => 0,
499
    '#description' => t('Choose whether to show the label or form key in each column header.'),
500
  );
501

    
502
  $form['select_options'] = array(
503
    '#type' => 'fieldset',
504
    '#title' => t('Select list options'),
505
    '#collapsible' => TRUE,
506
    '#collapsed' => TRUE,
507
  );
508

    
509
  $form['select_options']['select_keys'] = array(
510
    '#type' => 'radios',
511
    '#title' => t('Select keys'),
512
    '#options' => array(
513
      0 => t('Full, human-readable options (values)'),
514
      1 => t('Short, raw options (keys)'),
515
    ),
516
    '#default_value' => 0,
517
    '#description' => t('Choose which part of options should be displayed from key|value pairs.'),
518
  );
519

    
520
  $form['select_options']['select_format'] = array(
521
    '#type' => 'radios',
522
    '#title' => t('Select list format'),
523
    '#options' => array(
524
      'separate' => t('Separate'),
525
      'compact' => t('Compact'),
526
    ),
527
    '#default_value' => 'separate',
528
    '#attributes' => array('class' => array('webform-select-list-format')),
529
    '#theme' => 'webform_results_download_select_format',
530
  );
531

    
532
  $csv_components = array('info' => t('Submission information'));
533
  // Prepend information fields with "-" to indent.
534
  foreach (webform_results_download_submission_information($node) as $key => $title) {
535
    $csv_components[$key] = '-' . $title;
536
  }
537

    
538
  $csv_components += webform_component_list($node, 'csv', TRUE);
539

    
540
  $form['components'] = array(
541
    '#type' => 'select',
542
    '#title' => t('Included export components'),
543
    '#options' => $csv_components,
544
    '#default_value' => array_keys($csv_components),
545
    '#multiple' => TRUE,
546
    '#size' => 10,
547
    '#description' => t('The selected components will be included in the export.'),
548
    '#process' => array('webform_component_select'),
549
  );
550

    
551
  $form['range'] = array(
552
    '#type' => 'fieldset',
553
    '#title' => t('Download range options'),
554
    '#collapsible' => TRUE,
555
    '#collapsed' => TRUE,
556
    '#tree' => TRUE,
557
    '#theme' => 'webform_results_download_range',
558
    '#element_validate' => array('webform_results_download_range_validate'),
559
    '#after_build' => array('webform_results_download_range_after_build'),
560
  );
561

    
562
  $form['range']['range_type'] = array(
563
    '#type' => 'radios',
564
    '#options' => array(
565
      'all' => t('All submissions'),
566
      'new' => t('Only new submissions since your last download'),
567
      'latest' => t('Only the latest'),
568
      'range_serial' => t('All submissions starting from'),
569
      'range_date' => t('All submissions by date'),
570
    ),
571
    '#default_value' => 'all',
572
  );
573
  $form['range']['latest'] = array(
574
    '#type' => 'textfield',
575
    '#size' => 5,
576
    '#maxlength' => 8,
577
  );
578
  $form['range']['start'] = array(
579
    '#type' => 'textfield',
580
    '#size' => 5,
581
    '#maxlength' => 8,
582
  );
583
  $form['range']['end'] = array(
584
    '#type' => 'textfield',
585
    '#size' => 5,
586
    '#maxlength' => 8,
587
  );
588
  $date_attributes = array('placeholder' => format_date(REQUEST_TIME, 'custom', webform_date_format('short')));
589
  $form['range']['start_date'] = array(
590
    '#type' => 'textfield',
591
    '#size' => 20,
592
    '#attributes' => $date_attributes,
593
  );
594
  $form['range']['end_date'] = array(
595
    '#type' => 'textfield',
596
    '#size' => 20,
597
    '#attributes' => $date_attributes,
598
  );
599

    
600
  // If drafts are allowed, provide options to filter download based on draft
601
  // status.
602
  $form['range']['completion_type'] = array(
603
    '#type' => 'radios',
604
    '#title' => t('Included submissions'),
605
    '#default_value' => 'all',
606
    '#options' => array(
607
      'all' => t('Finished and draft submissions'),
608
      'finished' => t('Finished submissions only'),
609
      'draft' => t('Drafts only'),
610
    ),
611
    '#access' => ($node->webform['allow_draft'] || $node->webform['auto_save']),
612
  );
613

    
614
  // By default results are downloaded. User can override this value if
615
  // programmatically submitting this form.
616
  $form['download'] = array(
617
    '#type' => 'value',
618
    '#default_value' => TRUE,
619
  );
620

    
621
  $form['actions'] = array('#type' => 'actions');
622
  $form['actions']['submit'] = array(
623
    '#type' => 'submit',
624
    '#value' => t('Download'),
625
  );
626

    
627
  return $form;
628
}
629

    
630
/**
631
 * FormAPI element validate function for the range fieldset.
632
 */
633
function webform_results_download_range_validate($element, $form_state) {
634
  switch ($element['range_type']['#value']) {
635
    case 'latest':
636
      // Download latest x submissions.
637
      if ($element['latest']['#value'] == '') {
638
        form_error($element['latest'], t('Latest number of submissions field is required.'));
639
      }
640
      else {
641
        if (!is_numeric($element['latest']['#value'])) {
642
          form_error($element['latest'], t('Latest number of submissions must be numeric.'));
643
        }
644
        else {
645
          if ($element['latest']['#value'] <= 0) {
646
            form_error($element['latest'], t('Latest number of submissions must be greater than 0.'));
647
          }
648
        }
649
      }
650
      break;
651

    
652
    case 'range_serial':
653
      // Download Start-End range of submissions.
654
      // Start submission number.
655
      if ($element['start']['#value'] == '') {
656
        form_error($element['start'], t('Start submission number is required.'));
657
      }
658
      else {
659
        if (!is_numeric($element['start']['#value'])) {
660
          form_error($element['start'], t('Start submission number must be numeric.'));
661
        }
662
        else {
663
          if ($element['start']['#value'] <= 0) {
664
            form_error($element['start'], t('Start submission number must be greater than 0.'));
665
          }
666
        }
667
      }
668
      // End submission number.
669
      if ($element['end']['#value'] != '') {
670
        if (!is_numeric($element['end']['#value'])) {
671
          form_error($element['end'], t('End submission number must be numeric.'));
672
        }
673
        else {
674
          if ($element['end']['#value'] <= 0) {
675
            form_error($element['end'], t('End submission number must be greater than 0.'));
676
          }
677
          else {
678
            if ($element['end']['#value'] < $element['start']['#value']) {
679
              form_error($element['end'], t('End submission number must not be less than Start submission number.'));
680
            }
681
          }
682
        }
683
      }
684
      break;
685

    
686
    case 'range_date':
687
      // Download Start-end range of submissions.
688
      // Start submission time.
689
      $format = webform_date_format('short');
690
      $start_date = DateTime::createFromFormat($format, $element['start_date']['#value']);
691
      if ($element['start_date']['#value'] == '') {
692
        form_error($element['start_date'], t('Start date range is required.'));
693
      }
694
      elseif ($start_date === FALSE) {
695
        form_error($element['start_date'], t('Start date range is not in a valid format.'));
696
      }
697
      // End submission time.
698
      $end_date = DateTime::createFromFormat($format, $element['end_date']['#value']);
699
      if ($element['end_date']['#value'] != '') {
700
        if ($end_date === FALSE) {
701
          form_error($element['end_date'], t('End date range is not in a valid format.'));
702
        }
703
        elseif ($start_date !== FALSE && $start_date > $end_date) {
704
          form_error($element['end_date'], t('End date range must not be before the Start date.'));
705
        }
706
      }
707
      break;
708
  }
709

    
710
  // Check that the range will return something at all.
711
  $range_options = array(
712
    'range_type' => $element['range_type']['#value'],
713
    'start' => $element['start']['#value'],
714
    'end' => $element['end']['#value'],
715
    'latest' => $element['latest']['#value'],
716
    'start_date' => $element['start_date']['#value'],
717
    'end_date' => $element['end_date']['#value'],
718
    'completion_type' => $element['completion_type']['#value'],
719
    'batch_size' => 1,
720
    'batch_number' => 0,
721
  );
722
  if (!form_get_errors() && !webform_download_sids_count($form_state['values']['node']->nid, $range_options)) {
723
    form_error($element['range_type'], t('The specified range will not return any results.'));
724
  }
725

    
726
}
727

    
728
/**
729
 * FormAPI after build function for the download range fieldset.
730
 */
731
function webform_results_download_range_after_build($element, &$form_state) {
732
  $node = $form_state['values']['node'];
733

    
734
  // Build a list of counts of new and total submissions.
735
  $last_download = webform_download_last_download_info($node->nid);
736

    
737
  $element['#webform_download_info']['sid'] = $last_download ? $last_download['sid'] : 0;
738
  $element['#webform_download_info']['serial'] = $last_download ? $last_download['serial'] : NULL;
739
  $element['#webform_download_info']['requested'] = $last_download ? $last_download['requested'] : $node->created;
740
  $element['#webform_download_info']['total'] = webform_get_submission_count($node->nid, NULL, NULL);
741
  $element['#webform_download_info']['new'] = webform_download_sids_count($node->nid, array('range_type' => 'new'));
742

    
743
  return $element;
744
}
745

    
746
/**
747
 * Theme the output of the export range fieldset.
748
 */
749
function theme_webform_results_download_range($variables) {
750
  drupal_add_library('webform', 'admin');
751

    
752
  $element = $variables['element'];
753
  $download_info = $element['#webform_download_info'];
754

    
755
  // Set description for total of all submissions.
756
  $element['range_type']['all']['#theme_wrappers'] = array('webform_inline_radio');
757
  $element['range_type']['all']['#title'] .= ' (' . t('@count total', array('@count' => $download_info['total'])) . ')';
758

    
759
  // Set description for "New submissions since last download".
760
  $format = webform_date_format('short');
761
  $requested_date = format_date($download_info['requested'], 'custom', $format);
762
  $element['range_type']['new']['#theme_wrappers'] = array('webform_inline_radio');
763
  $element['range_type']['new']['#title'] .= ' (' . t('@count new since @date', array('@count' => $download_info['new'], '@date' => $requested_date)) . ')';
764

    
765
  // Disable option if there are no new submissions.
766
  if ($download_info['new'] == 0) {
767
    $element['range_type']['new']['#attributes']['disabled'] = 'disabled';
768
  }
769

    
770
  // Render latest x submissions option.
771
  $element['latest']['#attributes']['class'][] = 'webform-set-active';
772
  $element['latest']['#theme_wrappers'] = array();
773
  $element['range_type']['latest']['#theme_wrappers'] = array('webform_inline_radio');
774
  $element['range_type']['latest']['#title'] = t('Only the latest !number submissions', array('!number' => drupal_render($element['latest'])));
775

    
776
  // Render Start-End submissions option.
777
  $element['start']['#attributes']['class'][] = 'webform-set-active';
778
  $element['end']['#attributes']['class'][] = 'webform-set-active';
779
  $element['start']['#theme_wrappers'] = array();
780
  $element['end']['#theme_wrappers'] = array();
781
  $element['start_date']['#attributes']['class'] = array('webform-set-active');
782
  $element['end_date']['#attributes']['class'] = array('webform-set-active');
783
  $element['start_date']['#theme_wrappers'] = array();
784
  $element['end_date']['#theme_wrappers'] = array();
785
  $element['range_type']['range_serial']['#theme_wrappers'] = array('webform_inline_radio');
786
  $last_serial = $download_info['serial'] ? $download_info['serial'] : drupal_placeholder(t('none'));
787
  $element['range_type']['range_serial']['#title'] = t('Submissions by number from !start and optionally to: !end &nbsp; (Last downloaded: !serial)',
788
    array('!start' => drupal_render($element['start']), '!end' => drupal_render($element['end']), '!serial' => $last_serial));
789

    
790
  // Date range.
791
  $element['range_type']['range_date']['#theme_wrappers'] = array('webform_inline_radio');
792
  $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'])));
793

    
794
  return drupal_render_children($element);
795
}
796

    
797
/**
798
 * Theme the output of the select list format radio buttons.
799
 */
800
function theme_webform_results_download_select_format($variables) {
801
  drupal_add_library('webform', 'admin');
802

    
803
  $element = $variables['element'];
804
  $output = '';
805

    
806
  // Build an example table for the separate option.
807
  $header = array(t('Option A'), t('Option B'), t('Option C'));
808
  $rows = array(
809
    array('X', '', ''),
810
    array('X', '', 'X'),
811
    array('', 'X', 'X'),
812
  );
813

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

    
819
  // Build an example table for the compact option.
820
  $header = array(t('My select list'));
821
  $rows = array(
822
    array('Option A'),
823
    array('Option A,Option C'),
824
    array('Option B,Option C'),
825
  );
826

    
827
  $element['compact']['#attributes']['class'] = array();
828
  $element['compact']['#description'] = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE));
829
  $element['compact']['#description'] .= t('Compact options are more suitable for importing data into other systems.');
830
  $output .= drupal_render($element['compact']);
831

    
832
  return $output;
833
}
834

    
835
/**
836
 * Submit handler for webform_results_download_form().
837
 */
838
function webform_results_download_form_submit(&$form, &$form_state) {
839
  $node = $form_state['values']['node'];
840
  $format = $form_state['values']['format'];
841

    
842
  $options = array(
843
    'delimiter' => $form_state['values']['delimiter'],
844
    'components' => array_keys(array_filter($form_state['values']['components'])),
845
    'header_keys' => $form_state['values']['header_keys'],
846
    'select_keys' => $form_state['values']['select_keys'],
847
    'select_format' => $form_state['values']['select_format'],
848
    'range' => $form_state['values']['range'],
849
    'download' => $form_state['values']['download'],
850
  );
851

    
852
  $defaults = webform_results_download_default_options($node, $format);
853
  $options += $defaults;
854
  $options['range'] += $defaults['range'];
855

    
856
  // Determine an appropriate batch size based on the form and server specs.
857
  if (!isset($options['range']['batch_size'])) {
858
    $options['range']['batch_size'] = webform_export_batch_size($node);
859
  }
860

    
861
  $options['file_name'] = _webform_export_tempname();
862

    
863
  // Set up a batch to export the results.
864
  $batch = webform_results_export_batch($node, $format, $options);
865
  batch_set($batch);
866
}
867

    
868
/**
869
 * Calculate an appropriate batch size for bulk submission operations.
870
 *
871
 * @param object $node
872
 *   The webform node.
873
 *
874
 * @return int
875
 *   The number of submissions to be processed at once.
876
 */
877
function webform_export_batch_size($node) {
878
  // Start the batch size at 50,000 per batch, but divide by number of
879
  // components in the form. For example, if a form had 10 components, it would
880
  // export 5,000 submissions at a time.
881
  $batch_size = ceil(50000 / max(1, count($node->webform['components'])));
882

    
883
  // Every 32MB of additional memory after 64MB adds a multiplier in size.
884
  $memory_limit = parse_size(ini_get('memory_limit'));
885
  $mb = 1048576;
886
  $memory_modifier = max(1, ($memory_limit - (64 * $mb)) / (32 * $mb));
887
  $batch_size = ceil($batch_size * $memory_modifier);
888

    
889
  // For time reasons, limit the batch size to 5,000.
890
  $batch_size = min($batch_size, 5000);
891

    
892
  // Allow a non-UI configuration to override the batch size.
893
  $batch_size = variable_get('webform_export_batch_size', $batch_size);
894

    
895
  return $batch_size;
896
}
897

    
898
/**
899
 * Returns a temporary export filename.
900
 */
901
function _webform_export_tempname() {
902
  $webform_export_path = variable_get('webform_export_path', 'temporary://');
903

    
904
  // If the directory does not exist, create it.
905
  file_prepare_directory($webform_export_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
906
  return drupal_tempnam($webform_export_path, 'webform_');
907
}
908

    
909
/**
910
 * Generate a Excel-readable CSV file containing all submissions for a Webform.
911
 *
912
 * Note that this function is generally no longer utilized. Instead Batch API
913
 * should be used to generate a file over multiple requests.
914
 *
915
 * @see webform_results_export_batch()
916
 *
917
 * @deprecated This function is schedule to be removed in webform 7.x-5.x. Use
918
 * the batch opertions instead.
919
 *
920
 * @return array|null
921
 *   The array of export info or null if the file could not be opened.
922
 */
923
function webform_results_export($node, $format = 'delimited', $options = array()) {
924
  module_load_include('inc', 'webform', 'includes/webform.export');
925
  module_load_include('inc', 'webform', 'includes/webform.components');
926

    
927
  $defaults = webform_results_download_default_options($node, $format);
928
  $options += $defaults;
929
  $options['range'] += $defaults['range'];
930

    
931
  // Open a new Webform exporter object.
932
  $exporter = webform_export_create_handler($format, $options);
933

    
934
  $file_name = _webform_export_tempname();
935
  $handle = fopen($file_name, 'w');
936
  if (!$handle) {
937
    return;
938
  }
939

    
940
  // Add the beginning of file marker (little-endian usually for MS Excel).
941
  $exporter->bof($handle);
942

    
943
  // Add headers to the file.
944
  $row_count = 0;
945
  $col_count = 0;
946
  $headers = webform_results_download_headers($node, $options);
947
  foreach ($headers as $row) {
948
    // Output header if header_keys is non-negative. -1 means no headers.
949
    if ($options['header_keys'] >= 0) {
950
      $exporter->add_row($handle, $row, $row_count);
951
      $row_count++;
952
    }
953
    $col_count = count($row) > $col_count ? count($row) : $col_count;
954
  }
955

    
956
  // Write data from submissions. $last_is is non_NULL to trigger returning it
957
  // by reference.
958
  $last_sid = TRUE;
959
  $rows = webform_results_download_rows($node, $options, 0, $last_sid);
960
  foreach ($rows as $row) {
961
    $exporter->add_row($handle, $row, $row_count);
962
    $row_count++;
963
  }
964

    
965
  // Add the closing bytes.
966
  $exporter->eof($handle, $row_count, $col_count);
967

    
968
  // Close the file.
969
  @fclose($handle);
970

    
971
  $export_info['format'] = $format;
972
  $export_info['options'] = $options;
973
  $export_info['file_name'] = $file_name;
974
  $export_info['row_count'] = $row_count;
975
  $export_info['col_count'] = $col_count;
976
  $export_info['last_sid'] = $last_sid;
977
  $export_info['exporter'] = $exporter;
978

    
979
  return $export_info;
980
}
981

    
982
/**
983
 * Return a Batch API array of commands that will generate an export.
984
 *
985
 * @param $node
986
 *   The webform node on which to generate the analysis.
987
 * @param string $format
988
 *   (optional) Delimiter of the exported file.
989
 * @param array $options
990
 *   (optional) An associative array of options that define the output format.
991
 *   These are generally passed through from the GUI interface. Possible options
992
 *   include:
993
 *   - sids: An array of submission IDs to which this export may be filtered.
994
 *     May be used to generate exports that are per-user or other groups of
995
 *     submissions.
996
 *
997
 * @return array
998
 *   A Batch API array suitable to pass to batch_set().
999
 */
1000
function webform_results_export_batch($node, $format = 'delimited', array $options = array()) {
1001
  $defaults = webform_results_download_default_options($node, $format);
1002
  $options += $defaults;
1003
  $options['range'] += $defaults['range'];
1004

    
1005
  return array(
1006
    'operations' => array(
1007
      array('webform_results_batch_bof', array($node, $format, $options)),
1008
      array('webform_results_batch_headers', array($node, $format, $options)),
1009
      array('webform_results_batch_rows', array($node, $format, $options)),
1010
      array('webform_results_batch_eof', array($node, $format, $options)),
1011
      array('webform_results_batch_post_process', array($node, $format, $options)),
1012
      array('webform_results_batch_results', array($node, $format, $options)),
1013
    ),
1014
    'finished' => 'webform_results_batch_finished',
1015
    'title' => t('Exporting submissions'),
1016
    'init_message' => t('Creating export file'),
1017
    'error_message' => t('The export file could not be created because an error occurred.'),
1018
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
1019
  );
1020
}
1021

    
1022
/**
1023
 * Print the header rows for the downloadable webform data.
1024
 *
1025
 * @param $node
1026
 *   The webform node on which to generate the analysis.
1027
 * @param array $options
1028
 *   A list of options that define the output format. These are generally passed
1029
 *   through from the GUI interface.
1030
 */
1031
function webform_results_download_headers($node, array $options) {
1032
  module_load_include('inc', 'webform', 'includes/webform.components');
1033
  $submission_information = webform_results_download_submission_information($node, $options);
1034

    
1035
  // Fill in the header for the submission information (if any).
1036
  $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
1037
  if (count($submission_information)) {
1038
    $header[0][0] = $node->title;
1039

    
1040
    if ($options['header_keys']) {
1041
      $header[1][0] = t('submission_details');
1042
      $submission_information_headers = array_keys($submission_information);
1043
    }
1044
    else {
1045
      $header[1][0] = t('Submission Details');
1046
      $submission_information_headers = array_values($submission_information);
1047
    }
1048
    foreach ($submission_information_headers as $column => $label) {
1049
      $header[2][$column] = $label;
1050
    }
1051
  }
1052

    
1053
  // Compile header information for components.
1054
  foreach ($options['components'] as $cid) {
1055
    if (isset($node->webform['components'][$cid])) {
1056
      $component = $node->webform['components'][$cid];
1057

    
1058
      // Let each component determine its headers.
1059
      if (webform_component_feature($component['type'], 'csv')) {
1060
        $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
1061
        // Allow modules to modify the component CSV header.
1062
        drupal_alter('webform_csv_header', $component_header, $component);
1063

    
1064
        // Merge component CSV header to overall CSV header.
1065
        $header[0] = array_merge($header[0], (array) $component_header[0]);
1066
        $header[1] = array_merge($header[1], (array) $component_header[1]);
1067
        $header[2] = array_merge($header[2], (array) $component_header[2]);
1068
      }
1069
    }
1070
  }
1071

    
1072
  return $header;
1073
}
1074

    
1075
/**
1076
 * Returns rows of downloadable webform data.
1077
 *
1078
 * @param $node
1079
 *   The webform node on which to generate the analysis.
1080
 * @param array $options
1081
 *   A list of options that define the output format. These are generally passed
1082
 *   through from the GUI interface.
1083
 * @param int $serial_start
1084
 *   The starting position for the Serial column in the output.
1085
 * @param $last_sid
1086
 *   If set to a non-NULL value, the last sid will be returned.
1087
 *
1088
 * @return array
1089
 *   An array of rows built according to the provided $serial_start and
1090
 *   $pager_count variables. Note that the current page number is determined
1091
 *   by the super-global $_GET['page'] variable.
1092
 *
1093
 * @deprecated This function is scheduled to be removed in webform 7.x-5.x.
1094
 */
1095
function webform_results_download_rows($node, array $options, $serial_start = 0, &$last_sid = NULL) {
1096
  // Get all the required submissions for the download.
1097
  $filters['nid'] = $node->nid;
1098
  if (isset($options['sids'])) {
1099
    $filters['sid'] = $options['sids'];
1100
  }
1101
  elseif (!empty($options['completion_type']) && $options['completion_type'] !== 'all') {
1102
    $filters['is_draft'] = (int) ($options['completion_type'] === 'draft');
1103
  }
1104

    
1105
  $submissions = webform_get_submissions($filters, NULL);
1106

    
1107
  if (isset($last_sid)) {
1108
    $last_sid = end($submissions) ? key($submissions) : NULL;
1109
  }
1110

    
1111
  return webform_results_download_rows_process($node, $options, $serial_start, $submissions);
1112
}
1113

    
1114
/**
1115
 * Processes the submissions to be downloaded into exported rows.
1116
 *
1117
 * This is an internal routine and not intended for use by other modules.
1118
 *
1119
 * @param $node
1120
 *   The webform node on which to generate the analysis.
1121
 * @param array $options
1122
 *   A list of options that define the output format. These are generally passed
1123
 *   through from the GUI interface.
1124
 * @param $serial_start
1125
 *   The starting position for the Serial column in the output.
1126
 * @param array $submissions
1127
 *   An associative array of loaded submissions, indexed by sid.
1128
 *
1129
 * @return array
1130
 *   An array of rows built according to the provided $serial_start and
1131
 *   $pager_count variables. Note that the current page number is determined
1132
 *   by the super-global $_GET['page'] variable.
1133
 */
1134
function webform_results_download_rows_process($node, array $options, $serial_start, array $submissions) {
1135
  module_load_include('inc', 'webform', 'includes/webform.components');
1136

    
1137
  $submission_information = webform_results_download_submission_information($node, $options);
1138

    
1139
  // Generate a row for each submission.
1140
  $row_count = 0;
1141
  $rows = array();
1142
  foreach ($submissions as $sid => $submission) {
1143
    $row_count++;
1144

    
1145
    $row = array();
1146
    // Add submission information.
1147
    foreach (array_keys($submission_information) as $token) {
1148
      $cell = module_invoke_all('webform_results_download_submission_information_data', $token, $submission, $options, $serial_start, $row_count);
1149
      $context = array('token' => $token, 'submission' => $submission, 'options' => $options, 'serial_start' => $serial_start, 'row_count' => $row_count);
1150
      drupal_alter('webform_results_download_submission_information_data', $cell, $context);
1151
      // implode() to ensure everything from a single value goes into one
1152
      // column, even if more than one module responds to this item.
1153
      $row[] = implode(', ', $cell);
1154
    }
1155

    
1156
    foreach ($options['components'] as $cid) {
1157
      if (isset($node->webform['components'][$cid])) {
1158
        $component = $node->webform['components'][$cid];
1159
        // Let each component add its data.
1160
        $raw_data = isset($submission->data[$cid]) ? $submission->data[$cid] : NULL;
1161
        if (webform_component_feature($component['type'], 'csv')) {
1162
          $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);
1163

    
1164
          // Allow modules to modify the CSV data.
1165
          drupal_alter('webform_csv_data', $data, $component, $submission);
1166

    
1167
          if (is_array($data)) {
1168
            $row = array_merge($row, array_values($data));
1169
          }
1170
          else {
1171
            $row[] = isset($data) ? $data : '';
1172
          }
1173
        }
1174
      }
1175
    }
1176

    
1177
    $rows[$serial_start + $row_count] = $row;
1178
  }
1179

    
1180
  return $rows;
1181
}
1182

    
1183
/**
1184
 * Default columns for submission information.
1185
 *
1186
 * By default all exports have several columns of generic information that
1187
 * applies to all submissions. This function returns the list of generic columns
1188
 * plus columns added by other modules.
1189
 *
1190
 * @param $options
1191
 *   Filter down the list of columns based on a provided column list.
1192
 *
1193
 * @return array
1194
 *   List of generic columns plus columns added by other modules
1195
 */
1196
function webform_results_download_submission_information($node, $options = array()) {
1197
  $submission_information = module_invoke_all('webform_results_download_submission_information_info');
1198
  drupal_alter('webform_results_download_submission_information_info', $submission_information);
1199

    
1200
  if (isset($options['components'])) {
1201
    foreach ($submission_information as $key => $label) {
1202
      if (!in_array($key, $options['components'])) {
1203
        unset($submission_information[$key]);
1204
      }
1205
    }
1206
  }
1207

    
1208
  return $submission_information;
1209
}
1210

    
1211
/**
1212
 * Implements hook_webform_results_download_submission_information_info().
1213
 */
1214
function webform_webform_results_download_submission_information_info() {
1215
  return array(
1216
    'webform_serial' => t('Serial'),
1217
    'webform_sid' => t('SID'),
1218
    'webform_time' => t('Submitted Time'),
1219
    'webform_completed_time' => t('Completed Time'),
1220
    'webform_modified_time' => t('Modified Time'),
1221
    'webform_draft' => t('Draft'),
1222
    'webform_ip_address' => t('IP Address'),
1223
    'webform_uid' => t('UID'),
1224
    'webform_username' => t('Username'),
1225
  );
1226
}
1227

    
1228
/**
1229
 * Implements hook_webform_results_download_submission_information_data().
1230
 */
1231
function webform_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
1232
  switch ($token) {
1233
    case 'webform_serial':
1234
      return $submission->serial;
1235

    
1236
    case 'webform_sid':
1237
      return $submission->sid;
1238

    
1239
    case 'webform_time':
1240
      // Return timestamp in local time (not UTC).
1241
      if (!empty($options['iso8601_date'])) {
1242
        return format_date($submission->submitted, 'custom', 'Y-m-d\TH:i:s');
1243
      }
1244
      else {
1245
        return format_date($submission->submitted, 'short');
1246
      }
1247
    case 'webform_completed_time':
1248
      if (!$submission->completed) {
1249
        return '';
1250
      }
1251
      // Return timestamp in local time (not UTC).
1252
      elseif (!empty($options['iso8601_date'])) {
1253
        return format_date($submission->completed, 'custom', 'Y-m-d\TH:i:s');
1254
      }
1255
      else {
1256
        return format_date($submission->completed, 'short');
1257
      }
1258
    case 'webform_modified_time':
1259
      // Return timestamp in local time (not UTC).
1260
      if (!empty($options['iso8601_date'])) {
1261
        return format_date($submission->modified, 'custom', 'Y-m-d\TH:i:s');
1262
      }
1263
      else {
1264
        return format_date($submission->modified, 'short');
1265
      }
1266
    case 'webform_draft':
1267
      return $submission->is_draft;
1268

    
1269
    case 'webform_ip_address':
1270
      return $submission->remote_addr;
1271

    
1272
    case 'webform_uid':
1273
      return $submission->uid;
1274

    
1275
    case 'webform_username':
1276
      return $submission->name;
1277
  }
1278
}
1279

    
1280
/**
1281
 * Get options for creating downloadable versions of the webform data.
1282
 *
1283
 * @param $node
1284
 *   The webform node on which to generate the analysis.
1285
 * @param string $format
1286
 *   The export format being used.
1287
 *
1288
 * @return array
1289
 *   Option for creating downloadable version of the webform data.
1290
 */
1291
function webform_results_download_default_options($node, $format) {
1292
  $submission_information = webform_results_download_submission_information($node);
1293

    
1294
  $options = array(
1295
    'delimiter' => webform_variable_get('webform_csv_delimiter'),
1296
    'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
1297
    'header_keys' => 0,
1298
    'select_keys' => 0,
1299
    'select_format' => 'separate',
1300
    'range' => array(
1301
      'range_type' => 'all',
1302
      'completion_type' => 'all',
1303
    ),
1304
  );
1305

    
1306
  // Allow exporters to merge in additional options.
1307
  $exporter_information = webform_export_fetch_definition($format);
1308
  if (isset($exporter_information['options'])) {
1309
    $options = array_merge($options, $exporter_information['options']);
1310
  }
1311

    
1312
  return $options;
1313
}
1314

    
1315
/**
1316
 * Send a generated webform results file to the user's browser.
1317
 *
1318
 * @param $node
1319
 *   The webform node.
1320
 * @param $export_info
1321
 *   Export information array retrieved from webform_results_export().
1322
 */
1323
function webform_results_download($node, $export_info) {
1324
  // If the exporter provides a custom download method, use that.
1325
  if (method_exists($export_info['exporter'], 'download')) {
1326
    $export_info['exporter']->download($node, $export_info);
1327
  }
1328
  // Otherwise use the set_headers() method to set headers and then read in the
1329
  // file directly. Delete it when complete.
1330
  else {
1331
    $export_name = _webform_safe_name($node->title);
1332
    if (!strlen($export_name)) {
1333
      $export_name = t('Untitled');
1334
    }
1335
    $export_info['exporter']->set_headers($export_name);
1336
    ob_clean();
1337
    // The @ makes it silent.
1338
    @readfile($export_info['file_name']);
1339
    // Clean up, the @ makes it silent.
1340
    @unlink($export_info['file_name']);
1341
  }
1342

    
1343
  // Save the last exported sid for new-only exports.
1344
  webform_results_export_success($node, $export_info);
1345

    
1346
  exit();
1347
}
1348

    
1349
/**
1350
 * Save the last-exported sid for new-only exports.
1351
 *
1352
 * @param $node
1353
 *   The webform node.
1354
 * @param $export_info
1355
 *   Export information array retrieved from webform_results_export().
1356
 */
1357
function webform_results_export_success($node, $export_info) {
1358
  if (!in_array($export_info['options']['range']['range_type'], array('range', 'range_serial', 'range_date')) && !empty($export_info['last_sid'])) {
1359
    // Insert a new record or update an existing record.
1360
    db_merge('webform_last_download')
1361
      ->key(array(
1362
        'nid' => $node->nid,
1363
        'uid' => $GLOBALS['user']->uid,
1364
      ))
1365
      ->fields(array(
1366
        'sid' => $export_info['last_sid'],
1367
        'requested' => REQUEST_TIME,
1368
      ))
1369
      ->execute();
1370
  }
1371
}
1372

    
1373
/**
1374
 * Menu callback; Download an exported file.
1375
 *
1376
 * This callabck requires that an export file be already generated by a batch
1377
 * process. The $_SESSION settings are usually put in place by the
1378
 * webform_results_export_results() function.
1379
 *
1380
 * @param $node
1381
 *   The webform $node whose export file is being downloaded.
1382
 *
1383
 * @return null|string
1384
 *   Either an export file is downloaded with the appropriate HTTP headers set,
1385
 *   or an error page is shown if now export is available to download.
1386
 */
1387
function webform_results_download_callback($node) {
1388
  if (isset($_SESSION['webform_export_info'])) {
1389
    module_load_include('inc', 'webform', 'includes/webform.export');
1390

    
1391
    $export_info = $_SESSION['webform_export_info'];
1392
    $export_info['exporter'] = webform_export_create_handler($export_info['format'], $export_info['options']);
1393

    
1394
    unset($_SESSION['webform_export_info']);
1395
    if (isset($_COOKIE['webform_export_info'])) {
1396
      unset($_COOKIE['webform_export_info']);
1397
      $params = session_get_cookie_params();
1398
      setcookie('webform_export_info', '', -1, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1399
    }
1400

    
1401
    webform_results_download($node, $export_info);
1402
  }
1403
  else {
1404
    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')));
1405
  }
1406
}
1407

    
1408
/**
1409
 * Batch API callback; Write the opening byte in the export file.
1410
 */
1411
function webform_results_batch_bof($node, $format = 'delimited', $options = array(), &$context = NULL) {
1412
  module_load_include('inc', 'webform', 'includes/webform.export');
1413

    
1414
  $exporter = webform_export_create_handler($format, $options);
1415
  $handle = fopen($options['file_name'], 'w');
1416
  if (!$handle) {
1417
    return;
1418
  }
1419
  $exporter->bof($handle);
1420
  @fclose($handle);
1421
}
1422

    
1423
/**
1424
 * Batch API callback; Write the headers of the export to the export file.
1425
 */
1426
function webform_results_batch_headers($node, $format = 'delimited', $options = array(), &$context = NULL) {
1427
  module_load_include('inc', 'webform', 'includes/webform.export');
1428

    
1429
  $exporter = webform_export_create_handler($format, $options);
1430
  $handle = fopen($options['file_name'], 'a');
1431
  if (!$handle) {
1432
    return;
1433
  }
1434
  $headers = webform_results_download_headers($node, $options);
1435
  $row_count = 0;
1436
  $col_count = 0;
1437
  foreach ($headers as $row) {
1438
    // Output header if header_keys is non-negative. -1 means no headers.
1439
    if ($options['header_keys'] >= 0) {
1440
      $exporter->add_row($handle, $row, $row_count);
1441
      $row_count++;
1442
    }
1443
    $col_count = count($row) > $col_count ? count($row) : $col_count;
1444
  }
1445
  $context['results']['row_count'] = $row_count;
1446
  $context['results']['col_count'] = $col_count;
1447
  @fclose($handle);
1448
}
1449

    
1450
/**
1451
 * Batch API callback; Write the rows of the export to the export file.
1452
 */
1453
function webform_results_batch_rows($node, $format = 'delimited', $options = array(), &$context = NULL) {
1454
  module_load_include('inc', 'webform', 'includes/webform.export');
1455

    
1456
  // Initialize the sandbox if this is the first execution of the batch
1457
  // operation.
1458
  if (!isset($context['sandbox']['batch_number'])) {
1459
    $context['sandbox']['batch_number'] = 0;
1460
    $context['sandbox']['sid_count'] = webform_download_sids_count($node->nid, $options['range']);
1461
    $context['sandbox']['batch_max'] = max(1, ceil($context['sandbox']['sid_count'] / $options['range']['batch_size']));
1462
    $context['sandbox']['serial'] = 0;
1463
    $context['sandbox']['last_sid'] = 0;
1464
  }
1465

    
1466
  // Retrieve the submissions for this batch process.
1467
  $options['range']['batch_number'] = $context['sandbox']['batch_number'];
1468

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

    
1471
  // Join to the users table to include user name in results, as required by
1472
  // webform_results_download_rows_process.
1473
  $query->leftJoin('users', 'u', 'u.uid = ws.uid');
1474
  $query->fields('u', array('name'));
1475
  $query->fields('ws');
1476

    
1477
  if (!empty($options['sids'])) {
1478
    $query->condition('ws.sid', $options['sids'], 'IN');
1479
  }
1480

    
1481
  $submissions = webform_get_submissions_load($query);
1482

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

    
1485
  // Write these submissions to the file.
1486
  $exporter = webform_export_create_handler($format, $options);
1487
  $handle = fopen($options['file_name'], 'a');
1488
  if (!$handle) {
1489
    return;
1490
  }
1491
  foreach ($rows as $row) {
1492
    $exporter->add_row($handle, $row, $context['results']['row_count']);
1493
    $context['results']['row_count']++;
1494
  }
1495

    
1496
  $context['sandbox']['serial'] += count($submissions);
1497
  $context['sandbox']['last_sid'] = end($submissions) ? key($submissions) : NULL;
1498
  $context['sandbox']['batch_number']++;
1499

    
1500
  @fclose($handle);
1501

    
1502
  // Display status message.
1503
  $context['message'] = t('Exported @count of @total submissions...', array('@count' => $context['sandbox']['serial'], '@total' => $context['sandbox']['sid_count']));
1504
  $context['finished'] = $context['sandbox']['batch_number'] < $context['sandbox']['batch_max']
1505
                            ? $context['sandbox']['batch_number'] / $context['sandbox']['batch_max']
1506
                            : 1.0;
1507
  $context['results']['last_sid'] = $context['sandbox']['last_sid'];
1508
}
1509

    
1510
/**
1511
 * Batch API callback; Write the closing bytes in the export file.
1512
 */
1513
function webform_results_batch_eof($node, $format = 'delimited', $options = array(), &$context = NULL) {
1514
  module_load_include('inc', 'webform', 'includes/webform.export');
1515

    
1516
  $exporter = webform_export_create_handler($format, $options);
1517

    
1518
  // We open the file for reading and writing, rather than just appending for
1519
  // exporters that need to adjust the beginning of the files as well as the
1520
  // end, i.e. webform_exporter_excel_xlsx::eof().
1521
  $handle = fopen($options['file_name'], 'r+');
1522
  if (!$handle) {
1523
    return;
1524
  }
1525
  // Move pointer to the end of the file.
1526
  fseek($handle, 0, SEEK_END);
1527
  $exporter->eof($handle, $context['results']['row_count'], $context['results']['col_count']);
1528
  @fclose($handle);
1529
}
1530

    
1531
/**
1532
 * Batch API callback; Do any last processing on the finished export.
1533
 */
1534
function webform_results_batch_post_process($node, $format = 'delimited', $options = array(), &$context = NULL) {
1535
  module_load_include('inc', 'webform', 'includes/webform.export');
1536

    
1537
  $context['results']['node'] = $node;
1538
  $context['results']['file_name'] = $options['file_name'];
1539

    
1540
  $exporter = webform_export_create_handler($format, $options);
1541
  $exporter->post_process($context['results']);
1542
}
1543

    
1544
/**
1545
 * Batch API callback; Set the $_SESSION variables used to download the file.
1546
 *
1547
 * Because we want the user to be returned to the main form first, we have to
1548
 * temporarily store information about the created file, send the user to the
1549
 * form, then use JavaScript to request node/x/webform-results/download-file,
1550
 * which will execute webform_results_download_file().
1551
 */
1552
function webform_results_batch_results($node, $format, $options, &$context) {
1553

    
1554
  $export_info = array(
1555
    'format' => $format,
1556
    'options' => $options,
1557
    'file_name' => $context['results']['file_name'],
1558
    'row_count' => $context['results']['row_count'],
1559
    'last_sid' => $context['results']['last_sid'],
1560
  );
1561

    
1562
  if (isset($_SESSION)) {
1563
    // UI exection. Defer resetting last-downloaded sid until download page. Set
1564
    // a session variable containing the information referencing the exported
1565
    // file. A cookie is also set to allow the browser to ensure the redirect to
1566
    // the file only happens one time.
1567
    $_SESSION['webform_export_info'] = $export_info;
1568
    $params = session_get_cookie_params();
1569
    setcookie('webform_export_info', '1', REQUEST_TIME + 120, $params['path'], $params['domain'], $params['secure'], FALSE);
1570
  }
1571
  else {
1572
    // Drush execution of wfx command. Reset last-downloaded sid now. $_SESSION
1573
    // is not supported for command line execution.
1574
    webform_results_export_success($node, $export_info);
1575
  }
1576
}
1577

    
1578
/**
1579
 * Batch API completion callback; Display completion message and cleanup.
1580
 */
1581
function webform_results_batch_finished($success, $results, $operations) {
1582
  if ($success) {
1583
    $download_url = url('node/' . $results['node']->nid . '/webform-results/download-file');
1584
    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)));
1585
  }
1586
  else {
1587
    drupal_set_message(t('An error occurred while generating the export file.'));
1588
    if (isset($results['file_name']) && is_file($results['file_name'])) {
1589
      @unlink($results['file_name']);
1590
    }
1591
  }
1592
}
1593

    
1594
/**
1595
 * Provides a simple analysis of all submissions to a webform.
1596
 *
1597
 * @param $node
1598
 *   The webform node on which to generate the analysis.
1599
 * @param $sids
1600
 *   An array of submission IDs to which this analysis may be filtered. May be
1601
 *   used to generate results that are per-user or other groups of submissions.
1602
 * @param $analysis_component
1603
 *   A webform component. If passed in, additional information may be returned
1604
 *   relating specifically to that component's analysis, such as a list of
1605
 *   "Other" values within a select list.
1606
 *
1607
 * @return array
1608
 *   Renderable array: A simple analysis of all submissions to a webform.
1609
 */
1610
function webform_results_analysis($node, $sids = array(), $analysis_component = NULL) {
1611
  if (!is_array($sids)) {
1612
    $sids = array();
1613
  }
1614

    
1615
  // Build a renderable for the content of this page.
1616
  $analysis = array(
1617
    '#theme' => array('webform_analysis__' . $node->nid, 'webform_analysis'),
1618
    '#node' => $node,
1619
    '#component' => $analysis_component,
1620
  );
1621

    
1622
  // See if a query (possibly with exposed filter) needs to restrict the
1623
  // submissions that are being analyzed.
1624
  $query = NULL;
1625
  if (empty($sids)) {
1626
    $view = webform_get_view($node, 'webform_analysis');
1627
    if ($view->type != t('Default') || $view->name != 'webform_analysis') {
1628
      // The view has been customized from the no-op built-in view. Use it.
1629
      $view->set_display();
1630
      $view->init_handlers();
1631
      $view->override_url = $_GET['q'];
1632
      $view->preview = TRUE;
1633
      $view->pre_execute(array($node->nid));
1634
      $view->build();
1635
      // Let modules modify the view just prior to executing it.
1636
      foreach (module_implements('views_pre_execute') as $module) {
1637
        $function = $module . '_views_pre_execute';
1638
        $function($view);
1639
      }
1640
      // If the view is already executed, there was an error in generating it.
1641
      $query = $view->executed ? NULL : $view->query->query();
1642
      $view->post_execute();
1643

    
1644
      if (isset($view->exposed_widgets)) {
1645
        $analysis['exposed_filter']['#markup'] = $view->exposed_widgets;
1646
      }
1647
    }
1648
  }
1649

    
1650
  // If showing all components, display selection form.
1651
  if (!$analysis_component) {
1652
    $analysis['form'] = drupal_get_form('webform_analysis_components_form', $node);
1653
  }
1654

    
1655
  // Add all the components to the analysis renderable array.
1656
  $components = isset($analysis_component) ? array($analysis_component['cid']) : webform_analysis_enabled_components($node);
1657
  foreach ($components as $cid) {
1658
    // Do component specific call.
1659
    $component = $node->webform['components'][$cid];
1660
    if ($data = webform_component_invoke($component['type'], 'analysis', $component, $sids, isset($analysis_component), $query)) {
1661
      drupal_alter('webform_analysis_component_data', $data, $node, $component);
1662
      $analysis['data'][$cid] = array(
1663
        '#theme' => array('webform_analysis_component__' . $node->nid . '__' . $cid, 'webform_analysis_component__' . $node->nid, 'webform_analysis_component'),
1664
        '#node' => $node,
1665
        '#component' => $component,
1666
        '#data' => $data,
1667
      );
1668
      $analysis['data'][$cid]['basic'] = array(
1669
        '#theme' => array('webform_analysis_component_basic__' . $node->nid . '__' . $cid, 'webform_analysis_component_basic__' . $node->nid, 'webform_analysis_component_basic'),
1670
        '#component' => $component,
1671
        '#data' => $data,
1672
      );
1673
    }
1674
  }
1675

    
1676
  drupal_alter('webform_analysis', $analysis);
1677
  return $analysis;
1678
}
1679

    
1680
/**
1681
 * Prerender function for webform-analysis.tpl.php.
1682
 */
1683
function template_preprocess_webform_analysis(&$variables) {
1684
  $analysis = $variables['analysis'];
1685
  $variables['node'] = $analysis['#node'];
1686
  $variables['component'] = $analysis['#component'];
1687
}
1688

    
1689
/**
1690
 * Prerender function for webform-analysis-component.tpl.php.
1691
 */
1692
function template_preprocess_webform_analysis_component(&$variables) {
1693
  $component_analysis = $variables['component_analysis'];
1694
  $variables['node'] = $component_analysis['#node'];
1695
  $variables['component'] = $component_analysis['#component'];
1696

    
1697
  // Ensure defaults.
1698
  $variables['component_analysis']['#data'] += array(
1699
    'table_header' => NULL,
1700
    'table_rows' => array(),
1701
    'other_data' => array(),
1702
  );
1703
  $variables['classes_array'][] = 'webform-analysis-component-' . $variables['component']['type'];
1704
  $variables['classes_array'][] = 'webform-analysis-component--' . str_replace('_', '-', implode('--', webform_component_parent_keys($variables['node'], $variables['component'])));
1705
}
1706

    
1707
/**
1708
 * Render an individual component's analysis data in a table.
1709
 *
1710
 * @param $variables
1711
 *   An array of theming variables for this theme function. Included keys:
1712
 *   - $component: The component whose analysis is being rendered.
1713
 *   - $data: An array of array containing the analysis data. Contains the keys:
1714
 *     - table_header: If this table has more than a single column, an array
1715
 *       of header labels.
1716
 *     - table_rows: If this component has a table that should be rendered, an
1717
 *       array of values
1718
 *
1719
 * @return string
1720
 *   The rendered table.
1721
 */
1722
function theme_webform_analysis_component_basic($variables) {
1723
  $data = $variables['data'];
1724

    
1725
  // Ensure defaults.
1726
  $data += array(
1727
    'table_header' => NULL,
1728
    'table_rows' => array(),
1729
    'other_data' => array(),
1730
  );
1731

    
1732
  // Combine the "other data" into the table rows by default.
1733
  if (is_array($data['other_data'])) {
1734
    foreach ($data['other_data'] as $other_data) {
1735
      if (is_array($other_data)) {
1736
        $data['table_rows'][] = $other_data;
1737
      }
1738
      else {
1739
        $data['table_rows'][] = array(
1740
          array(
1741
            'colspan' => 2,
1742
            'data' => $other_data,
1743
          ),
1744
        );
1745
      }
1746
    }
1747
  }
1748
  elseif (strlen($data['other_data'])) {
1749
    $data['table_rows'][] = array(
1750
      'colspan' => 2,
1751
      'data' => $data['other_data'],
1752
    );
1753
  }
1754

    
1755
  return theme('table', array(
1756
    'header' => $data['table_header'],
1757
    'rows' => $data['table_rows'],
1758
    'sticky' => FALSE,
1759
    'attributes' => array('class' => array('webform-analysis-table')),
1760
  ));
1761
}
1762

    
1763
/**
1764
 * Return a list of components that should be displayed for analysis.
1765
 *
1766
 * @param $node
1767
 *   The node whose components' data is being analyzed.
1768
 *
1769
 * @return array
1770
 *   An array of component IDs.
1771
 */
1772
function webform_analysis_enabled_components($node) {
1773
  $cids = array();
1774
  foreach ($node->webform['components'] as $cid => $component) {
1775
    if (!empty($component['extra']['analysis'])) {
1776
      $cids[] = $cid;
1777
    }
1778
  }
1779
  return $cids;
1780
}
1781

    
1782
/**
1783
 * Form for selecting which components should be shown on the analysis page.
1784
 */
1785
function webform_analysis_components_form($form, &$form_state, $node) {
1786
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1787
  $form['#node'] = $node;
1788

    
1789
  $component_list = webform_component_list($node, 'analysis', TRUE);
1790
  $enabled_components = webform_analysis_enabled_components($node);
1791
  if (empty($component_list)) {
1792
    $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')));
1793
  }
1794
  elseif (empty($enabled_components)) {
1795
    $help = t('No components have analysis enabled in this form. Enable analysis under the "Add analysis components" fieldset.');
1796
  }
1797
  else {
1798
    $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.');
1799
  }
1800

    
1801
  $form['help'] = array(
1802
    '#markup' => '<p>' . $help . '</p>',
1803
    '#access' => !empty($help),
1804
    '#weight' => -100,
1805
  );
1806

    
1807
  $form['components'] = array(
1808
    '#type' => 'select',
1809
    '#title' => t('Add analysis components'),
1810
    '#options' => $component_list,
1811
    '#default_value' => $enabled_components,
1812
    '#multiple' => TRUE,
1813
    '#size' => 10,
1814
    '#description' => t('The selected components will be included on the analysis page.'),
1815
    '#process' => array('webform_component_select'),
1816
    '#access' => count($component_list),
1817
  );
1818

    
1819
  $form['actions'] = array(
1820
    '#type' => 'actions',
1821
    '#access' => count($component_list),
1822
  );
1823
  $form['actions']['submit'] = array(
1824
    '#type' => 'submit',
1825
    '#value' => t('Update analysis display'),
1826
  );
1827

    
1828
  return $form;
1829
}
1830

    
1831
/**
1832
 * Submit handler for webform_analysis_components_form().
1833
 */
1834
function webform_analysis_components_form_submit($form, $form_state) {
1835
  $node = $form['#node'];
1836
  foreach ($form_state['values']['components'] as $cid => $enabled) {
1837
    $node->webform['components'][$cid]['extra']['analysis'] = (bool) $enabled;
1838
  }
1839
  node_save($node);
1840
}
1841

    
1842
/**
1843
 * Output the content of the Analysis page.
1844
 *
1845
 * @see webform_results_analysis()
1846
 */
1847
function theme_webform_results_analysis($variables) {
1848
  $node = $variables['node'];
1849
  $data = $variables['data'];
1850
  $analysis_component = $variables['component'];
1851

    
1852
  $rows = array();
1853
  $question_number = 0;
1854
  $single = isset($analysis_component);
1855

    
1856
  $header = array(
1857
    $single ? $analysis_component['name'] : t('Q'),
1858
    array('data' => $single ? '&nbsp;' : t('responses'), 'colspan' => '10'),
1859
  );
1860

    
1861
  foreach ($data as $cid => $row_data) {
1862
    $question_number++;
1863

    
1864
    if (is_array($row_data)) {
1865
      $row = array();
1866
      if (!$single) {
1867
        $row['data'][] = array('data' => '<strong>' . $question_number . '</strong>', 'rowspan' => count($row_data) + 1, 'valign' => 'top');
1868
        $row['data'][] = array('data' => '<strong>' . check_plain($node->webform['components'][$cid]['name']) . '</strong>', 'colspan' => '10');
1869
        $row['class'][] = 'webform-results-question';
1870
      }
1871
      $rows = array_merge($rows, array_merge(array($row), $row_data));
1872
    }
1873
  }
1874

    
1875
  if (count($rows) == 0) {
1876
    $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));
1877
  }
1878

    
1879
  return theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('class' => array('webform-results-analysis'))));
1880
}
1881

    
1882
/**
1883
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1884
 *
1885
 * @deprecated This function is scheduled to be removed int webform 7.x-5.x.
1886
 * Use webform_download_sids_query() instead.
1887
 */
1888
function webform_download_sids($nid, $range_options, $uid = NULL) {
1889
  return webform_download_sids_query($nid, $range_options, $uid)
1890
    ->fields('ws', array('sid'))
1891
    ->execute()
1892
    ->fetchCol();
1893
}
1894

    
1895
/**
1896
 * Retrieves a count the number of matching submissions.
1897
 */
1898
function webform_download_sids_count($nid, $range_options, $uid = NULL) {
1899
  return webform_download_sids_query($nid, $range_options, $uid)
1900
    ->countQuery()
1901
    ->execute()
1902
    ->fetchField();
1903
}
1904

    
1905
/**
1906
 * Given a set of range options, return an unexecuted select query.
1907
 *
1908
 * The query will have no fields as they should be added by the caller as
1909
 * desired.
1910
 *
1911
 * @param int $nid
1912
 *   The node id of the webform.
1913
 * @param array $range_options
1914
 *   Associate array of range options.
1915
 * @param int $uid
1916
 *   The user id of the user whose last download information should be used,
1917
 *   or the current user if NULL. This is unrelated to which user submitted
1918
 *   the submissions.
1919
 *
1920
 * @return QueryAlterableInterface
1921
 *   The query object.
1922
 */
1923
function webform_download_sids_query($nid, array $range_options, $uid = NULL) {
1924
  $query = db_select('webform_submissions', 'ws')
1925
    ->condition('nid', $nid)
1926
    ->addTag('webform_download_sids');
1927

    
1928
  switch ($range_options['range_type']) {
1929
    case 'all':
1930
      // All Submissions.
1931
      $query->orderBy('ws.sid', 'ASC');
1932
      break;
1933

    
1934
    case 'new':
1935
      // All Since Last Download.
1936
      $download_info = webform_download_last_download_info($nid, $uid);
1937
      $last_sid = $download_info ? $download_info['sid'] : 0;
1938
      $query
1939
        ->condition('ws.sid', $last_sid, '>')
1940
        ->orderBy('ws.sid', 'ASC');
1941
      break;
1942

    
1943
    case 'latest':
1944
      // Last x Submissions.
1945
      $start_sid = webform_download_latest_start_sid($nid, $range_options['latest'], $range_options['completion_type']);
1946
      $query->condition('ws.sid', $start_sid, '>=');
1947
      break;
1948

    
1949
    case 'range':
1950
      // Submissions Start-End.
1951
      $query->condition('ws.sid', $range_options['start'], '>=');
1952
      if ($range_options['end']) {
1953
        $query->condition('ws.sid', $range_options['end'], '<=');
1954
      }
1955
      $query->orderBy('ws.sid', 'ASC');
1956
      break;
1957

    
1958
    case 'range_serial':
1959
      // Submissions Start-End, using serial numbers.
1960
      $query->condition('ws.serial', $range_options['start'], '>=');
1961
      if ($range_options['end']) {
1962
        $query->condition('ws.serial', $range_options['end'], '<=');
1963
      }
1964
      $query->orderBy('ws.serial', 'ASC');
1965
      break;
1966

    
1967
    case 'range_date':
1968
      $date_field = $range_options['completion_type'] == 'finished' ? 'ws.completed' : 'ws.submitted';
1969
      $format = webform_date_format('short');
1970
      $start_date = DateTime::createFromFormat($format, $range_options['start_date']);
1971
      $start_date->setTime(0, 0, 0);
1972
      $query->condition($date_field, $start_date->getTimestamp(), '>=');
1973
      $end_time = DateTime::createFromFormat($format, $range_options['end_date']);
1974
      if ($range_options['end_date'] != '' && ($end_time !== FALSE)) {
1975
        // Check for the full day's submissions.
1976
        $end_time->setTime(23, 59, 59);
1977
        $query->condition($date_field, $end_time->getTimestamp(), '<=');
1978
      }
1979
      $query->orderBy($date_field, 'ASC');
1980
      break;
1981
  }
1982

    
1983
  // Filter down to draft or finished submissions.
1984
  if (!empty($range_options['completion_type']) && $range_options['completion_type'] !== 'all') {
1985
    $query->condition('is_draft', (int) ($range_options['completion_type'] === 'draft'));
1986
  }
1987

    
1988
  if (isset($range_options['batch_number']) && !empty($range_options['batch_size'])) {
1989
    $query->range($range_options['batch_number'] * $range_options['batch_size'], $range_options['batch_size']);
1990
  }
1991
  return $query;
1992
}
1993

    
1994
/**
1995
 * Get this user's last download information, including the SID and timestamp.
1996
 *
1997
 * This function provides an array of information about the last download that
1998
 * a user had for a particular Webform node. Currently it only returns an array
1999
 * with two keys:
2000
 *  - sid: The last submission ID that was downloaded.
2001
 *  - requested: The timestamp of the last download request.
2002
 *
2003
 * @param $nid
2004
 *   The Webform NID.
2005
 * @param $uid
2006
 *   The user account ID for which to retrieve download information.
2007
 *
2008
 * @return array|false
2009
 *   An array of download information or FALSE if this user has never downloaded
2010
 *   results for this particular node.
2011
 */
2012
function webform_download_last_download_info($nid, $uid = NULL) {
2013
  $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
2014

    
2015
  $query = db_select('webform_last_download', 'wld');
2016
  $query->leftJoin('webform_submissions', 'wfs', 'wld.sid = wfs.sid');
2017
  $info = $query
2018
    ->fields('wld')
2019
    ->fields('wfs', array('serial'))
2020
    ->condition('wld.nid', $nid)
2021
    ->condition('wld.uid', $uid)
2022
    ->execute()
2023
    ->fetchAssoc();
2024

    
2025
  return $info;
2026
}
2027

    
2028
/**
2029
 * Get an SID based a requested latest count.
2030
 *
2031
 * @param int $nid
2032
 *   The webform NID.
2033
 * @param int $latest_count
2034
 *   The latest count on which the SID will be retrieved.
2035
 * @param string $completion_type
2036
 *   The completion type, either "finished", "draft", or "all".
2037
 *
2038
 * @return int
2039
 *   The submission ID that starts the latest sequence of submissions.
2040
 */
2041
function webform_download_latest_start_sid($nid, $latest_count, $completion_type = 'all') {
2042
  // @todo: Find a more efficient DBTNG query to retrieve this number.
2043
  $query = db_select('webform_submissions', 'ws')
2044
    ->fields('ws', array('sid'))
2045
    ->condition('nid', $nid)
2046
    ->orderBy('ws.sid', 'DESC')
2047
    ->range(0, $latest_count)
2048
    ->addTag('webform_download_latest_start_sid');
2049

    
2050
  if ($completion_type !== 'all') {
2051
    $query->condition('is_draft', (int) ($completion_type === 'draft'));
2052
  }
2053

    
2054
  $latest_sids = $query->execute()->fetchCol();
2055
  return $latest_sids ? min($latest_sids) : 1;
2056
}