PluginProbe
Code Engine – PHP Snippets, AI Functions & Automation for WordPress / 0.3.7
Code Engine – PHP Snippets, AI Functions & Automation for WordPress v0.3.7
0.5.7 0.5.6 0.5.5 0.5.4 0.5.3 0.5.2 0.5.1 0.5.0 0.4.9 0.4.8 0.4.7 0.4.6 trunk 0.0.1 0.0.2 0.2.8 0.2.9 0.3.0 0.3.1 0.3.2 0.3.3 0.3.4 0.3.5 0.3.6 0.3.7 All 33 releases
← All changes | classes/core.php +796 -611 0.2.90.3.7 View file →
@@ -6,756 +6,941 @@
6 6 use PhpParser\Error;
7 7
8 8 class Meow_MWCODE_Core
9 9 {
10 - public $admin = null;
11 - public $snippet = null;
12 - public $is_rest = false;
13 - public $is_cli = false;
14 - public $site_url = null;
15 - public $mwcode = null;
10 + public $admin = null;
11 + public $snippet = null;
12 + public $is_rest = false;
13 + public $is_cli = false;
14 + public $site_url = null;
15 + public $mwcode = null;
16 + public $licenser = null;
16 17
17 - private $option_name = 'mwcode_options';
18 + private $option_name = 'mwcode_options';
18 19
19 - public function __construct() {
20 - global $mwcode;
21 -
22 - $this->site_url = get_site_url();
23 - $this->is_rest = MeowCommon_Helpers::is_rest();
24 - $this->is_cli = defined( 'WP_CLI' ) && WP_CLI;
25 -
26 - // Snippets
27 - $snippet = new Meow_MWCODE_Modules_Snippet( $this );
28 - $this->snippet = $snippet;
20 + public function __construct() {
21 + global $mwcode;
29 22
30 - // Create API before plugins_loaded
31 - $this->mwcode = new Meow_MWCODE_API( $this, $snippet );
32 - $mwcode = $this->mwcode;
23 + $this->site_url = get_site_url();
24 + $this->is_rest = MeowCommon_Helpers::is_rest();
25 + $this->is_cli = defined( 'WP_CLI' ) && WP_CLI;
33 26
34 - // Add the shortcode for the "content" snippets
35 - add_shortcode( 'code-engine', [ $this, 'content_shortcode' ] );
36 -
37 - add_action( 'plugins_loaded', array( $this, 'init' ) );
38 - }
27 + // Snippets
28 + $snippet = new Meow_MWCODE_Modules_Snippet( $this );
29 + $this->snippet = $snippet;
39 30
40 - function init() {
41 - // Part of the core, settings and stuff
42 - $this->admin = new Meow_MWCODE_Admin( $this );
31 + // Create API before plugins_loaded
32 + $this->mwcode = new Meow_MWCODE_API( $this, $snippet );
33 + $mwcode = $this->mwcode;
43 34
44 - // Only for REST
45 - if ( $this->is_rest ) {
46 - new Meow_MWCODE_Rest( $this, $this->admin, $this->snippet );
47 - }
48 - }
35 + // Add the shortcode for the "content" snippets
36 + add_shortcode( 'code-engine', [ $this, 'content_shortcode' ] );
49 37
38 + add_action( 'plugins_loaded', array( $this, 'init' ) );
39 + }
50 40
51 - /**
52 - *
53 - * Roles & Access Rights
54 - *
55 - */
56 - #region Roles & Access Rights
57 - public function can_access_settings() {
58 - return apply_filters( 'mwcode_allow_setup', current_user_can( 'manage_options' ) );
59 - }
41 + function init() {
42 + // Initialize the licenser for Pro version
43 + if ( class_exists( 'MeowCommonPro_Licenser' ) ) {
44 + $this->licenser = new MeowCommonPro_Licenser( MWCODE_PREFIX, MWCODE_ENTRY, MWCODE_DOMAIN, MWCODE_ITEM_ID, MWCODE_VERSION );
45 + }
60 46
61 - public function can_access_features() {
62 - return apply_filters( 'mwcode_allow_usage', current_user_can( 'administrator' ) );
63 - }
47 + // Part of the core, settings and stuff
48 + $this->admin = new Meow_MWCODE_Admin( $this );
64 49
65 - public function check_rest_nonce( $request ) {
66 - $nonce = $request->get_header( 'X-WP-Nonce' );
67 - return wp_verify_nonce( $nonce, 'wp_rest' );
68 - }
69 - #endregion
50 + // Only for REST
51 + if ( $this->is_rest ) {
52 + new Meow_MWCODE_Rest( $this, $this->admin, $this->snippet );
53 + }
54 +
55 + // MCP integration - check both class and global variable
56 + if ( class_exists( 'Meow_MWAI_Core' ) || isset( $GLOBALS['mwai'] ) ) {
57 + new Meow_MWCODE_MCP( $this );
58 + }
59 + }
70 60
71 - #region Options
61 + /**
62 + *
63 + * Roles & Access Rights
64 + *
65 + */
66 + #region Roles & Access Rights
67 + public function can_access_settings() {
68 + return apply_filters( 'mwcode_allow_setup', current_user_can( 'manage_options' ) );
69 + }
72 70
73 - function get_option( $option, $default = null ) {
74 - $options = $this->get_all_options();
75 - return $options[$option] ?? $default;
76 - }
71 + public function can_access_features() {
72 + return apply_filters( 'mwcode_allow_usage', current_user_can( 'administrator' ) );
73 + }
77 74
78 - function list_options() {
79 - return [
80 - //Safemode
81 - "safe_mode_status" => "on", // on, off, whitelist
82 - "safe_mode_whitelist" => [],
83 -
84 - //LOGS
85 - "server_debug_mode" => false,
75 + public function check_rest_nonce( $request ) {
76 + $nonce = $request->get_header( 'X-WP-Nonce' );
77 + return wp_verify_nonce( $nonce, 'wp_rest' );
78 + }
79 + #endregion
86 80
87 - //UI
88 - "ui_show_preview" => true,
81 + #region Options
89 82
90 - //AI
91 - "ai_suggestions" => false,
92 - "ai_engine_status"=> false,
93 - "ai_engine_message" => "",
83 + function get_option( $option, $default = null ) {
84 + $options = $this->get_all_options();
85 + return $options[$option] ?? $default;
86 + }
94 87
95 - //API
96 - "api_endpoint" => false,
97 - "api_token" => md5( time() . rand() ),
98 - ];
99 - }
88 + function list_options() {
89 + return [
90 + //Safemode
91 + "safe_mode_status" => "on", // on, off, whitelist
92 + "safe_mode_whitelist" => [],
93 + //"disallow_block_php" => true, // Do not allow PHP code to be execute through Blocks "code" parameter
94 + "code_blocks" => false,
95 + "code_blocks_whitelist" => [], // Whitelist for code blocks, if empty, all code blocks are allowed
96 +
97 + //LOGS
98 + "server_debug_mode" => false,
100 99
101 - function get_all_options( ) {
102 - $options = get_option( $this->option_name, $this->list_options( ) );
103 - $options = $this->sanitize_options( $options );
104 -
105 - return $options;
106 - }
100 + //UI
101 + "ui_show_preview" => false,
107 102
108 - function update_options( $options ) {
109 - $current_options = get_option($this->option_name);
110 -
111 - if ($current_options === $options) {
112 - // $this->log('💾 The options are already the expected value.');
113 - } else {
114 - if ( !update_option( $this->option_name, $options, false ) ) {
115 - $this->log( '💾 There was an issue updating the options.' );
116 - }
117 - }
118 -
119 - $options = $this->sanitize_options( $options );
120 - return $options;
121 - }
103 + //AI
104 + "ai_suggestions" => false,
105 + "ai_engine_status"=> false,
106 + "ai_engine_message" => "",
122 107
123 - function update_option( $option, $value ) {
124 - $options = $this->get_all_options();
125 - $options[$option] = $value;
126 - return $this->update_options( $options );
127 - }
108 + //API
109 + "api_endpoint" => false,
110 + "api_token" => md5( time() . rand() ),
111 +
112 + //MCP
113 + "mcp_support" => false,
114 + ];
115 + }
128 116
129 - function reset_options() {
130 - if ( $this->get_all_options() === $this->list_options() ) {
131 - return true;
132 - }
133 - return $this->update_options( $this->list_options() );
134 - }
117 + function get_all_options( ) {
118 + $options = get_option( $this->option_name, [] );
119 + $defaults = $this->list_options();
120 +
121 + // Merge with defaults to ensure all options exist
122 + $options = array_merge( $defaults, $options );
123 +
124 + $options = $this->sanitize_options( $options );
125 + return $options;
126 + }
135 127
136 - // Validate and keep the options clean and logical.
137 - function sanitize_options( $options ) {
138 - $options_modified = false;
128 + function update_options( $options ) {
129 + $current_options = get_option($this->option_name);
139 130
140 - // Make sure safe mode whitelist is an array
141 - if ( ! is_array( $options['safe_mode_whitelist'] ) ) {
142 - $options['safe_mode_whitelist'] = explode( ",", $options['safe_mode_whitelist'] );
143 - $options_modified = true;
144 - }
131 + if ($current_options === $options) {
132 + // $this->log('💾 The options are already the expected value.');
133 + } else {
134 + if ( !update_option( $this->option_name, $options, false ) ) {
135 + $this->log( '💾 There was an issue updating the options.' );
136 + }
137 + }
145 138
146 - // Update AI Engine status
147 - $options_modified = $this->updateAIEngineStatus( $options ) || $options_modified;
139 + $options = $this->sanitize_options( $options );
140 + return $options;
141 + }
148 142
149 - // Disable AI related features if AI Engine is not available
150 - if ( ! $options['ai_engine_status'] && $options['ai_suggestions'] !== false ) {
151 - $options['ai_suggestions'] = false;
152 - $options_modified = true;
153 - }
143 + function update_option( $option, $value ) {
144 + $options = $this->get_all_options();
145 + $options[$option] = $value;
146 + return $this->update_options( $options );
147 + }
154 148
155 - if ( $options_modified ) {
156 - update_option( $this->option_name, $options, false );
157 - }
149 + function reset_options() {
150 + if ( $this->get_all_options() === $this->list_options() ) {
151 + return true;
152 + }
153 + return $this->update_options( $this->list_options() );
154 + }
158 155
159 - return $options;
160 - }
156 + // Validate and keep the options clean and logical.
157 + function sanitize_options( $options ) {
158 + $options_modified = false;
159 +
160 + // Ensure mcp_support exists in options
161 + if ( !isset( $options['mcp_support'] ) ) {
162 + $options['mcp_support'] = false;
163 + }
161 164
162 - private function updateAIEngineStatus( &$options ) {
163 - global $mwai;
165 + // Make sure safe mode whitelist is an array
166 + if ( ! is_array( $options['safe_mode_whitelist'] ) ) {
167 + $options['safe_mode_whitelist'] = explode( ",", $options['safe_mode_whitelist'] );
168 + $options_modified = true;
169 + }
164 170
165 - if ( is_null( $mwai ) || ! isset( $mwai ) ) {
166 - $options['ai_engine_status'] = false;
167 - $options['ai_engine_message'] = 'AI Engine is not available.';
168 - return true;
169 - }
171 + // Update AI Engine status
172 + $options_modified = $this->updateAIEngineStatus( $options ) || $options_modified;
170 173
171 - try {
172 - $status = $mwai->checkStatus();
174 + // Disable AI related features if AI Engine is not available
175 + if ( ! $options['ai_engine_status'] ) {
176 + if ( $options['ai_suggestions'] !== false ) {
177 + $options['ai_suggestions'] = false;
178 + $options_modified = true;
179 + }
180 + // Note: We don't disable MCP support here anymore
181 + // It will be checked at runtime in the MCP class
182 + }
173 183
174 - if ( $options['ai_engine_status'] != true || $options['ai_engine_message'] != $status ) {
175 - $options['ai_engine_status'] = true;
176 - $options['ai_engine_message'] = $status;
177 - return true;
178 - }
179 - } catch ( Exception $e ) {
180 - if ( $options['ai_engine_status'] != false || $options['ai_engine_message'] != $e->getMessage() ) {
181 - $options['ai_engine_status'] = false;
182 - $options['ai_engine_message'] = $e->getMessage();
183 - return true;
184 - }
185 - }
184 + if ( $options_modified ) {
185 + update_option( $this->option_name, $options, false );
186 + }
186 187
187 - return false;
188 - }
188 + return $options;
189 + }
189 190
190 - // #endregion
191 + private function updateAIEngineStatus( &$options ) {
192 + global $mwai;
191 193
192 - #region Snippets
194 + if ( is_null( $mwai ) || ! isset( $mwai ) ) {
195 + $options['ai_engine_status'] = false;
196 + $options['ai_engine_message'] = 'AI Engine is not available.';
197 + return true;
198 + }
193 199
194 - /**
195 - * Get snippet.
196 - *
197 - * @param $id
198 - * @return mixed
199 - */
200 - protected function get_snippet( $id ) {
201 - if ( $this->snippet === null ) {
202 - $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
203 - }
200 + try {
201 + $status = $mwai->checkStatus();
204 202
205 - return $this->snippet->select_one( $id );
203 + if ( $options['ai_engine_status'] != true || $options['ai_engine_message'] != $status ) {
204 + $options['ai_engine_status'] = true;
205 + $options['ai_engine_message'] = $status;
206 + return true;
207 + }
208 + } catch ( Exception $e ) {
209 + if ( $options['ai_engine_status'] != false || $options['ai_engine_message'] != $e->getMessage() ) {
210 + $options['ai_engine_status'] = false;
211 + $options['ai_engine_message'] = $e->getMessage();
212 + return true;
213 + }
206 214 }
207 215
208 - private function sanitize_arg( $name, $value ) {
209 - if ( $name[0] !== '$' ) { $name = '$' . $name; }
210 -
211 - if ( !empty( $value ) && !is_numeric( $value ) && $value[0] !== '"' && $value[strlen( $value ) - 1] !== '"' ) {
212 - $value = '"' . esc_sql( $value ) . '"';
213 - }
216 + return false;
217 + }
214 218
215 - return [ $name, $value ];
216 - }
219 + #endregion
217 220
218 - function run_non_fn_snippet( $id, $code = null, $test = false ) {
219 - // Retrieve the snippet code from the provided code or via the snippet ID.
220 - if ( $code ) {
221 - $snippet = [ 'code' => $code ];
222 - } else {
223 - $snippet = $this->get_snippet( $id );
224 - }
225 -
226 - // Remove any PHP opening tag.
227 - $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
228 -
221 + #region Snippets
229 222
230 - if ( $test ) {
231 - $snippet['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $snippet['code'] );
232 - }
233 -
234 - $error = null;
235 - $output = null;
236 -
237 - try {
238 - ob_start();
239 - eval( $snippet['code'] );
240 - $output = ob_get_clean();
241 - } catch ( Throwable $e ) {
242 - $error = new Exception( 'Error executing the snippet, ' . $e->getMessage() );
243 - ob_clean();
244 - } finally {
245 - restore_error_handler();
246 - }
247 -
248 - // If in test mode, return output as an array of lines with an 'error' key if needed.
249 - if ( $test ) {
250 - $output = explode( "\n", trim( $output ) );
251 - if ( $error !== null ) {
252 - $output['error'] = $error->getMessage();
253 - }
254 - } else {
255 - if ( $error !== null ) {
256 - throw $error;
257 - }
258 - }
259 -
260 - return $output;
261 - }
223 + /**
224 + * Get snippet.
225 + *
226 + * @param $id
227 + * @return mixed
228 + */
229 + protected function get_snippet( $id ) {
230 + if ( $this->snippet === null ) {
231 + $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
232 + }
262 233
263 - function run_snippet( $id, $args = [], $params = [] )
264 - {
265 - // Static array to track defined functions
266 - static $defined_functions = array();
234 + return $this->snippet->select_one( $id );
235 + }
267 236
268 - if ( $id ) { // If there is an ID, we get the snippet, if not we get the data from the params
269 - $snippet = $this->get_snippet( $id );
270 - $this->snippet->get_function_snippets_data( $snippet ); // adds the function data to the snippet
237 + function add_snippet( $params ) {
271 238
272 - $params = [ // We set the params according to the snippet we fetched
273 - 'test' => false, // If we pass an ID to the function, we are not testing the snippet
274 - // 'test' => $params['test'] ?? false if needed we can still use ID and test at the same time (should not happen)
275 - 'code' => $snippet['code'],
276 - 'name' => $snippet['functionName'],
277 - 'args' => $snippet['functionArgs'],
278 - 'values' => $snippet['functionArgsDict'] // Contains the default values of the arguments
279 - ];
280 - }
239 + $response = [
240 + "snippet" => null,
241 + "result" => false,
242 + ];
281 243
282 - // Sanitize all the arguments if the option is enabled
283 - if ( $this->get_option( 'sanitize_arguments', true ) ) {
244 + $this->snippet->validate( $params );
284 245
285 - if ( $args ) {
286 - foreach ( $args as $name => $value ) {
287 - list( $sanitizedName, $sanitizedValue ) = $this->sanitize_arg( $name, $value );
288 - unset( $args[$name] );
246 + $params = $this->snippet->formatParamsForDatabase( $params );
247 + $result = $this->snippet->insert( $params );
248 + $snippet = $this->snippet->select_one( $result );
289 249
290 - $args[$sanitizedName] = $sanitizedValue;
291 - }
292 - }
250 + if( $result ) {
251 + $params['id'] = (string)$result;
293 252
294 - foreach ( $params['values'] as $name => $value ) {
253 + $this->snippet->create_or_update_function_snippet( $params );
254 + $this->snippet->create_or_update_interval_snippet( $params );
295 255
296 - if( array_key_exists( 'input', $value) ) {
297 - list( $sanitizedInputName, $sanitizedInputValue ) = $this->sanitize_arg( $name, $value['input'] );
298 - $params['values'][$sanitizedInputName]['input'] = $sanitizedInputValue;
299 - }
300 -
301 - if( array_key_exists( 'default', $value) ) {
302 - list( $sanitizedDefaultValueName, $sanitizedDefaultValue ) = $this->sanitize_arg( $name, $value['default'] );
303 - $params['values'][$sanitizedDefaultValueName]['default'] = $sanitizedDefaultValue;
304 - }
305 - }
256 + $this->snippet->get_function_snippets_data( $snippet );
257 + }
306 258
307 - }
259 + $response['snippet'] = $snippet;
260 + $response['result'] = $result;
308 261
309 -
262 + return $response;
263 + }
310 264
311 - // Make sure the function is existing and is the one in the snippet
312 - if ( empty( $params['code'] ) ) {
313 - throw new Exception( 'Code Engine: The snippet code appears to be empty.' );
314 - }
315 -
316 - if ( empty( $params['name'] ) || ! str_contains( $params['code'], $params['name'] ) ) {
317 - throw new Exception( "Code Engine: Function name does not match. The name should be {$params['name']}." );
318 - }
265 + private function sanitize_arg( $name, $value, $type = null) {
266 + $real_type = gettype( $value );
319 267
320 - // Overwrite the default values with the provided ones
321 - if ( $args ) {
322 - foreach ( $args as $name => $value ) {
323 - $params['values'][$name]['input'] = $value;
324 - }
268 + if ( $name[0] !== '$' ) { $name = '$' . $name; }
325 269
326 - $this->log( '⚡ Arguments provided: ' . json_encode( $args ) );
327 - }
270 + if ( $type == null ) {
271 + $type = $real_type;
272 + }
328 273
329 - // Check if the function has already been defined
330 - if ( !in_array( $params['name'], $defined_functions ) ) {
274 + if ( $type != 'array' && !empty( $value ) && !is_numeric( $value ) && $value[0] !== '"' && $value[strlen( $value ) - 1] !== '"' ) {
275 + $value = '"' . esc_sql( $value ) . '"';
276 + }
331 277
332 - // If not, proceed with modification and definition
333 - if ( $params['test'] ) { // Make sure the echo statement uses a line break
334 - $params['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $params['code'] );
335 - } else { // Remove all echo statements
336 - $params['code'] = preg_replace( '/echo\s+(.+?);/s', '', $params['code'] );
337 - }
278 + if ( $type === 'array' && $real_type === 'string' ) {
279 + // We got a string like this: "["a", "b", "c"]" or "[ 1, 2, 3 ]"
280 + // We need to convert it to an array
281 + $value = str_replace( '"', '', $value );
282 + $value = str_replace( '[', '', $value );
283 + $value = str_replace( ']', '', $value );
284 + $value = explode( ',', $value );
285 + $value = array_map( 'trim', $value );
286 + }
338 287
339 - $params['code'] = "if (!function_exists('{$params['name']}')) {\n" . $params['code'] . "\n}\n";
288 + if ( $type === 'array' ) {
289 + $value = json_encode( $value );
290 + $value = str_replace( '\\', '', $value );
291 + }
340 292
341 - // Add the function name to the array to avoid redefinition
342 - $defined_functions[] = $params['name'];
343 - } else {
344 - // If already defined, just prepare to call the function without redefining it
345 - $params['code'] = '';
346 - }
293 + return [ $name, $value ];
294 + }
347 295
348 - // Prepare the code to be executed
349 - $params['code'] .= "\n\$mwcode_result = {$params['name']}(";
350 - foreach ( $params['args'] as $index => $arg ) {
351 - $value = 'null'; // In case the argument is not provided it will be null
296 + function run_non_fn_snippet( $id, $code = null, $test = false ) {
297 + // Retrieve the snippet code from the provided code or via the snippet ID.
298 + if ( $code ) {
299 + $snippet = [ 'code' => $code ];
300 + } else {
301 + $snippet = $this->get_snippet( $id );
302 + }
352 303
353 - if ( array_key_exists( $arg, $params['values'] ) ) { // Avoid warnings if the argument is not provided
304 + // Remove any PHP opening tag.
305 + $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
354 306
355 - // If the argument is provided, use it, if not use the default value
356 - if ( !empty( $params['values'][$arg]['input'] ) ) {
357 - $value = $params['values'][$arg]['input'];
307 + if ( $test ) {
308 + $snippet['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $snippet['code'] );
309 + }
310 +
311 + $error = null;
312 + $output = null;
313 +
314 + try {
315 + ob_start();
316 + eval( $snippet['code'] );
317 + $output = ob_get_clean();
318 + } catch ( Throwable $e ) {
319 + $snippet_id = $id ? " ( ID: $id )" : '(Content Gutenberg Block)';
320 + $this->log( '🔴 Error executing the snippet ' . $snippet_id . ' : ' . $e->getMessage() );
321 + ob_clean();
322 + } finally {
323 + restore_error_handler();
324 + }
325 +
326 + // If in test mode, return output as an array of lines with an 'error' key if needed.
327 + if ( $test ) {
328 + $output = explode( "\n", trim( $output ) );
329 + if ( $error !== null ) {
330 + $output['error'] = $error->getMessage();
331 + }
332 + } else {
333 + if ( $error !== null ) {
334 + throw $error;
335 + }
336 + }
337 +
338 + return $output;
339 + }
358 340
359 - } else if ( !empty( $params['values'][$arg]['default'] ) ) {
360 - $value = $params['values'][$arg]['default'];
361 - }
362 - }
341 + function run_snippet( $id, $args = [], $params = [] )
342 + {
343 + // Static array to track defined functions
344 + static $defined_functions = array();
363 345
364 - $params['code'] .= "{$value}";
365 - if ( $index < count( $params['args'] ) - 1 ) {
366 - $params['code'] .= ', ';
367 - }
368 - }
369 - $params['code'] .= ");\necho print_r(\$mwcode_result, true);";
346 + if ( $id ) { // If there is an ID, we get the snippet, if not we get the data from the params
347 + $snippet = $this->get_snippet( $id );
348 + $this->snippet->get_function_snippets_data( $snippet ); // adds the function data to the snippet
370 349
371 - $error = null;
372 - $output = null;
350 + $params = [ // We set the params according to the snippet we fetched
351 + 'test' => false, // If we pass an ID to the function, we are not testing the snippet
352 + // 'test' => $params['test'] ?? false if needed we can still use ID and test at the same time (should not happen)
353 + 'code' => $snippet['code'],
354 + 'name' => $snippet['functionName'],
355 + 'args' => $snippet['functionArgs'],
356 + 'values' => $snippet['functionArgsDict'] // Contains the default values of the arguments
357 + ];
358 + }
373 359
374 - try {
375 - ob_start();
376 - eval( $params['code'] );
377 - $output = ob_get_clean();
378 -
379 - if ( $params['test'] ){
380 - $output = explode( "\n", $output );
381 - }
382 -
383 - } catch ( Throwable $e ) {
384 - //$this->log('Code Engine: Error executing the function: ' . $e->getMessage());
385 - $error = new Exception(' Error executing the function, ' . $e->getMessage());
360 + // Sanitize all the arguments if the option is enabled
361 + if ( $this->get_option( 'sanitize_arguments', true ) ) {
386 362
387 - ob_clean();
388 - } finally {
389 - restore_error_handler();
390 - }
363 + if ( $args ) {
364 + foreach ( $args as $name => $value ) {
365 + list( $sanitizedName, $sanitizedValue ) = $this->sanitize_arg( $name, $value );
366 + unset( $args[$name] );
391 367
392 - if ( $error !== null ) {
393 - if( $params['test'] ){
394 - $output['error'] = $error->getMessage();
395 - } else {
396 - throw $error;
397 - }
398 - }
368 + $args[$sanitizedName] = $sanitizedValue;
369 + }
370 + }
399 371
400 - return $output;
401 - }
372 + foreach ( $params['values'] as $name => $value ) {
402 373
374 + if( array_key_exists( 'input', $value) ) {
375 + list( $sanitizedInputName, $sanitizedInputValue ) = $this->sanitize_arg( $name, $value['input'], $value['type'] );
376 + $params['values'][$sanitizedInputName]['input'] = $sanitizedInputValue;
377 + }
403 378
404 - function parse_snippet( $code, $new_snippet = false ){
405 - $parser = ( new ParserFactory( ) )->createForNewestSupportedVersion( );
379 + if( array_key_exists( 'default', $value) ) {
380 + list( $sanitizedDefaultValueName, $sanitizedDefaultValue ) = $this->sanitize_arg( $name, $value['default'], $value['type'] );
381 + $params['values'][$sanitizedDefaultValueName]['default'] = $sanitizedDefaultValue;
382 + }
383 + }
406 384
407 - if( !$this->snippet ){
408 - $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
409 - }
385 + }
410 386
411 - // First we check the function names are unique
412 - $fn = $this->snippet->sanitize_and_check_functions( $code, $new_snippet );
413 - if ( ! $fn['is_valid'] ) {
387 + // Make sure the function is existing and is the one in the snippet
388 + if ( empty( $params['code'] ) ) {
389 + throw new Exception( 'Code Engine: The snippet code appears to be empty.' );
390 + }
414 391
415 - $lint = [
416 - 'line' => 1,
417 - 'attributes' => $fn['attributes'][0],
418 - 'raw_message' => implode(', ', $fn['errors'][0]),
419 - 'message' => implode(', ', $fn['errors'][0]),
420 - ];
392 + if ( empty( $params['name'] ) || ! str_contains( $params['code'], $params['name'] ) ) {
393 + throw new Exception( "Code Engine: Function name does not match. The name should be {$params['name']}." );
394 + }
421 395
422 - return $lint;
423 - }
396 + // Overwrite the default values with the provided ones
397 + if ( $args ) {
398 + foreach ( $args as $name => $value ) {
399 + $params['values'][$name]['input'] = $value;
400 + }
424 401
425 - try {
426 - $stmts = $parser->parse( $code );
427 - $result = $stmts;
428 - } catch ( PhpParser\Error $e ) {
402 + $this->log( '⚡ Arguments provided: ' . json_encode( $args ) );
403 + }
429 404
430 - $lint = [
431 - 'line' => $e->getStartLine(),
432 - 'attributes' => $e->getAttributes(),
433 - 'raw_message' => $e->getRawMessage(),
434 - 'message' => $e->getMessage(),
435 - ];
405 + // Check if the function has already been defined
406 + if ( !in_array( $params['name'], $defined_functions ) ) {
436 407
437 - return $lint;
438 - }
408 + // If not, proceed with modification and definition
409 + if ( $params['test'] ) { // Make sure the echo statement uses a line break
410 + $params['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $params['code'] );
411 + } else { // Remove all echo statements
412 + $params['code'] = preg_replace( '/echo\s+(.+?);/s', '', $params['code'] );
413 + }
439 414
440 - return null;
441 - }
415 + $params['code'] = "if (!function_exists('{$params['name']}')) {\n" . $params['code'] . "\n}\n";
442 416
443 - public function get_js_functions_to_push() {
444 - $functions = $this->snippet->get_functions();
445 - $js_functions = [];
446 - foreach ( $functions as &$function ) {
447 - if ( !isset( $function['target'] ) ) {
448 - $function['target'] = 'php';
449 - }
450 - if ( $function['target'] == 'js' ) {
451 - $js_functions[] = $function;
452 - }
453 - }
454 - $snippets = [];
455 - foreach ( $js_functions as $function ) {
456 - $snippet = $this->snippet->select_one( $function['snippetId'] );
457 - $snippet['function_info'] = $function; // Add function info to snippet
458 - $snippets[] = $snippet;
459 - }
460 -
461 - return $this->generate_js_functions_code( $snippets );
462 - }
463 -
464 - function generate_js_functions_code ($snippets ) {
465 - $code = "";
466 - foreach ( $snippets as $snippet ) {
467 - $function_code = $snippet['code'];
468 - $function_info = $snippet['function_info'];
469 -
470 - // Extract function name and arguments
471 - preg_match( '/(?:const|let|var)?\s*(\w+)\s*=\s*\((.*?)\)\s*=>/', $function_code, $matches );
472 - $function_name = $matches[1] ?? $function_info['name'];
473 - $function_args = $matches[2] ?? '';
474 -
475 - // Prepare default values
476 - $default_args = [];
477 - foreach ( $function_info['args'] as $arg ) {
478 - if ( isset( $arg['default'] ) && $arg['default'] !== '' ) {
479 - $default_args[$arg['name']] = $arg['default'];
480 - }
481 - }
482 -
483 - // Modify function to use default values
484 - if ( !empty( $default_args ) ) {
485 - $new_args = explode( ',', $function_args );
486 - foreach ( $new_args as &$arg ) {
487 - $arg = trim( $arg );
488 - if ( isset( $default_args[$arg] ) ) {
489 - $arg .= " = " . json_encode( $default_args[$arg] );
490 - }
491 - }
492 - $new_args_string = implode( ', ', $new_args );
493 - $function_code = preg_replace(
494 - '/(\w+)\s*=\s*\((.*?)\)\s*=>/',
495 - "$1 = ($new_args_string) =>",
496 - $function_code
497 - );
498 - }
499 -
500 - $code .= $function_code . "\n\n";
501 - }
417 + // Add the function name to the array to avoid redefinition
418 + $defined_functions[] = $params['name'];
419 + } else {
420 + // If already defined, just prepare to call the function without redefining it
421 + $params['code'] = '';
422 + }
502 423
503 - return $code;
504 - }
424 + // Prepare the code to be executed
425 + $params['code'] .= "\n\$mwcode_result = {$params['name']}(";
426 + foreach ( $params['args'] as $index => $arg ) {
427 + $value = 'null'; // In case the argument is not provided it will be null
505 428
429 + if ( array_key_exists( $arg, $params['values'] ) ) { // Avoid warnings if the argument is not provided
506 430
507 - /**
508 - * [STATIC] Execute active snippets.
509 - *
510 - * @return array
511 - */
512 - public function execute_active_snippets() {
431 + // If the argument is provided, use it, if not use the default value
432 + if ( !empty( $params['values'][$arg]['input'] ) ) {
433 + $value = $params['values'][$arg]['input'];
513 434
514 - $blocked = false;
515 - $page = isset( $_GET["page"] ) ? sanitize_text_field( $_GET["page"] ) : null;
516 - if ( $page === 'mwcode_settings' || !Meow_MWCODE_Core::is_white_listed_rest() ) {
517 - $blocked = true;
518 - }
435 + } else if ( !empty( $params['values'][$arg]['default'] ) ) {
436 + $value = $params['values'][$arg]['default'];
437 + }
438 + }
519 439
520 - if ( empty( $this->snippet ) ) {
521 - $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
522 - }
440 + $params['code'] .= "{$value}";
441 + if ( $index < count( $params['args'] ) - 1 ) {
442 + $params['code'] .= ', ';
443 + }
444 + }
445 + $params['code'] .= ");\necho print_r(\$mwcode_result, true);";
523 446
524 - $ts = $this->get_option( 'thrown_snippet', null );
525 - if ( !empty( $ts ) ) {
526 - $this->log( "⚠️ Your snippet \"{$ts['name']}\" has thrown a fatal error last time, so we disabled it. Please check the logs for more information." );
527 - $this->snippet->force_disable( $ts['id'] );
528 - $this->update_option( 'thrown_snippet', null );
529 - }
447 + $error = null;
448 + $output = null;
530 449
531 - $scope = is_admin() ? [ 'backend', 'persistent' ] : [ 'frontend', 'persistent' ];
532 - // Get all active snippets
450 + try {
451 + ob_start();
452 + eval( $params['code'] );
453 + $output = ob_get_clean();
454 +
455 + if ( $params['test'] ){
456 + $output = explode( "\n", $output );
457 + }
458 +
459 + } catch ( Throwable $e ) {
460 + //$this->log('Code Engine: Error executing the function: ' . $e->getMessage());
461 + $error = new Exception(' Error executing the function, ' . $e->getMessage());
533 462
534 -
463 + ob_clean();
464 + } finally {
465 + restore_error_handler();
466 + }
535 467
536 - $snippets = $this->snippet->select(
537 - null, // offset
538 - -1, // limit
539 - [
540 - [ 'accessor' => 'active', 'value' => 1 ],
541 - [ 'accessor' => 'scope', 'value' => $scope ],
542 - ], // filter
543 - [ 'accessor' => 'priority', 'by' => 'DESC' ] // sort
544 - )['data'];
468 + if ( $error !== null ) {
469 + if( $params['test'] ){
470 + $output['error'] = $error->getMessage();
471 + } else {
472 + throw $error;
473 + }
474 + }
545 475
476 + return $output;
477 + }
546 478
547 - if ( empty( $snippets ) ) {
548 - return;
479 +
480 + function parse_snippet( $code, $new_snippet = false ){
481 + $parser = ( new ParserFactory( ) )->createForNewestSupportedVersion( );
482 +
483 + if( !$this->snippet ){
484 + $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
485 + }
486 +
487 + // First we check the function names are unique
488 + $fn = $this->snippet->sanitize_and_check_functions( $code, $new_snippet );
489 + if ( ! $fn['is_valid'] ) {
490 +
491 + $lint = [
492 + 'line' => 1,
493 + 'attributes' => $fn['attributes'][0],
494 + 'raw_message' => implode(', ', $fn['errors'][0]),
495 + 'message' => implode(', ', $fn['errors'][0]),
496 + ];
497 +
498 + return $lint;
499 + }
500 +
501 + try {
502 + $stmts = $parser->parse( $code );
503 + $result = $stmts;
504 + } catch ( PhpParser\Error $e ) {
505 +
506 + $lint = [
507 + 'line' => $e->getStartLine(),
508 + 'attributes' => $e->getAttributes(),
509 + 'raw_message' => $e->getRawMessage(),
510 + 'message' => $e->getMessage(),
511 + ];
512 +
513 + return $lint;
514 + }
515 +
516 + return null;
517 + }
518 +
519 + public function get_js_functions_to_push() {
520 + $functions = $this->snippet->get_functions();
521 + $js_functions = [];
522 + foreach ( $functions as &$function ) {
523 + if ( !isset( $function['target'] ) ) {
524 + $function['target'] = 'php';
525 + }
526 + if ( $function['target'] == 'js' ) {
527 + $js_functions[] = $function;
528 + }
529 + }
530 + $snippets = [];
531 + foreach ( $js_functions as $function ) {
532 + $snippet = $this->snippet->select_one( $function['snippetId'] );
533 + $snippet['function_info'] = $function; // Add function info to snippet
534 + $snippets[] = $snippet;
535 + }
536 +
537 + return $this->generate_js_functions_code( $snippets );
538 + }
539 +
540 + function generate_js_functions_code ($snippets ) {
541 + $code = "";
542 + foreach ( $snippets as $snippet ) {
543 + $function_code = $snippet['code'];
544 + $function_info = $snippet['function_info'];
545 +
546 + // Extract function name and arguments
547 + preg_match( '/(?:const|let|var)?\s*(\w+)\s*=\s*\((.*?)\)\s*=>/', $function_code, $matches );
548 + $function_name = $matches[1] ?? $function_info['name'];
549 + $function_args = $matches[2] ?? '';
550 +
551 + // Prepare default values
552 + $default_args = [];
553 + foreach ( $function_info['args'] as $arg ) {
554 + if ( isset( $arg['default'] ) && $arg['default'] !== '' ) {
555 + $default_args[$arg['name']] = $arg['default'];
549 556 }
557 + }
550 558
551 - $snippets = array_map( function ( $snippet ) use ( $blocked ) {
552 - $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
553 - $snippet['blocked'] = $blocked;
559 + // Modify function to use default values
560 + if ( !empty( $default_args ) ) {
561 + $new_args = explode( ',', $function_args );
562 + foreach ( $new_args as &$arg ) {
563 + $arg = trim( $arg );
564 + if ( isset( $default_args[$arg] ) ) {
565 + $arg .= " = " . json_encode( $default_args[$arg] );
566 + }
567 + }
568 + $new_args_string = implode( ', ', $new_args );
569 + $function_code = preg_replace(
570 + '/(\w+)\s*=\s*\((.*?)\)\s*=>/',
571 + "$1 = ($new_args_string) =>",
572 + $function_code
573 + );
574 + }
554 575
555 - // If the snippet must be executed only in the frontend, we bypass the block
556 - if ( !is_admin() && $snippet['scope'] === 'frontend' ) {
557 - $snippet['blocked'] = false;
558 - }
576 + $code .= $function_code . "\n\n";
577 + }
559 578
560 - return $snippet;
561 - }, $snippets );
579 + return $code;
580 + }
562 581
563 -
564 582
565 - return $snippets;
583 + /**
584 + * [STATIC] Execute active snippets.
585 + *
586 + * @return array
587 + */
588 + public function execute_active_snippets() {
589 +
590 + $blocked = false;
591 + $page = isset( $_GET["page"] ) ? sanitize_text_field( $_GET["page"] ) : null;
592 +
593 +
594 + if ( $page === 'mwcode_settings' ) {
595 + // If we blocks global snippets like nonce_life filter, we would block the settings page so let's remove the block for this page
596 +
597 + $blocked = false;
598 + //$blocked = true;
566 599 }
600 + // Block REST requests that aren't whitelisted
601 + elseif ( MeowCommon_Helpers::is_rest() && !Meow_MWCODE_Core::is_white_listed_rest() ) {
602 + $blocked = true;
603 + }
567 604
605 + if ( empty( $this->snippet ) ) {
606 + $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
607 + }
568 608
569 - #endregion
609 + $ts = $this->get_option( 'thrown_snippet', null );
610 + if ( !empty( $ts ) ) {
611 + $this->log( "⚠️ Your snippet \"{$ts['name']}\" has thrown a fatal error last time, so we disabled it. Please check the logs for more information." );
612 + $this->snippet->force_disable( $ts['id'] );
613 + $this->update_option( 'thrown_snippet', null );
614 + }
570 615
571 - #reion Shortcodes
616 + $scope = is_admin() ? [ 'backend', 'persistent' ] : [ 'frontend', 'persistent' ];
617 + // Get all active snippets
572 618
573 - function content_shortcode( $atts ) {
619 + $snippets = $this->snippet->select(
620 + null, // offset
621 + -1, // limit
622 + [
623 + [ 'accessor' => 'active', 'value' => 1 ],
624 + [ 'accessor' => 'scope', 'value' => $scope ],
625 + ], // filter
626 + [ 'accessor' => 'priority', 'by' => 'DESC' ] // sort
627 + )['data'];
574 628
575 - $atts = shortcode_atts( array(
576 - 'id' => null,
577 - ), $atts );
629 + if ( empty( $snippets ) ) {
630 + return;
631 + }
578 632
579 - $id = $atts['id'];
580 - if ( empty( $id ) ) {
581 - return '<b>Code Engine:</b> Please provide a snippet ID.';
582 - }
633 + $snippets = array_map( function ( $snippet ) use ( $blocked ) {
634 + $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
635 + $snippet['blocked'] = $blocked;
583 636
584 - $snippet = $this->get_snippet( $id );
637 + // If the snippet must be executed only in the frontend, we bypass the block
638 + if ( !is_admin() && $snippet['scope'] === 'frontend' ) {
639 + $snippet['blocked'] = false;
640 + }
585 641
586 - if ( empty( $snippet ) ) {
587 - return '<b>Code Engine:</b> The snippet does not exist.';
588 - }
642 + return $snippet;
643 + }, $snippets );
589 644
590 - //Check if the snippet scope is either content_php or content_js
591 - $is_content_php = $snippet['scope'] === 'content_php';
592 - $is_content_js = $snippet['scope'] === 'content_js';
645 + return $snippets;
646 + }
593 647
594 - if ( !$is_content_php && !$is_content_js ) {
595 - return '<b>Code Engine:</b> The snippet is not a content snippet.';
596 - }
597 648
598 - //Check if the snippet is active
599 - if ( !$snippet['active'] ) {
600 - return '<b>Code Engine:</b> The snippet is not active.';
601 - }
649 + #endregion
602 650
603 - $output = '<b>Code Engine:</b> No output.';
651 + #region Shortcodes
604 652
605 - if ( $is_content_js ) {
606 - $output = '<script>' . $snippet['code'] . '</script>';
607 - }
653 + function content_shortcode( $atts ) {
608 654
609 - if ( $is_content_php ) {
610 - $output = $this->run_non_fn_snippet( $id );
611 - }
655 + $atts = shortcode_atts( array(
656 + 'id' => null,
657 + 'target' => null,
658 + 'code' => null,
659 + ), $atts );
612 660
613 - return $output;
614 - }
661 + $id = $atts['id'];
662 + $target = $atts['target'];
663 + $code = $atts['code'];
664 + $current_post = get_post();
665 +
666 + $no_js = defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML;
667 + $allow_php = $this->get_option( 'code_blocks', false );
668 + $allow_php_whitelist = $this->get_option( 'code_blocks_whitelist', [] );
669 +
670 + // If the ID is null, it means it comes from a Guttenberg block
671 + $is_block = empty( $id ) && !empty( $code );
615 672
616 - #endregion
673 + if( $is_block ) {
617 674
618 - #region Logs
675 + if( $target !== 'js' && $target !== 'php' ) {
676 + return '<b>Code Engine:</b> Please provide a valid target (js or php).';
677 + }
619 678
620 - function get_logs() {
621 - $log_file_path = $this->get_logs_path();
679 + if ( $no_js && $target === 'js' ) {
680 + return '<b>Code Engine:</b> Code Block JS are disabled because unfiltered HTML is not allowed on your server.';
681 + }
622 682
623 - if ( !file_exists( $log_file_path ) ) {
624 - return "Empty log file.";
625 - }
683 + if ( $target === 'php' ) {
626 684
627 - $content = file_get_contents( $log_file_path );
628 - $lines = explode( "\n", $content );
629 - $lines = array_filter( $lines );
630 - $lines = array_reverse( $lines );
631 - $content = implode( "\n", $lines );
632 - return $content;
633 - }
685 + if ( !$allow_php ) {
686 + return '<b>Code Engine:</b> Code Block PHP are disabled. If you are an administrator, you can enable it in the settings, this is not recommended. Please use a Content Snippet ( PHP ) instead.';
687 + }
634 688
635 - function clear_logs() {
636 - $logPath = $this->get_logs_path();
637 - if ( file_exists( $logPath ) ) {
638 - unlink( $logPath );
639 - }
689 + if ( !empty( $allow_php_whitelist ) && !in_array( $current_post->ID, $allow_php_whitelist ) ) {
690 + return '<b>Code Engine:</b> Code Block PHP are disabled for this post. If you are an administrator, you can enable it in the settings, this is not recommended. Please use a Content Snippet ( PHP ) instead.';
691 + }
692 + }
640 693
641 - $options = $this->get_all_options();
642 - $options['logs_path'] = null;
643 - $this->update_options( $options );
644 - }
694 + // Because the code from Blocks are sanitized, we need to replace the &quot; with "
695 + $code = str_replace( '&quot;', '"', $code );
645 696
646 - function get_logs_path() {
647 - $uploads_dir = wp_upload_dir();
648 - $uploads_dir_path = trailingslashit( $uploads_dir['basedir'] );
697 + if ( $target === 'js' ) {
698 + $output = '<script>' . $code . '</script>';
699 + }
649 700
650 - $path = $this->get_option( 'logs_path' );
701 + if ( $target === 'php' ) {
702 + $output = $this->run_non_fn_snippet( null, $code );
703 + }
651 704
652 - if ( $path && file_exists( $path ) ) {
653 - // make sure the path is legal (within the uploads directory with the MWCODE_PREFIX and log extension)
654 - if ( strpos( $path, $uploads_dir_path ) !== 0 || strpos( $path, MWCODE_PREFIX ) === false || substr( $path, -4 ) !== '.log' ) {
655 - $path = null;
656 - } else {
657 - return $path;
658 - }
659 - }
705 + return $output;
706 + }
660 707
661 - if ( !$path ) {
662 - $path = $uploads_dir_path . MWCODE_PREFIX . "_" . $this->random_ascii_chars() . ".log";
663 - if ( !file_exists( $path ) ) {
664 - touch( $path );
665 - }
666 - $options = $this->get_all_options();
667 - $options['logs_path'] = $path;
668 - $this->update_options( $options );
669 - }
708 + // If not a block, we get the snippet by ID
709 + // If the ID is not null, it means it comes from a shortcode
710 + if ( empty( $id ) && empty( $code ) ) {
711 + return '<b>Code Engine:</b> Please provide a snippet ID.';
712 + }
670 713
671 - return $path;
672 - }
714 + $snippet = $this->get_snippet( $id );
673 715
674 - function log( $data = null ) {
675 - if ( !$this->get_option( 'server_debug_mode', false ) ) { return false; }
676 - $log_file_path = $this->get_logs_path();
677 - $fh = @fopen( $log_file_path, 'a' );
678 - if ( !$fh ) { return false; }
679 - $date = date( "Y-m-d H:i:s" );
680 - if ( is_null( $data ) ) {
681 - fwrite( $fh, "\n" );
682 - }
683 - else {
684 - fwrite( $fh, "$date: {$data}\n" );
685 - //$this->log( "[MWCODE] $data" );
686 - }
687 - fclose( $fh );
688 - return true;
689 - }
716 + if ( empty( $snippet ) ) {
717 + return '<b>Code Engine:</b> The snippet does not exist.';
718 + }
690 719
691 - private function random_ascii_chars( $length = 8 ) {
692 - $characters = array_merge( range( 'A', 'Z' ), range( 'a', 'z' ), range( '0', '9' ) );
693 - $characters_length = count( $characters );
694 - $random_string = '';
720 + //Check if the snippet scope is either content_php or content_js
721 + $is_content_php = $snippet['scope'] === 'content_php';
722 + $is_content_js = $snippet['scope'] === 'content_js';
695 723
696 - for ( $i = 0; $i < $length; $i++ ) {
697 - $random_string .= $characters[rand(0, $characters_length - 1)];
698 - }
724 + if ( !$is_content_php && !$is_content_js ) {
725 + return '<b>Code Engine:</b> The snippet is not a content snippet.';
726 + }
699 727
700 - return $random_string;
701 - }
728 + if( $no_js && $is_content_js ) {
729 + return '<b>Code Engine:</b> Code Engine JS snippets are disabled because unfiltered HTML is not allowed on your server.';
730 + }
702 731
703 - #endregion
732 + //Check if the snippet is active
733 + if ( !$snippet['active'] ) {
734 + return '<b>Code Engine:</b> The snippet is not active.';
735 + }
704 736
705 - #region Helpers
737 + $output = '<b>Code Engine:</b> No output.';
706 738
707 - /**
708 - * Check if the request is from a white-listed REST route.
709 - *
710 - * @return bool
711 - */
712 - public static function is_white_listed_rest() {
713 - $authorized = false;
714 - $white_listed = array(
715 - 'mwai/v1',
716 - 'mwai-ui/v1',
717 - 'media-file-renamer/v1',
718 - 'media-cleaner/v1',
719 - 'wplr/v1',
720 - 'code-engine/v1',
721 - 'wp/v2',
722 - 'meow-gallery/v1',
723 - );
739 + if ( $is_content_js ) {
740 + $output = '<script>' . $snippet['code'] . '</script>';
741 + }
724 742
725 - $white_listed = apply_filters( 'meow_mwcode_white_listed_rest', $white_listed );
743 + if ( $is_content_php ) {
744 + $output = $this->run_non_fn_snippet( $id );
745 + }
726 746
727 - $route = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : null;
728 - $requested_route = null;
729 -
730 - if ( $route ) {
731 - $route_parts = explode( '/wp-json/', $route );
732 -
733 - if ( isset( $route_parts[1] ) ) {
734 - $requested_route = trim( $route_parts[1], '/' );
735 - foreach ( $white_listed as $white_listed_route ) {
736 - if ( strpos( $requested_route, $white_listed_route ) === 0 ) {
737 - $authorized = true;
738 - $authorized = apply_filters( 'meow_mwcode_white_listed_rest_authorized', $authorized, $requested_route );
739 - return $authorized;
740 - }
741 - }
742 - }
743 -
744 - if ( is_admin() ) {
745 - $authorized = true;
747 + return $output;
748 + }
746 749
747 - $authorized = apply_filters( 'meow_mwcode_white_listed_rest_authorized', $authorized, $requested_route );
748 - return $authorized;
749 - }
750 + #endregion
750 751
752 + #region Logs
751 753
752 - }
754 + function get_logs() {
755 + $log_file_path = $this->get_logs_path();
753 756
754 - $authorized = apply_filters( 'meow_mwcode_white_listed_rest_authorized', $authorized, $requested_route );
755 - return $authorized;
757 + if ( !file_exists( $log_file_path ) ) {
758 + return "Empty log file.";
756 759 }
757 760
758 - #endregion
761 + $content = file_get_contents( $log_file_path );
762 + $lines = explode( "\n", $content );
763 + $lines = array_filter( $lines );
764 + $lines = array_reverse( $lines );
765 + $content = implode( "\n", $lines );
766 + return $content;
767 + }
768 +
769 + function clear_logs() {
770 + $logPath = $this->get_logs_path();
771 + if ( file_exists( $logPath ) ) {
772 + unlink( $logPath );
773 + }
774 +
775 + $options = $this->get_all_options();
776 + $options['logs_path'] = null;
777 + $this->update_options( $options );
778 + }
779 +
780 + function get_logs_path() {
781 + $uploads_dir = wp_upload_dir();
782 + $uploads_dir_path = trailingslashit( $uploads_dir['basedir'] );
783 +
784 + $path = $this->get_option( 'logs_path' );
785 +
786 + if ( $path && file_exists( $path ) ) {
787 + // make sure the path is legal (within the uploads directory with the MWCODE_PREFIX and log extension)
788 + if ( strpos( $path, $uploads_dir_path ) !== 0 || strpos( $path, MWCODE_PREFIX ) === false || substr( $path, -4 ) !== '.log' ) {
789 + $path = null;
790 + } else {
791 + return $path;
792 + }
793 + }
794 +
795 + if ( !$path ) {
796 + $path = $uploads_dir_path . MWCODE_PREFIX . "_" . $this->random_ascii_chars() . ".log";
797 + if ( !file_exists( $path ) ) {
798 + touch( $path );
799 + }
800 + $options = $this->get_all_options();
801 + $options['logs_path'] = $path;
802 + $this->update_options( $options );
803 + }
804 +
805 + return $path;
806 + }
807 +
808 + function log( $data = null ) {
809 + if ( !$this->get_option( 'server_debug_mode', false ) ) { return false; }
810 + $log_file_path = $this->get_logs_path();
811 + $fh = @fopen( $log_file_path, 'a' );
812 + if ( !$fh ) { return false; }
813 + $date = date( "Y-m-d H:i:s" );
814 + if ( is_null( $data ) ) {
815 + fwrite( $fh, "\n" );
816 + }
817 + else {
818 + fwrite( $fh, "$date: {$data}\n" );
819 + //$this->log( "[MWCODE] $data" );
820 + }
821 + fclose( $fh );
822 + return true;
823 + }
824 +
825 + private function random_ascii_chars( $length = 8 ) {
826 + $characters = array_merge( range( 'A', 'Z' ), range( 'a', 'z' ), range( '0', '9' ) );
827 + $characters_length = count( $characters );
828 + $random_string = '';
829 +
830 + for ( $i = 0; $i < $length; $i++ ) {
831 + $random_string .= $characters[rand(0, $characters_length - 1)];
832 + }
833 +
834 + return $random_string;
835 + }
836 +
837 + #endregion
838 +
839 + #region Helpers
840 +
841 + /**
842 + * Check if the request is from a white-listed REST route.
843 + *
844 + * @return bool
845 + */
846 + public static function is_white_listed_rest() {
847 + $options = get_option( 'mwcode_snippet_vault_options', array() );
848 +
849 + // Early return if bypass is enabled
850 + if ( !empty( $options['bypass_rest_security'] ) ) {
851 + return true;
852 + }
853 +
854 + // Early return for admin requests
855 + if ( is_admin() ) {
856 + return apply_filters( 'mwcode_rest_authorized', true, null );
857 + }
858 +
859 + // Get the requested route
860 + $requested_route = self::get_requested_rest_route();
861 + if ( !$requested_route ) {
862 + return apply_filters( 'mwcode_rest_authorized', false, null );
863 + }
864 +
865 + // Check against whitelist
866 + $white_listed = apply_filters( 'mwcode_rest_whitelist', array(
867 + 'mwai/v1',
868 + 'mwai-ui/v1',
869 + 'media-file-renamer/v1',
870 + 'media-cleaner/v1',
871 + 'wplr/v1',
872 + 'code-engine/v1',
873 + 'wp/v2',
874 + 'meow-gallery/v1',
875 + 'mcp/v1',
876 + ));
877 +
878 + $authorized = self::is_route_whitelisted( $requested_route, $white_listed );
879 +
880 + // Log if debug mode is enabled
881 + if ( !empty( $options['server_debug_mode'] ) ) {
882 + self::log_route_status( $requested_route, $authorized );
883 + }
884 +
885 + return apply_filters( 'mwcode_rest_authorized', $authorized, $requested_route );
886 + }
887 +
888 + /**
889 + * Extract the REST route from the request URI.
890 + *
891 + * @return string|null
892 + */
893 + public static function get_requested_rest_route() {
894 + if ( !isset( $_SERVER['REQUEST_URI'] ) ) {
895 + return null;
896 + }
897 +
898 + $route_parts = explode( '/wp-json/', $_SERVER['REQUEST_URI'] );
899 +
900 + if ( isset( $route_parts[1] ) ) {
901 + return trim( $route_parts[1], '/' );
902 + }
903 +
904 + return null;
905 + }
906 +
907 + /**
908 + * Check if a route is in the whitelist.
909 + *
910 + * @param string $route The route to check
911 + * @param array $white_listed The whitelist array
912 + * @return bool
913 + */
914 + private static function is_route_whitelisted( $route, $white_listed ) {
915 + foreach ( $white_listed as $white_listed_route ) {
916 + if ( strpos( $route, $white_listed_route ) === 0 ) {
917 + return true;
918 + }
919 + }
920 + return false;
921 + }
922 +
923 + /**
924 + * Log the route authorization status.
925 + *
926 + * @param string $route The route being checked
927 + * @param bool $authorized Whether the route is authorized
928 + */
929 + private static function log_route_status( $route, $authorized ) {
930 + global $mwcode_core;
931 +
932 + $message = $authorized
933 + ? "✅ REST route authorized: " . $route
934 + : "❌ REST route rejected (not whitelisted): " . $route;
935 +
936 + if ( isset( $mwcode_core ) ) {
937 + $mwcode_core->log( $message );
938 + } else {
939 + error_log( "[Code Engine] " . $message );
940 + }
941 + }
942 +
943 + #endregion
759 944 }
760 945
761 946 ?>