ctools.drush.inc 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. <?php
  2. /**
  3. * @file
  4. * CTools Drush commands.
  5. */
  6. /**
  7. * Implements hook_drush_command().
  8. */
  9. function ctools_drush_command() {
  10. $items = array();
  11. $module_text = 'Filter the list of exportables by module. This will come from the \'export_module\' key on the exportable.';
  12. $all_text = 'Perform this operation all CTools exportables available on the system (all tables).';
  13. $items['ctools-export'] = array(
  14. 'aliases' => array('ctex'),
  15. 'callback' => 'ctools_drush_export',
  16. 'description' => 'Export multiple CTools exportable objects directly to code.',
  17. 'arguments' => array(
  18. 'module' => 'Name of your module.',
  19. ),
  20. 'options' => array(
  21. 'subdir' => 'The name of the sub directory to create the module in. Defaults to ctools_export which will be placed into sites/all/modules.',
  22. 'remove' => 'Remove existing files before writing, except the .module file.',
  23. 'filter' => 'Filter the list of exportables by status. Available options are enabled, disabled, overridden, database, code and all. Defaults to enabled.',
  24. 'tables' => 'Comma separated list of exportable table names to filter by.',
  25. ),
  26. 'examples' => array(
  27. 'drush ctex export_module' => 'Export CTools exportables to a module called "export_module".',
  28. 'drush ctex export_module --subdir=exports' => 'Same as above, but into the sites/all/modules/exports directory.',
  29. 'drush ctex export_module --subdir=exports --remove' => 'Same as above, but automatically removing all files, except for the .module file.',
  30. 'drush ctex --filter="views_view"' => 'Filter export selection to the views_view table only.',
  31. ),
  32. );
  33. $items['ctools-export-info'] = array(
  34. 'aliases' => array('ctei'),
  35. 'callback' => 'ctools_drush_export_info',
  36. 'description' => 'Show available CTools exportable objects.',
  37. 'arguments' => array(),
  38. 'options' => array(
  39. 'format' => 'Display exportables info in a different format such as print_r, json, export. The default is to show in a tabular format.',
  40. 'tables-only' => 'Only show list of exportable types/table names and not available objects.',
  41. 'filter' => 'Filter the list of exportables by status. Available options are enabled, disabled, overridden, database, and code.',
  42. 'module' => $module_text,
  43. ),
  44. 'examples' => array(
  45. 'drush ctools-export-info' => 'View export info on all exportables.',
  46. 'drush ctools-export-info views_view variable' => 'View export info for views_view and variable exportable types only.',
  47. 'drush ctei --filter=enabled' => 'Show all enabled exportables.',
  48. 'drush ctei views_view --filter=disabled' => 'Show all enabled exportables.',
  49. 'drush ctei views_view --module=node' => 'Show all exportables provided by/on behalf of the node module.',
  50. ),
  51. );
  52. $items['ctools-export-view'] = array(
  53. 'aliases' => array('ctev'),
  54. 'callback' => 'ctools_drush_export_op_command',
  55. 'description' => 'View CTools exportable object code output.',
  56. 'arguments' => array(
  57. 'table name' => 'Base table of the exportable you want to view.',
  58. 'machine names' => 'Space separated list of exportables you want to view.',
  59. ),
  60. 'options' => array(
  61. 'indent' => 'The string to use for indentation when displaying the exportable export code. Defaults to \'\'.',
  62. 'no-colour' => 'Remove any colour formatting from export string output. Ideal if you are sending the output of this command to a file.',
  63. 'module' => $module_text,
  64. 'all' => $all_text,
  65. ),
  66. 'examples' => array(
  67. 'drush ctools-export-view views_view' => 'View all views exportable objects.',
  68. 'drush ctools-export-view views_view archive' => 'View default views archive view.',
  69. ),
  70. );
  71. $items['ctools-export-revert'] = array(
  72. 'aliases' => array('cter'),
  73. 'callback' => 'ctools_drush_export_op_command',
  74. 'description' => 'Revert CTools exportables from changes overridden in the database.',
  75. 'arguments' => array(
  76. 'table name' => 'Base table of the exportable you want to revert.',
  77. 'machine names' => 'Space separated list of exportables you want to revert.',
  78. ),
  79. 'options' => array(
  80. 'module' => $module_text,
  81. 'all' => $all_text,
  82. ),
  83. 'examples' => array(
  84. 'drush ctools-export-revert views_view' => 'Revert all overridden views exportable objects.',
  85. 'drush ctools-export-revert views_view archive' => 'Revert overridden default views archive view.',
  86. 'drush ctools-export-revert --all' => 'Revert all exportables on the system.',
  87. ),
  88. );
  89. $items['ctools-export-enable'] = array(
  90. 'aliases' => array('ctee'),
  91. 'callback' => 'ctools_drush_export_op_command',
  92. 'description' => 'Enable CTools exportables.',
  93. 'arguments' => array(
  94. 'table name' => 'Base table of the exportable you want to enable.',
  95. 'machine names' => 'Space separated list of exportables you want to enable.',
  96. ),
  97. 'options' => array(
  98. 'module' => $module_text,
  99. 'all' => $all_text,
  100. ),
  101. 'examples' => array(
  102. 'drush ctools-export-enable views_view' => 'Enable all overridden views exportable objects.',
  103. 'drush ctools-export-enable views_view archive' => 'Enable overridden default views archive view.',
  104. ),
  105. );
  106. $items['ctools-export-disable'] = array(
  107. 'aliases' => array('cted'),
  108. 'callback' => 'ctools_drush_export_op_command',
  109. 'description' => 'Disable CTools exportables.',
  110. 'arguments' => array(
  111. 'table name' => 'Base table of the exportable you want to disable.',
  112. 'machine names' => 'Space separated list of exportables you want to disable.',
  113. ),
  114. 'options' => array(
  115. 'module' => $module_text,
  116. 'all' => $all_text,
  117. ),
  118. 'examples' => array(
  119. 'drush ctools-export-disable views_view' => 'Disable all overridden views exportable objects.',
  120. 'drush ctools-export-disable views_view archive' => 'Disable overridden default views archive view.',
  121. ),
  122. );
  123. return $items;
  124. }
  125. /**
  126. * Implementation of hook_drush_help().
  127. */
  128. function ctools_drush_help($section) {
  129. switch ($section) {
  130. case 'meta:ctools:title':
  131. return dt('CTools commands');
  132. case 'meta:entity:summary':
  133. return dt('CTools drush commands.');
  134. }
  135. }
  136. /**
  137. * Drush callback: export.
  138. */
  139. function ctools_drush_export($module = 'foo') {
  140. $error = FALSE;
  141. if (preg_match('@[^a-z_]+@', $module)) {
  142. $error = dt('The name of the module must contain only lowercase letters and underscores') . '.';
  143. drush_log($error, 'error');
  144. return;
  145. }
  146. // Filter by tables.
  147. $tables = _ctools_drush_explode_options('tables');
  148. // Check status.
  149. $filter = drush_get_option('filter', FALSE);
  150. if (empty($filter)) {
  151. drush_set_option('filter', 'enabled');
  152. }
  153. // Selection.
  154. $options = array('all' => dt('Export everything'), 'select' => dt('Make selection'));
  155. $selection = drush_choice($options, dt('Select to proceed'));
  156. if (!$selection) {
  157. return;
  158. }
  159. // Present the selection screens.
  160. if ($selection == 'select') {
  161. $selections = _ctools_drush_selection_screen($tables);
  162. }
  163. else {
  164. $info = _ctools_drush_export_info($tables, TRUE);
  165. $selections = $info['exportables'];
  166. }
  167. // Subdirectory.
  168. $dest_exists = FALSE;
  169. $subdir = drush_get_option('subdir', 'ctools_export');
  170. $dest = 'sites/all/modules/' . $subdir . '/' . $module;
  171. // Overwriting files can be set with 'remove' argument.
  172. $remove = drush_get_option('remove', FALSE);
  173. // Check if folder exists.
  174. if (file_exists($dest)) {
  175. $dest_exists = TRUE;
  176. if ($remove) {
  177. if (drush_confirm(dt('All files except for the .info and .module files in !module will be removed. You can choose later if you want to overwrite these files as well. Are you sure you want to proceed ?', array('!module' => $module)))) {
  178. $remove = TRUE;
  179. drush_log(dt('Files will be removed'), 'success');
  180. }
  181. else {
  182. drush_log(dt('Export aborted.'), 'success');
  183. return;
  184. }
  185. }
  186. }
  187. // Remove files (except for the .module file) if the destination folder exists.
  188. if ($remove && $dest_exists) {
  189. _ctools_drush_file_delete($dest);
  190. }
  191. // Create new dir if needed.
  192. if (!$dest_exists) {
  193. if (!file_exists('sites/all/modules/' . $subdir)) {
  194. drush_mkdir('sites/all/modules/' . $subdir);
  195. }
  196. }
  197. // Create destination directory.
  198. drush_mkdir($dest);
  199. // Load bulk export module.
  200. module_load_include('module', 'bulk_export');
  201. // Create options and call Bulk export function.
  202. // We create an array, because maybe in the future we can pass in more
  203. // options to the export function (pre-selected modules and/or exportables).
  204. $options = array(
  205. 'name' => $module,
  206. 'selections' => $selections,
  207. );
  208. $files = bulk_export_export(TRUE, $options);
  209. $alter = array(
  210. 'module' => $module,
  211. 'files' => $files,
  212. );
  213. // Let other drush commands alter the files.
  214. drush_command_invoke_all_ref('drush_ctex_files_alter', $alter);
  215. $files = $alter['files'];
  216. // Start writing.
  217. if (is_array($files)) {
  218. foreach ($files as $base_file => $data) {
  219. $filename = $dest . '/' . $base_file;
  220. // Extra check for .module file.
  221. if ($base_file == ($module . '.module' || $module . '.info') && file_exists($filename)) {
  222. if (!drush_confirm(dt('Do you want to overwrite !module_file', array('!module_file' => $base_file)))) {
  223. drush_log(dt('Writing of !filename skipped. This is the code that was supposed to be written:', array('!filename' => $filename)), 'success');
  224. drush_print('---------');
  225. drush_print(shellColours::getColouredOutput("\n$data", 'light_green'));
  226. drush_print('---------');
  227. continue;
  228. }
  229. }
  230. if (file_put_contents($filename, $data)) {
  231. drush_log(dt('Succesfully written !filename', array('!filename' => $filename)), 'success');
  232. }
  233. else {
  234. drush_log(dt('Error writing !filename', array('!filename' => $filename)), 'error');
  235. }
  236. }
  237. }
  238. else {
  239. drush_log(dt('No files were found to be written.'), 'error');
  240. }
  241. }
  242. /**
  243. * Helper function to select the exportables. By default, all exportables
  244. * will be selected, so it will be easier to deselect them.
  245. *
  246. * @param $tables
  247. */
  248. function _ctools_drush_selection_screen(array $tables = array()) {
  249. $selections = $build = array();
  250. $files = system_rebuild_module_data();
  251. $selection_number = 0;
  252. $info = _ctools_drush_export_info($tables, TRUE);
  253. $exportables = $info['exportables'];
  254. $schemas = $info['schemas'];
  255. $export_tables = array();
  256. foreach (array_keys($exportables) as $table) {
  257. natcasesort($exportables[$table]);
  258. $export_tables[$table] = $files[$schemas[$table]['module']]->info['name'] . ' (' . $table . ')';
  259. }
  260. foreach ($export_tables as $table => $table_title) {
  261. if (!empty($exportables[$table])) {
  262. $table_count = count($exportables[$table]);
  263. $selection_number += $table_count;
  264. foreach ($exportables[$table] as $key => $title) {
  265. $build[$table]['title'] = $table_title;
  266. $build[$table]['items'][$key] = $title;
  267. $build[$table]['count'] = $table_count;
  268. $selections[$table][$key] = $key;
  269. }
  270. }
  271. }
  272. drush_print(dt('Number of exportables selected: !number', array('!number' => $selection_number)));
  273. drush_print(dt('By default all exportables are selected. Select a table to deselect exportables. Select "cancel" to start writing the files.'));
  274. // Let's go into a loop.
  275. $return = FALSE;
  276. while (!$return) {
  277. // Present the tables choice.
  278. $table_rows = array();
  279. foreach ($build as $table => $info) {
  280. $table_rows[$table] = $info['title'] . ' (' . $info['count'] . ')';
  281. }
  282. $table_choice = drush_choice($table_rows, dt('Select a table. Select cancel to start writing files.'));
  283. // Bail out.
  284. if (!$table_choice) {
  285. drush_log(dt('Selection mode done, starting to write the files.'), 'notice');
  286. $return = TRUE;
  287. return $selections;
  288. }
  289. // Present the exportables choice, using the drush_choice_multiple.
  290. $max = count($build[$table_choice]['items']);
  291. $exportable_rows = array();
  292. foreach ($build[$table_choice]['items'] as $key => $title) {
  293. $exportable_rows[$key] = $title;
  294. }
  295. drush_print(dt('Exportables from !table', array('!table' => $build[$table_choice]['title'])));
  296. $multi_select = drush_choice_multiple($exportable_rows, $selections[$table_choice], dt('Select exportables.'), '!value', '!value (selected)', 0, $max);
  297. // Update selections.
  298. if (is_array($multi_select)) {
  299. $build[$table_choice]['count'] = count($multi_select);
  300. $selections[$table_choice] = array();
  301. foreach ($multi_select as $key) {
  302. $selections[$table_choice][$key] = $key;
  303. }
  304. }
  305. }
  306. }
  307. /**
  308. * Delete files in a directory, keeping the .module and .info files.
  309. *
  310. * @param $path
  311. * Path to directory in which to remove files.
  312. */
  313. function _ctools_drush_file_delete($path) {
  314. if (is_dir($path)) {
  315. $files = new DirectoryIterator($path);
  316. foreach ($files as $fileInfo) {
  317. if (!$fileInfo->isDot() && !in_array($fileInfo->getExtension(), array('module', 'info'))) {
  318. unlink($fileInfo->getPathname());
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * Drush callback: Export info.
  325. *
  326. * @params $table_names
  327. * Each argument will be taken as a CTools exportable table name.
  328. */
  329. function ctools_drush_export_info() {
  330. // Collect array of table names from args.
  331. $table_names = func_get_args();
  332. // Get format option to allow for alternative output.
  333. $format = drush_get_option('format', FALSE);
  334. $tables_only = drush_get_option('tables-only', FALSE);
  335. $filter = drush_get_option('filter', FALSE);
  336. $export_module = drush_get_option('module', FALSE);
  337. $load = (bool) $filter || $export_module;
  338. // Get info on these tables, or all tables if none specified.
  339. $info = _ctools_drush_export_info($table_names, $load);
  340. $schemas = $info['schemas'];
  341. $exportables = $info['exportables'];
  342. if (empty($exportables)) {
  343. drush_log(dt('There are no exportables available.'), 'warning');
  344. return;
  345. }
  346. // Filter by export module.
  347. if (is_string($export_module)) {
  348. $exportables = _ctools_drush_export_module_filter($exportables, $export_module);
  349. }
  350. if (empty($exportables)) {
  351. drush_log(dt('There are no exportables matching this criteria.'), 'notice');
  352. return;
  353. }
  354. $exportable_counts = _ctools_drush_count_exportables($exportables);
  355. // Only use array keys if --tables-only option is set.
  356. if ($tables_only) {
  357. $exportables = array_keys($exportables);
  358. }
  359. // Use format from --format option if it's present, and send to drush_format.
  360. if ($format) {
  361. // Create array with all exportable info and counts in one.
  362. $output = array(
  363. 'exportables' => $exportables,
  364. 'count' => $exportable_counts,
  365. );
  366. drush_print(drush_format($output, NULL, $format));
  367. }
  368. // Build a tabular output as default.
  369. else {
  370. $header = $tables_only ? array() : array(dt('Module'), dt('Base table'), dt('Exportables'));
  371. $rows = array();
  372. foreach ($exportables as $table => $info) {
  373. if (is_array($info)) {
  374. $row = array(
  375. $schemas[$table]['module'],
  376. $table,
  377. // Machine name is better for this?
  378. shellColours::getColouredOutput(implode("\n", array_keys($info)), 'light_green') . "\n",
  379. );
  380. $rows[] = $row;
  381. }
  382. else {
  383. $rows[] = array($info);
  384. }
  385. }
  386. if (!empty($rows)) {
  387. drush_print("\n");
  388. array_unshift($rows, $header);
  389. drush_print_table($rows, TRUE, array(20, 20));
  390. drush_print(dt('Total exportables found: !total', array('!total' => $exportable_counts['total'])));
  391. foreach ($exportable_counts['exportables'] as $table_name => $count) {
  392. drush_print(dt('!table_name (!count)', array('!table_name' => $table_name, '!count' => $count)), 2);
  393. }
  394. drush_print("\n");
  395. }
  396. }
  397. }
  398. /**
  399. * Drush callback: Acts as the hub for all op commands to keep
  400. * all arg handling etc in one place.
  401. */
  402. function ctools_drush_export_op_command() {
  403. $args = func_get_args();
  404. // Get all info for the current drush command.
  405. $command = drush_get_command();
  406. $op = '';
  407. switch ($command['command']) {
  408. case 'ctools-export-view':
  409. $op = 'view';
  410. break;
  411. case 'ctools-export-revert':
  412. // Revert is same as deleting. As any objects in the db are deleted.
  413. $op = 'delete';
  414. break;
  415. case 'ctools-export-enable':
  416. $op = 'enable';
  417. break;
  418. case 'ctools-export-disable':
  419. $op = 'disable';
  420. break;
  421. }
  422. if (!$op) {
  423. return;
  424. }
  425. if (drush_get_option('all', FALSE)) {
  426. $info = _ctools_drush_export_info(array(), TRUE);
  427. $exportable_info = $info['exportables'];
  428. $all = drush_confirm(dt('Are you sure you would like to !op all exportables on the system?',
  429. array('!op' => _ctools_drush_export_op_alias($op))));
  430. if ($all && $exportable_info) {
  431. foreach ($exportable_info as $table => $exportables) {
  432. if (!empty($exportables)) {
  433. ctools_drush_export_op($op, $table, $exportables);
  434. }
  435. }
  436. }
  437. }
  438. else {
  439. // Table name should always be first arg...
  440. $table_name = array_shift($args);
  441. // Any additional args are assumed to be exportable names.
  442. $object_names = $args;
  443. // Return any exportables based on table name, object names, options.
  444. $exportables = _ctools_drush_export_op_command_logic($op, $table_name, $object_names);
  445. if ($exportables) {
  446. ctools_drush_export_op($op, $table_name, $exportables);
  447. }
  448. }
  449. }
  450. /**
  451. * Iterate through exportable object names, load them, and pass each
  452. * object to the correct op function.
  453. *
  454. * @param $op
  455. * @param $table_name
  456. * @param $exportables
  457. */
  458. function ctools_drush_export_op($op = '', $table_name = '', $exportables = NULL) {
  459. $objects = ctools_export_crud_load_multiple($table_name, array_keys($exportables));
  460. $function = '_ctools_drush_export_' . $op;
  461. if (function_exists($function)) {
  462. foreach ($objects as $object) {
  463. $function($table_name, $object);
  464. }
  465. }
  466. else {
  467. drush_log(dt('CTools CRUD function !function doesn\'t exist.',
  468. array('!function' => $function)), 'error');
  469. }
  470. }
  471. /**
  472. * Helper function to abstract logic for selecting exportable types/objects
  473. * from individual commands as they will all share this same error
  474. * handling/arguments for returning list of exportables.
  475. *
  476. * @param $table_name
  477. * @param $object_names
  478. *
  479. * @return
  480. * Array of exportable objects (filtered if necessary, by name etc..) or FALSE if not.
  481. */
  482. function _ctools_drush_export_op_command_logic($op = '', $table_name = NULL, array $object_names = array()) {
  483. if (!$table_name) {
  484. drush_log(dt('Exportable table name empty. Use the --all command if you want to perform this operation on all tables.'), 'error');
  485. return FALSE;
  486. }
  487. // Get export info based on table name.
  488. $info = _ctools_drush_export_info(array($table_name), TRUE);
  489. if (!isset($info['exportables'][$table_name])) {
  490. drush_log(dt('Exportable table name not found.'), 'error');
  491. return FALSE;
  492. }
  493. $exportables = &$info['exportables'];
  494. if (empty($object_names)) {
  495. $all = drush_confirm(dt('No object names entered. Would you like to try and !op all exportables of type !type',
  496. array('!op' => _ctools_drush_export_op_alias($op), '!type' => $table_name)));
  497. if (!$all) {
  498. drush_log(dt('Command cancelled'), 'success');
  499. return FALSE;
  500. }
  501. }
  502. else {
  503. // Iterate through object names and check they exist in exportables array.
  504. // Log error and unset them if they don't.
  505. foreach ($object_names as $object_name) {
  506. if (!isset($exportables[$table_name][$object_name])) {
  507. drush_log(dt('Invalid exportable: !exportable', array('!exportable' => $object_name)), 'error');
  508. unset($object_names[$table_name][$object_name]);
  509. }
  510. }
  511. // Iterate through exportables to get just a list of selected ones.
  512. foreach (array_keys($exportables[$table_name]) as $exportable) {
  513. if (!in_array($exportable, $object_names)) {
  514. unset($exportables[$table_name][$exportable]);
  515. }
  516. }
  517. }
  518. $export_module = drush_get_option('module', FALSE);
  519. if (is_string($export_module)) {
  520. $exportables = _ctools_drush_export_module_filter($exportables, $export_module);
  521. }
  522. return $exportables[$table_name];
  523. }
  524. /**
  525. * Return array of CTools exportable info based on available tables returned from
  526. * ctools_export_get_schemas().
  527. *
  528. * @param $table_names
  529. * Array of table names to return.
  530. * @param $load
  531. * (bool) should ctools exportable objects be loaded for each type.
  532. * The default behaviour will load just a list of exportable names.
  533. *
  534. * @return
  535. * Nested arrays of available exportables, keyed by table name.
  536. */
  537. function _ctools_drush_export_info(array $table_names = array(), $load = FALSE) {
  538. ctools_include('export');
  539. // Get available schemas that declare exports.
  540. $schemas = ctools_export_get_schemas(TRUE);
  541. $exportables = array();
  542. if (!empty($schemas)) {
  543. // Remove types we don't want, if any.
  544. if (!empty($table_names)) {
  545. foreach (array_keys($schemas) as $table_name) {
  546. if (!in_array($table_name, $table_names)) {
  547. unset($schemas[$table_name]);
  548. }
  549. }
  550. }
  551. // Load array of available exportables for each schema.
  552. foreach ($schemas as $table_name => $schema) {
  553. // Load all objects.
  554. if ($load) {
  555. $exportables[$table_name] = ctools_export_crud_load_all($table_name);
  556. }
  557. // Get a list of exportable names.
  558. else {
  559. if (!empty($schema['export']['list callback']) && function_exists($schema['export']['list callback'])) {
  560. $exportables[$table_name] = $schema['export']['list callback']();
  561. }
  562. else {
  563. $exportables[$table_name] = ctools_export_default_list($table_name, $schema);
  564. }
  565. }
  566. }
  567. }
  568. if ($load) {
  569. $filter = drush_get_option('filter', FALSE);
  570. $exportables = _ctools_drush_filter_exportables($exportables, $filter);
  571. }
  572. return array('exportables' => $exportables, 'schemas' => $schemas);
  573. }
  574. /**
  575. * View a single object.
  576. *
  577. * @param $table_name
  578. * @param $object
  579. */
  580. function _ctools_drush_export_view($table_name, $object) {
  581. $indent = drush_get_option('indent', '');
  582. $no_colour = drush_get_option('no-colour', FALSE);
  583. $export = ctools_export_crud_export($table_name, $object, $indent);
  584. if ($no_colour) {
  585. drush_print("\n$export");
  586. }
  587. else {
  588. drush_print(shellColours::getColouredOutput("\n$export", 'light_green'));
  589. }
  590. }
  591. /**
  592. * Revert a single object.
  593. *
  594. * @param $table_name
  595. * @param $object
  596. */
  597. function _ctools_drush_export_delete($table_name, $object) {
  598. $name = _ctools_drush_get_export_name($table_name, $object);
  599. if (_ctools_drush_object_is_overridden($object)) {
  600. // Remove from db.
  601. ctools_export_crud_delete($table_name, $object);
  602. drush_log("Reverted object: $name", 'success');
  603. }
  604. else {
  605. drush_log("Nothing to revert for: $name", 'notice');
  606. }
  607. }
  608. /**
  609. * Enable a single object.
  610. *
  611. * @param $table_name
  612. * @param $object
  613. */
  614. function _ctools_drush_export_enable($table_name, $object) {
  615. $name = _ctools_drush_get_export_name($table_name, $object);
  616. if (_ctools_drush_object_is_disabled($object)) {
  617. // Enable object.
  618. ctools_export_crud_enable($table_name, $object);
  619. drush_log("Enabled object: $name", 'success');
  620. }
  621. else {
  622. drush_log("$name is already Enabled", 'notice');
  623. }
  624. }
  625. /**
  626. * Disable a single object.
  627. *
  628. * @param $table_name
  629. * @param $object
  630. */
  631. function _ctools_drush_export_disable($table_name, $object) {
  632. $name = _ctools_drush_get_export_name($table_name, $object);
  633. if (!_ctools_drush_object_is_disabled($object)) {
  634. // Disable object.
  635. ctools_export_crud_disable($table_name, $object);
  636. drush_log("Disabled object: $name", 'success');
  637. }
  638. else {
  639. drush_log("$name is already disabled", 'notice');
  640. }
  641. }
  642. /**
  643. * Filter a nested array of exportables by export module.
  644. *
  645. * @param array $exportables
  646. * Passed by reference. A nested array of exportables, keyed by table name.
  647. * @param string $export_module
  648. * The name of the export module providing the exportable.
  649. */
  650. function _ctools_drush_export_module_filter($exportables, $export_module) {
  651. $module_list = module_list();
  652. if (!isset($module_list[$export_module])) {
  653. drush_log(dt('Invalid export module: !export_module', array('!export_module' => $export_module)), 'error');
  654. }
  655. foreach ($exportables as $table => $objects) {
  656. foreach ($objects as $key => $object) {
  657. if (empty($object->export_module) || ($object->export_module !== $export_module)) {
  658. unset($exportables[$table][$key]);
  659. }
  660. }
  661. }
  662. return array_filter($exportables);
  663. }
  664. /**
  665. * Gets the key for an exportable type.
  666. *
  667. * @param $table_name
  668. * The exportable table name.
  669. * @param $object
  670. * The exportable object.
  671. *
  672. * @return string
  673. * The key defined in the export schema data.
  674. */
  675. function _ctools_drush_get_export_name($table_name, $object) {
  676. $info = _ctools_drush_export_info(array($table_name));
  677. $key = $info['schemas'][$table_name]['export']['key'];
  678. return $object->{$key};
  679. }
  680. /**
  681. * Determine if an object is disabled.
  682. *
  683. * @param $object
  684. * Loaded CTools exportable object.
  685. *
  686. * @return TRUE or FALSE
  687. */
  688. function _ctools_drush_object_is_disabled($object) {
  689. return (isset($object->disabled) && ($object->disabled == TRUE)) ? TRUE : FALSE;
  690. }
  691. /**
  692. * Determine if an object is enabled.
  693. *
  694. * @see _ctools_drush_object_is_disabled()
  695. */
  696. function _ctools_drush_object_is_enabled($object) {
  697. return (empty($object->disabled)) ? TRUE : FALSE;
  698. }
  699. /**
  700. * Determine if an object is overridden.
  701. */
  702. function _ctools_drush_object_is_overridden($object) {
  703. $status = EXPORT_IN_CODE + EXPORT_IN_DATABASE;
  704. return ($object->export_type == $status) ? TRUE : FALSE;
  705. }
  706. /**
  707. * Determine if an object is not overridden.
  708. */
  709. function _ctools_drush_object_is_not_overridden($object) {
  710. $status = EXPORT_IN_CODE + EXPORT_IN_DATABASE;
  711. return ($object->export_type == $status) ? FALSE : TRUE;
  712. }
  713. /**
  714. * Determine if an object is only in the db.
  715. */
  716. function _ctools_drush_object_is_db_only($object) {
  717. return ($object->export_type == EXPORT_IN_DATABASE) ? TRUE : FALSE;
  718. }
  719. /**
  720. * Determine if an object is not in the db.
  721. */
  722. function _ctools_drush_object_is_not_db_only($object) {
  723. return ($object->export_type == EXPORT_IN_DATABASE) ? FALSE : TRUE;
  724. }
  725. /**
  726. * Determine if an object is a code only default.
  727. */
  728. function _ctools_drush_object_is_code_only($object) {
  729. return ($object->export_type == EXPORT_IN_CODE) ? TRUE : FALSE;
  730. }
  731. /**
  732. * Determine if an object is not a code only default.
  733. */
  734. function _ctools_drush_object_is_not_code_only($object) {
  735. return ($object->export_type == EXPORT_IN_CODE) ? FALSE : TRUE;
  736. }
  737. /**
  738. * Return an array of count information based on exportables array.
  739. *
  740. * @param $exportables
  741. * Array of exportables to count.
  742. *
  743. * @return
  744. * Array of count data containing the following:
  745. * 'total' - A total count of all exportables.
  746. * 'exportables' - An array of exportable counts per table.
  747. */
  748. function _ctools_drush_count_exportables($exportables) {
  749. $count = array('exportables' => array());
  750. foreach ($exportables as $table => $objects) {
  751. // Add the object count for each table.
  752. $count['exportables'][$table] = count($objects);
  753. }
  754. // Once all tables have been counted, total these up.
  755. $count['total'] = array_sum($count['exportables']);
  756. return $count;
  757. }
  758. /**
  759. * Filters a collection of exportables based on filters.
  760. *
  761. * @param $exportables
  762. * @param $filter
  763. */
  764. function _ctools_drush_filter_exportables($exportables, $filter) {
  765. $eval = FALSE;
  766. if (is_string($filter)) {
  767. switch ($filter) {
  768. // Show enabled exportables only.
  769. case 'enabled':
  770. $eval = '_ctools_drush_object_is_disabled';
  771. break;
  772. // Show disabled exportables only.
  773. case 'disabled':
  774. $eval = '_ctools_drush_object_is_enabled';
  775. break;
  776. // Show overridden exportables only.
  777. case 'overridden':
  778. $eval = '_ctools_drush_object_is_not_overridden';
  779. break;
  780. // Show database only exportables.
  781. case 'database':
  782. $eval = '_ctools_drush_object_is_not_db_only';
  783. break;
  784. // Show code only exportables.
  785. case 'code':
  786. $eval = '_ctools_drush_object_is_not_code_only';
  787. break;
  788. // Do nothing.
  789. case 'all':
  790. break;
  791. default:
  792. drush_log(dt('Invalid filter option. Available options are: enabled, disabled, overridden, database, and code.'), 'error');
  793. return;
  794. }
  795. if ($eval) {
  796. foreach ($exportables as $table => $objects) {
  797. foreach ($objects as $key => $object) {
  798. if ($eval($object)) {
  799. unset($exportables[$table][$key]);
  800. }
  801. }
  802. }
  803. }
  804. }
  805. return array_filter($exportables);
  806. }
  807. /**
  808. * Return an alias for an op, that will be used to show as output.
  809. * For now, this is mainly necessary for delete => revert alias.
  810. *
  811. * @param $op
  812. * The op name. Such as 'enable', 'disable', or 'delete'.
  813. *
  814. * @return
  815. * The matched alias value or the original $op passed in if not found.
  816. */
  817. function _ctools_drush_export_op_alias($op) {
  818. $aliases = array(
  819. 'delete' => 'revert',
  820. );
  821. if (isset($aliases[$op])) {
  822. return $aliases[$op];
  823. }
  824. return $op;
  825. }
  826. /**
  827. * Convert the drush options from a csv list into an array.
  828. *
  829. * @param $drush_option
  830. * The drush option name to invoke.
  831. *
  832. * @return
  833. * Exploded array of options.
  834. */
  835. function _ctools_drush_explode_options($drush_option) {
  836. $options = drush_get_option($drush_option, array());
  837. if (!empty($options)) {
  838. $options = explode(',', $options);
  839. return array_map('trim', $options);
  840. }
  841. return $options;
  842. }
  843. /**
  844. * Class to deal with wrapping output strings with
  845. * colour formatting for the shell.
  846. */
  847. class shellColours {
  848. private static $foreground_colours = array(
  849. 'black' => '0;30',
  850. 'dark_gray' => '1;30',
  851. 'blue' => '0;34',
  852. 'light_blue' => '1;34',
  853. 'green' => '0;32',
  854. 'light_green' => '1;32',
  855. 'cyan' => '0;36',
  856. 'light_cyan' => '1;36',
  857. 'red' => '0;31',
  858. 'light_red' => '1;31',
  859. 'purple' => '0;35',
  860. 'light_purple' => '1;35',
  861. 'brown' => '0;33',
  862. 'yellow' => '1;33',
  863. 'light_gray' => '0;37',
  864. 'white' => '1;37',
  865. );
  866. private static $background_colours = array(
  867. 'black' => '40',
  868. 'red' => '41',
  869. 'green' => '42',
  870. 'yellow' => '43',
  871. 'blue' => '44',
  872. 'magenta' => '45',
  873. 'cyan' => '46',
  874. 'light_gray' => '47',
  875. );
  876. /**
  877. * shellColours constructor.
  878. */
  879. private function __construct() {}
  880. /**
  881. * Returns coloured string.
  882. */
  883. public static function getColouredOutput($string, $foreground_colour = NULL, $background_colour = NULL) {
  884. $coloured_string = "";
  885. // Check if given foreground colour found.
  886. if ($foreground_colour) {
  887. $coloured_string .= "\033[" . self::$foreground_colours[$foreground_colour] . "m";
  888. }
  889. // Check if given background colour found.
  890. if ($background_colour) {
  891. $coloured_string .= "\033[" . self::$background_colours[$background_colour] . "m";
  892. }
  893. // Add string and end colouring.
  894. $coloured_string .= $string . "\033[0m";
  895. return $coloured_string;
  896. }
  897. /**
  898. * Returns all foreground colour names.
  899. */
  900. public static function getForegroundColours() {
  901. return array_keys(self::$foreground_colours);
  902. }
  903. /**
  904. * Returns all background colour names.
  905. */
  906. public static function getBackgroundColours() {
  907. return array_keys(self::$background_colours);
  908. }
  909. } // shellColours