PluginProbe
Code Engine – PHP Snippets, AI Functions & Automation for WordPress / 0.4.0
Code Engine – PHP Snippets, AI Functions & Automation for WordPress v0.4.0
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 +87 -239 0.5.50.4.0 View file →
@@ -14,12 +14,8 @@
14 14 public $site_url = null;
15 15 public $mwcode = null;
16 16 public $licenser = null;
17 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 18 private $option_name = 'mwcode_options';
23 19
24 20 public function __construct() {
25 21 global $mwcode;
@@ -106,9 +102,8 @@
106 102
107 103 //AI
108 104 "ai_suggestions" => false,
109 105 "ai_engine_status"=> false,
110 - "mwai_active" => false,
111 106 "ai_engine_message" => "",
112 107
113 108 //API
114 109 "api_endpoint" => false,
@@ -115,9 +110,8 @@
115 110 "api_token" => md5( time() . rand() ),
116 111
117 112 //MCP
118 113 "mcp_support" => false,
119 - "mcp_functions" => false,
120 114
121 115 //MAINTENANCE
122 116 "clean_uninstall" => false,
123 117 ];
@@ -138,9 +132,9 @@
138 132
139 133 $options = $this->sanitize_options( $options );
140 134
141 135 if ( !update_option( $this->option_name, $options, false ) ) {
142 - //$this->log( '💾 There was an issue updating the options.' );
136 + $this->log( '💾 There was an issue updating the options.' );
143 137 }
144 138
145 139 return $options;
146 140 }
@@ -173,9 +167,9 @@
173 167 $options_modified = true;
174 168 }
175 169
176 170 // Update AI Engine status
177 - $options = $this->updateAIEngineStatus( $options );
171 + $options_modified = $this->updateAIEngineStatus( $options ) || $options_modified;
178 172
179 173 // Disable AI related features if AI Engine is not available
180 174 if ( ! $options['ai_engine_status'] ) {
181 175 if ( $options['ai_suggestions'] !== false ) {
@@ -191,17 +185,31 @@
191 185
192 186 private function updateAIEngineStatus( &$options ) {
193 187 global $mwai;
194 188
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'];
189 + if ( is_null( $mwai ) || ! isset( $mwai ) ) {
190 + $options['ai_engine_status'] = false;
191 + $options['ai_engine_message'] = 'AI Engine is not available.';
192 + return true;
193 + }
202 194
203 - return $options;
195 + try {
196 + $status = $mwai->checkStatus();
197 +
198 + if ( $options['ai_engine_status'] != true || $options['ai_engine_message'] != $status ) {
199 + $options['ai_engine_status'] = true;
200 + $options['ai_engine_message'] = $status;
201 + return true;
202 + }
203 + } catch ( Exception $e ) {
204 + if ( $options['ai_engine_status'] != false || $options['ai_engine_message'] != $e->getMessage() ) {
205 + $options['ai_engine_status'] = false;
206 + $options['ai_engine_message'] = $e->getMessage();
207 + return true;
208 + }
209 + }
210 +
211 + return false;
204 212 }
205 213
206 214 #endregion
207 215
@@ -230,24 +238,9 @@
230 238
231 239 $this->snippet->validate( $params );
232 240
233 241 $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 - }
242 + $result = $this->snippet->insert( $params );
250 243 $snippet = $this->snippet->select_one( $result );
251 244
252 245 if( $result ) {
253 246 $params['id'] = (string)$result;
@@ -294,9 +287,9 @@
294 287
295 288 return [ $name, $value ];
296 289 }
297 290
298 - function run_non_fn_snippet( $id, $code = null, $test = false, $prefix = '' ) {
291 + function run_non_fn_snippet( $id, $code = null, $test = false ) {
299 292 // Retrieve the snippet code from the provided code or via the snippet ID.
300 293 if ( $code ) {
301 294 $snippet = [ 'code' => $code ];
302 295 } else {
@@ -303,17 +296,13 @@
303 296 $snippet = $this->get_snippet( $id );
304 297 }
305 298
306 299 // Remove any PHP opening tag.
307 - $snippet['code'] = $this->snippet->sanitize_code( $snippet['code'] );
300 + $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
308 301
309 302 if ( $test ) {
310 303 $snippet['code'] = preg_replace( '/echo\s+(.+?);/s', 'echo $1 . "\n";', $snippet['code'] );
311 304 }
312 -
313 - if( $prefix ) {
314 - $snippet['code'] = $prefix . "\n" . $snippet['code'];
315 - }
316 305
317 306 $error = null;
318 307 $output = null;
319 308
@@ -362,17 +351,35 @@
362 351 'values' => $snippet['functionArgsDict'] // Contains the default values of the arguments
363 352 ];
364 353 }
365 354
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.
355 + // Sanitize all the arguments if the option is enabled
356 + if ( $this->get_option( 'sanitize_arguments', true ) ) {
374 357
358 + if ( $args ) {
359 + foreach ( $args as $name => $value ) {
360 + list( $sanitizedName, $sanitizedValue ) = $this->sanitize_arg( $name, $value );
361 + unset( $args[$name] );
362 +
363 + $args[$sanitizedName] = $sanitizedValue;
364 + }
365 + }
366 +
367 + foreach ( $params['values'] as $name => $value ) {
368 +
369 + if( array_key_exists( 'input', $value) ) {
370 + list( $sanitizedInputName, $sanitizedInputValue ) = $this->sanitize_arg( $name, $value['input'], $value['type'] );
371 + $params['values'][$sanitizedInputName]['input'] = $sanitizedInputValue;
372 + }
373 +
374 + if( array_key_exists( 'default', $value) ) {
375 + list( $sanitizedDefaultValueName, $sanitizedDefaultValue ) = $this->sanitize_arg( $name, $value['default'], $value['type'] );
376 + $params['values'][$sanitizedDefaultValueName]['default'] = $sanitizedDefaultValue;
377 + }
378 + }
379 +
380 + }
381 +
375 382 // Make sure the function is existing and is the one in the snippet
376 383 if ( empty( $params['code'] ) ) {
377 384 throw new Exception( 'Code Engine: The snippet code appears to be empty.' );
378 385 }
@@ -380,32 +387,17 @@
380 387 if ( empty( $params['name'] ) || ! str_contains( $params['code'], $params['name'] ) ) {
381 388 throw new Exception( "Code Engine: Function name does not match. The name should be {$params['name']}." );
382 389 }
383 390
384 - // Collect the provided values, keyed by their normalized (dollar-less) name.
385 - // Incoming keys come from the AI/MCP schema, where register_function_tools()
386 - // strips a leading "$" from the declared name. The stored arg names can still
387 - // carry the "$", so we normalize both sides before matching below. Without this
388 - // a value provided as "style" never binds to an argument declared "$style".
389 - $provided = [];
391 + // Overwrite the default values with the provided ones
390 392 if ( $args ) {
391 393 foreach ( $args as $name => $value ) {
392 - $provided[ ltrim( $name, '$' ) ] = $value;
394 + $params['values'][$name]['input'] = $value;
393 395 }
394 396
395 397 $this->log( '⚡ Arguments provided: ' . json_encode( $args ) );
396 398 }
397 399
398 - // Global snippets are meant to be always accessible. On non-whitelisted REST routes
399 - // (Workflow Engine, MCP, AI function-calling) the plugins_loaded pass blocks them, so
400 - // make sure their helper library is loaded before we run a function that may call it.
401 - $this->load_global_snippets();
402 -
403 - // Make every *other* active PHP function snippet available so this function can
404 - // call its siblings. We pass the current name as the exception so the target is
405 - // still defined below (with the edited/test code when testing), not pre-defined here.
406 - $this->define_all_functions( $params['name'] );
407 -
408 400 // Check if the function has already been defined
409 401 if ( !in_array( $params['name'], $defined_functions ) ) {
410 402
411 403 // If not, proceed with modification and definition
@@ -423,58 +415,49 @@
423 415 // If already defined, just prepare to call the function without redefining it
424 416 $params['code'] = '';
425 417 }
426 418
427 - // Resolve the arguments as REAL PHP values, in the function's declared order.
428 - // The previous version concatenated each value into a string of PHP and eval-ed
429 - // the call, which broke on any string or edge-case value with a parse error
430 - // ("syntax error, unexpected token ')'"). call_user_func_array passes them as
431 - // data, so no value can ever corrupt the call syntax.
432 - $callArgs = [];
433 - foreach ( $params['args'] as $arg ) {
434 - $key = ltrim( $arg, '$' ); // Match the normalized name the caller sent.
435 - $value = null; // Not provided and no default -> null.
436 - // array_key_exists, not !empty: a legitimately provided 0, "0", "" or false
437 - // must reach the function instead of silently falling back to the default.
438 - if ( array_key_exists( $key, $provided ) ) {
439 - $value = $provided[ $key ];
440 - } else if ( isset( $params['values'][$arg]['default'] ) && $params['values'][$arg]['default'] !== '' ) {
441 - $value = $params['values'][$arg]['default'];
419 + // Prepare the code to be executed
420 + $params['code'] .= "\n\$mwcode_result = {$params['name']}(";
421 + foreach ( $params['args'] as $index => $arg ) {
422 + $value = 'null'; // In case the argument is not provided it will be null
423 +
424 + if ( array_key_exists( $arg, $params['values'] ) ) { // Avoid warnings if the argument is not provided
425 +
426 + // If the argument is provided, use it, if not use the default value
427 + if ( !empty( $params['values'][$arg]['input'] ) ) {
428 + $value = $params['values'][$arg]['input'];
429 +
430 + } else if ( !empty( $params['values'][$arg]['default'] ) ) {
431 + $value = $params['values'][$arg]['default'];
432 + }
442 433 }
443 - // An array-typed argument can arrive as a string like "[1, 2, 3]"; turn it
444 - // into a real array so the function receives what its signature expects.
445 - if ( ( $params['values'][$arg]['type'] ?? null ) === 'array' && is_string( $value ) ) {
446 - $decoded = json_decode( $value, true );
447 - $value = is_array( $decoded ) ? $decoded : array_map( 'trim', explode( ',', trim( $value, "[] \t\n\r" ) ) );
434 +
435 + $params['code'] .= "{$value}";
436 + if ( $index < count( $params['args'] ) - 1 ) {
437 + $params['code'] .= ', ';
448 438 }
449 - $callArgs[] = $value;
450 439 }
451 440
441 + $params['code'] .= ");\necho print_r(\$mwcode_result, true);";
442 +
452 443 $error = null;
453 444 $output = null;
454 -
445 +
455 446 try {
456 447 ob_start();
457 - // $params['code'] holds the function definition (empty if it was already
458 - // defined earlier this request). Declare it, then invoke it as data.
459 - if ( $params['code'] !== '' ) {
460 - eval( $params['code'] );
461 - }
462 - $mwcode_result = call_user_func_array( $params['name'], $callArgs );
463 - echo print_r( $mwcode_result, true );
448 + eval( $params['code'] );
464 449 $output = ob_get_clean();
465 -
466 - if ( $params['test'] ) {
450 +
451 + if ( $params['test'] ){
467 452 $output = explode( "\n", $output );
468 453 }
469 -
454 +
470 455 } catch ( Throwable $e ) {
471 456 //$this->log('Code Engine: Error executing the function: ' . $e->getMessage());
472 457 $error = new Exception(' Error executing the function, ' . $e->getMessage());
473 458
474 - if ( ob_get_level() > 0 ) {
475 - ob_end_clean();
476 - }
459 + ob_clean();
477 460 } finally {
478 461 restore_error_handler();
479 462 }
480 463
@@ -528,132 +511,8 @@
528 511
529 512 return null;
530 513 }
531 514
532 - /**
533 - * Load the active global snippets (persistent + backend/frontend for this context)
534 - * that haven't already run this request, so on-demand function execution has the same
535 - * always-available helper library a normal page load would. Callable functions are
536 - * typically small wrappers around these globals.
537 - *
538 - * On non-whitelisted REST routes (Workflow Engine, MCP, AI function-calling) the
539 - * plugins_loaded pass blocks global snippets for safety; this restores them for the
540 - * deliberate, authorized act of executing a snippet. The loaded-id registry guarantees
541 - * each global runs at most once per request, so nothing is ever re-declared.
542 - */
543 - function load_global_snippets() {
544 - global $current_mwcode_snippet;
545 - static $done = false;
546 - if ( $done ) {
547 - return;
548 - }
549 - $done = true;
550 -
551 - if ( empty( $this->snippet ) ) {
552 - $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
553 - }
554 -
555 - $scope = is_admin() ? [ 'backend', 'persistent' ] : [ 'frontend', 'persistent' ];
556 -
557 - $snippets = $this->snippet->select(
558 - null, // offset
559 - -1, // limit (all)
560 - [
561 - [ 'accessor' => 'active', 'value' => 1 ],
562 - [ 'accessor' => 'scope', 'value' => $scope ],
563 - ],
564 - [ 'accessor' => 'priority', 'by' => 'DESC' ]
565 - )['data'] ?? [];
566 -
567 - foreach ( $snippets as $snippet ) {
568 - // Skip globals already executed this request (e.g. by the plugins_loaded pass).
569 - if ( in_array( $snippet['id'], $this->loaded_global_ids ) ) {
570 - continue;
571 - }
572 - $this->loaded_global_ids[] = $snippet['id'];
573 -
574 - $code = $this->snippet->sanitize_code( $snippet['code'] );
575 - $current_mwcode_snippet = $snippet;
576 - try {
577 - ob_start();
578 - eval( $code );
579 - ob_end_clean();
580 - } catch ( Throwable $e ) {
581 - ob_end_clean();
582 - $this->log( "⚠️ Code Engine: Failed to load global snippet \"{$snippet['name']}\": " . $e->getMessage() );
583 - }
584 - }
585 - $current_mwcode_snippet = null;
586 - }
587 -
588 - /**
589 - * Declare every active PHP function snippet in the current request, without
590 - * invoking any of them, so function snippets can call one another.
591 - *
592 - * Function snippets are not auto-loaded on every request (unlike global/backend/
593 - * frontend scopes) — they are meant to run on demand. This is the PHP counterpart
594 - * to get_js_functions_to_push(): it makes the whole library of functions callable
595 - * before a function is executed (via REST, MCP, AI function-calling, Workflow Engine).
596 - *
597 - * Idempotent: a static guard runs the full pass only once per request, and each
598 - * definition is wrapped in function_exists() so nothing is ever redefined.
599 - *
600 - * @param string|null $except Function name to skip (the one run_snippet is about to
601 - * define itself, so edited/test code keeps priority).
602 - */
603 - function define_all_functions( $except = null ) {
604 - static $loaded = false;
605 - if ( $loaded ) {
606 - return;
607 - }
608 - $loaded = true;
609 -
610 - if ( empty( $this->snippet ) ) {
611 - $this->snippet = new Meow_MWCODE_Modules_Snippet( $this );
612 - }
613 -
614 - // One query for every active function snippet (code included), then enrich with
615 - // the function metadata (name + target) the same way run_snippet does.
616 - $snippets = $this->snippet->select(
617 - null, // offset
618 - -1, // limit (all)
619 - [
620 - [ 'accessor' => 'active', 'value' => 1 ],
621 - [ 'accessor' => 'scope', 'value' => 'function' ],
622 - ],
623 - [] // sort
624 - )['data'] ?? [];
625 -
626 - if ( empty( $snippets ) ) {
627 - return;
628 - }
629 -
630 - $this->snippet->get_function_snippets_data( $snippets );
631 -
632 - foreach ( $snippets as $snippet ) {
633 - $name = $snippet['functionName'] ?? '';
634 - $target = strtolower( $snippet['functionTarget'] ?? 'php' );
635 -
636 - // Skip JS functions (pushed to the front-end separately), the function the
637 - // caller will define itself, and anything already declared in this request.
638 - if ( $name === '' || $target === 'js' || $name === $except || function_exists( $name ) ) {
639 - continue;
640 - }
641 -
642 - // Mirror run_snippet()'s non-test handling: drop echo statements, then declare
643 - // (never call) the function, guarded so a later run_snippet() call is a no-op.
644 - $code = $this->snippet->sanitize_code( $snippet['code'] );
645 - $code = preg_replace( '/echo\s+(.+?);/s', '', $code );
646 - $code = "if (!function_exists('{$name}')) {\n{$code}\n}\n";
647 -
648 - try {
649 - eval( $code );
650 - } catch ( Throwable $e ) {
651 - $this->log( "⚠️ Code Engine: Failed to pre-define function \"{$name}\": " . $e->getMessage() );
652 - }
653 - }
654 - }
655 -
656 515 public function get_js_functions_to_push() {
657 516 $functions = $this->snippet->get_functions();
658 517 $js_functions = [];
659 518 foreach ( $functions as &$function ) {
@@ -767,9 +626,9 @@
767 626 return;
768 627 }
769 628
770 629 $snippets = array_map( function ( $snippet ) use ( $blocked ) {
771 - $snippet['code'] = $this->snippet->sanitize_code( $snippet['code'] );
630 + $snippet['code'] = preg_replace( '/<\?php/', '', $snippet['code'], 1 );
772 631 $snippet['blocked'] = $blocked;
773 632
774 633 // If the snippet must be executed only in the frontend, we bypass the block
775 634 if ( !is_admin() && $snippet['scope'] === 'frontend' ) {
@@ -785,26 +644,16 @@
785 644
786 645 #endregion
787 646
788 647 #region Shortcodes
789 - function separate_mwcode_atts( $atts ) {
790 648
791 - if( array_key_exists( 'id', $atts ) ) unset( $atts['id'] );
792 - if( array_key_exists( 'target', $atts ) ) unset( $atts['target'] );
793 - if( array_key_exists( 'code', $atts ) ) unset( $atts['code'] );
794 -
795 - return $atts;
796 - }
797 -
798 649 function content_shortcode( $atts ) {
799 650
800 - $user_atts = $this->separate_mwcode_atts( $atts );
801 -
802 651 $atts = shortcode_atts( array(
803 - 'id' => null,
804 - 'target' => null, // js or php
805 - 'code' => null, // For Guttenberg block usage
806 - ), $atts, 'code-engine' );
652 + 'id' => null,
653 + 'target' => null,
654 + 'code' => null,
655 + ), $atts );
807 656
808 657 $id = $atts['id'];
809 658 $target = $atts['target'];
810 659 $code = $atts['code'];
@@ -887,10 +736,9 @@
887 736 $output = '<script>' . $snippet['code'] . '</script>';
888 737 }
889 738
890 739 if ( $is_content_php ) {
891 - $prefix = "\$mwcode_atts = unserialize( '" . serialize( $user_atts ) . "' );";
892 - $output = $this->run_non_fn_snippet( $id, null, false, $prefix );
740 + $output = $this->run_non_fn_snippet( $id );
893 741 }
894 742
895 743 return $output;
896 744 }