Projet

Général

Profil

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

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

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
 *   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
 *
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
 *
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
      $start_date = strtotime($element['start_date']['#value']);
690
      if ($element['start_date']['#value'] == '') {
691
        form_error($element['start_date'], t('Start date range is required.'));
692
      }
693
      elseif ($start_date === FALSE) {
694
        form_error($element['start_date'], t('Start date range is not in a valid format.'));
695
      }
696
      // End submission time.
697
      $end_date = strtotime($element['end_date']['#value']);
698
      if ($element['end_date']['#value'] != '') {
699
        if ($end_date === FALSE) {
700
          form_error($element['end_date'], t('End date range is not in a valid format.'));
701
        }
702
        elseif ($start_date !== FALSE && $start_date > $end_date) {
703
          form_error($element['end_date'], t('End date range must not be before the Start date.'));
704
        }
705
      }
706
      break;
707
  }
708

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

    
725
}
726

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

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

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

    
742
  return $element;
743
}
744

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

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

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

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

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

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

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

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

    
793
  return drupal_render_children($element);
794
}
795

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

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

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

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

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

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

    
831
  return $output;
832
}
833

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

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

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

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

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

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

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

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

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

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

    
894
  return $batch_size;
895
}
896

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

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

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

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

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

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

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

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

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

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

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

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

    
978
  return $export_info;
979
}
980

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

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

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

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

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

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

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

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

    
1071
  return $header;
1072
}
1073

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

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

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

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

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

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

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

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

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

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

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

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

    
1179
  return $rows;
1180
}
1181

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

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

    
1207
  return $submission_information;
1208
}
1209

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

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

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

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

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

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

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

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

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

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

    
1311
  return $options;
1312
}
1313

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

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

    
1345
  exit();
1346
}
1347

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1480
  $submissions = webform_get_submissions_load($query);
1481

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

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

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

    
1499
  @fclose($handle);
1500

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1827
  return $form;
1828
}
1829

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

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

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

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

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

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

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

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

    
1881
/**
1882
 * Given a set of range options, retrieve a set of SIDs for a webform node.
1883
 *
1884
 * @deprecated This function is scheduled to be removed int webform 7.x-5.x.
1885
 * Use webform_download_sids_query() instead.
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('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
      $query->condition($date_field, strtotime($range_options['start_date']), '>=');
1969
      if ($range_options['end_date'] != '' && ($end_time = strtotime($range_options['end_date'])) !== FALSE) {
1970
        if ($end_time == strtotime('midnight', $end_time)) {
1971
          // Full day specified
1972
          // 86400 is a full day of seconds.
1973
          $end_time += 86399;
1974
        }
1975
        $query->condition($date_field, $end_time, '<=');
1976
      }
1977
      $query->orderBy($date_field, 'ASC');
1978
      break;
1979
  }
1980

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

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

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

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

    
2023
  return $info;
2024
}
2025

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

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

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