Projet

Général

Profil

Paste
Télécharger (12,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views_data_export / views_data_export.drush.inc @ 74f6bef0

1
<?php
2

    
3
/**
4
 * Implementation of hook_drush_command().
5
 */
6
function views_data_export_drush_command() {
7
  $items = array();
8

    
9
  $items['views-data-export'] = array (
10
    'aliases' => array (
11
      'vde',
12
    ),
13
    'description' => 'Fully executes a views_data_export display of a view and writes the output to file.',
14
    'arguments' => array (
15
      'view_name' => 'The name of the view',
16
      'display_id' => 'The id of the views_data_export display to execute on the view',
17
      'output_file' => 'The file to write the results to - will be overwritten if it already exists',
18
    ),
19
    'options' => array (
20
      '--arguments' => 'Comma separated list of arguments to be passed to the view.',
21
      '--format' => 'csv,doc,txt,xls or xml. These options are ignored if the display_id passed is a "views_data_export" display.',
22
      '--separator' => 'csv only: What character separates the fields (default:,)',
23
      '--trim-whitespace' => 'csv only: Trim whitespace from either side of fields (default:1)',
24
      '--header-row' => 'csv only: Make the first row a row of headers (default:1)',
25
      '--quote-values' => 'csv only: Surround each field in quotes (default:1)',
26
    ),
27
    'examples' => array (
28
      'drush views-data-export myviewname views_data_export_1 output.csv' => 'Export myviewname:views_data_export_1 and write the output to output.csv in the current directory',
29
    ),
30
    'drupal dependencies' => array (
31
      'views_data_export',
32
    ),
33
    'core' => array('7'),
34
  );
35

    
36
  return $items;
37
}
38

    
39

    
40
/**
41
 * Implementation of hook_drush_help().
42
 *
43
 * This function is called whenever a drush user calls
44
 * 'drush help <name-of-your-command>'
45
 *
46
 * @param
47
 *   A string with the help section (prepend with 'drush:')
48
 *
49
 * @return
50
 *   A string with the help text for your command.
51
 */
52
function views_data_export_drush_help($section) {
53
  switch ($section) {
54
    case 'drush:views-data-export':
55
      return dt("This command may be used to fully execute a views_data_export display of a view, batched if need be, and write the output to a file.");
56
  }
57
}
58

    
59
/**
60
 * Implementation of drush_hook_COMMAND_validate().
61
 */
62
function drush_views_data_export_validate() {
63
  // Because of a bug in the way that Drush 4 computes the name of functions to
64
  // call from a Drush command, we may end up getting called twice, so we just
65
  // don't do anything on subsequent invocations.
66
  static $already_run = FALSE;
67
  if ($already_run) {
68
    return;
69
  }
70
  $already_run = TRUE;
71

    
72
  $args = drush_get_arguments();
73
  array_shift($args);
74

    
75
  if (count($args) !== 3) {
76
    return drush_set_error('ARGUMENTS_REQUIRED', dt('All arguments are required.'));
77
  }
78

    
79
  if (!$view = views_get_view($args[0])) {
80
    return drush_set_error('VIEW_DOES_NOT_EXIST', dt('The view !view does not exist.', array ('!view' => $args[0])));
81
  }
82

    
83
  if (!$view->set_display($args[1])) {
84
    return drush_set_error('VIEW_DOES_NOT_EXIST', dt('The view !view does not have the !display display.', array ('!view' => $args[0], '!display' => $args[1])));
85
  }
86
  else {
87
    if ($view->current_display != $args[1]) {
88
      drush_log(dt('Using different display from specified display: @display', array('@display' => $view->current_display)), 'notice');
89
    }
90
    drush_set_option('views_data_export_display_id', $view->current_display);
91
  }
92

    
93
  $format = drush_get_option('format');
94
  $valid_formats = array('csv', 'doc', 'txt', 'xls', 'xml');
95
  if (!empty($format) && !in_array($format, $valid_formats)) {
96
    return drush_set_error('VIEWS_DATA_EXPORT_INVALID_OPTION', dt('The "--format" option is invalid, please supply one of the following: !formats', array('!formats' => implode(', ', $valid_formats))));
97
  }
98
}
99

    
100
/**
101
 * Drush command callback to export a views data to a file.
102
 *
103
 * @see drush_views_data_export_validate().
104
 * @see views_data_export_views_data_export_batch_alter().
105
 */
106
function drush_views_data_export($view_name, $display_id, $output_file) {
107
  // Because of a bug in the way that Drush 4 computes the name of functions to
108
  // call from a Drush command, we may end up getting called twice, so we just
109
  // don't do anything on subsequent invocations.
110
  static $already_run = FALSE;
111
  if ($already_run) {
112
    return;
113
  }
114
  $already_run = TRUE;
115

    
116
  // Set the display to the one that we computed earlier.
117
  $display_id = drush_get_option('views_data_export_display_id', 'default');
118

    
119
  $view = views_get_view($view_name);
120

    
121
  // If the given display_id is not views_data_alter then
122
  // we programatically clone it to a views_data_alter display
123
  // and then execute that one instead
124
  if ($view->display[$display_id]->display_plugin != 'views_data_export') {
125
    //drush_log("Display '$display_id' is not views_data_export. Making one that is and executing that instead =).", 'success');
126

    
127
    $format = drush_get_option('format');
128
    $settings = array();
129
    switch ($format) {
130
      case 'doc':
131
      case 'xls':
132
      case 'xml':
133
      case 'txt':
134
        $settings['display_options']['style_plugin'] = 'views_data_export_' . $format;
135
        break;
136
      case 'csv':
137
      default:
138
      $settings['display_options']['style_plugin'] = 'views_data_export_csv';
139
      if ($separator = drush_get_option('separator')) {
140
        $settings['display_options']['style_options']['separator'] = $separator;
141
      }
142
      if (!$trim = drush_get_option('trim-whitespace')) {
143
        $settings['display_options']['style_options']['trim'] = 0;
144
      }
145
      if (!$header = drush_get_option('header-row')) {
146
        $settings['display_options']['style_options']['header'] = 0;
147
      }
148
      if (!$quote = drush_get_option('quote-values')) {
149
        $settings['display_options']['style_options']['quote'] = 0;
150
      }
151
      // Seperator
152
    }
153

    
154
    $display_id = _drush_views_data_export_clone_display($view, $display_id, $settings);
155
  }
156

    
157
  $view->set_display($display_id);
158

    
159
  // We execute the view normally, and take advantage
160
  // of an alter function to interject later and batch it ourselves
161

    
162
  $options = array (
163
    'output_file' => realpath(drush_get_context('DRUSH_OLDCWD', getcwd())) . '/' . $output_file,
164
  );
165
  if ($view->display_handler->is_batched()) {
166
    // This is a batched export, and needs to be handled as such.
167
    _drush_views_data_export_override_batch($view_name, $display_id, $options);
168

    
169
    $arguments = drush_get_option('arguments', '');
170
    $arguments = explode(',', $arguments);
171
    $view->execute_display($display_id, $arguments);
172
  }
173
  else {
174
    // This export isn't batched.
175
    ob_start();
176
    $view->execute_display($display_id);
177
    // Get the results, and clean the output buffer.
178
    $result = ob_get_contents();
179
    // Clean the buffer.
180
    ob_end_clean();
181
    // Save the results to file.
182
    // Copy file over
183
    if (file_put_contents($options['output_file'], $result)) {
184
      drush_log("Data export saved to " . $options['output_file'], 'success');
185
    }
186
    else {
187
      drush_set_error('VIEWS_DATA_EXPORT_COPY_ERROR', dt("The file could not be copied to the selected destination"));
188
    }
189
  }
190

    
191
}
192

    
193

    
194
/**
195
 * Helper function that indicates that we want to
196
 * override the batch that the views_data_export view creates
197
 * on it's initial time through.
198
 *
199
 * Also provides a place to stash options that need to stay around
200
 * until the end of the batch
201
 */
202
function _drush_views_data_export_override_batch($view = NULL, $display = NULL, $options = TRUE) {
203
  static $_views;
204
  if (isset($view)) {
205
    $_views[$view][$display] = $options;
206
  }
207
  return $_views;
208
}
209

    
210
/**
211
 * Implementation of hook_views_data_export_batch_alter()
212
 */
213
function views_data_export_views_data_export_batch_alter(&$batch, &$final_destination, &$querystring) {
214

    
215
  // Copy the batch, because we're going to monkey with it, a lot!
216
  $new_batch = $batch;
217

    
218
  $view_name = $new_batch['view_name'];
219
  $display_id = $new_batch['display_id'];
220

    
221
  $ok_to_override = _drush_views_data_export_override_batch();
222

    
223
  // Make sure we do nothing if we are called not following the execution of
224
  // our drush command. This could happen if the file with this function in it
225
  // is included during the normal execution of the view
226
  if (!$ok_to_override[$view_name][$display_id]) {
227
    return;
228
  }
229

    
230
  $options = $ok_to_override[$view_name][$display_id];
231

    
232
  // We actually never return from the drupal_alter, but
233
  // use drush's batch system to run the same batch
234

    
235
  // Add a final callback
236
  $new_batch['operations'][] = array(
237
    '_drush_views_data_export_batch_finished', array($batch['eid'], $options['output_file']),
238
  );
239

    
240
  batch_set($new_batch);
241
  $new_batch =& batch_get();
242
  // Drush handles the different processes, so instruct BatchAPI not to.
243
  $new_batch['progressive'] = FALSE;
244
  // Process the batch using drush.
245
  drush_backend_batch_process();
246

    
247
  // Instruct the view display plugin that it shouldn't set a batch.
248
  $batch = array();
249
}
250

    
251

    
252
/**
253
 * Get's called at the end of the drush batch process that generated our export
254
 */
255
function _drush_views_data_export_batch_finished($eid, $output_file, &$context) {
256
  // Fetch export info
257
  $export = views_data_export_get($eid);
258

    
259
  // Perform cleanup
260
  $view = views_data_export_view_retrieve($eid);
261
  $view->set_display($export->view_display_id);
262
  $view->display_handler->batched_execution_state = $export;
263
  $view->display_handler->remove_index();
264

    
265
  // Get path to temp file
266
  $temp_file = $view->display_handler->outputfile_path();
267

    
268
  // Copy file over
269
  if (@drush_op('copy', $temp_file, $output_file)) {
270
    drush_log("Data export saved to " . $output_file, 'success');
271
  }
272
  else {
273
    drush_set_error('VIEWS_DATA_EXPORT_COPY_ERROR', dt("The file could not be copied to the selected destination"));
274
  }
275

    
276
}
277

    
278

    
279
/**
280
 * Helper function that takes a view and returns a clone of it
281
 * that has cloned a given display to one of type views_data_export
282
 *
283
 * @param &$view
284
 *   Modified to contain the new display
285
 *
286
 * @return
287
 *   The new display_id
288
 */
289
function _drush_views_data_export_clone_display(&$view, $display_id, $settings = array()) {
290

    
291
  // Create the new display
292
  $new_display_id = _drush_views_data_export_generate_display_id($view, 'views_data_export');
293
  $view->display[$new_display_id] = clone $view->display[$display_id];
294

    
295
  // Ensure we have settings we'll need for our display
296
  $default_settings = array (
297
    'id' => $new_display_id,
298
    'display_plugin' => 'views_data_export',
299
    'position' => 99,
300
    'display_options' => array (
301
      'style_plugin' => 'views_data_export_csv',
302
      'style_options' => array(
303
        'attach_text' => 'CSV',
304
        'provide_file' => 1,
305
        'filename' => 'view-%view.csv',
306
        'parent_sort' => 1,
307
        'separator' => ',',
308
        'quote' => 1,
309
        'trim' => 1,
310
        'header' => 1,
311
      ),
312
      'use_batch' => 'batch',
313
      'path' => '',
314
      'displays' => array (
315
        'default' => 'default',
316
      ),
317
    ),
318
  );
319
  $settings = array_replace_recursive($default_settings, $settings);
320

    
321
  $view->display[$new_display_id] = (object)array_replace_recursive((array)$view->display[$new_display_id], $settings);
322

    
323
  return $new_display_id;
324
}
325

    
326

    
327
/**
328
 * Generate a display id of a certain plugin type.
329
 * See http://drupal.org/files/issues/348975-clone-display.patch
330
 *
331
 * @param $type
332
 *   Which plugin should be used for the new display id.
333
 */
334
function _drush_views_data_export_generate_display_id($view, $type) {
335
  // 'default' is singular and is unique, so just go with 'default'
336
  // for it. For all others, start counting.
337
  if ($type == 'default') {
338
    return 'default';
339
  }
340
  // Initial id.
341
  $id = $type . '_1';
342
  $count = 1;
343

    
344
  // Loop through IDs based upon our style plugin name until
345
  // we find one that is unused.
346
  while (!empty($view->display[$id])) {
347
    $id = $type . '_' . ++$count;
348
  }
349

    
350
  return $id;
351
}
352

    
353
/**
354
 * If we're using PHP < 5.3.0 then we'll need
355
 * to define this function ourselves.
356
 * See: http://phpmyanmar.com/phpcodes/manual/function.array-replace-recursive.php
357
 */
358
if (!function_exists('array_replace_recursive')) {
359
function array_replace_recursive($array, $array1) {
360
  // Get array arguments
361
  $arrays = func_get_args();
362

    
363
  // Define the original array
364
  $original = array_shift($arrays);
365

    
366
  // Loop through arrays
367
  foreach ($arrays as $array) {
368
    // Loop through array key/value pairs
369
    foreach ($array as $key => $value) {
370
      // Value is an array
371
      if (is_array($value)) {
372
        // Traverse the array; replace or add result to original array
373
        $original[$key] = array_replace_recursive($original[$key], $array[$key]);
374
      }
375

    
376
      // Value is not an array
377
      else {
378
        // Replace or add current value to original array
379
        $original[$key] = $value;
380
      }
381
    }
382
  }
383

    
384
  // Return the joined array
385
  return $original;
386
}
387
}