views_data_export.drush.inc 13 KB

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