Skip to content

Commit bc727cf

Browse files
committed
Prevent snippet from running twice when being checked for errors on save
1 parent cbac6f4 commit bc727cf

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

php/admin-menus/class-edit-menu.php

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ public function __construct() {
1515
);
1616

1717
add_action( 'admin_init', array( $this, 'remove_incompatible_codemirror' ) );
18+
19+
if ( isset( $_POST['save_snippet'] ) && $_POST['save_snippet'] ) {
20+
add_action( 'code_snippets/allow_execute_snippet', array( $this, 'prevent_exec_on_save' ), 10, 2 );
21+
}
1822
}
1923

2024
/**
@@ -35,6 +39,30 @@ public function register() {
3539
}
3640
}
3741

42+
/**
43+
* Prevent the snippet currently being saved from being executed
44+
* so it is not run twice (once normally, once
45+
*
46+
* @param bool $exec Whether the snippet will be executed
47+
* @param int $exec_id The ID of the snippet being executed
48+
*
49+
* @return bool Whether the snippet will be executed
50+
*/
51+
function prevent_exec_on_save( $exec, $exec_id ) {
52+
53+
if ( ! isset( $_POST['save_snippet'], $_POST['snippet_id'] ) ) {
54+
return $exec;
55+
}
56+
57+
$id = intval( $_POST['snippet_id'] );
58+
59+
if ( $id == $exec_id ) {
60+
return false;
61+
}
62+
63+
return $exec;
64+
}
65+
3866
/**
3967
* Executed when the menu is loaded
4068
*/
@@ -143,7 +171,7 @@ private function unshare_network_snippet( $snippet_id ) {
143171
private function code_error_callback( $out ) {
144172
$error = error_get_last();
145173

146-
if ( is_null( $error ) || ! in_array( $error['type'], array( E_ERROR, E_COMPILE_ERROR, E_USER_ERROR ) ) ) {
174+
if ( is_null( $error ) ) {
147175
return $out;
148176
}
149177

@@ -170,11 +198,6 @@ private function validate_code( Snippet $snippet ) {
170198
return false;
171199
}
172200

173-
/* Skip snippets that contain named functions */
174-
if ( preg_match( '/(?:function|class)\s+\w+/i', $snippet->code ) ) {
175-
return false;
176-
}
177-
178201
ob_start( array( $this, 'code_error_callback' ) );
179202
$result = eval( $snippet->code );
180203
ob_end_clean();

0 commit comments

Comments
 (0)