views_data_export.drush.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. /**
  3. * Implementation of hook_drush_command().
  4. */
  5. function views_data_export_drush_command() {
  6. $items = array();
  7. $items['views-data-export'] = array (
  8. 'aliases' => array (
  9. 'vde',
  10. ),
  11. 'description' => 'Fully executes a views_data_export display of a view and writes the output to file.',
  12. 'arguments' => array (
  13. 'view_name' => 'The name of the view',
  14. 'display_id' => 'The id of the views_data_export display to execute on the view',
  15. 'output_file' => 'The file to write the results to - will be overwritten if it already exists',
  16. ),
  17. 'options' => array (
  18. '--format' => 'csv,doc,txt,xls or xml. These options are ignored if the display_id passed is a "views_data_export" display.',
  19. '--separator' => 'csv only: What character separates the fields (default:,)',
  20. '--trim-whitespace' => 'csv only: Trim whitespace from either side of fields (default:1)',
  21. '--header-row' => 'csv only: Make the first row a row of headers (default:1)',
  22. '--quote-values' => 'csv only: Surround each field in quotes (default:1)',
  23. ),
  24. 'examples' => array (
  25. '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',
  26. ),
  27. 'drupal dependencies' => array (
  28. 'views_data_export',
  29. ),
  30. 'core' => array('7'),
  31. );
  32. return $items;
  33. }
  34. /**
  35. * Implementation of hook_drush_help().
  36. *
  37. * This function is called whenever a drush user calls
  38. * 'drush help <name-of-your-command>'
  39. *
  40. * @param
  41. * A string with the help section (prepend with 'drush:')
  42. *
  43. * @return
  44. * A string with the help text for your command.
  45. */
  46. function views_data_export_drush_help($section) {
  47. switch ($section) {
  48. case 'drush:views-data-export':
  49. 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.");
  50. }
  51. }
  52. /**
  53. * Implementation of drush_hook_COMMAND_validate().
  54. */
  55. function drush_views_data_export_validate() {
  56. // Because of a bug in the way that Drush 4 computes the name of functions to
  57. // call from a Drush command, we may end up getting called twice, so we just
  58. // don't do anything on subsequent invocations.
  59. static $already_run = FALSE;
  60. if ($already_run) {
  61. return;
  62. }
  63. $already_run = TRUE;
  64. $args = drush_get_arguments();
  65. array_shift($args);
  66. if (count($args) !== 3) {
  67. return drush_set_error('ARGUMENTS_REQUIRED', dt('All arguments are required.'));
  68. }
  69. if (!$view = views_get_view($args[0])) {
  70. return drush_set_error('VIEW_DOES_NOT_EXIST', dt('The view !view does not exist.', array ('!view' => $args[0])));
  71. }
  72. if (!$view->set_display($args[1])) {
  73. 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])));
  74. }
  75. else {
  76. if ($view->current_display != $args[1]) {
  77. drush_log(dt('Using different display from specified display: @display', array('@display' => $view->current_display)), 'notice');
  78. }
  79. drush_set_option('views_data_export_display_id', $view->current_display);
  80. }
  81. $format = drush_get_option('format');
  82. $valid_formats = array('csv', 'doc', 'txt', 'xls', 'xml');
  83. if (!empty($format) && !in_array($format, $valid_formats)) {
  84. 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))));
  85. }
  86. }
  87. /**
  88. * Drush command callback to export a views data to a file.
  89. *
  90. * @see drush_views_data_export_validate().
  91. * @see views_data_export_views_data_export_batch_alter().
  92. */
  93. function drush_views_data_export($view_name, $display_id, $output_file) {
  94. // Because of a bug in the way that Drush 4 computes the name of functions to
  95. // call from a Drush command, we may end up getting called twice, so we just
  96. // don't do anything on subsequent invocations.
  97. static $already_run = FALSE;
  98. if ($already_run) {
  99. return;
  100. }
  101. $already_run = TRUE;
  102. // Set the display to the one that we computed earlier.
  103. $display_id = drush_get_option('views_data_export_display_id', 'default');
  104. $view = views_get_view($view_name);
  105. // If the given display_id is not views_data_alter then
  106. // we programatically clone it to a views_data_alter display
  107. // and then execute that one instead
  108. if ($view->display[$display_id]->display_plugin != 'views_data_export') {
  109. //drush_log("Display '$display_id' is not views_data_export. Making one that is and executing that instead =).", 'success');
  110. $format = drush_get_option('format');
  111. $settings = array();
  112. switch ($format) {
  113. case 'doc':
  114. case 'xls':
  115. case 'xml':
  116. case 'txt':
  117. $settings['display_options']['style_plugin'] = 'views_data_export_' . $format;
  118. break;
  119. case 'csv':
  120. default:
  121. $settings['display_options']['style_plugin'] = 'views_data_export_csv';
  122. if ($separator = drush_get_option('separator')) {
  123. $settings['display_options']['style_options']['separator'] = $separator;
  124. }
  125. if (!$trim = drush_get_option('trim-whitespace')) {
  126. $settings['display_options']['style_options']['trim'] = 0;
  127. }
  128. if (!$header = drush_get_option('header-row')) {
  129. $settings['display_options']['style_options']['header'] = 0;
  130. }
  131. if (!$quote = drush_get_option('quote-values')) {
  132. $settings['display_options']['style_options']['quote'] = 0;
  133. }
  134. // Seperator
  135. }
  136. $display_id = _drush_views_data_export_clone_display($view, $display_id, $settings);
  137. }
  138. $view->set_display($display_id);
  139. // We execute the view normally, and take advantage
  140. // of an alter function to interject later and batch it ourselves
  141. $options = array (
  142. 'output_file' => realpath(drush_get_context('DRUSH_OLDCWD', getcwd())) . '/' . $output_file,
  143. );
  144. _drush_views_data_export_override_batch($view_name, $display_id, $options);
  145. $view->execute_display($display_id);
  146. }
  147. /**
  148. * Helper function that indicates that we want to
  149. * override the batch that the views_data_export view creates
  150. * on it's initial time through.
  151. *
  152. * Also provides a place to stash options that need to stay around
  153. * until the end of the batch
  154. */
  155. function _drush_views_data_export_override_batch($view = NULL, $display = NULL, $options = TRUE) {
  156. static $_views;
  157. if (isset($view)) {
  158. $_views[$view][$display] = $options;
  159. }
  160. return $_views;
  161. }
  162. /**
  163. * Implementation of hook_views_data_export_batch_alter()
  164. */
  165. function views_data_export_views_data_export_batch_alter(&$batch, &$final_destination, &$querystring) {
  166. // Copy the batch, because we're going to monkey with it, a lot!
  167. $new_batch = $batch;
  168. $view_name = $new_batch['view_name'];
  169. $display_id = $new_batch['display_id'];
  170. $ok_to_override = _drush_views_data_export_override_batch();
  171. // Make sure we do nothing if we are called not following the execution of
  172. // our drush command. This could happen if the file with this function in it
  173. // is included during the normal execution of the view
  174. if (!$ok_to_override[$view_name][$display_id]) {
  175. return;
  176. }
  177. $options = $ok_to_override[$view_name][$display_id];
  178. // We actually never return from the drupal_alter, but
  179. // use drush's batch system to run the same batch
  180. // Add a final callback
  181. $new_batch['operations'][] = array(
  182. '_drush_views_data_export_batch_finished', array($batch['eid'], $options['output_file']),
  183. );
  184. batch_set($new_batch);
  185. $new_batch =& batch_get();
  186. // Drush handles the different processes, so instruct BatchAPI not to.
  187. $new_batch['progressive'] = FALSE;
  188. // Process the batch using drush.
  189. drush_backend_batch_process();
  190. // Instruct the view display plugin that it shouldn't set a batch.
  191. $batch = array();
  192. }
  193. /**
  194. * Get's called at the end of the drush batch process that generated our export
  195. */
  196. function _drush_views_data_export_batch_finished($eid, $output_file, &$context) {
  197. // Fetch export info
  198. $export = views_data_export_get($eid);
  199. // Perform cleanup
  200. $view = views_data_export_view_retrieve($eid);
  201. $view->set_display($export->view_display_id);
  202. $view->display_handler->batched_execution_state = $export;
  203. $view->display_handler->remove_index();
  204. // Get path to temp file
  205. $temp_file = $view->display_handler->outputfile_path();
  206. // Copy file over
  207. if (@drush_op('copy', $temp_file, $output_file)) {
  208. drush_log("Data export saved to " . $output_file, 'success');
  209. }
  210. else {
  211. drush_set_error('VIEWS_DATA_EXPORT_COPY_ERROR', dt("The file could not be copied to the selected destination"));
  212. }
  213. }
  214. /**
  215. * Helper function that takes a view and returns a clone of it
  216. * that has cloned a given display to one of type views_data_export
  217. *
  218. * @param &$view
  219. * Modified to contain the new display
  220. *
  221. * @return
  222. * The new display_id
  223. */
  224. function _drush_views_data_export_clone_display(&$view, $display_id, $settings = array()) {
  225. // Create the new display
  226. $new_display_id = _drush_views_data_export_generate_display_id($view, 'views_data_export');
  227. $view->display[$new_display_id] = clone $view->display[$display_id];
  228. // Ensure we have settings we'll need for our display
  229. $default_settings = array (
  230. 'id' => $new_display_id,
  231. 'display_plugin' => 'views_data_export',
  232. 'position' => 99,
  233. 'display_options' => array (
  234. 'style_plugin' => 'views_data_export_csv',
  235. 'style_options' => array(
  236. 'attach_text' => 'CSV',
  237. 'provide_file' => 1,
  238. 'filename' => 'view-%view.csv',
  239. 'parent_sort' => 1,
  240. 'separator' => ',',
  241. 'quote' => 1,
  242. 'trim' => 1,
  243. 'header' => 1,
  244. ),
  245. 'use_batch' => 'batch',
  246. 'path' => '',
  247. 'displays' => array (
  248. 'default' => 'default',
  249. ),
  250. ),
  251. );
  252. $settings = array_replace_recursive($default_settings, $settings);
  253. $view->display[$new_display_id] = (object)array_replace_recursive((array)$view->display[$new_display_id], $settings);
  254. return $new_display_id;
  255. }
  256. /**
  257. * Generate a display id of a certain plugin type.
  258. * See http://drupal.org/files/issues/348975-clone-display.patch
  259. *
  260. * @param $type
  261. * Which plugin should be used for the new display id.
  262. */
  263. function _drush_views_data_export_generate_display_id($view, $type) {
  264. // 'default' is singular and is unique, so just go with 'default'
  265. // for it. For all others, start counting.
  266. if ($type == 'default') {
  267. return 'default';
  268. }
  269. // Initial id.
  270. $id = $type . '_1';
  271. $count = 1;
  272. // Loop through IDs based upon our style plugin name until
  273. // we find one that is unused.
  274. while (!empty($view->display[$id])) {
  275. $id = $type . '_' . ++$count;
  276. }
  277. return $id;
  278. }
  279. /**
  280. * If we're using PHP < 5.3.0 then we'll need
  281. * to define this function ourselves.
  282. * See: http://phpmyanmar.com/phpcodes/manual/function.array-replace-recursive.php
  283. */
  284. if (!function_exists('array_replace_recursive')) {
  285. function array_replace_recursive($array, $array1) {
  286. // Get array arguments
  287. $arrays = func_get_args();
  288. // Define the original array
  289. $original = array_shift($arrays);
  290. // Loop through arrays
  291. foreach ($arrays as $array) {
  292. // Loop through array key/value pairs
  293. foreach ($array as $key => $value) {
  294. // Value is an array
  295. if (is_array($value)) {
  296. // Traverse the array; replace or add result to original array
  297. $original[$key] = array_replace_recursive($original[$key], $array[$key]);
  298. }
  299. // Value is not an array
  300. else {
  301. // Replace or add current value to original array
  302. $original[$key] = $value;
  303. }
  304. }
  305. }
  306. // Return the joined array
  307. return $original;
  308. }
  309. }