diff --git a/includes/functions.php b/includes/functions.php index 8ea93c84d91da8d10d7f45784718556532d78bb2..c62b8369c96a0b07d0902f9ff250ff12d8703d84 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2,6 +2,57 @@ namespace Automattic\WP\WP_CLI_Cron_Control_Offload; +/** + * Create cron event for a given WP-CLI command + * + * return bool|\WP_Error + */ +function schedule_cli_command( $args ) { + $event_args = validate_args( $args ); + + if ( is_wp_error( $event_args ) ) { + return $event_args; + } + + $scheduled = wp_schedule_single_event( strtotime( '+30 seconds' ), ACTION, array( 'command' => $event_args ) ); + + return false !== $scheduled; +} + +/** + * Validate WP-CLI command to be scheduled + * + * @param string $args + * @return array|\WP_Error + */ +function validate_args( $args ) { + // Strip `wp` if included + if ( 0 === stripos( $args, 'wp' ) ) { + $args = trim( substr( $args, 2 ) ); + } + + // Block disallowed commands + $command = explode( ' ', $args ); + $command = array_shift( $command ); + if ( ! is_command_allowed( $command ) ) { + return new \WP_Error( "$command not allowed" ); + } + + // Don't worry about the user WP-CLI runs as + if ( false === stripos( $args, '--allow-root' ) ) { + $args .= ' --allow-root'; + } + + // TODO: validate further + + // Nothing to run + if ( empty( $args ) ) { + return new \WP_Error( 'Invalid command provided' ); + } + + return $args; +} + /** * Check if command is allowed * @@ -71,54 +122,3 @@ function get_command_blacklist() { 'server', ); } - -/** - * Create cron event for a given WP-CLI command - * - * return bool|\WP_Error - */ -function schedule_cli_command( $args ) { - $event_args = validate_args( $args ); - - if ( is_wp_error( $event_args ) ) { - return $event_args; - } - - $scheduled = wp_schedule_single_event( strtotime( '+30 seconds' ), ACTION, array( 'command' => $event_args ) ); - - return false !== $scheduled; -} - -/** - * Validate WP-CLI command to be scheduled - * - * @param string $args - * @return array|\WP_Error - */ -function validate_args( $args ) { - // Strip `wp` if included - if ( 0 === stripos( $args, 'wp' ) ) { - $args = trim( substr( $args, 2 ) ); - } - - // Block disallowed commands - $command = explode( ' ', $args ); - $command = array_shift( $command ); - if ( ! is_command_allowed( $command ) ) { - return new \WP_Error( "$command not allowed" ); - } - - // Don't worry about the user WP-CLI runs as - if ( false === stripos( $args, '--allow-root' ) ) { - $args .= ' --allow-root'; - } - - // TODO: validate further - - // Nothing to run - if ( empty( $args ) ) { - return new \WP_Error( 'Invalid command provided' ); - } - - return $args; -}