PluginProbe
Code Engine – PHP Snippets, AI Functions & Automation for WordPress / 0.4.3
Code Engine – PHP Snippets, AI Functions & Automation for WordPress v0.4.3
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 +67 -201 0.5.40.4.3 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 }
@@ -191,16 +185,27 @@
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.';
202 192
193 + return $options;
194 + }
195 +
196 + try {
197 + $status = $mwai->checkStatus();
198 +
199 + $options['ai_engine_status'] = true;
200 + $options['ai_engine_message'] = is_array( $status ) ? "Environments: " . implode( ', ', $status ) : $status;
201 +
202 + } catch ( Exception $e ) {
203 +
204 + $options['ai_engine_status'] = false;
205 + $options['ai_engine_message'] = $e->getMessage();
206 + }
207 +
203 208 return $options;
204 209 }
205 210
206 211 #endregion
@@ -230,24 +235,9 @@
230 235
231 236 $this->snippet->validate( $params );
232 237
233 238 $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 - }
239 + $result = $this->snippet->insert( $params );
250 240 $snippet = $this->snippet->select_one( $result );
251 241
252 242 if( $result ) {
253 243 $params['id'] = (string)$result;
@@ -362,17 +352,35 @@
362 352 'values' => $snippet['functionArgsDict'] // Contains the default values of the arguments
363 353 ];
364 354 }
365 355
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.
356 + // Sanitize all the arguments if the option is enabled
357 + if ( $this->get_option( 'sanitize_arguments', true ) ) {
374 358
359 + if ( $args ) {
360 + foreach ( $args as $name => $value ) {
361 + list( $sanitizedName, $sanitizedValue ) = $this->sanitize_arg( $name, $value );
362 + unset( $args[$name] );
363 +
364 + $args[$sanitizedName] = $sanitizedValue;
365 + }
366 + }
367 +
368 + foreach ( $params['values'] as $name => $value ) {
369 +
370 + if( array_key_exists( 'input', $value) ) {
371 + list( $sanitizedInputName, $sanitizedInputValue ) = $this->sanitize_arg( $name, $value['input'], $value['type'] );
372 + $params['values'][$sanitizedInputName]['input'] = $sanitizedInputValue;
373 + }
374 +
375 + if( array_key_exists( 'default', $value) ) {
376 + list( $sanitizedDefaultValueName, $sanitizedDefaultValue ) = $this->sanitize_arg( $name, $value['default'], $value['type'] );
377 + $params['values'][$sanitizedDefaultValueName]['default'] = $sanitizedDefaultValue;
378 + }
379 + }
380 +
381 + }
382 +
375 383 // Make sure the function is existing and is the one in the snippet
376 384 if ( empty( $params['code'] ) ) {
377 385 throw new Exception( 'Code Engine: The snippet code appears to be empty.' );
378 386 }
@@ -389,18 +397,8 @@
389 397
390 398 $this->log( '⚡ Arguments provided: ' . json_encode( $args ) );
391 399 }
392 400
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 401 // Check if the function has already been defined
404 402 if ( !in_array( $params['name'], $defined_functions ) ) {
405 403
406 404 // If not, proceed with modification and definition
@@ -418,57 +416,49 @@
418 416 // If already defined, just prepare to call the function without redefining it
419 417 $params['code'] = '';
420 418 }
421 419
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'] ) ) {
420 + // Prepare the code to be executed
421 + $params['code'] .= "\n\$mwcode_result = {$params['name']}(";
422 + foreach ( $params['args'] as $index => $arg ) {
423 + $value = 'null'; // In case the argument is not provided it will be null
424 +
425 + if ( array_key_exists( $arg, $params['values'] ) ) { // Avoid warnings if the argument is not provided
426 +
427 + // If the argument is provided, use it, if not use the default value
431 428 if ( !empty( $params['values'][$arg]['input'] ) ) {
432 429 $value = $params['values'][$arg]['input'];
430 +
433 431 } else if ( !empty( $params['values'][$arg]['default'] ) ) {
434 432 $value = $params['values'][$arg]['default'];
435 433 }
436 434 }
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" ) ) );
435 +
436 + $params['code'] .= "{$value}";
437 + if ( $index < count( $params['args'] ) - 1 ) {
438 + $params['code'] .= ', ';
442 439 }
443 - $callArgs[] = $value;
444 440 }
445 441
442 + $params['code'] .= ");\necho print_r(\$mwcode_result, true);";
443 +
446 444 $error = null;
447 445 $output = null;
448 -
446 +
449 447 try {
450 448 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 );
449 + eval( $params['code'] );
458 450 $output = ob_get_clean();
459 -
460 - if ( $params['test'] ) {
451 +
452 + if ( $params['test'] ){
461 453 $output = explode( "\n", $output );
462 454 }
463 -
455 +
464 456 } catch ( Throwable $e ) {
465 457 //$this->log('Code Engine: Error executing the function: ' . $e->getMessage());
466 458 $error = new Exception(' Error executing the function, ' . $e->getMessage());
467 459
468 - if ( ob_get_level() > 0 ) {
469 - ob_end_clean();
470 - }
460 + ob_clean();
471 461 } finally {
472 462 restore_error_handler();
473 463 }
474 464
@@ -520,132 +510,8 @@
520 510 return $lint;
521 511 }
522 512
523 513 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 514 }
649 515
650 516 public function get_js_functions_to_push() {
651 517 $functions = $this->snippet->get_functions();