Projet

Général

Profil

Paste
Télécharger (71,9 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

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

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

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

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

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

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

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

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

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

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

    
103
  return drupal_render($element);
104

    
105
}
106

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

    
130
/**
131
 * Theme the list of links for selecting the number of results per page.
132
 *
133
 * @param 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($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 = theme('webform_results_table', array('node' => $node, 'components' => $node->webform['components'], 'submissions' => $submissions, 'total_count' => $total_count, 'pager_count' => $pager_count));
240
  if ($pager_count) {
241
    $output .= theme('pager');
242
  }
243
  return $output;
244
}
245

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

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

    
275
  $node = $variables['node'];
276
  $components = $variables['components'];
277
  $submissions = $variables['submissions'];
278
  $total_count = $variables['total_count'];
279
  $pager_count = $variables['pager_count'];
280

    
281
  $header = array();
282
  $rows = array();
283
  $cell = array();
284

    
285
  // This header has to be generated separately so we can add the SQL necessary.
286
  // to sort the results.
287
  $header = theme('webform_results_table_header', array('node' => $node));
288

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

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

    
308
    $rows[] = $cell;
309
    unset($cell);
310
  }
311
  if (!empty($component_headers)) {
312
    $header = array_merge($header, $component_headers);
313
  }
314

    
315
  if (count($rows) == 0) {
316
    $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));
317
  }
318

    
319

    
320
  $output = '';
321
  $output .= theme('webform_results_per_page', array('total_count' => $total_count, 'pager_count' => $pager_count));
322
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
323
  return $output;
324
}
325

    
326
/**
327
 * Delete all submissions for a node.
328
 *
329
 * @param $nid
330
 *   The node id whose submissions will be deleted.
331
 * @param $batch_size
332
 *   The number of submissions to be processed. NULL means all submissions.
333
 * @return
334
 *   The number of submissions processed.
335
 */
336
function webform_results_clear($nid, $batch_size = NULL) {
337
  $node = node_load($nid);
338
  $submissions = webform_get_submissions($nid, NULL, $batch_size);
339
  $count = 0;
340
  foreach ($submissions as $submission) {
341
    webform_submission_delete($node, $submission);
342
    $count++;
343
  }
344
  return $count;
345
}
346

    
347
/**
348
 * Confirmation form to delete all submissions for a node.
349
 *
350
 * @param $nid
351
 *   ID of node for which to clear submissions.
352
 */
353
function webform_results_clear_form($form, $form_state, $node) {
354
  drupal_set_title(t('Clear Form Submissions'));
355

    
356
  $form = array();
357
  $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
358
  $question = t('Are you sure you want to delete all submissions for this form?');
359

    
360
  return confirm_form($form, $question, 'node/' . $node->nid . '/webform-results', NULL, t('Clear'), t('Cancel'));
361
}
362

    
363
function webform_results_clear_form_submit($form, &$form_state) {
364
  $nid = $form_state['values']['nid'];
365
  $node = node_load($nid);
366
  // Set a modest batch size, due to the inefficiency of the hooks invoked when
367
  // submissions are deleted.
368
  $batch_size = min(webform_export_batch_size($node), 500);
369

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

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

    
399
  // Clear a batch of submissions.
400
  $count = webform_results_clear($node->nid, $batch_size);
401
  $context['results']['count'] += $count;
402

    
403
  // Display status message
404
  $context['message'] = t('Cleared @count of @total submissions...', array('@count' => $context['results']['count'], '@total' => $context['results']['total']));
405
  $context['finished'] = $count > 0
406
                            ? $context['results']['count'] / $context['results']['total']
407
                            : 1.0;
408
}
409

    
410
/**
411
 * Batch API completion callback; Finish clearing submissions.
412
 */
413
function webform_clear_batch_finished($success, $results, $operations) {
414
  if ($success) {
415
    $title = $results['node']->title;
416
    drupal_set_message(t('Webform %title entries cleared.', array('%title' => $title)));
417
    watchdog('webform', 'Webform %title entries cleared.', array('%title' => $title));
418
  }
419
}
420

    
421
/**
422
 * Form to configure the download of CSV files.
423
 */
424
function webform_results_download_form($form, &$form_state, $node) {
425
  module_load_include('inc', 'webform', 'includes/webform.export');
426
  module_load_include('inc', 'webform', 'includes/webform.components');
427

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

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

    
437
  $form['node'] = array(
438
    '#type' => 'value',
439
    '#value' => $node,
440
  );
441

    
442
  $form['format'] = array(
443
    '#type' => 'radios',
444
    '#title' => t('Export format'),
445
    '#options' => webform_export_list(),
446
    '#default_value' => webform_variable_get('webform_export_format'),
447
  );
448

    
449
  $form['delimited_options'] = array(
450
    '#type' => 'container',
451
    'warning' => array(
452
      '#markup' => '<p>' .
453
        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.',
454
        array('!link' => url('https://www.google.com/search?q=spreadsheet+formula+injection'))) .
455
        '</p>',
456
    ),
457
    'delimiter' => array(
458
      '#type' => 'select',
459
      '#title' => t('Delimited text format'),
460
      '#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.'),
461
      '#default_value' => webform_variable_get('webform_csv_delimiter'),
462
      '#options' => array(
463
        ','  => t('Comma (,)'),
464
        '\t' => t('Tab (\t)'),
465
        ';'  => t('Semicolon (;)'),
466
        ':'  => t('Colon (:)'),
467
        '|'  => t('Pipe (|)'),
468
        '.'  => t('Period (.)'),
469
        ' '  => t('Space ( )'),
470
      ),
471
    ),
472
    '#states' => array(
473
      'visible' => array(
474
        ':input[name=format]' => array('value' => 'delimited'),
475
      ),
476
    ),
477
  );
478

    
479
  $form['header_keys'] = array(
480
    '#type' => 'radios',
481
    '#title' => t('Column header format'),
482
    '#options' => array(
483
      -1 => t('None'),
484
      0 => t('Label'),
485
      1 => t('Form Key'),
486
    ),
487
    '#default_value' => 0,
488
    '#description' => t('Choose whether to show the label or form key in each column header.'),
489
  );
490

    
491
  $form['select_options'] = array(
492
    '#type' => 'fieldset',
493
    '#title' => t('Select list options'),
494
    '#collapsible' => TRUE,
495
    '#collapsed' => TRUE,
496
  );
497

    
498
  $form['select_options']['select_keys'] = array(
499
    '#type' => 'radios',
500
    '#title' => t('Select keys'),
501
    '#options' => array(
502
      0 => t('Full, human-readable options (values)'),
503
      1 => t('Short, raw options (keys)'),
504
    ),
505
    '#default_value' => 0,
506
    '#description' => t('Choose which part of options should be displayed from key|value pairs.'),
507
  );
508

    
509
  $form['select_options']['select_format'] = array(
510
    '#type' => 'radios',
511
    '#title' => t('Select list format'),
512
    '#options' => array(
513
      'separate' => t('Separate'),
514
      'compact' => t('Compact'),
515
    ),
516
    '#default_value' => 'separate',
517
    '#attributes' => array('class' => array('webform-select-list-format')),
518
    '#theme' => 'webform_results_download_select_format',
519
  );
520

    
521
  $csv_components = array('info' => t('Submission information'));
522
  // Prepend information fields with "-" to indent.
523
  foreach (webform_results_download_submission_information($node) as $key => $title) {
524
    $csv_components[$key] = '-' . $title;
525
  }
526

    
527
  $csv_components += webform_component_list($node, 'csv', TRUE);
528

    
529
  $form['components'] = array(
530
    '#type' => 'select',
531
    '#title' => t('Included export components'),
532
    '#options' => $csv_components,
533
    '#default_value' => array_keys($csv_components),
534
    '#multiple' => TRUE,
535
    '#size' => 10,
536
    '#description' => t('The selected components will be included in the export.'),
537
    '#process' => array('webform_component_select'),
538
  );
539

    
540
  $form['range'] = array(
541
    '#type' => 'fieldset',
542
    '#title' => t('Download range options'),
543
    '#collapsible' => TRUE,
544
    '#collapsed' => TRUE,
545
    '#tree' => TRUE,
546
    '#theme' => 'webform_results_download_range',
547
    '#element_validate' => array('webform_results_download_range_validate'),
548
    '#after_build' => array('webform_results_download_range_after_build'),
549
  );
550

    
551
  $form['range']['range_type'] = array(
552
    '#type' => 'radios',
553
    '#options' => array(
554
      'all' => t('All submissions'),
555
      'new' => t('Only new submissions since your last download'),
556
      'latest' => t('Only the latest'),
557
      'range_serial' => t('All submissions starting from'),
558
      'range_date' => t('All submissions by date'),
559
    ),
560
    '#default_value' => 'all',
561
  );
562
  $form['range']['latest'] = array(
563
    '#type' => 'textfield',
564
    '#size' => 5,
565
    '#maxlength' => 8,
566
  );
567
  $form['range']['start'] = array(
568
    '#type' => 'textfield',
569
    '#size' => 5,
570
    '#maxlength' => 8,
571
  );
572
  $form['range']['end'] = array(
573
    '#type' => 'textfield',
574
    '#size' => 5,
575
    '#maxlength' => 8,
576
  );
577
  $date_attributes = array('placeholder' => format_date(REQUEST_TIME, 'custom', webform_date_format('short')));
578
  $form['range']['start_date'] = array(
579
    '#type' => 'textfield',
580
    '#size' => 20,
581
    '#attributes' => $date_attributes,
582
  );
583
  $form['range']['end_date'] = array(
584
    '#type' => 'textfield',
585
    '#size' => 20,
586
    '#attributes' => $date_attributes,
587
  );
588

    
589
  // If drafts are allowed, provide options to filter download based on draft
590
  // status.
591
  $form['range']['completion_type'] = array(
592
    '#type' => 'radios',
593
    '#title' => t('Included submissions'),
594
    '#default_value' => 'all',
595
    '#options' => array(
596
      'all' => t('Finished and draft submissions'),
597
      'finished' => t('Finished submissions only'),
598
      'draft' => t('Drafts only'),
599
    ),
600
    '#access' => ($node->webform['allow_draft'] || $node->webform['auto_save']),
601
  );
602

    
603
  // By default results are downloaded. User can override this value if
604
  // programmatically submitting this form.
605
  $form['download'] = array(
606
    '#type' => 'value',
607
    '#default_value' => TRUE
608
  );
609

    
610
  $form['actions'] = array('#type' => 'actions');
611
  $form['actions']['submit'] = array(
612
    '#type' => 'submit',
613
    '#value' => t('Download'),
614
  );
615

    
616
  return $form;
617
}
618

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

    
696
  // Check that the range will return something at all.
697
  $range_options = array(
698
    'range_type' => $element['range_type']['#value'],
699
    'start' => $element['start']['#value'],
700
    'end' => $element['end']['#value'],
701
    'latest' => $element['latest']['#value'],
702
    'start_date' => $element['start_date']['#value'],
703
    'end_date' => $element['end_date']['#value'],
704
    'completion_type' => $element['completion_type']['#value'],
705
    'batch_size' => 1,
706
    'batch_number' => 0,
707
  );
708
  if (!form_get_errors() && !webform_download_sids_count($form_state['values']['node']->nid, $range_options)) {
709
    form_error($element['range_type'], t('The specified range will not return any results.'));
710
  }
711

    
712
}
713

    
714
/**
715
 * FormAPI after build function for the download range fieldset.
716
 */
717
function webform_results_download_range_after_build($element, &$form_state) {
718
  $node = $form_state['values']['node'];
719

    
720
  // Build a list of counts of new and total submissions.
721
  $last_download = webform_download_last_download_info($node->nid);
722

    
723
  $element['#webform_download_info']['sid'] = $last_download ? $last_download['sid'] : 0;
724
  $element['#webform_download_info']['serial'] = $last_download ? $last_download['serial'] : NULL;
725
  $element['#webform_download_info']['requested'] = $last_download ? $last_download['requested'] : $node->created;
726
  $element['#webform_download_info']['total'] = webform_get_submission_count($node->nid, NULL, NULL);
727
  $element['#webform_download_info']['new'] = webform_download_sids_count($node->nid, array('range_type' => 'new'));
728

    
729
  return $element;
730
}
731

    
732
/**
733
 * Theme the output of the export range fieldset.
734
 */
735
function theme_webform_results_download_range($variables) {
736
  drupal_add_library('webform', 'admin');
737

    
738
  $element = $variables['element'];
739
  $download_info = $element['#webform_download_info'];
740

    
741
  // Set description for total of all submissions.
742
  $element['range_type']['all']['#theme_wrappers'] = array('webform_inline_radio');
743
  $element['range_type']['all']['#title'] .= ' (' . t('@count total', array('@count' => $download_info['total'])) . ')';
744

    
745
  // Set description for "New submissions since last download".
746
  $format = webform_date_format('short');
747
  $requested_date = format_date($download_info['requested'], 'custom', $format);
748
  $element['range_type']['new']['#theme_wrappers'] = array('webform_inline_radio');
749
  $element['range_type']['new']['#title'] .= ' (' . t('@count new since @date', array('@count' => $download_info['new'], '@date' => $requested_date)) . ')';
750

    
751

    
752
  // Disable option if there are no new submissions.
753
  if ($download_info['new'] == 0) {
754
    $element['range_type']['new']['#attributes']['disabled'] = 'disabled';
755
  }
756

    
757
  // Render latest x submissions option.
758
  $element['latest']['#attributes']['class'][] = 'webform-set-active';
759
  $element['latest']['#theme_wrappers'] = array();
760
  $element['range_type']['latest']['#theme_wrappers'] = array('webform_inline_radio');
761
  $element['range_type']['latest']['#title'] = t('Only the latest !number submissions', array('!number' => drupal_render($element['latest'])));
762

    
763
  // Render Start-End submissions option.
764
  $element['start']['#attributes']['class'][] = 'webform-set-active';
765
  $element['end']['#attributes']['class'][] = 'webform-set-active';
766
  $element['start']['#theme_wrappers'] = array();
767
  $element['end']['#theme_wrappers'] = array();
768
  $element['start_date']['#attributes']['class'] = array('webform-set-active');
769
  $element['end_date']['#attributes']['class'] = array('webform-set-active');
770
  $element['start_date']['#theme_wrappers'] = array();
771
  $element['end_date']['#theme_wrappers'] = array();
772
  $element['range_type']['range_serial']['#theme_wrappers'] = array('webform_inline_radio');
773
  $last_serial = $download_info['serial'] ? $download_info['serial'] : drupal_placeholder(t('none'));
774
  $element['range_type']['range_serial']['#title'] = t('Submissions by number from !start and optionally to: !end &nbsp; (Last downloaded: !serial)',
775
    array('!start' => drupal_render($element['start']), '!end' => drupal_render($element['end']), '!serial' => $last_serial));
776

    
777
  // date range
778
  $element['range_type']['range_date']['#theme_wrappers'] = array('webform_inline_radio');
779
  $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'])));
780

    
781
  return drupal_render_children($element);
782
}
783

    
784
/**
785
 * Theme the output of the select list format radio buttons.
786
 */
787
function theme_webform_results_download_select_format($variables) {
788
  drupal_add_library('webform', 'admin');
789

    
790
  $element = $variables['element'];
791
  $output = '';
792

    
793
  // Build an example table for the separate option.
794
  $header = array(t('Option A'), t('Option B'), t('Option C'));
795
  $rows = array(
796
    array('X', '', ''),
797
    array('X', '', 'X'),
798
    array('', 'X', 'X'),
799
  );
800

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

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

    
814
  $element['compact']['#attributes']['class'] = array();
815
  $element['compact']['#description'] = theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE));
816
  $element['compact']['#description'] .= t('Compact options are more suitable for importing data into other systems.');
817
  $output .= drupal_render($element['compact']);
818

    
819
  return $output;
820
}
821

    
822
/**
823
 * Submit handler for webform_results_download_form().
824
 */
825
function webform_results_download_form_submit(&$form, &$form_state) {
826
  $node = $form_state['values']['node'];
827
  $format = $form_state['values']['format'];
828

    
829
  $options = array(
830
    'delimiter' => $form_state['values']['delimiter'],
831
    'components' => array_keys(array_filter($form_state['values']['components'])),
832
    'header_keys' => $form_state['values']['header_keys'],
833
    'select_keys' => $form_state['values']['select_keys'],
834
    'select_format' => $form_state['values']['select_format'],
835
    'range' => $form_state['values']['range'],
836
    'download' => $form_state['values']['download'],
837
  );
838

    
839
  $defaults = webform_results_download_default_options($node, $format);
840
  $options += $defaults;
841
  $options['range'] += $defaults['range'];
842

    
843
  // Determine an appropriate batch size based on the form and server specs.
844
  if (!isset($options['range']['batch_size'])) {
845
    $options['range']['batch_size'] = webform_export_batch_size($node);
846
  }
847

    
848
  $options['file_name'] = _webform_export_tempname();
849

    
850
  // Set up a batch to export the results.
851
  $batch = webform_results_export_batch($node, $format, $options);
852
  batch_set($batch);
853
}
854

    
855
/**
856
 * Calculate an appropriate batch size for bulk submission operations.
857
 *
858
 * @param object $node
859
 *   The webform node.
860
 * @return integer
861
 *   The number of submissions to be processed at once.
862
 */
863
function webform_export_batch_size($node) {
864
  // Start the batch size at 50,000 per batch, but divide by number of
865
  // components in the form. For example, if a form had 10 components, it would
866
  // export 5,000 submissions at a time.
867
  $batch_size = ceil(50000 / max(1, count($node->webform['components'])));
868

    
869
  // Every 32MB of additional memory after 64MB adds a multiplier in size.
870
  $memory_limit = parse_size(ini_get('memory_limit'));
871
  $mb = 1048576;
872
  $memory_modifier = max(1, ($memory_limit - (64 * $mb)) / (32 * $mb));
873
  $batch_size = ceil($batch_size * $memory_modifier);
874

    
875
  // For time reasons, limit the batch size to 5,000.
876
  $batch_size = min($batch_size, 5000);
877

    
878
  // Allow a non-UI configuration to override the batch size.
879
  $batch_size = variable_get('webform_export_batch_size', $batch_size);
880

    
881
  return $batch_size;
882
}
883

    
884
/**
885
 * Returns a temporary export filename.
886
 */
887
function _webform_export_tempname() {
888
  return drupal_tempnam(variable_get('webform_export_path', 'temporary://'), 'webform_');
889
}
890

    
891
/**
892
 * Generate a Excel-readable CSV file containing all submissions for a Webform.
893
 *
894
 * Note that this function is generally no longer utilized. Instead Batch API
895
 * should be used to generate a file over multiple requests.
896
 *
897
 * @see webform_results_export_batch()
898
 *
899
 * @deprecated This function is schedule to be removed in webform 7.x-5.x. Use
900
 * the batch opertions instead.
901
 *
902
 * @return array|null
903
 *   The array of export info or null if the file could not be opened.
904
 */
905
function webform_results_export($node, $format = 'delimited', $options = array()) {
906
  module_load_include('inc', 'webform', 'includes/webform.export');
907
  module_load_include('inc', 'webform', 'includes/webform.components');
908

    
909
  $defaults = webform_results_download_default_options($node, $format);
910
  $options += $defaults;
911
  $options['range'] += $defaults['range'];
912

    
913
  // Open a new Webform exporter object.
914
  $exporter = webform_export_create_handler($format, $options);
915

    
916
  $file_name = _webform_export_tempname();
917
  $handle = fopen($file_name, 'w');
918
  if (!$handle) {
919
    return;
920
  }
921

    
922
  // Add the beginning of file marker (little-endian usually for MS Excel).
923
  $exporter->bof($handle);
924

    
925
  // Add headers to the file.
926
  $row_count = 0;
927
  $col_count = 0;
928
  $headers = webform_results_download_headers($node, $options);
929
  foreach ($headers as $row) {
930
    // Output header if header_keys is non-negative. -1 means no headers.
931
    if ($options['header_keys'] >= 0) {
932
      $exporter->add_row($handle, $row, $row_count);
933
      $row_count++;
934
    }
935
    $col_count = count($row) > $col_count ? count($row) : $col_count;
936
  }
937

    
938
  // Write data from submissions. $last_is is non_NULL to trigger returning it
939
  // by reference.
940
  $last_sid = TRUE;
941
  $rows = webform_results_download_rows($node, $options, 0, $last_sid);
942
  foreach ($rows as $row) {
943
    $exporter->add_row($handle, $row, $row_count);
944
    $row_count++;
945
  }
946

    
947
  // Add the closing bytes.
948
  $exporter->eof($handle, $row_count, $col_count);
949

    
950
  // Close the file.
951
  @fclose($handle);
952

    
953
  $export_info['format'] = $format;
954
  $export_info['options'] = $options;
955
  $export_info['file_name'] = $file_name;
956
  $export_info['row_count'] = $row_count;
957
  $export_info['col_count'] = $col_count;
958
  $export_info['last_sid'] = $last_sid;
959
  $export_info['exporter'] = $exporter;
960

    
961
  return $export_info;
962
}
963

    
964
/**
965
 * Return a Batch API array of commands that will generate an export.
966
 *
967
 * @param $node
968
 *   The webform node on which to generate the analysis.
969
 * @param string $format
970
 *   (optional) Delimiter of the exported file.
971
 * @param array $options
972
 *   (optional) An associative array of options that define the output format.
973
 *   These are generally passed through from the GUI interface. Possible options
974
 *   include:
975
 *   - sids: An array of submission IDs to which this export may be filtered.
976
 *     May be used to generate exports that are per-user or other groups of
977
 *     submissions.
978
 *
979
 * @return array
980
 *   A Batch API array suitable to pass to batch_set().
981
 */
982
function webform_results_export_batch($node, $format = 'delimited', $options = array()) {
983
  $defaults = webform_results_download_default_options($node, $format);
984
  $options += $defaults;
985
  $options['range'] += $defaults['range'];
986

    
987
  return array(
988
    'operations' => array(
989
      array('webform_results_batch_bof', array($node, $format, $options)),
990
      array('webform_results_batch_headers', array($node, $format, $options)),
991
      array('webform_results_batch_rows', array($node, $format, $options)),
992
      array('webform_results_batch_eof', array($node, $format, $options)),
993
      array('webform_results_batch_post_process', array($node, $format, $options)),
994
      array('webform_results_batch_results', array($node, $format, $options)),
995
    ),
996
    'finished' => 'webform_results_batch_finished',
997
    'title' => t('Exporting submissions'),
998
    'init_message' => t('Creating export file'),
999
    'error_message' => t('The export file could not be created because an error occurred.'),
1000
    'file' => drupal_get_path('module', 'webform') . '/includes/webform.report.inc',
1001
  );
1002
}
1003

    
1004
/**
1005
 * Print the header rows for the downloadable webform data.
1006
 *
1007
 * @param $node
1008
 *   The webform node on which to generate the analysis.
1009
 * @param array $options
1010
 *   A list of options that define the output format. These are generally passed
1011
 *   through from the GUI interface.
1012
 */
1013
function webform_results_download_headers($node, $options) {
1014
  module_load_include('inc', 'webform', 'includes/webform.components');
1015
  $submission_information = webform_results_download_submission_information($node, $options);
1016

    
1017
  // Fill in the header for the submission information (if any).
1018
  $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
1019
  if (count($submission_information)) {
1020
    $header[0][0] = $node->title;
1021

    
1022
    if ($options['header_keys']) {
1023
      $header[1][0] = t('submission_details');
1024
      $submission_information_headers = array_keys($submission_information);
1025
    }
1026
    else {
1027
      $header[1][0] = t('Submission Details');
1028
      $submission_information_headers = array_values($submission_information);
1029
    }
1030
    foreach ($submission_information_headers as $column => $label) {
1031
      $header[2][$column] = $label;
1032
    }
1033
  }
1034

    
1035
  // Compile header information for components.
1036
  foreach ($options['components'] as $cid) {
1037
    if (isset($node->webform['components'][$cid])) {
1038
      $component = $node->webform['components'][$cid];
1039

    
1040
      // Let each component determine its headers.
1041
      if (webform_component_feature($component['type'], 'csv')) {
1042
        $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
1043
        // Allow modules to modify the component CSV header.
1044
        drupal_alter('webform_csv_header', $component_header, $component);
1045

    
1046
        // Merge component CSV header to overall CSV header
1047
        $header[0] = array_merge($header[0], (array) $component_header[0]);
1048
        $header[1] = array_merge($header[1], (array) $component_header[1]);
1049
        $header[2] = array_merge($header[2], (array) $component_header[2]);
1050
      }
1051
    }
1052
  }
1053

    
1054
  return $header;
1055
}
1056

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

    
1087
  $submissions = webform_get_submissions($filters, NULL);
1088

    
1089
  if (isset($last_sid)) {
1090
    $last_sid = end($submissions) ? key($submissions) : NULL;
1091
  }
1092

    
1093
  return webform_results_download_rows_process($node, $options, $serial_start, $submissions);
1094
}
1095

    
1096
/**
1097
 * Processes the submissions to be downloaded into exported rows.
1098
 *
1099
 * This is an internal routine and not intended for use by other modules.
1100
 *
1101
 * @param $node
1102
 *   The webform node on which to generate the analysis.
1103
 * @param array $options
1104
 *   A list of options that define the output format. These are generally passed
1105
 *   through from the GUI interface.
1106
 * @param $serial_start
1107
 *   The starting position for the Serial column in the output.
1108
 * @param array $submissions
1109
 *   An associative array of loaded submissions, indexed by sid.
1110
 *
1111
 * @return array $rows
1112
 *   An array of rows built according to the provided $serial_start and
1113
 *   $pager_count variables. Note that the current page number is determined
1114
 *   by the super-global $_GET['page'] variable.
1115
 */
1116
function webform_results_download_rows_process($node, $options, $serial_start, $submissions) {
1117
  module_load_include('inc', 'webform', 'includes/webform.components');
1118

    
1119
  $submission_information = webform_results_download_submission_information($node, $options);
1120

    
1121
  // Generate a row for each submission.
1122
  $row_count = 0;
1123
  $rows = array();
1124
  foreach ($submissions as $sid => $submission) {
1125
    $row_count++;
1126

    
1127
    $row = array();
1128
    // Add submission information.
1129
    foreach (array_keys($submission_information) as $token) {
1130
      $cell = module_invoke_all('webform_results_download_submission_information_data', $token, $submission, $options, $serial_start, $row_count);
1131
      $context = array('token' => $token, 'submission' => $submission, 'options' => $options, 'serial_start' => $serial_start, 'row_count' => $row_count);
1132
      drupal_alter('webform_results_download_submission_information_data', $cell, $context);
1133
      // implode() to ensure everything from a single value goes into one
1134
      // column, even if more than one module responds to this item.
1135
      $row[] = implode(', ', $cell);
1136
    }
1137

    
1138
    foreach ($options['components'] as $cid) {
1139
      if (isset($node->webform['components'][$cid])) {
1140
        $component = $node->webform['components'][$cid];
1141
        // Let each component add its data.
1142
        $raw_data = isset($submission->data[$cid]) ? $submission->data[$cid] : NULL;
1143
        if (webform_component_feature($component['type'], 'csv')) {
1144
          $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);
1145

    
1146
          // Allow modules to modify the CSV data.
1147
          drupal_alter('webform_csv_data', $data, $component, $submission);
1148

    
1149
          if (is_array($data)) {
1150
            $row = array_merge($row, array_values($data));
1151
          }
1152
          else {
1153
            $row[] = isset($data) ? $data : '';
1154
          }
1155
        }
1156
      }
1157
    }
1158

    
1159
    $rows[$serial_start + $row_count] = $row;
1160
  }
1161

    
1162
  return $rows;
1163
}
1164

    
1165
/**
1166
 * Default columns for submission information.
1167
 *
1168
 * By default all exports have several columns of generic information that
1169
 * applies to all submissions. This function returns the list of generic columns
1170
 * plus columns added by other modules.
1171
 *
1172
 * @param $options
1173
 *   Filter down the list of columns based on a provided column list.
1174
 *
1175
 * @return array
1176
 *   List of generic columns plus columns added by other modules
1177
 */
1178
function webform_results_download_submission_information($node, $options = array()) {
1179
  $submission_information = module_invoke_all('webform_results_download_submission_information_info');
1180
  drupal_alter('webform_results_download_submission_information_info', $submission_information);
1181

    
1182
  if (isset($options['components'])) {
1183
    foreach ($submission_information as $key => $label) {
1184
      if (!in_array($key, $options['components'])) {
1185
        unset($submission_information[$key]);
1186
      }
1187
    }
1188
  }
1189

    
1190
  return $submission_information;
1191
}
1192

    
1193
/**
1194
 * Implements hook_webform_results_download_submission_information_info().
1195
 */
1196
function webform_webform_results_download_submission_information_info() {
1197
  return array(
1198
    'webform_serial' => t('Serial'),
1199
    'webform_sid' => t('SID'),
1200
    'webform_time' => t('Submitted Time'),
1201
    'webform_completed_time' => t('Completed Time'),
1202
    'webform_modified_time' => t('Modified Time'),
1203
    'webform_draft' => t('Draft'),
1204
    'webform_ip_address' => t('IP Address'),
1205
    'webform_uid' => t('UID'),
1206
    'webform_username' => t('Username'),
1207
  );
1208
}
1209

    
1210
/**
1211
 * Implements hook_webform_results_download_submission_information_data().
1212
 */
1213
function webform_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
1214
  switch ($token) {
1215
    case 'webform_serial':
1216
      return $submission->serial;
1217
    case 'webform_sid':
1218
      return $submission->sid;
1219
    case 'webform_time':
1220
      // Return timestamp in local time (not UTC).
1221
      if (!empty($options['iso8601_date'])) {
1222
        return format_date($submission->submitted, 'custom', 'Y-m-d\TH:i:s');
1223
      }
1224
      else {
1225
        return format_date($submission->submitted, 'short');
1226
      }
1227
    case 'webform_completed_time':
1228
      if (!$submission->completed) {
1229
        return '';
1230
      }
1231
      // Return timestamp in local time (not UTC).
1232
      elseif (!empty($options['iso8601_date'])) {
1233
        return format_date($submission->completed, 'custom', 'Y-m-d\TH:i:s');
1234
      }
1235
      else {
1236
        return format_date($submission->completed, 'short');
1237
      }
1238
    case 'webform_modified_time':
1239
      // Return timestamp in local time (not UTC).
1240
      if (!empty($options['iso8601_date'])) {
1241
        return format_date($submission->modified, 'custom', 'Y-m-d\TH:i:s');
1242
      }
1243
      else {
1244
        return format_date($submission->modified, 'short');
1245
      }
1246
    case 'webform_draft':
1247
      return $submission->is_draft;
1248
    case 'webform_ip_address':
1249
      return $submission->remote_addr;
1250
    case 'webform_uid':
1251
      return $submission->uid;
1252
    case 'webform_username':
1253
      return $submission->name;
1254
  }
1255
}
1256

    
1257
/**
1258
 * Get options for creating downloadable versions of the webform data.
1259
 *
1260
 * @param $node
1261
 *   The webform node on which to generate the analysis.
1262
 * @param string $format
1263
 *   The export format being used.
1264
 * @param array $options
1265
 *   A list of options that define the output format. These are generally passed
1266
 *   through from the GUI interface.
1267
 *
1268
 * @return array
1269
 *   Option for creating downloadable version of the webform data.
1270
 */
1271
function webform_results_download_default_options($node, $format) {
1272
  $submission_information = webform_results_download_submission_information($node);
1273

    
1274
  $options = array(
1275
    'delimiter' => webform_variable_get('webform_csv_delimiter'),
1276
    'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
1277
    'header_keys' => 0,
1278
    'select_keys' => 0,
1279
    'select_format' => 'separate',
1280
    'range' => array(
1281
      'range_type' => 'all',
1282
      'completion_type' => 'all',
1283
    ),
1284
  );
1285

    
1286
  // Allow exporters to merge in additional options.
1287
  $exporter_information = webform_export_fetch_definition($format);
1288
  if (isset($exporter_information['options'])) {
1289
    $options = array_merge($options, $exporter_information['options']);
1290
  }
1291

    
1292
  return $options;
1293
}
1294

    
1295
/**
1296
 * Send a generated webform results file to the user's browser.
1297
 *
1298
 * @param $node
1299
 *   The webform node.
1300
 * @param $export_info
1301
 *   Export information array retrieved from webform_results_export().
1302
 */
1303
function webform_results_download($node, $export_info) {
1304
  // If the exporter provides a custom download method, use that.
1305
  if (method_exists($export_info['exporter'], 'download')) {
1306
    $export_info['exporter']->download($node, $export_info);
1307
  }
1308
  // Otherwise use the set_headers() method to set headers and then read in the
1309
  // file directly. Delete it when complete.
1310
  else {
1311
    $export_name = _webform_safe_name($node->title);
1312
    if (!strlen($export_name)) {
1313
      $export_name  = t('Untitled');
1314
    }
1315
    $export_info['exporter']->set_headers($export_name);
1316
    ob_clean();
1317
    @readfile($export_info['file_name']);  // The @ makes it silent.
1318
    @unlink($export_info['file_name']);  // Clean up, the @ makes it silent.
1319
  }
1320

    
1321
  // Save the last exported sid for new-only exports.
1322
  webform_results_export_success($node, $export_info);
1323

    
1324
  exit();
1325
}
1326

    
1327
/**
1328
 * Save the last-exported sid for new-only exports.
1329
 *
1330
 * @param $node
1331
 *   The webform node.
1332
 * @param $export_info
1333
 *   Export information array retrieved from webform_results_export().
1334
 */
1335
function webform_results_export_success($node, $export_info) {
1336
  if (!in_array($export_info['options']['range']['range_type'], array('range', 'range_serial', 'range_date')) && !empty($export_info['last_sid'])) {
1337
    // Insert a new record or update an existing record.
1338
    db_merge('webform_last_download')
1339
      ->key(array(
1340
        'nid' => $node->nid,
1341
        'uid' => $GLOBALS['user']->uid,
1342
      ))
1343
      ->fields(array(
1344
        'sid' => $export_info['last_sid'],
1345
        'requested' => REQUEST_TIME,
1346
      ))
1347
      ->execute();
1348
  }
1349
}
1350

    
1351
/**
1352
 * Menu callback; Download an exported file.
1353
 *
1354
 * This callabck requires that an export file be already generated by a batch
1355
 * process. The $_SESSION settings are usually put in place by the
1356
 * webform_results_export_results() function.
1357
 *
1358
 * @param $node
1359
 *   The webform $node whose export file is being downloaded.
1360
 *
1361
 * @return null|string
1362
 *   Either an export file is downloaded with the appropriate HTTP headers set,
1363
 *   or an error page is shown if now export is available to download.
1364
 */
1365
function webform_results_download_callback($node) {
1366
  if (isset($_SESSION['webform_export_info'])) {
1367
    module_load_include('inc', 'webform', 'includes/webform.export');
1368

    
1369
    $export_info = $_SESSION['webform_export_info'];
1370
    $export_info['exporter'] = webform_export_create_handler($export_info['format'], $export_info['options']);
1371

    
1372
    unset($_SESSION['webform_export_info']);
1373
    if (isset($_COOKIE['webform_export_info'])) {
1374
      unset($_COOKIE['webform_export_info']);
1375
      $params = session_get_cookie_params();
1376
      setcookie('webform_export_info', '', -1, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1377
    }
1378

    
1379
    webform_results_download($node, $export_info);
1380
  }
1381
  else {
1382
    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')));
1383
  }
1384
}
1385

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

    
1392
  $exporter = webform_export_create_handler($format, $options);
1393
  $handle = fopen($options['file_name'], 'w');
1394
  if (!$handle) {
1395
    return;
1396
  }
1397
  $exporter->bof($handle);
1398
  @fclose($handle);
1399
}
1400

    
1401
/**
1402
 * Batch API callback; Write the headers of the export to the export file.
1403
 */
1404
function webform_results_batch_headers($node, $format = 'delimited', $options = array(), &$context) {
1405
  module_load_include('inc', 'webform', 'includes/webform.export');
1406

    
1407
  $exporter = webform_export_create_handler($format, $options);
1408
  $handle = fopen($options['file_name'], 'a');
1409
  if (!$handle) {
1410
    return;
1411
  }
1412
  $headers = webform_results_download_headers($node, $options);
1413
  $row_count = 0;
1414
  $col_count = 0;
1415
  foreach ($headers as $row) {
1416
    // Output header if header_keys is non-negative. -1 means no headers.
1417
    if ($options['header_keys'] >= 0) {
1418
      $exporter->add_row($handle, $row, $row_count);
1419
      $row_count++;
1420
    }
1421
    $col_count = count($row) > $col_count ? count($row) : $col_count;
1422
  }
1423
  $context['results']['row_count'] = $row_count;
1424
  $context['results']['col_count'] = $col_count;
1425
  @fclose($handle);
1426
}
1427

    
1428
/**
1429
 * Batch API callback; Write the rows of the export to the export file.
1430
 */
1431
function webform_results_batch_rows($node, $format = 'delimited', $options = array(), &$context) {
1432
  module_load_include('inc', 'webform', 'includes/webform.export');
1433

    
1434
  // Initialize the sandbox if this is the first execution of the batch
1435
  // operation.
1436
  if (!isset($context['sandbox']['batch_number'])) {
1437
    $context['sandbox']['batch_number'] = 0;
1438
    $context['sandbox']['sid_count'] = webform_download_sids_count($node->nid, $options['range']);
1439
    $context['sandbox']['batch_max'] = max(1, ceil($context['sandbox']['sid_count'] / $options['range']['batch_size']));
1440
    $context['sandbox']['serial'] = 0;
1441
    $context['sandbox']['last_sid'] = 0;
1442
  }
1443

    
1444
  // Retrieve the submissions for this batch process.
1445
  $options['range']['batch_number'] = $context['sandbox']['batch_number'];
1446

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

    
1449
  // Join to the users table to include user name in results, as required by
1450
  // webform_results_download_rows_process.
1451
  $query->leftJoin('users', 'u', 'u.uid = ws.uid');
1452
  $query->fields('u', array('name'));
1453
  $query->fields('ws');
1454

    
1455
  if (!empty($options['sids'])) {
1456
    $query->condition('ws.sid', $options['sids'], 'IN');
1457
  }
1458

    
1459
  $submissions = webform_get_submissions_load($query);
1460

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

    
1463
  // Write these submissions to the file.
1464
  $exporter = webform_export_create_handler($format, $options);
1465
  $handle = fopen($options['file_name'], 'a');
1466
  if (!$handle) {
1467
    return;
1468
  }
1469
  foreach ($rows as $row) {
1470
    $exporter->add_row($handle, $row, $context['results']['row_count']);
1471
    $context['results']['row_count']++;
1472
  }
1473

    
1474
  $context['sandbox']['serial'] += count($submissions);
1475
  $context['sandbox']['last_sid'] = end($submissions) ? key($submissions) : NULL;
1476
  $context['sandbox']['batch_number']++;
1477

    
1478
  @fclose($handle);
1479

    
1480
  // Display status message
1481
  $context['message'] = t('Exported @count of @total submissions...', array('@count' => $context['sandbox']['serial'], '@total' => $context['sandbox']['sid_count']));
1482
  $context['finished'] = $context['sandbox']['batch_number'] < $context['sandbox']['batch_max']
1483
                            ? $context['sandbox']['batch_number'] / $context['sandbox']['batch_max']
1484
                            : 1.0;
1485
  $context['results']['last_sid'] = $context['sandbox']['last_sid'];
1486
}
1487

    
1488
/**
1489
 * Batch API callback; Write the closing bytes in the export file.
1490
 */
1491
function webform_results_batch_eof($node, $format = 'delimited', $options = array(), &$context) {
1492
  module_load_include('inc', 'webform', 'includes/webform.export');
1493

    
1494
  $exporter = webform_export_create_handler($format, $options);
1495

    
1496
  // We open the file for reading and writing, rather than just appending for
1497
  // exporters that need to adjust the beginning of the files as well as the
1498
  // end, i.e. webform_exporter_excel_xlsx::eof().
1499
  $handle = fopen($options['file_name'], 'r+');
1500
  if (!$handle) {
1501
    return;
1502
  }
1503
  fseek($handle, 0, SEEK_END); // Move pointer to the end of the file.
1504
  $exporter->eof($handle, $context['results']['row_count'], $context['results']['col_count']);
1505
  @fclose($handle);
1506
}
1507

    
1508
/**
1509
 * Batch API callback; Do any last processing on the finished export.
1510
 */
1511
function webform_results_batch_post_process($node, $format = 'delimited', $options = array(), &$context) {
1512
  module_load_include('inc', 'webform', 'includes/webform.export');
1513

    
1514
  $context['results']['node'] = $node;
1515
  $context['results']['file_name'] = $options['file_name'];
1516

    
1517
  $exporter = webform_export_create_handler($format, $options);
1518
  $exporter->post_process($context['results']);
1519
}
1520

    
1521
/**
1522
 * Batch API callback; Set the $_SESSION variables used to download the file.
1523
 *
1524
 * Because we want the user to be returned to the main form first, we have to
1525
 * temporarily store information about the created file, send the user to the
1526
 * form, then use JavaScript to request node/x/webform-results/download-file,
1527
 * which will execute webform_results_download_file().
1528
 */
1529
function webform_results_batch_results($node, $format, $options, &$context) {
1530

    
1531
  $export_info = array(
1532
    'format' => $format,
1533
    'options' => $options,
1534
    'file_name' => $context['results']['file_name'],
1535
    'row_count' => $context['results']['row_count'],
1536
    'last_sid' => $context['results']['last_sid'],
1537
  );
1538

    
1539
  if (isset($_SESSION)) {
1540
    // UI exection. Defer resetting last-downloaded sid until download page.
1541
    // Set a session variable containing the information referencing the exported
1542
    // file. A cookie is also set to allow the browser to ensure the redirect
1543
    // to the file only happens one time.
1544
    $_SESSION['webform_export_info'] = $export_info;
1545
    $params = session_get_cookie_params();
1546
    setcookie('webform_export_info', '1', REQUEST_TIME + 120, $params['path'], $params['domain'], $params['secure'], FALSE);
1547
  }
1548
  else {
1549
    // Drush execution of wfx command. Reset last-downloaded sid now. $_SESSION
1550
    // is not supported for command line execution.
1551
    webform_results_export_success($node, $export_info);
1552
  }
1553
}
1554

    
1555
/**
1556
 * Batch API completion callback; Display completion message and cleanup.
1557
 */
1558
function webform_results_batch_finished($success, $results, $operations) {
1559
  if ($success) {
1560
    $download_url = url('node/' . $results['node']->nid . '/webform-results/download-file');
1561
    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)));
1562
  }
1563
  else {
1564
    drupal_set_message(t('An error occurred while generating the export file.'));
1565
    if (isset($results['file_name']) && is_file($results['file_name'])) {
1566
      @unlink($results['file_name']);
1567
    }
1568
  }
1569
}
1570

    
1571
/**
1572
 * Provides a simple analysis of all submissions to a webform.
1573
 *
1574
 * @param $node
1575
 *   The webform node on which to generate the analysis.
1576
 * @param $sids
1577
 *   An array of submission IDs to which this analysis may be filtered. May be
1578
 *   used to generate results that are per-user or other groups of submissions.
1579
 * @param $analysis_component
1580
 *   A webform component. If passed in, additional information may be returned
1581
 *   relating specifically to that component's analysis, such as a list of
1582
 *   "Other" values within a select list.
1583
 *
1584
 * @return string
1585
 *   Provides a simple analysis of all submissions to a webform.
1586
 */
1587
function webform_results_analysis($node, $sids = array(), $analysis_component = NULL) {
1588
  if (!is_array($sids)) {
1589
    $sids = array();
1590
  }
1591

    
1592
  // Build a renderable for the content of this page.
1593
  $analysis = array(
1594
    '#theme' => array('webform_analysis__' . $node->nid, 'webform_analysis'),
1595
    '#node' => $node,
1596
    '#component' => $analysis_component,
1597
  );
1598

    
1599
  // See if a query (possibly with exposed filter) needs to restrict the
1600
  // submissions that are being analyzed.
1601
  $query = NULL;
1602
  if (empty($sids)) {
1603
    $view = webform_get_view($node, 'webform_analysis');
1604
    if ($view->type != t('Default') || $view->name != 'webform_analysis') {
1605
      // The view has been customized from the no-op built-in view. Use it.
1606
      $view->set_display();
1607
      $view->init_handlers();
1608
      $view->override_url = $_GET['q'];
1609
      $view->preview = TRUE;
1610
      $view->pre_execute(array($node->nid));
1611
      $view->build();
1612
      // Let modules modify the view just prior to executing it.
1613
      foreach (module_implements('views_pre_execute') as $module) {
1614
        $function = $module . '_views_pre_execute';
1615
        $function($view);
1616
      }
1617
      // If the view is already executed, there was an error in generating it.
1618
      $query = $view->executed ? NULL : $view->query->query();
1619
      $view->post_execute();
1620

    
1621
      if (isset($view->exposed_widgets)) {
1622
        $analysis['exposed_filter']['#markup'] = $view->exposed_widgets;
1623
      }
1624
    }
1625
  }
1626

    
1627
  // If showing all components, display selection form.
1628
  if (!$analysis_component) {
1629
    $analysis['form'] = drupal_get_form('webform_analysis_components_form', $node);
1630
  }
1631

    
1632
  // Add all the components to the analysis renderable array.
1633
  $components = isset($analysis_component) ? array($analysis_component['cid']) : webform_analysis_enabled_components($node);
1634
  foreach ($components as $cid) {
1635
    // Do component specific call.
1636
    $component = $node->webform['components'][$cid];
1637
    if ($data = webform_component_invoke($component['type'], 'analysis', $component, $sids, isset($analysis_component), $query)) {
1638
      drupal_alter('webform_analysis_component_data', $data, $node, $component);
1639
      $analysis['data'][$cid] = array(
1640
        '#theme' => array('webform_analysis_component__' . $node->nid . '__' . $cid, 'webform_analysis_component__' . $node->nid, 'webform_analysis_component'),
1641
        '#node' => $node,
1642
        '#component' => $component,
1643
        '#data' => $data,
1644
      );
1645
      $analysis['data'][$cid]['basic'] = array(
1646
        '#theme' => array('webform_analysis_component_basic__' . $node->nid . '__' . $cid, 'webform_analysis_component_basic__' . $node->nid, 'webform_analysis_component_basic'),
1647
        '#component' => $component,
1648
        '#data' => $data,
1649
      );
1650
    }
1651
  }
1652

    
1653
  drupal_alter('webform_analysis', $analysis);
1654
  return drupal_render($analysis);
1655
}
1656

    
1657
/**
1658
 * Prerender function for webform-analysis.tpl.php.
1659
 */
1660
function template_preprocess_webform_analysis(&$variables) {
1661
  $analysis = $variables['analysis'];
1662
  $variables['node'] = $analysis['#node'];
1663
  $variables['component'] = $analysis['#component'];
1664
}
1665

    
1666
/**
1667
 * Prerender function for webform-analysis-component.tpl.php.
1668
 */
1669
function template_preprocess_webform_analysis_component(&$variables) {
1670
  $component_analysis = $variables['component_analysis'];
1671
  $variables['node'] = $component_analysis['#node'];
1672
  $variables['component'] = $component_analysis['#component'];
1673

    
1674
  // Ensure defaults.
1675
  $variables['component_analysis']['#data'] += array(
1676
    'table_header' => NULL,
1677
    'table_rows' => array(),
1678
    'other_data' => array(),
1679
  );
1680
  $variables['classes_array'][] = 'webform-analysis-component-' . $variables['component']['type'];
1681
  $variables['classes_array'][] = 'webform-analysis-component--' . str_replace('_', '-', implode('--', webform_component_parent_keys($variables['node'], $variables['component'])));
1682
}
1683

    
1684
/**
1685
 * Render an individual component's analysis data in a table.
1686
 *
1687
 * @param $variables
1688
 *   An array of theming variables for this theme function. Included keys:
1689
 *   - $component: The component whose analysis is being rendered.
1690
 *   - $data: An array of array containing the analysis data. Contains the keys:
1691
 *     - table_header: If this table has more than a single column, an array
1692
 *       of header labels.
1693
 *     - table_rows: If this component has a table that should be rendered, an
1694
 *       array of values
1695
 *
1696
 * @return string
1697
 */
1698
function theme_webform_analysis_component_basic($variables) {
1699
  $data = $variables['data'];
1700

    
1701
  // Ensure defaults.
1702
  $data += array(
1703
    'table_header' => NULL,
1704
    'table_rows' => array(),
1705
    'other_data' => array(),
1706
  );
1707

    
1708
  // Combine the "other data" into the table rows by default.
1709
  if (is_array($data['other_data'])) {
1710
    foreach ($data['other_data'] as $other_data) {
1711
      if (is_array($other_data)) {
1712
        $data['table_rows'][] = $other_data;
1713
      }
1714
      else {
1715
        $data['table_rows'][] = array(array(
1716
          'colspan' => 2,
1717
          'data' => $other_data,
1718
        ));
1719
      }
1720
    }
1721
  }
1722
  elseif (strlen($data['other_data'])) {
1723
    $data['table_rows'][] = array(
1724
      'colspan' => 2,
1725
      'data' => $data['other_data'],
1726
    );
1727
  }
1728

    
1729
  return theme('table', array(
1730
    'header' => $data['table_header'],
1731
    'rows' => $data['table_rows'],
1732
    'sticky' => FALSE,
1733
    'attributes' => array('class' => array('webform-analysis-table')),
1734
  ));
1735
}
1736

    
1737
/**
1738
 * Return a list of components that should be displayed for analysis.
1739
 *
1740
 * @param $node
1741
 *   The node whose components' data is being analyzed.
1742
 * @return array
1743
 *   An array of component IDs.
1744
 */
1745
function webform_analysis_enabled_components($node) {
1746
  $cids = array();
1747
  foreach ($node->webform['components'] as $cid => $component) {
1748
    if (!empty($component['extra']['analysis'])) {
1749
      $cids[] = $cid;
1750
    }
1751
  }
1752
  return $cids;
1753
}
1754

    
1755
/**
1756
 * Form for selecting which components should be shown on the analysis page.
1757
 */
1758
function webform_analysis_components_form($form, &$form_state, $node) {
1759
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1760
  $form['#node'] = $node;
1761

    
1762
  $component_list = webform_component_list($node, 'analysis', TRUE);
1763
  $enabled_components = webform_analysis_enabled_components($node);
1764
  if (empty($component_list)) {
1765
    $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')));
1766
  }
1767
  elseif (empty($enabled_components)) {
1768
    $help = t('No components have analysis enabled in this form. Enable analysis under the "Add analysis components" fieldset.');
1769
  }
1770
  else {
1771
    $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.');
1772
  }
1773

    
1774
  $form['help'] = array(
1775
    '#markup' => '<p>' . $help . '</p>',
1776
    '#access' => !empty($help),
1777
    '#weight' => -100,
1778
  );
1779

    
1780
  $form['components'] = array(
1781
    '#type' => 'select',
1782
    '#title' => t('Add analysis components'),
1783
    '#options' => $component_list,
1784
    '#default_value' => $enabled_components,
1785
    '#multiple' => TRUE,
1786
    '#size' => 10,
1787
    '#description' => t('The selected components will be included on the analysis page.'),
1788
    '#process' => array('webform_component_select'),
1789
    '#access' => count($component_list),
1790
  );
1791

    
1792
  $form['actions'] = array(
1793
    '#type' => 'actions',
1794
    '#access' => count($component_list),
1795
  );
1796
  $form['actions']['submit'] = array(
1797
    '#type' => 'submit',
1798
    '#value' => t('Update analysis display'),
1799
  );
1800

    
1801
  return $form;
1802
}
1803

    
1804
/**
1805
 * Submit handler for webform_analysis_components_form().
1806
 */
1807
function webform_analysis_components_form_submit($form, $form_state) {
1808
  $node = $form['#node'];
1809
  foreach ($form_state['values']['components'] as $cid => $enabled) {
1810
    $node->webform['components'][$cid]['extra']['analysis'] = (bool) $enabled;
1811
  }
1812
  node_save($node);
1813
}
1814

    
1815
/**
1816
 * Output the content of the Analysis page.
1817
 *
1818
 * @see webform_results_analysis()
1819
 */
1820
function theme_webform_results_analysis($variables) {
1821
  $node = $variables['node'];
1822
  $data = $variables['data'];
1823
  $sids = $variables['sids'];
1824
  $analysis_component = $variables['component'];
1825

    
1826
  $rows = array();
1827
  $question_number = 0;
1828
  $single = isset($analysis_component);
1829

    
1830
  $header = array(
1831
    $single ? $analysis_component['name'] : t('Q'),
1832
    array('data' => $single ? '&nbsp;' : t('responses'), 'colspan' => '10')
1833
  );
1834

    
1835
  foreach ($data as $cid => $row_data) {
1836
    $question_number++;
1837

    
1838
    if (is_array($row_data)) {
1839
      $row = array();
1840
      if (!$single) {
1841
        $row['data'][] = array('data' => '<strong>' . $question_number . '</strong>', 'rowspan' => count($row_data) + 1, 'valign' => 'top');
1842
        $row['data'][] = array('data' => '<strong>' . check_plain($node->webform['components'][$cid]['name']) . '</strong>', 'colspan' => '10');
1843
        $row['class'][] = 'webform-results-question';
1844
      }
1845
      $rows = array_merge($rows, array_merge(array($row), $row_data));
1846
    }
1847
  }
1848

    
1849
  if (count($rows) == 0) {
1850
    $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));
1851
  }
1852

    
1853
  return theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('class' => array('webform-results-analysis'))));
1854
}
1855

    
1856
/**
1857
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1858
 *
1859
 * @deprecated This function is scheduled to be removed int webform 7.x-5.x.
1860
 * Use webform_download_sids_query() instead.
1861
 *
1862
 */
1863
function webform_download_sids($nid, $range_options, $uid = NULL) {
1864
  return webform_download_sids_query($nid, $range_options, $uid)
1865
    ->fields('ws', array('sid'))
1866
    ->execute()
1867
    ->fetchCol();
1868
}
1869

    
1870
/**
1871
 * Retrieves a count the number of matching submissions.
1872
 *
1873
 */
1874
function webform_download_sids_count($nid, $range_options, $uid = NULL) {
1875
  return webform_download_sids_query($nid, $range_options, $uid)
1876
    ->countQuery()
1877
    ->execute()
1878
    ->fetchField();
1879
}
1880

    
1881
/**
1882
 * Given a set of range options, return an unexecuted select query.
1883
 *
1884
 * The query will have no fields as they should be added by the caller as
1885
 * desired.
1886
 *
1887
 * @param integer $nid
1888
 *   The node id of the webform.
1889
 * @param array $range_options
1890
 *   Associate array of range options.
1891
 * @param integer $uid
1892
 *   The user id of the user whose last download information should be used,
1893
 *   or the current user if NULL. This is unrelated to which user submitted
1894
 *   the submissions.
1895
 *
1896
 * @return QueryAlterableInterface
1897
 */
1898
function webform_download_sids_query($nid, $range_options, $uid = NULL) {
1899
  $query = db_select('webform_submissions', 'ws')
1900
    ->condition('nid', $nid)
1901
    ->addTag('webform_download_sids');
1902

    
1903
  switch ($range_options['range_type']) {
1904
    case 'all':
1905
      // All Submissions.
1906
      $query->orderBy('ws.sid', 'ASC');
1907
      break;
1908
    case 'new':
1909
      // All Since Last Download.
1910
      $download_info = webform_download_last_download_info($nid, $uid);
1911
      $last_sid = $download_info ? $download_info['sid'] : 0;
1912
      $query
1913
        ->condition('ws.sid', $last_sid, '>')
1914
        ->orderBy('ws.sid', 'ASC');
1915
      break;
1916
    case 'latest':
1917
      // Last x Submissions.
1918
      $start_sid = webform_download_latest_start_sid($nid, $range_options['latest'], $range_options['completion_type']);
1919
      $query->condition('ws.sid', $start_sid, '>=');
1920
      break;
1921
    case 'range':
1922
      // Submissions Start-End.
1923
      $query->condition('ws.sid', $range_options['start'], '>=');
1924
      if ($range_options['end']) {
1925
        $query->condition('ws.sid', $range_options['end'], '<=');
1926
      }
1927
      $query->orderBy('ws.sid', 'ASC');
1928
      break;
1929
    case 'range_serial':
1930
      // Submissions Start-End, using serial numbers.
1931
      $query->condition('ws.serial', $range_options['start'], '>=');
1932
      if ($range_options['end']) {
1933
        $query->condition('ws.serial', $range_options['end'], '<=');
1934
      }
1935
      $query->orderBy('ws.serial', 'ASC');
1936
      break;
1937
    case 'range_date':
1938
      $date_field = $range_options['completion_type'] == 'finished' ? 'ws.completed' : 'ws.submitted';
1939
      $query->condition($date_field, strtotime($range_options['start_date']), '>=');
1940
      if ($range_options['end_date'] != '' && ($end_time = strtotime($range_options['end_date'])) !== FALSE) {
1941
        if ($end_time == strtotime('midnight', $end_time)) {
1942
          // Full day specified
1943
          $end_time += 86399; // 86400 is a full day of seconds.
1944
        }
1945
        $query->condition($date_field, $end_time, '<=');
1946
      }
1947
      ;
1948
      $query->orderBy($date_field, 'ASC');
1949
      break;
1950
  }
1951

    
1952
  // Filter down to draft or finished submissions.
1953
  if (!empty($range_options['completion_type']) && $range_options['completion_type'] !== 'all') {
1954
    $query->condition('is_draft', (int) ($range_options['completion_type'] === 'draft'));
1955
  }
1956

    
1957
  if (isset($range_options['batch_number']) && !empty($range_options['batch_size'])) {
1958
    $query->range($range_options['batch_number'] * $range_options['batch_size'], $range_options['batch_size']);
1959
  }
1960
  return $query;
1961
}
1962

    
1963
/**
1964
 * Get this user's last download information, including the SID and timestamp.
1965
 *
1966
 * This function provides an array of information about the last download that
1967
 * a user had for a particular Webform node. Currently it only returns an array
1968
 * with two keys:
1969
 *  - sid: The last submission ID that was downloaded.
1970
 *  - requested: The timestamp of the last download request.
1971
 *
1972
 * @param $nid
1973
 *   The Webform NID.
1974
 * @param $uid
1975
 *   The user account ID for which to retrieve download information.
1976
 * @return
1977
 *   An array of download information or FALSE if this user has never downloaded
1978
 *   results for this particular node.
1979
 */
1980
function webform_download_last_download_info($nid, $uid = NULL) {
1981
  $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
1982

    
1983
  $query = db_select('webform_last_download', 'wld');
1984
  $query->leftJoin('webform_submissions', 'wfs', 'wld.sid = wfs.sid');
1985
  $info = $query
1986
    ->fields('wld')
1987
    ->fields('wfs', array('serial'))
1988
    ->condition('wld.nid', $nid)
1989
    ->condition('wld.uid', $uid)
1990
    ->execute()
1991
    ->fetchAssoc();
1992

    
1993
  return $info;
1994
}
1995

    
1996
/**
1997
 * Get an SID based a requested latest count.
1998
 *
1999
 * @param int $nid
2000
 *   The webform NID.
2001
 * @param int $latest_count
2002
 *   The latest count on which the SID will be retrieved.
2003
 * @param string $completion_type
2004
 *   The completion type, either "finished", "draft", or "all".
2005
 * @return
2006
 *   The submission ID that starts the latest sequence of submissions.
2007
 */
2008
function webform_download_latest_start_sid($nid, $latest_count, $completion_type = 'all') {
2009
  // TODO: Find a more efficient DBTNG query to retrieve this number.
2010
  $query = db_select('webform_submissions', 'ws')
2011
    ->fields('ws', array('sid'))
2012
    ->condition('nid', $nid)
2013
    ->orderBy('ws.sid', 'DESC')
2014
    ->range(0, $latest_count)
2015
    ->addTag('webform_download_latest_start_sid');
2016

    
2017
  if ($completion_type !== 'all') {
2018
    $query->condition('is_draft', (int) ($completion_type === 'draft'));
2019
  }
2020

    
2021
  $latest_sids = $query->execute()->fetchCol();
2022
  return $latest_sids ? min($latest_sids) : 1;
2023
}