PluginProbe
Code Engine – PHP Snippets, AI Functions & Automation for WordPress / 0.5.4
Code Engine – PHP Snippets, AI Functions & Automation for WordPress v0.5.4
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 0.3.8 All 32 releases
code-engine / classes / core.php

core.php in Code Engine – PHP Snippets, AI Functions & Automation for WordPress 0.5.4, at classes/core.php

1,089 lines 33.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 require_once ( MWCODE_PATH . '/vendor/autoload.php' );
4 use PhpParser\ParserFactory;
5 use PhpParser\NodeDumper;
6 use PhpParser\Error;
7
8 class Meow_MWCODE_Core
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;
16 public $licenser = null;
17
18 // IDs of global snippets already executed this request (by the plugins_loaded pass
19 // or by load_global_snippets), so a global never runs twice and never re-declares.
20 public $loaded_global_ids = [];
21
22 private $option_name = 'mwcode_options';
23
24 public function __construct() {
25 global $mwcode;
26
27 $this->site_url = get_site_url();
28 $this->is_rest = MeowKit_MWCODE_Helpers::is_rest();
29 $this->is_cli = defined( 'WP_CLI' ) && WP_CLI;
30
31 // Snippets
32 $snippet = new Meow_MWCODE_Modules_Snippet( $this );
33 $this->snippet = $snippet;
34
35 // Create API before plugins_loaded
36 $this->mwcode = new Meow_MWCODE_API( $this, $snippet );
37 $mwcode = $this->mwcode;
38
39 // Add the shortcode for the "content" snippets
40 add_shortcode( 'code-engine', [ $this, 'content_shortcode' ] );
41
42 add_action( 'plugins_loaded', array( $this, 'init' ) );
43 }
44
45 function init() {
46 // Initialize the licenser for Pro version
47 if ( class_exists( 'MeowKitPro_MWCODE_Licenser' ) ) {
48 $this->licenser = new MeowKitPro_MWCODE_Licenser( MWCODE_PREFIX, MWCODE_ENTRY, MWCODE_DOMAIN, MWCODE_ITEM_ID, MWCODE_VERSION );
49 }
50
51 // Part of the core, settings and stuff
52 $this->admin = new Meow_MWCODE_Admin( $this );
53
54 // Only for REST
55 if ( $this->is_rest ) {
56 new Meow_MWCODE_Rest( $this, $this->admin, $this->snippet );
57 }
58
59 // MCP integration - check both class and global variable
60 if ( class_exists( 'Meow_MWAI_Core' ) || isset( $GLOBALS['mwai'] ) ) {
61 new Meow_MWCODE_MCP( $this );
62 }
63 }
64
65 /**
66 *
67 * Roles & Access Rights
68 *
69 */
70 #region Roles & Access Rights
71 public function can_access_settings() {
72 return apply_filters( 'mwcode_allow_setup', current_user_can( 'manage_options' ) );
73 }
74
75 public function can_access_features() {
76 return apply_filters( 'mwcode_allow_usage', current_user_can( 'administrator' ) );
77 }
78
79 public function check_rest_nonce( $request ) {
80 $nonce = $request->get_header( 'X-WP-Nonce' );
81 return wp_verify_nonce( $nonce, 'wp_rest' );
82 }
83 #endregion
84
85 #region Options
86
87 function get_option( $option, $default = null ) {
88 $options = $this->get_all_options();
89 return $options[$option] ?? $default;
90 }
91
92 function list_options() {
93 return [
94 //Safemode
95 "safe_mode_status" => "on", // on, off, whitelist
96 "safe_mode_whitelist" => [],
97 //"disallow_block_php" => true, // Do not allow PHP code to be execute through Blocks "code" parameter
98 "code_blocks" => false,
99 "code_blocks_whitelist" => [], // Whitelist for code blocks, if empty, all code blocks are allowed
100
101 //LOGS
102 "server_debug_mode" => false,
103
104 //UI
105 "ui_show_preview" => false,
106
107 //AI
108 "ai_suggestions" => false,
109 "ai_engine_status"=> false,
110 "mwai_active" => false,
111 "ai_engine_message" => "",
112
113 //API
114 "api_endpoint" => false,
115 "api_token" => md5( time() . rand() ),
116
117 //MCP
118 "mcp_support" => false,
119 "mcp_functions" => false,
120
121 //MAINTENANCE
122 "clean_uninstall" => false,
123 ];
124 }
125
126 function get_all_options( ) {
127 $options = get_option( $this->option_name, [] );
128 $defaults = $this->list_options();
129
130 // Merge with defaults to ensure all options exist
131 $options = array_merge( $defaults, $options );
132
133 $options = $this->sanitize_options( $options );
134 return $options;
135 }
136
137 function update_options( $options ) {
138
139 $options = $this->sanitize_options( $options );
140
141 if ( !update_option( $this->option_name, $options, false ) ) {
142 //$this->log( '💾 There was an issue updating the options.' );
143 }
144
145 return $options;
146 }
147
148 function update_option( $option, $value ) {
149 $options = $this->get_all_options();
150 $options[$option] = $value;
151 return $this->update_options( $options );
152 }
153
154 function reset_options() {
155 if ( $this->get_all_options() === $this->list_options() ) {
156 return true;
157 }
158 return $this->update_options( $this->list_options() );
159 }
160
161 // Validate and keep the options clean and logical.
162 function sanitize_options( $options ) {
163 $options_modified = false;
164
165 // Ensure mcp_support exists in options
166 if ( !isset( $options['mcp_support'] ) ) {
167 $options['mcp_support'] = false;
168 }
169
170 // Make sure safe mode whitelist is an array
171 if ( ! is_array( $options['safe_mode_whitelist'] ) ) {
172 $options['safe_mode_whitelist'] = explode( ",", $options['safe_mode_whitelist'] );
173 $options_modified = true;
174 }
175
176 // Update AI Engine status
177 $options = $this->updateAIEngineStatus( $options );
178
179 // Disable AI related features if AI Engine is not available
180 if ( ! $options['ai_engine_status'] ) {
181 if ( $options['ai_suggestions'] !== false ) {
182 $options['ai_suggestions'] = false;
183 $options_modified = true;
184 }
185 // Note: We don't disable MCP support here anymore
186 // It will be checked at runtime in the MCP class
187 }
188
189 return $options;
190 }
191
192 private function updateAIEngineStatus( &$options ) {
193 global $mwai;
194
195 // AI Engine is active (regardless of whether an API key is configured).
196 // MCP exposure only needs AI Engine present, not a key, so the MCP toggles
197 // gate on this rather than on mwai_has_ai.
198 $options['mwai_active'] = !empty( $mwai );
199 $options['mwai_has_ai'] = !empty( $mwai ) && method_exists( $mwai, 'hasAI' ) && $mwai->hasAI();
200 // Legacy
201 $options['ai_engine_status'] = $options['mwai_has_ai'];
202
203 return $options;
204 }
205
206 #endregion
207
208 #region Snippets
209
210 /**
211 * Get snippet.
212 *
213 * @param $id
214 * @return mixed
215 */
216 protected function get_snippet( $id ) {
217 if ( $this->snippet === null ) {
218 $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
219 }
220
221 return $this->snippet->select_one( $id );
222 }
223
224 function add_snippet( $params ) {
225
226 $response = [
227 "snippet" => null,
228 "result" => false,
229 ];
230
231 $this->snippet->validate( $params );
232
233 $params = $this->snippet->formatParamsForDatabase( $params );
234
235 // Route to UPDATE when an existing snippet id is provided (updateSnippet / the
236 // MCP mwcode_update_snippet tool). This previously always insert()ed, so an
237 // update tried to INSERT a row with an already-used primary key: that fails on
238 // the SQLite backend (Studio/Playground) with "Could not insert the snippet",
239 // and duplicates or errors elsewhere. The admin UI was unaffected because it
240 // calls snippet->update() directly.
241 $existing = !empty( $params['id'] ) ? $this->snippet->select_one( $params['id'] ) : null;
242 if ( $existing ) {
243 $this->snippet->update( $params );
244 $result = $params['id'];
245 }
246 else {
247 unset( $params['id'] );
248 $result = $this->snippet->insert( $params );
249 }
250 $snippet = $this->snippet->select_one( $result );
251
252 if( $result ) {
253 $params['id'] = (string)$result;
254
255 $this->snippet->create_or_update_function_snippet( $params );
256 $this->snippet->create_or_update_interval_snippet( $params );
257
258 $this->snippet->get_function_snippets_data( $snippet );
259 }
260
261 $response['snippet'] = $snippet;
262 $response['result'] = $result;
263
264 return $response;
265 }
266
267 private function sanitize_arg( $name, $value, $type = null) {
268 $real_type = gettype( $value );
269
270 if ( $name[0] !== '$' ) { $name = '$' . $name; }
271
272 if ( $type == null ) {
273 $type = $real_type;
274 }
275
276 if ( $type != 'array' && !empty( $value ) && !is_numeric( $value ) && $value[0] !== '"' && $value[strlen( $value ) - 1] !== '"' ) {
277 $value = '"' . esc_sql( $value ) . '"';
278 }
279
280 if ( $type === 'array' && $real_type === 'string' ) {
281 // We got a string like this: "["a", "b", "c"]" or "[ 1, 2, 3 ]"
282 // We need to convert it to an array
283 $value = str_replace( '"', '', $value );
284 $value = str_replace( '[', '', $value );
285 $value = str_replace( ']', '', $value );
286 $value = explode( ',', $value );
287 $value = array_map( 'trim', $value );
288 }
289
290 if ( $type === 'array' ) {
291 // Convert to PHP array format instead of JSON
292 $value = var_export( $value, true );
293 }
294
295 return [ $name, $value ];
296 }
297
298 function run_non_fn_snippet( $id, $code = null, $test = false, $prefix = '' ) {
299 // Retrieve the snippet code from the provided code or via the snippet ID.
300 if ( $code ) {
301 $snippet = [ 'code' => $code ];
302 } else {
303 $snippet = $this->get_snippet( $id );
304 }
305
306 // Remove any PHP opening tag.
307 $snippet['code'] = $this->snippet->sanitize_code( $snippet['code'] );
308
309 if ( $test ) {
310 $snippet['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $snippet['code'] );
311 }
312
313 if( $prefix ) {
314 $snippet['code'] = $prefix . "\n" . $snippet['code'];
315 }
316
317 $error = null;
318 $output = null;
319
320 try {
321 ob_start();
322 eval( $snippet['code'] );
323 $output = ob_get_clean();
324 } catch ( Throwable $e ) {
325 $snippet_id = $id ? " ( ID: $id )" : '(Content Gutenberg Block)';
326 $this->log( '🔴 Error executing the snippet ' . $snippet_id . ' : ' . $e->getMessage() );
327 ob_clean();
328 } finally {
329 restore_error_handler();
330 }
331
332 // If in test mode, return output as an array of lines with an 'error' key if needed.
333 if ( $test ) {
334 $output = explode( "\n", trim( $output ) );
335 if ( $error !== null ) {
336 $output['error'] = $error->getMessage();
337 }
338 } else {
339 if ( $error !== null ) {
340 throw $error;
341 }
342 }
343
344 return $output;
345 }
346
347 function run_snippet( $id, $args = [], $params = [] )
348 {
349 // Static array to track defined functions
350 static $defined_functions = array();
351
352 if ( $id ) { // If there is an ID, we get the snippet, if not we get the data from the params
353 $snippet = $this->get_snippet( $id );
354 $this->snippet->get_function_snippets_data( $snippet ); // adds the function data to the snippet
355
356 $params = [ // We set the params according to the snippet we fetched
357 'test' => false, // If we pass an ID to the function, we are not testing the snippet
358 // 'test' => $params['test'] ?? false if needed we can still use ID and test at the same time (should not happen)
359 'code' => $snippet['code'],
360 'name' => $snippet['functionName'],
361 'args' => $snippet['functionArgs'],
362 'values' => $snippet['functionArgsDict'] // Contains the default values of the arguments
363 ];
364 }
365
366 // Arguments used to be sanitized into PHP-literal strings here (quoting,
367 // esc_sql, var_export) so they could be concatenated into a string of PHP and
368 // eval-ed. That is gone: the function is now called with call_user_func_array
369 // (see below), so values are passed as data and need no literal-formatting.
370 // The old formatting also prefixed argument keys with "$" via sanitize_arg,
371 // which stored the provided value under "$name" while the call read "name", so
372 // provided arguments never reached the function. Passing the raw values through
373 // fixes both issues at once.
374
375 // Make sure the function is existing and is the one in the snippet
376 if ( empty( $params['code'] ) ) {
377 throw new Exception( 'Code Engine: The snippet code appears to be empty.' );
378 }
379
380 if ( empty( $params['name'] ) || ! str_contains( $params['code'], $params['name'] ) ) {
381 throw new Exception( "Code Engine: Function name does not match. The name should be {$params['name']}." );
382 }
383
384 // Overwrite the default values with the provided ones
385 if ( $args ) {
386 foreach ( $args as $name => $value ) {
387 $params['values'][$name]['input'] = $value;
388 }
389
390 $this->log( '⚡ Arguments provided: ' . json_encode( $args ) );
391 }
392
393 // Global snippets are meant to be always accessible. On non-whitelisted REST routes
394 // (Workflow Engine, MCP, AI function-calling) the plugins_loaded pass blocks them, so
395 // make sure their helper library is loaded before we run a function that may call it.
396 $this->load_global_snippets();
397
398 // Make every *other* active PHP function snippet available so this function can
399 // call its siblings. We pass the current name as the exception so the target is
400 // still defined below (with the edited/test code when testing), not pre-defined here.
401 $this->define_all_functions( $params['name'] );
402
403 // Check if the function has already been defined
404 if ( !in_array( $params['name'], $defined_functions ) ) {
405
406 // If not, proceed with modification and definition
407 if ( $params['test'] ) { // Make sure the echo statement uses a line break
408 $params['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $params['code'] );
409 } else { // Remove all echo statements
410 $params['code'] = preg_replace( '/echo\s+(.+?);/s', '', $params['code'] );
411 }
412
413 $params['code'] = "if (!function_exists('{$params['name']}')) {\n" . $params['code'] . "\n}\n";
414
415 // Add the function name to the array to avoid redefinition
416 $defined_functions[] = $params['name'];
417 } else {
418 // If already defined, just prepare to call the function without redefining it
419 $params['code'] = '';
420 }
421
422 // Resolve the arguments as REAL PHP values, in the function's declared order.
423 // The previous version concatenated each value into a string of PHP and eval-ed
424 // the call, which broke on any string or edge-case value with a parse error
425 // ("syntax error, unexpected token ')'"). call_user_func_array passes them as
426 // data, so no value can ever corrupt the call syntax.
427 $callArgs = [];
428 foreach ( $params['args'] as $arg ) {
429 $value = null; // Not provided and no default -> null.
430 if ( array_key_exists( $arg, $params['values'] ) ) {
431 if ( !empty( $params['values'][$arg]['input'] ) ) {
432 $value = $params['values'][$arg]['input'];
433 } else if ( !empty( $params['values'][$arg]['default'] ) ) {
434 $value = $params['values'][$arg]['default'];
435 }
436 }
437 // An array-typed argument can arrive as a string like "[1, 2, 3]"; turn it
438 // into a real array so the function receives what its signature expects.
439 if ( ( $params['values'][$arg]['type'] ?? null ) === 'array' && is_string( $value ) ) {
440 $decoded = json_decode( $value, true );
441 $value = is_array( $decoded ) ? $decoded : array_map( 'trim', explode( ',', trim( $value, "[] \t\n\r" ) ) );
442 }
443 $callArgs[] = $value;
444 }
445
446 $error = null;
447 $output = null;
448
449 try {
450 ob_start();
451 // $params['code'] holds the function definition (empty if it was already
452 // defined earlier this request). Declare it, then invoke it as data.
453 if ( $params['code'] !== '' ) {
454 eval( $params['code'] );
455 }
456 $mwcode_result = call_user_func_array( $params['name'], $callArgs );
457 echo print_r( $mwcode_result, true );
458 $output = ob_get_clean();
459
460 if ( $params['test'] ) {
461 $output = explode( "\n", $output );
462 }
463
464 } catch ( Throwable $e ) {
465 //$this->log('Code Engine: Error executing the function: ' . $e->getMessage());
466 $error = new Exception(' Error executing the function, ' . $e->getMessage());
467
468 if ( ob_get_level() > 0 ) {
469 ob_end_clean();
470 }
471 } finally {
472 restore_error_handler();
473 }
474
475 if ( $error !== null ) {
476 if( $params['test'] ){
477 $output['error'] = $error->getMessage();
478 } else {
479 throw $error;
480 }
481 }
482
483 return $output;
484 }
485
486
487 function parse_snippet( $code, $new_snippet = false ){
488 $parser = ( new ParserFactory( ) )->createForNewestSupportedVersion( );
489
490 if( !$this->snippet ){
491 $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
492 }
493
494 // First we check the function names are unique
495 $fn = $this->snippet->sanitize_and_check_functions( $code, $new_snippet );
496 if ( ! $fn['is_valid'] ) {
497
498 $lint = [
499 'line' => 1,
500 'attributes' => $fn['attributes'][0],
501 'raw_message' => implode(', ', $fn['errors'][0]),
502 'message' => implode(', ', $fn['errors'][0]),
503 ];
504
505 return $lint;
506 }
507
508 try {
509 $stmts = $parser->parse( $code );
510 $result = $stmts;
511 } catch ( PhpParser\Error $e ) {
512
513 $lint = [
514 'line' => $e->getStartLine(),
515 'attributes' => $e->getAttributes(),
516 'raw_message' => $e->getRawMessage(),
517 'message' => $e->getMessage(),
518 ];
519
520 return $lint;
521 }
522
523 return null;
524 }
525
526 /**
527 * Load the active global snippets (persistent + backend/frontend for this context)
528 * that haven't already run this request, so on-demand function execution has the same
529 * always-available helper library a normal page load would. Callable functions are
530 * typically small wrappers around these globals.
531 *
532 * On non-whitelisted REST routes (Workflow Engine, MCP, AI function-calling) the
533 * plugins_loaded pass blocks global snippets for safety; this restores them for the
534 * deliberate, authorized act of executing a snippet. The loaded-id registry guarantees
535 * each global runs at most once per request, so nothing is ever re-declared.
536 */
537 function load_global_snippets() {
538 global $current_mwcode_snippet;
539 static $done = false;
540 if ( $done ) {
541 return;
542 }
543 $done = true;
544
545 if ( empty( $this->snippet ) ) {
546 $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
547 }
548
549 $scope = is_admin() ? [ 'backend', 'persistent' ] : [ 'frontend', 'persistent' ];
550
551 $snippets = $this->snippet->select(
552 null, // offset
553 -1, // limit (all)
554 [
555 [ 'accessor' => 'active', 'value' => 1 ],
556 [ 'accessor' => 'scope', 'value' => $scope ],
557 ],
558 [ 'accessor' => 'priority', 'by' => 'DESC' ]
559 )['data'] ?? [];
560
561 foreach ( $snippets as $snippet ) {
562 // Skip globals already executed this request (e.g. by the plugins_loaded pass).
563 if ( in_array( $snippet['id'], $this->loaded_global_ids ) ) {
564 continue;
565 }
566 $this->loaded_global_ids[] = $snippet['id'];
567
568 $code = $this->snippet->sanitize_code( $snippet['code'] );
569 $current_mwcode_snippet = $snippet;
570 try {
571 ob_start();
572 eval( $code );
573 ob_end_clean();
574 } catch ( Throwable $e ) {
575 ob_end_clean();
576 $this->log( "⚠️ Code Engine: Failed to load global snippet \"{$snippet['name']}\": " . $e->getMessage() );
577 }
578 }
579 $current_mwcode_snippet = null;
580 }
581
582 /**
583 * Declare every active PHP function snippet in the current request, without
584 * invoking any of them, so function snippets can call one another.
585 *
586 * Function snippets are not auto-loaded on every request (unlike global/backend/
587 * frontend scopes) — they are meant to run on demand. This is the PHP counterpart
588 * to get_js_functions_to_push(): it makes the whole library of functions callable
589 * before a function is executed (via REST, MCP, AI function-calling, Workflow Engine).
590 *
591 * Idempotent: a static guard runs the full pass only once per request, and each
592 * definition is wrapped in function_exists() so nothing is ever redefined.
593 *
594 * @param string|null $except Function name to skip (the one run_snippet is about to
595 * define itself, so edited/test code keeps priority).
596 */
597 function define_all_functions( $except = null ) {
598 static $loaded = false;
599 if ( $loaded ) {
600 return;
601 }
602 $loaded = true;
603
604 if ( empty( $this->snippet ) ) {
605 $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
606 }
607
608 // One query for every active function snippet (code included), then enrich with
609 // the function metadata (name + target) the same way run_snippet does.
610 $snippets = $this->snippet->select(
611 null, // offset
612 -1, // limit (all)
613 [
614 [ 'accessor' => 'active', 'value' => 1 ],
615 [ 'accessor' => 'scope', 'value' => 'function' ],
616 ],
617 [] // sort
618 )['data'] ?? [];
619
620 if ( empty( $snippets ) ) {
621 return;
622 }
623
624 $this->snippet->get_function_snippets_data( $snippets );
625
626 foreach ( $snippets as $snippet ) {
627 $name = $snippet['functionName'] ?? '';
628 $target = strtolower( $snippet['functionTarget'] ?? 'php' );
629
630 // Skip JS functions (pushed to the front-end separately), the function the
631 // caller will define itself, and anything already declared in this request.
632 if ( $name === '' || $target === 'js' || $name === $except || function_exists( $name ) ) {
633 continue;
634 }
635
636 // Mirror run_snippet()'s non-test handling: drop echo statements, then declare
637 // (never call) the function, guarded so a later run_snippet() call is a no-op.
638 $code = $this->snippet->sanitize_code( $snippet['code'] );
639 $code = preg_replace( '/echo\s+(.+?);/s', '', $code );
640 $code = "if (!function_exists('{$name}')) {\n{$code}\n}\n";
641
642 try {
643 eval( $code );
644 } catch ( Throwable $e ) {
645 $this->log( "⚠️ Code Engine: Failed to pre-define function \"{$name}\": " . $e->getMessage() );
646 }
647 }
648 }
649
650 public function get_js_functions_to_push() {
651 $functions = $this->snippet->get_functions();
652 $js_functions = [];
653 foreach ( $functions as &$function ) {
654 if ( !isset( $function['target'] ) ) {
655 $function['target'] = 'php';
656 }
657 if ( $function['target'] == 'js' ) {
658 $js_functions[] = $function;
659 }
660 }
661 $snippets = [];
662 foreach ( $js_functions as $function ) {
663 $snippet = $this->snippet->select_one( $function['snippetId'] );
664 $snippet['function_info'] = $function; // Add function info to snippet
665 $snippets[] = $snippet;
666 }
667
668 return $this->generate_js_functions_code( $snippets );
669 }
670
671 function generate_js_functions_code ($snippets ) {
672 $code = "";
673 foreach ( $snippets as $snippet ) {
674 $function_code = $snippet['code'];
675 $function_info = $snippet['function_info'];
676
677 // Extract function name and arguments
678 preg_match( '/(?:const|let|var)?\s*(\w+)\s*=\s*\((.*?)\)\s*=>/', $function_code, $matches );
679 $function_name = $matches[1] ?? $function_info['name'];
680 $function_args = $matches[2] ?? '';
681
682 // Prepare default values
683 $default_args = [];
684 foreach ( $function_info['args'] as $arg ) {
685 if ( isset( $arg['default'] ) && $arg['default'] !== '' ) {
686 $default_args[$arg['name']] = $arg['default'];
687 }
688 }
689
690 // Modify function to use default values
691 if ( !empty( $default_args ) ) {
692 $new_args = explode( ',', $function_args );
693 foreach ( $new_args as &$arg ) {
694 $arg = trim( $arg );
695 if ( isset( $default_args[$arg] ) ) {
696 $arg .= " = " . json_encode( $default_args[$arg] );
697 }
698 }
699 $new_args_string = implode( ', ', $new_args );
700 $function_code = preg_replace(
701 '/(\w+)\s*=\s*\((.*?)\)\s*=>/',
702 "$1 = ($new_args_string) =>",
703 $function_code
704 );
705 }
706
707 $code .= $function_code . "\n\n";
708 }
709
710 return $code;
711 }
712
713
714 /**
715 * [STATIC] Execute active snippets.
716 *
717 * @return array
718 */
719 public function execute_active_snippets() {
720
721 $blocked = false;
722 $page = isset( $_GET["page"] ) ? sanitize_text_field( $_GET["page"] ) : null;
723
724
725 if ( $page === 'mwcode_settings' ) {
726 // If we blocks global snippets like nonce_life filter, we would block the settings page so let's remove the block for this page
727
728 $blocked = false;
729 //$blocked = true;
730 }
731 // Block REST requests that aren't whitelisted
732 elseif ( MeowKit_MWCODE_Helpers::is_rest() && !Meow_MWCODE_Core::is_white_listed_rest() ) {
733 $blocked = true;
734 }
735
736 if ( empty( $this->snippet ) ) {
737 $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
738 }
739
740 $ts = $this->get_option( 'thrown_snippet', null );
741 if ( !empty( $ts ) ) {
742 $this->log( "⚠️ Your snippet \"{$ts['name']}\" has thrown a fatal error last time, so we disabled it. Please check the logs for more information." );
743 $this->snippet->force_disable( $ts['id'] );
744 $this->update_option( 'thrown_snippet', null );
745 }
746
747 $scope = is_admin() ? [ 'backend', 'persistent' ] : [ 'frontend', 'persistent' ];
748 // Get all active snippets
749
750 $snippets = $this->snippet->select(
751 null, // offset
752 -1, // limit
753 [
754 [ 'accessor' => 'active', 'value' => 1 ],
755 [ 'accessor' => 'scope', 'value' => $scope ],
756 ], // filter
757 [ 'accessor' => 'priority', 'by' => 'DESC' ] // sort
758 )['data'];
759
760 if ( empty( $snippets ) ) {
761 return;
762 }
763
764 $snippets = array_map( function ( $snippet ) use ( $blocked ) {
765 $snippet['code'] = $this->snippet->sanitize_code( $snippet['code'] );
766 $snippet['blocked'] = $blocked;
767
768 // If the snippet must be executed only in the frontend, we bypass the block
769 if ( !is_admin() && $snippet['scope'] === 'frontend' ) {
770 $snippet['blocked'] = false;
771 }
772
773 return $snippet;
774 }, $snippets );
775
776 return $snippets;
777 }
778
779
780 #endregion
781
782 #region Shortcodes
783 function separate_mwcode_atts( $atts ) {
784
785 if( array_key_exists( 'id', $atts ) ) unset( $atts['id'] );
786 if( array_key_exists( 'target', $atts ) ) unset( $atts['target'] );
787 if( array_key_exists( 'code', $atts ) ) unset( $atts['code'] );
788
789 return $atts;
790 }
791
792 function content_shortcode( $atts ) {
793
794 $user_atts = $this->separate_mwcode_atts( $atts );
795
796 $atts = shortcode_atts( array(
797 'id' => null,
798 'target' => null, // js or php
799 'code' => null, // For Guttenberg block usage
800 ), $atts, 'code-engine' );
801
802 $id = $atts['id'];
803 $target = $atts['target'];
804 $code = $atts['code'];
805 $current_post = get_post();
806
807 $no_js = defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML;
808 $allow_php = $this->get_option( 'code_blocks', false );
809 $allow_php_whitelist = $this->get_option( 'code_blocks_whitelist', [] );
810
811 // If the ID is null, it means it comes from a Guttenberg block
812 $is_block = empty( $id ) && !empty( $code );
813
814 if( $is_block ) {
815
816 if( $target !== 'js' && $target !== 'php' ) {
817 return '<b>Code Engine:</b> Please provide a valid target (js or php).';
818 }
819
820 if ( $no_js && $target === 'js' ) {
821 return '<b>Code Engine:</b> Code Block JS are disabled because unfiltered HTML is not allowed on your server.';
822 }
823
824 if ( $target === 'php' ) {
825
826 if ( !$allow_php ) {
827 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.';
828 }
829
830 if ( !empty( $allow_php_whitelist ) && !in_array( $current_post->ID, $allow_php_whitelist ) ) {
831 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.';
832 }
833 }
834
835 // Because the code from Blocks are sanitized, we need to replace the &quot; with "
836 $code = str_replace( '&quot;', '"', $code );
837
838 if ( $target === 'js' ) {
839 $output = '<script>' . $code . '</script>';
840 }
841
842 if ( $target === 'php' ) {
843 $output = $this->run_non_fn_snippet( null, $code );
844 }
845
846 return $output;
847 }
848
849 // If not a block, we get the snippet by ID
850 // If the ID is not null, it means it comes from a shortcode
851 if ( empty( $id ) && empty( $code ) ) {
852 return '<b>Code Engine:</b> Please provide a snippet ID.';
853 }
854
855 $snippet = $this->get_snippet( $id );
856
857 if ( empty( $snippet ) ) {
858 return '<b>Code Engine:</b> The snippet does not exist.';
859 }
860
861 //Check if the snippet scope is either content_php or content_js
862 $is_content_php = $snippet['scope'] === 'content_php';
863 $is_content_js = $snippet['scope'] === 'content_js';
864
865 if ( !$is_content_php && !$is_content_js ) {
866 return '<b>Code Engine:</b> The snippet is not a content snippet.';
867 }
868
869 if( $no_js && $is_content_js ) {
870 return '<b>Code Engine:</b> Code Engine JS snippets are disabled because unfiltered HTML is not allowed on your server.';
871 }
872
873 //Check if the snippet is active
874 if ( !$snippet['active'] ) {
875 return '<b>Code Engine:</b> The snippet is not active.';
876 }
877
878 $output = '<b>Code Engine:</b> No output.';
879
880 if ( $is_content_js ) {
881 $output = '<script>' . $snippet['code'] . '</script>';
882 }
883
884 if ( $is_content_php ) {
885 $prefix = "\$mwcode_atts = unserialize( '" . serialize( $user_atts ) . "' );";
886 $output = $this->run_non_fn_snippet( $id, null, false, $prefix );
887 }
888
889 return $output;
890 }
891
892 #endregion
893
894 #region Logs
895
896 function get_logs() {
897 $log_file_path = $this->get_logs_path();
898
899 if ( !file_exists( $log_file_path ) ) {
900 return "Empty log file.";
901 }
902
903 $content = file_get_contents( $log_file_path );
904 $lines = explode( "\n", $content );
905 $lines = array_filter( $lines );
906 $lines = array_reverse( $lines );
907 $content = implode( "\n", $lines );
908 return $content;
909 }
910
911 function clear_logs() {
912 $logPath = $this->get_logs_path();
913 if ( file_exists( $logPath ) ) {
914 unlink( $logPath );
915 }
916
917 $options = $this->get_all_options();
918 $options['logs_path'] = null;
919 $this->update_options( $options );
920 }
921
922 function get_logs_path() {
923 $uploads_dir = wp_upload_dir();
924 $uploads_dir_path = trailingslashit( $uploads_dir['basedir'] );
925
926 $path = $this->get_option( 'logs_path' );
927
928 if ( $path && file_exists( $path ) ) {
929 // make sure the path is legal (within the uploads directory with the MWCODE_PREFIX and log extension)
930 if ( strpos( $path, $uploads_dir_path ) !== 0 || strpos( $path, MWCODE_PREFIX ) === false || substr( $path, -4 ) !== '.log' ) {
931 $path = null;
932 } else {
933 return $path;
934 }
935 }
936
937 if ( !$path ) {
938 $path = $uploads_dir_path . MWCODE_PREFIX . "_" . $this->random_ascii_chars() . ".log";
939 if ( !file_exists( $path ) ) {
940 touch( $path );
941 }
942 $options = $this->get_all_options();
943 $options['logs_path'] = $path;
944 $this->update_options( $options );
945 }
946
947 return $path;
948 }
949
950 function log( $data = null ) {
951 if ( !$this->get_option( 'server_debug_mode', false ) ) { return false; }
952 $log_file_path = $this->get_logs_path();
953 $fh = @fopen( $log_file_path, 'a' );
954 if ( !$fh ) { return false; }
955 $date = date( "Y-m-d H:i:s" );
956 if ( is_null( $data ) ) {
957 fwrite( $fh, "\n" );
958 }
959 else {
960 fwrite( $fh, "$date: {$data}\n" );
961 //$this->log( "[MWCODE] $data" );
962 }
963 fclose( $fh );
964 return true;
965 }
966
967 private function random_ascii_chars( $length = 8 ) {
968 $characters = array_merge( range( 'A', 'Z' ), range( 'a', 'z' ), range( '0', '9' ) );
969 $characters_length = count( $characters );
970 $random_string = '';
971
972 for ( $i = 0; $i < $length; $i++ ) {
973 $random_string .= $characters[rand(0, $characters_length - 1)];
974 }
975
976 return $random_string;
977 }
978
979 #endregion
980
981 #region Helpers
982
983 /**
984 * Check if the request is from a white-listed REST route.
985 *
986 * @return bool
987 */
988 public static function is_white_listed_rest() {
989 $options = get_option( 'mwcode_snippet_vault_options', array() );
990
991 // Early return if bypass is enabled
992 if ( !empty( $options['bypass_rest_security'] ) ) {
993 return true;
994 }
995
996 // Early return for admin requests
997 if ( is_admin() ) {
998 return apply_filters( 'mwcode_rest_authorized', true, null );
999 }
1000
1001 // Get the requested route
1002 $requested_route = self::get_requested_rest_route();
1003 if ( !$requested_route ) {
1004 return apply_filters( 'mwcode_rest_authorized', false, null );
1005 }
1006
1007 // Check against whitelist
1008 $white_listed = apply_filters( 'mwcode_rest_whitelist', array(
1009 'mwai/v1',
1010 'mwai-ui/v1',
1011 'media-file-renamer/v1',
1012 'media-cleaner/v1',
1013 'wplr/v1',
1014 'code-engine/v1',
1015 'wp/v2',
1016 'meow-gallery/v1',
1017 'mcp/v1',
1018 ));
1019
1020 $authorized = self::is_route_whitelisted( $requested_route, $white_listed );
1021
1022 // Log if debug mode is enabled
1023 if ( !empty( $options['server_debug_mode'] ) ) {
1024 self::log_route_status( $requested_route, $authorized );
1025 }
1026
1027 return apply_filters( 'mwcode_rest_authorized', $authorized, $requested_route );
1028 }
1029
1030 /**
1031 * Extract the REST route from the request URI.
1032 *
1033 * @return string|null
1034 */
1035 public static function get_requested_rest_route() {
1036 if ( !isset( $_SERVER['REQUEST_URI'] ) ) {
1037 return null;
1038 }
1039
1040 $route_parts = explode( '/wp-json/', $_SERVER['REQUEST_URI'] );
1041
1042 if ( isset( $route_parts[1] ) ) {
1043 return trim( $route_parts[1], '/' );
1044 }
1045
1046 return null;
1047 }
1048
1049 /**
1050 * Check if a route is in the whitelist.
1051 *
1052 * @param string $route The route to check
1053 * @param array $white_listed The whitelist array
1054 * @return bool
1055 */
1056 private static function is_route_whitelisted( $route, $white_listed ) {
1057 foreach ( $white_listed as $white_listed_route ) {
1058 if ( strpos( $route, $white_listed_route ) === 0 ) {
1059 return true;
1060 }
1061 }
1062 return false;
1063 }
1064
1065 /**
1066 * Log the route authorization status.
1067 *
1068 * @param string $route The route being checked
1069 * @param bool $authorized Whether the route is authorized
1070 */
1071 private static function log_route_status( $route, $authorized ) {
1072 global $mwcode_core;
1073
1074 $message = $authorized
1075 ? "�
1076 REST route authorized: " . $route
1077 : " REST route rejected (not whitelisted): " . $route;
1078
1079 if ( isset( $mwcode_core ) ) {
1080 $mwcode_core->log( $message );
1081 } else {
1082 error_log( "[Code Engine] " . $message );
1083 }
1084 }
1085
1086 #endregion
1087 }
1088
1089 ?>