Project

General

Profile

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

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

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions relating to Drush integration.
6
 */
7

    
8
/**
9
 * Implements hook_drush_command().
10
 */
11
function webform_drush_command() {
12
  return array(
13
    'webform-export' => array(
14
      'description' => 'Exports webform data to a file.',
15
      'arguments' => array(
16
        'nid' => 'The node ID of the webform you want to export (required)',
17
      ),
18
      'options' => array(
19
        'file' => 'The file path to export to (defaults to print to stdout)',
20
        'format' => 'The exporter format to use. Out-of-the-box this may be "delimited" or "excel".',
21
        'delimiter' => 'Delimiter between columns (defaults to site-wide setting). This option may need to be wrapped in quotes. i.e. --delimter="\t".',
22
        'components' => 'Comma-separated list of component IDs or form keys to include.' . "\n" .
23
        'May also include "webform_serial", "webform_sid", "webform_time", "webform_complete_time", "webform_modified_time", "webform_draft", "webform_ip_address", "webform_uid", and "webform_username".',
24
        'header-keys' => 'Integer -1 for none, 0 for label (default) or 1 for form key.',
25
        'select-keys' => 'Integer 0 or 1 value. Set to 1 to print select list values by their form keys instead of labels.',
26
        'select-format' => 'Set to "separate" (default) or "compact" to determine how select list values are exported.',
27
        'range-type' => 'Range of submissions to export: "all", "new", "latest", "range" (by sid, default if start is supplied), "range-serial", or "range-date".',
28
        'range-latest' => 'Integer specifying the latest X submissions will be downloaded. Used if "range-type" is "latest" or no other range options are provided.',
29
        'range-start' => 'The submission ID, serial number, or start date at which to start exporting.',
30
        'range-end' => 'The submission ID, serial number, or end date at which to end exporting.',
31
        'completion-type' => 'Submissions to be included: "finished", "draft" or "all" (default).',
32
        'batch-size' => 'The size of batches in rows (default 10000). If encountering out of memory errors, set this number lower to export fewer submissions per batch.',
33
      ),
34
      'aliases' => array('wfx'),
35
    ),
36
    'webform-clear' => array(
37
      'description' => 'Clear a webform by deleting all its submissions.',
38
      'arguments' => array(
39
        'nid' => 'The node ID of the webform you want to clear (required)',
40
      ),
41
      'options' => array(
42
        'batch-size' => 'The size of batches in rows (default 10000). If encountering out of memory errors, set this number lower to export fewer submissions per batch.',
43
      ),
44
    ),
45
  );
46
}
47

    
48
/**
49
 * Exports a webform via drush.
50
 *
51
 * This is useful for large data dumps that would otherwise time out due to
52
 * memory consumption.
53
 *
54
 * @param bool|int $nid
55
 *   Node ID of the webform that we want to export.
56
 *
57
 * @return false|null
58
 *   The value returned from drush_set_error() or NULL if that function is not
59
 *   called.
60
 */
61
function drush_webform_export($nid = FALSE) {
62
  if (!$nid) {
63
    return drush_set_error('The node ID of the webform you want to export is required.');
64
  }
65
  $node = node_load($nid);
66
  if (!$node) {
67
    return drush_set_error(dt('Node !nid was not found.', array('!nid' => $nid)));
68
  }
69

    
70
  module_load_include('inc', 'webform', 'includes/webform.submissions');
71
  module_load_include('inc', 'webform', 'includes/webform.export');
72
  module_load_include('inc', 'webform', 'includes/webform.components');
73
  module_load_include('inc', 'webform', 'includes/webform.report');
74

    
75
  // Pull in options from drush to override the defaults.
76
  $format = drush_get_option('format', 'delimited');
77
  $options = webform_results_download_default_options($node, $format);
78
  foreach ($options as $option_name => $option_value) {
79
    $options[$option_name] = drush_get_option(str_replace('_', '-', $option_name), $option_value);
80
  }
81
  $options['components'] = is_array($options['components']) ? $options['components'] : explode(',', $options['components']);
82

    
83
  // Map form keys to cids.
84
  $form_keys = array();
85
  foreach ($node->webform['components'] as $cid => $component) {
86
    $form_keys[$component['form_key']] = $cid;
87
  }
88
  foreach ($options['components'] as $key => &$component) {
89
    if (isset($form_keys[$component])) {
90
      $component = $form_keys[$component];
91
    }
92
  }
93
  // Drop PHP reference.
94
  unset($component);
95

    
96
  // Get the range options.
97
  unset($options['range']['range_type']);
98
  foreach (drush_get_merged_prefixed_options('range-') as $option_name => $option_value) {
99
    if ($option_name == 'type' && in_array($option_value, array('all', 'new', 'latest', 'range', 'range-serial', 'range-date'))) {
100
      $options['range']['range_type'] = str_replace('-', '_', $option_value);
101
    }
102
    elseif (in_array($option_name, array('start', 'end', 'latest')) && is_numeric($option_value)) {
103
      $options['range'][$option_name] = $option_value;
104
    }
105
    elseif (in_array($option_name, array('start', 'end')) && strtotime($option_value)) {
106
      $options['range']['range_type'] = 'range_date';
107
      $options['range'][$option_name . '_date'] = $option_value;
108
    }
109
    else {
110
      return drush_set_error(dt('Unsupported range option or argument: !opt=!val',
111
                                array('!opt' => "range-$option_name", '!val' => $option_value)));
112
    }
113
  }
114

    
115
  // Determine the range type based on provided input, if not explicitly set.
116
  if (empty($options['range']['range_type'])) {
117
    $options['range']['range_type'] = isset($options['range']['start'])
118
      ? 'range'
119
      : (isset($options['range']['latest'])
120
      ? 'latest'
121
      : 'all');
122
  }
123

    
124
  // Set defaults for any missing range arguments.
125
  switch ($options['range']['range_type']) {
126
    case 'latest':
127
      if (empty($options['range']['latest'])) {
128
        drush_log('Argument range-latest defaulted to 100.', 'ok');
129
        $options['range']['latest'] = 100;
130
      }
131
      break;
132

    
133
    case 'range':
134
    case 'range_serial':
135
      if (empty($options['range']['start'])) {
136
        $options['range']['start'] = 1;
137
      }
138
      break;
139

    
140
    case 'range_date':
141
      if (empty($options['range']['start_date'])) {
142
        $options['range']['start_date'] = "1/1/1970";
143
      }
144
      break;
145
  }
146

    
147
  // Get the preferred completion type.
148
  $options['range']['completion_type'] = drush_get_option('completion-type', NULL);
149
  if (isset($options['range']['completion_type']) && !in_array($options['range']['completion_type'], array('finished', 'draft', 'all'))) {
150
    return drush_set_error('Unsupported completion-type. The available options are "finished", "draft", or "all".');
151
  }
152

    
153
  // Set the export options.
154
  $options['range']['batch_size'] = drush_get_option('batch-size', 10000);
155
  $options['file_name'] = drush_get_option('file', tempnam(variable_get('file_directory_temp', file_directory_temp()), 'webform_'));
156

    
157
  $batch = webform_results_export_batch($node, $format, $options);
158
  batch_set($batch);
159
  drush_backend_batch_process();
160

    
161
  // If no filename was specified, print the file and delete it.
162
  if (drush_get_option('file', FALSE) === FALSE) {
163
    // The @ makes it silent.
164
    drush_print(file_get_contents($options['file_name']));
165
    // Clean up, the @ makes it silent.
166
    @unlink($options['file_name']);
167
  }
168
}
169

    
170
/**
171
 * Clears a webform via drush.
172
 *
173
 * This is useful for webforms with many submissions that would otherwise fail
174
 * due to time out due or memory consumption.
175
 *
176
 * @param int $nid
177
 *   Node ID of the webform to clear.
178
 */
179
function drush_webform_clear($nid = FALSE) {
180
  if (!$nid) {
181
    return drush_set_error('The node ID of the webform to be cleared is required.');
182
  }
183
  $node = node_load($nid);
184
  if (!$node) {
185
    return drush_set_error(dt('Node !nid was not found.', array('!nid' => $nid)));
186
  }
187
  if (!drush_confirm(dt('Clear submissions from webform "@title"?', array('@title' => $node->title)))) {
188
    return drush_set_error('webform-clear cancelled.');
189
  }
190

    
191
  // @code
192
  // module_load_include('inc', 'webform', 'includes/webform.submissions');
193
  // module_load_include('inc', 'webform', 'includes/webform.components');
194
  // @endcode
195
  module_load_include('inc', 'webform', 'includes/webform.report');
196

    
197
  // Pull in option from drush to override the default.
198
  $batch_size = drush_get_option('batch-size', 10000);
199
  $count = 0;
200
  while ($deleted = webform_results_clear($nid, $batch_size)) {
201
    $count += $deleted;
202
  }
203
  // Alas, there is no drush version of format_plural, so use the ugly "(s)".
204
  drush_log(dt('@count submission(s) in webform "@title" cleared.', array('@count' => $count, '@title' => $node->title)), 'ok');
205
}
206

    
207
/**
208
 * Implements hook_drush_sql_sync_sanitize().
209
 */
210
function webform_drush_sql_sync_sanitize($source) {
211
  // Fetch list of all table.
212
  $all_tables = drush_sql_get_class()->listTables();
213
  $tables_to_truncate = array('webform_submitted_data', 'webform_submissions');
214

    
215
  $truncate_webform_tables_query = array();
216
  foreach ($tables_to_truncate as $table) {
217
    if (in_array($table, $all_tables, TRUE)) {
218
      $truncate_webform_tables_query[] = 'TRUNCATE ' . $table . ';';
219
    }
220
  }
221

    
222
  drush_sql_register_post_sync_op('webform_submitted_data',
223
    dt('Delete all data submitted to webforms (depending on the site config, may contain sensitive data).'),
224
    implode(' ', $truncate_webform_tables_query));
225
}