Skip to content

Commit

Permalink
Make launch_editor_for_input() usable without WordPress available
Browse files Browse the repository at this point in the history
Internalize the core logic of generating a random temp file.
  • Loading branch information
danielbachhuber committed Apr 13, 2016
1 parent 100d21d commit 639e52c
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions php/utils.php
Expand Up @@ -338,12 +338,28 @@ function pick_fields( $item, $fields ) {
* @return str|bool Edited text, if file is saved from editor
* False, if no change to file
*/
function launch_editor_for_input( $input, $title = 'WP-CLI' ) {

$tmpfile = wp_tempnam( $title );
function launch_editor_for_input( $input, $filename = 'WP-CLI' ) {

$tmpdir = get_temp_dir();

do {
$tmpfile = basename( $filename );
$tmpfile = preg_replace( '|\.[^.]*$|', '', $tmpfile );
$tmpfile .= '-' . substr( md5( rand() ), 0, 6 );
$tmpfile = $tmpdir . $tmpfile . '.tmp';
$fp = @fopen( $tmpfile, 'x' );
if ( ! $fp && is_writable( $tmpdir ) && file_exists( $tmpfile ) ) {
$tmpfile = '';
continue;
}
if ( $fp ) {
fclose( $fp );
}
} while( ! $tmpfile );

if ( !$tmpfile )
if ( ! $tmpfile ) {
\WP_CLI::error( 'Error creating temporary file.' );
}

$output = '';
file_put_contents( $tmpfile, $input );
Expand Down

0 comments on commit 639e52c

Please sign in to comment.