从JavaScript执行PHP伪代码的JSON块

时间:2013-01-04 15:57:16

标签: php javascript ajax json

在我正在处理的插件中,我想提供执行PHP伪代码的JSON块的功能。我意识到我需要设计一种特殊形式的JSON方式,允许我的后端PHP解析它并在其中执行伪代码。

在将JavaScript发送到服务器之前,这是一个有问题的JSON块,因为它存在于JavaScript中:

var codeBlock = {
    opts: 
    [
        {
            http: {
                method: "GET",
                header: "Accept-language: en\r\n" +
                        "Cookie: foo=bar\r\n"
            }
        }
    ],
    context: 
    {
        stream_context_create: ['opts']
    },
    contents: 
    {
        file_get_contents: ['http://www.YourDomain.com/', false, 'context']
    },
    html: 
    {
        htmlentities: ['contents']
    }
}

在上面的代码块中,我告诉PHP我要调用file_get_contents。为了做到这一点,我需要定义一个名为$opts的选项数组,该数组传递给stream_context_create。然后,stream_context_create返回的结果将存储在名为$contents的变量中。然后,我们将file_get_contents的返回结果存储到名为$contents的变量中。最后,我们将返回的数据从file_get_contents转换为变量$html

首先,我们需要构建一个将JSON发送到服务器的简单处理程序。

最重要的是,我们需要创建一个后端函数来解析我们的结果并发回我们的数据。

问题是,我们如何在开放式上下文中进行此操作(可能会传递任何可能的PHP函数调用序列和代码)?

1 个答案:

答案 0 :(得分:1)

处理这种动态解析和执行JSON“编码”PHP的主要功能如下。基本上我们按顺序解析JSON以识别变量名称。当我们遇到一个PHP对象时,我们就知道存在一个PHP函数调用。我们遍历函数参数的数组,寻找字符串“指针”,然后我们用那些指针值替换它们。指针只是对我们JSON中先前定义的变量的引用,这些变量需要作为参数发送到我们的函数调用。一旦创建了我们的新参数数组,我们用这些参数调用所请求的函数,然后将结果返回到该函数对象变量定义,其中它可能会或可能不会被用作另一个函数调用的参数。

/**
 * Iterates over an array containing PHP and handles calls to enabled functions and executes them.
 * @param {phpObj} array A JSON decoded array of representational PHP.
 * @return {*} Will return the results of the last function call passed in through phpObj.
 */
function parse_php_object( $arr, $config ) {

    // We define a pointer array that contains reference names to parameter placeholders
    // that will be replaced by real data.
    $pointers = array();

    foreach ( $arr as $k => $v ) {

        // Create variable definition with our first level array keys
        ${$k} = $v;

        // Populate our pointers index
        $pointers[$k] = $k;

        // When a value is an object we attempt to call functions defined within
        if ( is_object( ${$k} ) ) {

            // Convert our function object to an array
            $funcArr = (Array)${$k};

            // Use the first key of the function array as our function name to call
            $func_name = array_keys($funcArr);
            $func_name = $func_name[0];

            // Get the array of arguments to parse to our arguments array
            $func_args = $funcArr[$func_name];

            // Create an array to store the arguments to pass to our function call
            $args_arr = array();

            // Now we iterate over our function arguments looking for reference strings
            foreach ( $func_args as $arg ) {

                // We compare against the keys in our pointers index which was created above
                if ( array_key_exists( $arg, $pointers ) ) {

                    // This is now a reference to ${$k}, the originally defined definition, the returned
                    // result of the last sucessful function call
                    $p = ${$arg};

                    // We push our arguments onto the args_array which will be passed to our function call
                    array_push( $args_arr, $p );

                } else {

                    // We push our arguments onto the args_array which will be passed to our function call
                    array_push( $args_arr, $arg );
                }
            }


            // Based on the security mode selected, use either our blacklist or whitelist.
            switch ( $config['SEC_MODE'] ) {
                case 'blacklist' :
                    if ( function_exists( $func_name ) 
                         && !in_array( $func_name, $config['LISTS']['blacklist'] ) ) {
                        $function_allowed = true;
                    } else {
                        $function_allowed = false;
                    }
                    break;

                case 'whitelist' :
                    if ( function_exists( $func_name ) 
                         && in_array( $func_name, $config['LISTS']['whitelist'] ) ) {
                        $function_allowed = true;
                    } else {
                        $function_allowed = false;
                    }
                    break;
            }

            // Call the requested function if permitted
            if ( $function_allowed === true ) {

                // Reassign our variable the returned value of a function call so that further function calls can
                // search for the existence of pointers and then use the updated variable definitions. This logic
                // takes advantage of the procedural nature of PHP and the order of the sub-blocks in the php object. 
                ${$k} = call_user_func_array( $func_name, $args_arr );
            } else {
                return ("Function you requested $func_name has been disabled by backend configuration.");
            }
        }

        // When we're not an object we're something else like an array, string, int, etc. If we're an array we need
        // to recursively iterate over ourselves to convert any objects into arrays.
        else {  
            if ( is_array( ${$k} ) ) {
                array_walk_recursive( ${$k}, 'object_to_array' );
            }
        }

    }

    // Return the returned result from our final function call
    return ${$k};
}

/**
 * Converts PHP objects to arrays by typecasting.
 * @param {object} Object A self referencing PHP object.
 */
function object_to_array( &$object ) {
    if ( is_object( $object ) ) {
        (Array)$object;
    }
}

我认为这种方法使用反射模式,因为命令决策是根据传递的数据类型做出的。此外,这可以与大量基于AJAX的项目一起使用,而无需专门定义函数的处理接口。

当然,在我们将结果发送回客户端之前,会有更多代码执行某些类型检查,安全性测试和JSON编码,但上面显示的函数可以解决大部分问题。