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