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