Projet

Général

Profil

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

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

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, useful for large data dumps that would otherwise
50
 * time out due to memory consumption.
51
 *
52
 * @param bool|int $nid
53
 *   Node ID of the webform that we want to export.
54
 *
55
 * @return
56
 *   The value returned from drush_set_error().
57
 */
58
function drush_webform_export($nid = FALSE) {
59
  if (!$nid) {
60
    return drush_set_error('The node ID of the webform you want to export is required.');
61
  }
62
  $node = node_load($nid);
63
  if (!$node) {
64
    return drush_set_error(dt('Node !nid was not found.', array('!nid' => $nid)));
65
  }
66

    
67
  module_load_include('inc', 'webform', 'includes/webform.submissions');
68
  module_load_include('inc', 'webform', 'includes/webform.export');
69
  module_load_include('inc', 'webform', 'includes/webform.components');
70
  module_load_include('inc', 'webform', 'includes/webform.report');
71

    
72

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

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

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

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

    
121
  // Set defaults for any missing range arguments.
122
  switch ($options['range']['range_type']) {
123
    case 'latest':
124
      if (empty($options['range']['latest'])) {
125
        drush_log('Argument range-latest defaulted to 100.', 'ok');
126
        $options['range']['latest'] = 100;
127
      }
128
      break;
129
    case 'range':
130
    case 'range_serial':
131
      if (empty($options['range']['start'])) {
132
        $options['range']['start'] = 1;
133
      }
134
      break;
135
    case 'range_date':
136
      if (empty($options['range']['start_date'])) {
137
        $options['range']['start_date'] = "1/1/1970";
138
      }
139
      break;
140
  }
141

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

    
148
  // Set the export options.
149
  $options['range']['batch_size'] = drush_get_option('batch-size', 10000);
150
  $options['file_name'] = drush_get_option('file', tempnam(variable_get('file_directory_temp', file_directory_temp()), 'webform_'));
151

    
152
  $batch = webform_results_export_batch($node, $format, $options);
153
  batch_set($batch);
154
  drush_backend_batch_process();
155

    
156
  // If no filename was specified, print the file and delete it.
157
  if (drush_get_option('file', FALSE) === FALSE) {
158
    drush_print(file_get_contents($options['file_name']));  // The @ makes it silent.
159
    @unlink($options['file_name']);  // Clean up, the @ makes it silent.
160
  }
161
}
162

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

    
182
  //module_load_include('inc', 'webform', 'includes/webform.submissions');
183
  //module_load_include('inc', 'webform', 'includes/webform.components');
184
  module_load_include('inc', 'webform', 'includes/webform.report');
185

    
186

    
187
  // Pull in option from drush to override the default.
188
  $batch_size = drush_get_option('batch-size', 10000);
189
  $count = 0;
190
  while ($deleted = webform_results_clear($nid, $batch_size)) {
191
    $count += $deleted;
192
  }
193
  // Alas, there is no drush version of format_plural, so use the ugly "(s)".
194
  drush_log(dt('@count submission(s) in webform "@title" cleared.', array('@count' => $count, '@title' => $node->title)), 'ok');
195
}
196

    
197
/**
198
 * Implements hook_drush_sql_sync_sanitize().
199
 */
200
function webform_drush_sql_sync_sanitize($source) {
201
  // Fetch list of all table.
202
  $all_tables = drush_sql_get_class()->listTables();
203
  $tables_to_truncate = array('webform_submitted_data', 'webform_submissions');
204

    
205
  $truncate_webform_tables_query = array();
206
  foreach ($tables_to_truncate as $table) {
207
    if (in_array($table, $all_tables, TRUE)) {
208
      $truncate_webform_tables_query[] = 'TRUNCATE ' . $table . ';';
209
    }
210
  }
211

    
212
  drush_sql_register_post_sync_op('webform_submitted_data',
213
    dt('Delete all data submitted to webforms (depending on the site config, may contain sensitive data).'),
214
    implode(' ', $truncate_webform_tables_query));
215
}