Projet

Général

Profil

Paste
Télécharger (72,5 ko) Statistiques
| Branche: | Révision:

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

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
 * @deprecated in webform:7.x-4.8 and is removed from webform:7.x-5.0. Use
913
 * webform_results_export_batch().
914
 * @see https://www.drupal.org/project/webform/issues/2465291
915
 *
916
 * @return array|null
917
 *   The array of export info or null if the file could not be opened.
918
 */
919
function webform_results_export($node, $format = 'delimited', $options = array()) {
920
  module_load_include('inc', 'webform', 'includes/webform.export');
921
  module_load_include('inc', 'webform', 'includes/webform.components');
922

    
923
  $defaults = webform_results_download_default_options($node, $format);
924
  $options += $defaults;
925
  $options['range'] += $defaults['range'];
926

    
927
  // Open a new Webform exporter object.
928
  $exporter = webform_export_create_handler($format, $options);
929

    
930
  $file_name = _webform_export_tempname();
931
  $handle = fopen($file_name, 'w');
932
  if (!$handle) {
933
    return;
934
  }
935

    
936
  // Add the beginning of file marker (little-endian usually for MS Excel).
937
  $exporter->bof($handle);
938

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

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

    
961
  // Add the closing bytes.
962
  $exporter->eof($handle, $row_count, $col_count);
963

    
964
  // Close the file.
965
  @fclose($handle);
966

    
967
  $export_info['format'] = $format;
968
  $export_info['options'] = $options;
969
  $export_info['file_name'] = $file_name;
970
  $export_info['row_count'] = $row_count;
971
  $export_info['col_count'] = $col_count;
972
  $export_info['last_sid'] = $last_sid;
973
  $export_info['exporter'] = $exporter;
974

    
975
  return $export_info;
976
}
977

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

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

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

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

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

    
1049
  // Compile header information for components.
1050
  foreach ($options['components'] as $cid) {
1051
    if (isset($node->webform['components'][$cid])) {
1052
      $component = $node->webform['components'][$cid];
1053

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

    
1060
        // Merge component CSV header to overall CSV header.
1061
        $header[0] = array_merge($header[0], (array) $component_header[0]);
1062
        $header[1] = array_merge($header[1], (array) $component_header[1]);
1063
        $header[2] = array_merge($header[2], (array) $component_header[2]);
1064
      }
1065
    }
1066
  }
1067

    
1068
  return $header;
1069
}
1070

    
1071
/**
1072
 * Returns rows of downloadable webform data.
1073
 *
1074
 * @deprecated in webform:7.x-4.8 and is removed from webform:7.x-5.0. See
1075
 * webform_results_download_rows_process().
1076
 * @see https://www.drupal.org/project/webform/issues/2465291
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
function webform_results_download_rows($node, array $options, $serial_start = 0, &$last_sid = NULL) {
1094
  // Get all the required submissions for the download.
1095
  $filters['nid'] = $node->nid;
1096
  if (isset($options['sids'])) {
1097
    $filters['sid'] = $options['sids'];
1098
  }
1099
  elseif (!empty($options['completion_type']) && $options['completion_type'] !== 'all') {
1100
    $filters['is_draft'] = (int) ($options['completion_type'] === 'draft');
1101
  }
1102

    
1103
  $submissions = webform_get_submissions($filters, NULL);
1104

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

    
1109
  return webform_results_download_rows_process($node, $options, $serial_start, $submissions);
1110
}
1111

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

    
1135
  $submission_information = webform_results_download_submission_information($node, $options);
1136

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

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

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

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

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

    
1175
    $rows[$serial_start + $row_count] = $row;
1176
  }
1177

    
1178
  return $rows;
1179
}
1180

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

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

    
1206
  return $submission_information;
1207
}
1208

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

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

    
1234
    case 'webform_sid':
1235
      return $submission->sid;
1236

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

    
1267
    case 'webform_ip_address':
1268
      return $submission->remote_addr;
1269

    
1270
    case 'webform_uid':
1271
      return $submission->uid;
1272

    
1273
    case 'webform_username':
1274
      return $submission->name;
1275
  }
1276
}
1277

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

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

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

    
1310
  return $options;
1311
}
1312

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

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

    
1344
  exit();
1345
}
1346

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1479
  $submissions = webform_get_submissions_load($query);
1480

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

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

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

    
1498
  @fclose($handle);
1499

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

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

    
1514
  $exporter = webform_export_create_handler($format, $options);
1515

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

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

    
1535
  $context['results']['node'] = $node;
1536
  $context['results']['file_name'] = $options['file_name'];
1537

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

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

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

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

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

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

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

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

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

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

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

    
1674
  drupal_alter('webform_analysis', $analysis);
1675
  return $analysis;
1676
}
1677

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1826
  return $form;
1827
}
1828

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

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

    
1850
  $rows = array();
1851
  $question_number = 0;
1852
  $single = isset($analysis_component);
1853

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

    
1859
  foreach ($data as $cid => $row_data) {
1860
    $question_number++;
1861

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

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

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

    
1880
/**
1881
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1882
 *
1883
 * @deprecated in webform:7.x-4.8 and is removed from webform:7.x-5.0. Use
1884
 * webform_download_sids_query().
1885
 * @see https://www.drupal.org/project/webform/issues/2465291
1886
 */
1887
function webform_download_sids($nid, $range_options, $uid = NULL) {
1888
  return webform_download_sids_query($nid, $range_options, $uid)
1889
    ->fields('ws', array('sid'))
1890
    ->execute()
1891
    ->fetchCol();
1892
}
1893

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

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

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

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

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

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

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

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

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

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

    
1991
  drupal_alter('webform_download_sids_query', $query);
1992

    
1993
  return $query;
1994
}
1995

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

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

    
2027
  return $info;
2028
}
2029

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

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

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