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, '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…
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.
_drush_format_table

File

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