output.inc

  1. 8.0.x includes/output.inc
  2. 6.x includes/output.inc
  3. 7.x includes/output.inc
  4. 5.x includes/output.inc
  5. master includes/output.inc

Functions

Namesort descending Description
drush_format Prepares a variable for printing. Loads the requested output formatter and uses it to process the provided input.
drush_format_table Format a table of data.
drush_hide_empty_fields Hide any fields that are empty
drush_html_to_text Convert html to readable text. Compatible API to drupal_html_to_text, but less functional. Caller might prefer to call drupal_html_to_text if there is a bootstrapped Drupal site available.
drush_json_decode Converts an HTML-safe JSON string into its PHP equivalent.
drush_json_encode Converts a PHP variable into its Javascript equivalent.
drush_key_value_to_array_table Convert an associative array of key : value pairs into a table suitable for processing by drush_print_table.
drush_lookup_field_by_path Return a specific item inside an array, as identified by the provided path.
drush_output_get_selected_field Given a table array (an associative array of associative arrays), return an array of all of the values with the specified field name.
drush_print Prints a message with optional indentation. In general, drush_log($message, LogLevel::OK) is often a better choice than this function. That gets your confirmation message (for example) into the logs for this drush request. Consider that drush requests…
drush_print_file Print the contents of a file.
drush_print_format Format some data and print it out. Respect --format option.
drush_print_pipe Stores a message which is printed during drush_shutdown() if in compact mode.
drush_print_prompt Print a prompt -- that is, a message with no trailing newline.
drush_print_r Prints an array or string.
drush_print_table Print a formatted table.
drush_rows_of_key_value_to_array_table Convert an array of data rows, where each row contains an associative array of key : value pairs, into a table suitable for processing by drush_print_table. The provided $header determines the order that the items will appear in the output. Only data…
drush_select_fields Select the fields that should be used.
drush_select_output_fields Select the fields from the input array that should be output.
drush_table_column_autowidth Determine the best fit for column widths.
drush_var_export Drupal-friendly var_export(). Taken from utility.inc in Drupal 8.
dt Rudimentary replacement for Drupal API t() function.
find_legacy_dt_args Return an array containing all of the items in the input array that begin with a '!'.
_drush_format_table

File

includes/output.inc
View source
  1. <?php
  2. use Drush\Log\LogLevel;
  3. /**
  4. * @defgroup outputfunctions Process output text.
  5. * @{
  6. */
  7. /**
  8. * Prints a message with optional indentation. In general,
  9. * drush_log($message, LogLevel::OK) is often a better choice than this function.
  10. * That gets your confirmation message (for example) into the logs for this
  11. * drush request. Consider that drush requests may be executed remotely and
  12. * non interactively.
  13. *
  14. * @param $message
  15. * The message to print.
  16. * @param $indent
  17. * The indentation (space chars)
  18. * @param $handle
  19. * File handle to write to. NULL will write
  20. * to standard output, STDERR will write to the standard
  21. * error. See http://php.net/manual/en/features.commandline.io-streams.php
  22. * @param $newline
  23. * Add a "\n" to the end of the output. Defaults to TRUE.
  24. */
  25. function drush_print($message = '', $indent = 0, $handle = NULL, $newline = TRUE) {
  26. $msg = str_repeat(' ', $indent) . (string)$message;
  27. if ($newline) {
  28. $msg .= "\n";
  29. }
  30. if (($charset = drush_get_option('output_charset')) && function_exists('iconv')) {
  31. $msg = iconv('UTF-8', $charset, $msg);
  32. }
  33. if (isset($handle)) {
  34. fwrite($handle, $msg);
  35. }
  36. else {
  37. print $msg;
  38. //$output = \Drush::service('output');
  39. //$output->write($msg);
  40. }
  41. }
  42. /**
  43. * Print a prompt -- that is, a message with no trailing newline.
  44. */
  45. function drush_print_prompt($message, $indent = 0, $handle = NULL) {
  46. drush_print($message, $indent, $handle, FALSE);
  47. }
  48. /**
  49. * Stores a message which is printed during drush_shutdown() if in compact mode.
  50. * @param $message
  51. * The message to print. If $message is an array,
  52. * then each element of the array is printed on a
  53. * separate line.
  54. */
  55. function drush_print_pipe($message = '') {
  56. $buffer = &drush_get_context('DRUSH_PIPE_BUFFER' , '');
  57. if (is_array($message)) {
  58. $message = implode("\n", $message) . "\n";
  59. }
  60. $buffer .= $message;
  61. }
  62. /**
  63. * Prints an array or string.
  64. * @param $array
  65. * The array to print.
  66. * @param $newline
  67. * Add a "\n" to the end of the output. Defaults to TRUE.
  68. */
  69. function drush_print_r($array, $handle = NULL, $newline = TRUE) {
  70. drush_print(print_r($array, TRUE), 0, $handle, $newline);
  71. }
  72. /**
  73. * Format some data and print it out. Respect --format option.
  74. */
  75. function drush_print_format($input, $default_format, $metadata = NULL) {
  76. drush_print(drush_format($input, $metadata, drush_get_option('format', $default_format)));
  77. }
  78. /**
  79. * Prepares a variable for printing. Loads the requested output
  80. * formatter and uses it to process the provided input.
  81. *
  82. * @param mixed $input
  83. * A variable.
  84. * @param string $metadata
  85. * Optional formatting metadata. Not used by all formats.
  86. * 'label' - text to label data with in some formats (e.g. export, config)
  87. * @param string $format
  88. * Optional format; defaults to print_r.
  89. * @return string
  90. * The variable formatted according to specified format.
  91. * Ready for drush_print().
  92. */
  93. function drush_format($input, $metadata = NULL, $format = NULL) {
  94. $output = '';
  95. // Look up the format and label, and fill in default values for metadata
  96. if (is_string($metadata)) {
  97. $metadata = array('label' => $metadata);
  98. }
  99. if (!is_array($metadata)) {
  100. $metadata = array();
  101. }
  102. $metadata += array(
  103. 'metameta' => array(),
  104. );
  105. if (isset($metadata['format'])) {
  106. // If the format is set in metadata, then it will
  107. // override whatever is passed in via the $format parameter.
  108. $format = $metadata['format'];
  109. }
  110. if (!isset($format)) {
  111. // TODO: we shouldn't ever call drush_get_option here.
  112. // Get rid of this once we confirm that there are no
  113. // callers that still need it.
  114. $format = drush_get_option('format', 'print-r');
  115. }
  116. $formatter = drush_load_engine('outputformat', $format);
  117. if ($formatter) {
  118. if ($formatter === TRUE) {
  119. return drush_set_error(dt('No outputformat class defined for !format', array('!format' => $format)));
  120. }
  121. $output = $formatter->process($input, $metadata);
  122. }
  123. return $output;
  124. }
  125. /**
  126. * Rudimentary replacement for Drupal API t() function.
  127. *
  128. * @param string
  129. * String to process, possibly with replacement item.
  130. * @param array
  131. * An associative array of replacement items.
  132. *
  133. * @return
  134. * The processed string.
  135. *
  136. * @see t()
  137. */
  138. function dt($string, $args = array()) {
  139. $output = NULL;
  140. if (function_exists('t') && drush_drupal_major_version() == 7) {
  141. $output = t($string, $args);
  142. }
  143. // The language system requires a working container which has the string
  144. // translation service.
  145. else if (drush_drupal_major_version() >= 8 && \Drupal::hasService('string_translation')) {
  146. // Drupal 8 removes !var replacements, creating a user-level error when
  147. // these are used, so we'll pre-replace these before calling translate().
  148. $legacy_args = find_legacy_dt_args($args);
  149. $string = strtr($string, $legacy_args);
  150. // Remove the legacy replacements.
  151. foreach (array_keys($legacy_args) as $legacy_arg_key) {
  152. unset($args[$legacy_arg_key]);
  153. }
  154. $output = (string) \Drupal::translation()->translate($string, $args);
  155. }
  156. else if (function_exists('t') && drush_drupal_major_version() <= 7 && function_exists('theme')) {
  157. $output = t($string, $args);
  158. }
  159. // If Drupal's t() function unavailable.
  160. if (!isset($output)) {
  161. if (!empty($args)) {
  162. $output = strtr($string, $args);
  163. }
  164. else {
  165. $output = $string;
  166. }
  167. }
  168. return $output;
  169. }
  170. /**
  171. * Return an array containing all of the items in the input
  172. * array that begin with a '!'.
  173. *
  174. * Since array_filter operates on the array value, and there
  175. * is no corresponding function that operates on the key, we
  176. * will flip the array twice to filter on the key.
  177. */
  178. function find_legacy_dt_args($args) {
  179. $legacy_args = array();
  180. foreach ($args as $arg => $replacement) {
  181. if ($arg[0] == '!') {
  182. $legacy_args[$arg] = $replacement;
  183. }
  184. }
  185. return $legacy_args;
  186. }
  187. /**
  188. * Convert html to readable text. Compatible API to
  189. * drupal_html_to_text, but less functional. Caller
  190. * might prefer to call drupal_html_to_text if there
  191. * is a bootstrapped Drupal site available.
  192. *
  193. * @param string $html
  194. * The html text to convert.
  195. *
  196. * @return string
  197. * The plain-text representation of the input.
  198. */
  199. function drush_html_to_text($html, $allowed_tags = NULL) {
  200. $replacements = array(
  201. '<hr>' => '------------------------------------------------------------------------------',
  202. '<li>' => ' * ',
  203. '<h1>' => '===== ',
  204. '</h1>' => ' =====',
  205. '<h2>' => '---- ',
  206. '</h2>' => ' ----',
  207. '<h3>' => '::: ',
  208. '</h3>' => ' :::',
  209. '<br/>' => "\n",
  210. );
  211. $text = str_replace(array_keys($replacements), array_values($replacements), $html);
  212. return html_entity_decode(preg_replace('/ *<[^>]*> */', ' ', $text));
  213. }
  214. /**
  215. * Print a formatted table.
  216. *
  217. * @param $rows
  218. * The rows to print.
  219. * @param $header
  220. * If TRUE, the first line will be treated as table header.
  221. * @param $widths
  222. * An associative array whose keys are column IDs and values are widths of each column (in characters).
  223. * If not specified this will be determined automatically, based on a "best fit" algorithm.
  224. * @param $handle
  225. * File handle to write to. NULL will write
  226. * to standard output, STDERR will write to the standard
  227. * error. See http://php.net/manual/en/features.commandline.io-streams.php
  228. * @return $tbl
  229. * Use $tbl->getTable() to get the output from the return value.
  230. */
  231. function drush_print_table($rows, $header = FALSE, $widths = array(), $handle = NULL) {
  232. $tbl = _drush_format_table($rows, $header, $widths);
  233. $output = $tbl->getTable();
  234. if (!stristr(PHP_OS, 'WIN')) {
  235. $output = str_replace("\r\n", PHP_EOL, $output);
  236. }
  237. drush_print(rtrim($output), 0, $handle);
  238. return $tbl;
  239. }
  240. /**
  241. * Format a table of data.
  242. *
  243. * @param $rows
  244. * The rows to print.
  245. * @param $header
  246. * If TRUE, the first line will be treated as table header.
  247. * @param $widths
  248. * An associative array whose keys are column IDs and values are widths of each column (in characters).
  249. * If not specified this will be determined automatically, based on a "best fit" algorithm.
  250. * @param array $console_table_options
  251. * An array that is passed along when constructing a Console_Table instance.
  252. * @return $output
  253. * The formatted output.
  254. */
  255. function drush_format_table($rows, $header = FALSE, $widths = array(), $console_table_options = array()) {
  256. $tbl = _drush_format_table($rows, $header, $widths, $console_table_options);
  257. $output = $tbl->getTable();
  258. if (!drush_is_windows()) {
  259. $output = str_replace("\r\n", PHP_EOL, $output);
  260. }
  261. return $output;
  262. }
  263. function _drush_format_table($rows, $header = FALSE, $widths = array(), $console_table_options = array()) {
  264. // Add defaults.
  265. $tbl = new ReflectionClass('Console_Table');
  266. $console_table_options += array(CONSOLE_TABLE_ALIGN_LEFT , '');
  267. $tbl = $tbl->newInstanceArgs($console_table_options);
  268. $auto_widths = drush_table_column_autowidth($rows, $widths);
  269. // Do wordwrap on all cells.
  270. $newrows = array();
  271. foreach ($rows as $rowkey => $row) {
  272. foreach ($row as $col_num => $cell) {
  273. $newrows[$rowkey][$col_num] = wordwrap($cell, $auto_widths[$col_num], "\n", TRUE);
  274. if (isset($widths[$col_num])) {
  275. $newrows[$rowkey][$col_num] = str_pad($newrows[$rowkey][$col_num], $widths[$col_num]);
  276. }
  277. }
  278. }
  279. if ($header) {
  280. $headers = array_shift($newrows);
  281. $tbl->setHeaders($headers);
  282. }
  283. $tbl->addData($newrows);
  284. return $tbl;
  285. }
  286. /**
  287. * Convert an associative array of key : value pairs into
  288. * a table suitable for processing by drush_print_table.
  289. *
  290. * @param $keyvalue_table
  291. * An associative array of key : value pairs.
  292. * @param $metadata
  293. * 'key-value-item': If the value is an array, then
  294. * the item key determines which item from the value
  295. * will appear in the output.
  296. * @return
  297. * An array of arrays, where the keys from the input
  298. * array are stored in the first column, and the values
  299. * are stored in the third. A second colum is created
  300. * specifically to hold the ':' separator.
  301. */
  302. function drush_key_value_to_array_table($keyvalue_table, $metadata = array()) {
  303. if (!is_array($keyvalue_table)) {
  304. return drush_set_error('DRUSH_INVALID_FORMAT', dt("Data not compatible with selected key-value output format."));
  305. }
  306. if (!is_array($metadata)) {
  307. $metadata = array('key-value-item' => $metadata);
  308. }
  309. $item_key = array_key_exists('key-value-item', $metadata) ? $metadata['key-value-item'] : NULL;
  310. $metadata += array(
  311. 'format' => 'list',
  312. 'separator' => ' ',
  313. );
  314. $table = array();
  315. foreach ($keyvalue_table as $key => $value) {
  316. if (isset($value)) {
  317. if (is_array($value) && isset($item_key)) {
  318. $value = $value[$item_key];
  319. }
  320. // We should only have simple values here, but if
  321. // we don't, use drush_format() to flatten as a fallback.
  322. if (is_array($value)) {
  323. $value = drush_format($value, $metadata, 'list');
  324. }
  325. }
  326. if (isset($metadata['include-field-labels']) && !$metadata['include-field-labels']) {
  327. $table[] = array(isset($value) ? $value : '');
  328. }
  329. elseif (isset($value)) {
  330. $table[] = array($key, ' :', $value);
  331. }
  332. else {
  333. $table[] = array($key . ':', '', '');
  334. }
  335. }
  336. return $table;
  337. }
  338. /**
  339. * Select the fields that should be used.
  340. */
  341. function drush_select_fields($all_field_labels, $fields, $strict = TRUE) {
  342. $field_labels = array();
  343. foreach ($fields as $field) {
  344. if (array_key_exists($field, $all_field_labels)) {
  345. $field_labels[$field] = $all_field_labels[$field];
  346. }
  347. else {
  348. // Allow the user to select fields via their human-readable names.
  349. // This is less convenient than the field name (since the human-readable
  350. // names may contain spaces, and must therefore be quoted), but these are
  351. // the values that the user sees in the command output. n.b. the help
  352. // text lists fields by their more convenient machine names.
  353. $key = array_search(strtolower($field), array_map('strtolower', $all_field_labels));
  354. if ($key !== FALSE) {
  355. $field_labels[$key] = $all_field_labels[$key];
  356. }
  357. elseif (!$strict) {
  358. $field_labels[$field] = $field;
  359. }
  360. }
  361. }
  362. return $field_labels;
  363. }
  364. /**
  365. * Select the fields from the input array that should be output.
  366. *
  367. * @param $input
  368. * An associative array of key:value pairs to be output
  369. * @param $fields
  370. * An associative array that maps FROM a field in $input
  371. * TO the corresponding field name in $output.
  372. * @param $mapping
  373. * An associative array that maps FROM a field in $fields
  374. * TO the actual field in $input to use in the preceeding
  375. * translation described above.
  376. * @return
  377. * The input array, re-ordered and re-keyed per $fields
  378. */
  379. function drush_select_output_fields($input, $fields, $mapping = array(), $default_value = NULL) {
  380. $result = array();
  381. if (empty($fields)) {
  382. $result = $input;
  383. }
  384. else {
  385. foreach ($fields as $key => $label) {
  386. $value = drush_lookup_field_by_path($input, $key, $mapping, $default_value);
  387. if (isset($value)) {
  388. $result[$label] = $value;
  389. }
  390. }
  391. }
  392. return $result;
  393. }
  394. /**
  395. * Return a specific item inside an array, as identified
  396. * by the provided path.
  397. *
  398. * @param $input:
  399. * An array of items, potentially multiple layers deep.
  400. * @param $path:
  401. * A specifier of array keys, either in an array or separated by
  402. * a '/', that list the elements of the array to access. This
  403. * works much like a very simple version of xpath for arrays, with
  404. * all items being treated identically (like elements).
  405. * @param $mapping:
  406. * (optional) An array whose keys may correspond to the $path parameter and
  407. * whose values are the corresponding paths to be used in $input.
  408. *
  409. * Example 1:
  410. *
  411. * $input = array('#name' => 'site.dev', '#id' => '222');
  412. * $path = '#name';
  413. * result: 'site.dev';
  414. *
  415. * Example 2:
  416. *
  417. * $input = array('ca' => array('sf' => array('mission'=>array('1700'=>'woodward'))));
  418. * $path = 'ca/sf/mission/1701';
  419. * result: 'woodward'
  420. *
  421. * Example 3:
  422. *
  423. * $input = array('#name' => 'site.dev', '#id' => '222');
  424. * $path = 'name';
  425. * $mapping = array('name' => '#name');
  426. * result: 'site.dev';
  427. */
  428. function drush_lookup_field_by_path($input, $path, $mapping = array(), $default_value = NULL) {
  429. $result = '';
  430. if (isset($mapping[$path])) {
  431. $path = $mapping[$path];
  432. }
  433. if (!is_array($path)) {
  434. $parts = explode('/', $path);
  435. }
  436. if (!empty($parts)) {
  437. $result = $input;
  438. foreach ($parts as $key) {
  439. if ((is_array($result)) && (isset($result[$key]))) {
  440. $result = $result[$key];
  441. }
  442. else {
  443. return $default_value;
  444. }
  445. }
  446. }
  447. return $result;
  448. }
  449. /**
  450. * Given a table array (an associative array of associative arrays),
  451. * return an array of all of the values with the specified field name.
  452. */
  453. function drush_output_get_selected_field($input, $field_name, $default_value = '') {
  454. $result = array();
  455. foreach ($input as $key => $data) {
  456. if (is_array($data) && isset($data[$field_name])) {
  457. $result[] = $data[$field_name];
  458. }
  459. else {
  460. $result[] = $default_value;
  461. }
  462. }
  463. return $result;
  464. }
  465. /**
  466. * Hide any fields that are empty
  467. */
  468. function drush_hide_empty_fields($input, $fields) {
  469. $has_data = array();
  470. foreach ($input as $key => $data) {
  471. foreach ($fields as $field => $label) {
  472. if (isset($data[$field]) && !empty($data[$field])) {
  473. $has_data[$field] = TRUE;
  474. }
  475. }
  476. }
  477. foreach ($fields as $field => $label) {
  478. if (!isset($has_data[$field])) {
  479. unset($fields[$field]);
  480. }
  481. }
  482. return $fields;
  483. }
  484. /**
  485. * Convert an array of data rows, where each row contains an
  486. * associative array of key : value pairs, into
  487. * a table suitable for processing by drush_print_table.
  488. * The provided $header determines the order that the items
  489. * will appear in the output. Only data items listed in the
  490. * header will be placed in the output.
  491. *
  492. * @param $rows_of_keyvalue_table
  493. * array(
  494. * 'row1' => array('col1' => 'data', 'col2' => 'data'),
  495. * 'row2' => array('col1' => 'data', 'col2' => 'data'),
  496. * )
  497. * @param $header
  498. * array('col1' => 'Column 1 Label', 'col2' => 'Column 2 Label')
  499. * @param $metadata
  500. * (optional) An array of special options, all optional:
  501. * - strip-tags: call the strip_tags function on the data
  502. * before placing it in the table
  503. * - concatenate-columns: an array of:
  504. * - dest-col: array('src-col1', 'src-col2')
  505. * Appends all of the src columns with whatever is
  506. * in the destination column. Appended columns are
  507. * separated by newlines.
  508. * - transform-columns: an array of:
  509. * - dest-col: array('from' => 'to'),
  510. * Transforms any occurance of 'from' in 'dest-col' to 'to'.
  511. * - format-cell: Drush output format name to use to format
  512. * any cell that is an array.
  513. * - process-cell: php function name to use to process
  514. * any cell that is an array.
  515. * - field-mappings: an array whose keys are some or all of the keys in
  516. * $header and whose values are the corresponding keys to use when
  517. * indexing the values of $rows_of_keyvalue_table.
  518. * @return
  519. * An array of arrays
  520. */
  521. function drush_rows_of_key_value_to_array_table($rows_of_keyvalue_table, $header, $metadata) {
  522. if (isset($metadata['hide-empty-fields'])) {
  523. $header = drush_hide_empty_fields($rows_of_keyvalue_table, $header);
  524. }
  525. if (empty($header)) {
  526. $first = (array)reset($rows_of_keyvalue_table);
  527. $keys = array_keys($first);
  528. $header = array_combine($keys, $keys);
  529. }
  530. $table = array(array_values($header));
  531. if (isset($rows_of_keyvalue_table) && is_array($rows_of_keyvalue_table) && !empty($rows_of_keyvalue_table)) {
  532. foreach ($rows_of_keyvalue_table as $row_index => $row_data) {
  533. $row_data = (array)$row_data;
  534. $row = array();
  535. foreach ($header as $column_key => $column_label) {
  536. $data = drush_lookup_field_by_path($row_data, $column_key, $metadata['field-mappings']);
  537. if (array_key_exists('transform-columns', $metadata)) {
  538. foreach ($metadata['transform-columns'] as $dest_col => $transformations) {
  539. if ($dest_col == $column_key) {
  540. $data = str_replace(array_keys($transformations), array_values($transformations), $data);
  541. }
  542. }
  543. }
  544. if (array_key_exists('concatenate-columns', $metadata)) {
  545. foreach ($metadata['concatenate-columns'] as $dest_col => $src_cols) {
  546. if ($dest_col == $column_key) {
  547. $data = '';
  548. if (!is_array($src_cols)) {
  549. $src_cols = array($src_cols);
  550. }
  551. foreach($src_cols as $src) {
  552. if (array_key_exists($src, $row_data) && !empty($row_data[$src])) {
  553. if (!empty($data)) {
  554. $data .= "\n";
  555. }
  556. $data .= $row_data[$src];
  557. }
  558. }
  559. }
  560. }
  561. }
  562. if (array_key_exists('format-cell', $metadata) && is_array($data)) {
  563. $data = drush_format($data, array(), $metadata['format-cell']);
  564. }
  565. if (array_key_exists('process-cell', $metadata) && is_array($data)) {
  566. $data = $metadata['process-cell']($data, $metadata);
  567. }
  568. if (array_key_exists('strip-tags', $metadata)) {
  569. $data = strip_tags($data);
  570. }
  571. $row[] = $data;
  572. }
  573. $table[] = $row;
  574. }
  575. }
  576. return $table;
  577. }
  578. /**
  579. * Determine the best fit for column widths.
  580. *
  581. * @param $rows
  582. * The rows to use for calculations.
  583. * @param $widths
  584. * Manually specified widths of each column (in characters) - these will be
  585. * left as is.
  586. */
  587. function drush_table_column_autowidth($rows, $widths) {
  588. $auto_widths = $widths;
  589. // First we determine the distribution of row lengths in each column.
  590. // This is an array of descending character length keys (i.e. starting at
  591. // the rightmost character column), with the value indicating the number
  592. // of rows where that character column is present.
  593. $col_dist = array();
  594. foreach ($rows as $rowkey => $row) {
  595. foreach ($row as $col_id => $cell) {
  596. if (empty($widths[$col_id])) {
  597. $length = strlen($cell);
  598. if ($length == 0) {
  599. $col_dist[$col_id][0] = 0;
  600. }
  601. while ($length > 0) {
  602. if (!isset($col_dist[$col_id][$length])) {
  603. $col_dist[$col_id][$length] = 0;
  604. }
  605. $col_dist[$col_id][$length]++;
  606. $length--;
  607. }
  608. }
  609. }
  610. }
  611. foreach ($col_dist as $col_id => $count) {
  612. // Sort the distribution in decending key order.
  613. krsort($col_dist[$col_id]);
  614. // Initially we set all columns to their "ideal" longest width
  615. // - i.e. the width of their longest column.
  616. $auto_widths[$col_id] = max(array_keys($col_dist[$col_id]));
  617. }
  618. // We determine what width we have available to use, and what width the
  619. // above "ideal" columns take up.
  620. $available_width = drush_get_context('DRUSH_COLUMNS', 80) - (count($auto_widths) * 2);
  621. $auto_width_current = array_sum($auto_widths);
  622. // If we need to reduce a column so that we can fit the space we use this
  623. // loop to figure out which column will cause the "least wrapping",
  624. // (relative to the other columns) and reduce the width of that column.
  625. while ($auto_width_current > $available_width) {
  626. $count = 0;
  627. $width = 0;
  628. foreach ($col_dist as $col_id => $counts) {
  629. // If we are just starting out, select the first column.
  630. if ($count == 0 ||
  631. // OR: if this column would cause less wrapping than the currently
  632. // selected column, then select it.
  633. (current($counts) < $count) ||
  634. // OR: if this column would cause the same amount of wrapping, but is
  635. // longer, then we choose to wrap the longer column (proportionally
  636. // less wrapping, and helps avoid triple line wraps).
  637. (current($counts) == $count && key($counts) > $width)) {
  638. // Select the column number, and record the count and current width
  639. // for later comparisons.
  640. $column = $col_id;
  641. $count = current($counts);
  642. $width = key($counts);
  643. }
  644. }
  645. if ($width <= 1) {
  646. // If we have reached a width of 1 then give up, so wordwrap can still progress.
  647. break;
  648. }
  649. // Reduce the width of the selected column.
  650. $auto_widths[$column]--;
  651. // Reduce our overall table width counter.
  652. $auto_width_current--;
  653. // Remove the corresponding data from the disctribution, so next time
  654. // around we use the data for the row to the left.
  655. unset($col_dist[$column][$width]);
  656. }
  657. return $auto_widths;
  658. }
  659. /**
  660. * Print the contents of a file.
  661. *
  662. * @param string $file
  663. * Full path to a file.
  664. */
  665. function drush_print_file($file) {
  666. // Don't even bother to print the file in --no mode
  667. if (drush_get_context('DRUSH_NEGATIVE')) {
  668. return;
  669. }
  670. if ((substr($file,-4) == ".htm") || (substr($file,-5) == ".html")) {
  671. $tmp_file = drush_tempnam(basename($file));
  672. file_put_contents($tmp_file, drush_html_to_text(file_get_contents($file)));
  673. $file = $tmp_file;
  674. }
  675. // Do not wait for user input in --yes or --pipe modes
  676. if (drush_get_context('DRUSH_PIPE')) {
  677. drush_print_pipe(file_get_contents($file));
  678. }
  679. elseif (drush_get_context('DRUSH_AFFIRMATIVE')) {
  680. drush_print(file_get_contents($file));
  681. }
  682. elseif (drush_shell_exec_interactive("less %s", $file)) {
  683. return;
  684. }
  685. elseif (drush_shell_exec_interactive("more %s", $file)) {
  686. return;
  687. }
  688. else {
  689. drush_print(file_get_contents($file));
  690. }
  691. }
  692. /**
  693. * Converts a PHP variable into its Javascript equivalent.
  694. *
  695. * We provide a copy of D7's drupal_json_encode since this function is
  696. * unavailable on earlier versions of Drupal.
  697. *
  698. * @see drupal_json_decode()
  699. * @ingroup php_wrappers
  700. */
  701. function drush_json_encode($var) {
  702. $json = json_encode($var, JSON_PRETTY_PRINT);
  703. // json_encode() does not escape <, > and &, so we do it with str_replace().
  704. return str_replace(array('<', '>', '&'), array('\u003c', '\u003e', '\u0026'), $json);
  705. }
  706. /**
  707. * Converts an HTML-safe JSON string into its PHP equivalent.
  708. *
  709. * We provide a copy of D7's drupal_json_decode since this function is
  710. * unavailable on earlier versions of Drupal.
  711. *
  712. * @see drupal_json_encode()
  713. * @ingroup php_wrappers
  714. */
  715. function drush_json_decode($var) {
  716. return json_decode($var, TRUE);
  717. }
  718. /**
  719. * Drupal-friendly var_export(). Taken from utility.inc in Drupal 8.
  720. *
  721. * @param $var
  722. * The variable to export.
  723. * @param $prefix
  724. * A prefix that will be added at the beginning of every lines of the output.
  725. *
  726. * @return
  727. * The variable exported in a way compatible to Drupal's coding standards.
  728. */
  729. function drush_var_export($var, $prefix = '') {
  730. if (is_array($var)) {
  731. if (empty($var)) {
  732. $output = 'array()';
  733. }
  734. else {
  735. $output = "array(\n";
  736. // Don't export keys if the array is non associative.
  737. $export_keys = array_values($var) != $var;
  738. foreach ($var as $key => $value) {
  739. $output .= ' ' . ($export_keys ? drush_var_export($key) . ' => ' : '') . drush_var_export($value, ' ', FALSE) . ",\n";
  740. }
  741. $output .= ')';
  742. }
  743. }
  744. elseif (is_bool($var)) {
  745. $output = $var ? 'TRUE' : 'FALSE';
  746. }
  747. elseif (is_string($var)) {
  748. $line_safe_var = str_replace("\n", '\n', $var);
  749. if (strpos($var, "\n") !== FALSE || strpos($var, "'") !== FALSE) {
  750. // If the string contains a line break or a single quote, use the
  751. // double quote export mode. Encode backslash and double quotes and
  752. // transform some common control characters.
  753. $var = str_replace(array('\\', '"', "\n", "\r", "\t"), array('\\\\', '\"', '\n', '\r', '\t'), $var);
  754. $output = '"' . $var . '"';
  755. }
  756. else {
  757. $output = "'" . $var . "'";
  758. }
  759. }
  760. elseif (is_object($var) && get_class($var) === 'stdClass') {
  761. // var_export() will export stdClass objects using an undefined
  762. // magic method __set_state() leaving the export broken. This
  763. // workaround avoids this by casting the object as an array for
  764. // export and casting it back to an object when evaluated.
  765. $output = '(object) ' . drush_var_export((array) $var, $prefix);
  766. }
  767. else {
  768. $output = var_export($var, TRUE);
  769. }
  770. if ($prefix) {
  771. $output = str_replace("\n", "\n$prefix", $output);
  772. }
  773. return $output;
  774. }
  775. /**
  776. * @} End of "defgroup outputfunctions".
  777. */