Beispiel #1
0
function wfu_ajax_action_callback()
{
    if (!isset($_REQUEST['session_token'])) {
        die;
    }
    $session_token = sanitize_text_field($_REQUEST["session_token"]);
    if ($session_token == "") {
        die;
    }
    /* This section is executed when forceclassic is enabled or when redirection to the classic uploader was performed */
    if (isset($_REQUEST['sid']) && isset($_REQUEST['start_time'])) {
        //this request came from classic non-HTML5 uploader
        $sid = sanitize_text_field($_REQUEST["sid"]);
        if ($sid == "") {
            die;
        }
        $start_time = sanitize_text_field($_REQUEST["start_time"]);
        $_SESSION['wfu_check_refresh_' . $sid] = 'form button pressed';
        $_SESSION['wfu_start_time_' . $sid] = $start_time;
        die("wfu_response_success:");
    }
    /* This section is executed when normal HTML5 upload is performed */
    if (!isset($_REQUEST['params_index'])) {
        die;
    }
    $params_index = sanitize_text_field($_REQUEST["params_index"]);
    if ($params_index == "") {
        die;
    }
    $user = wp_get_current_user();
    $arr = wfu_get_params_fields_from_index($params_index);
    $sid = $arr['shortcode_id'];
    //check referrer using server sessions to avoid CSRF attacks
    if ($_SESSION["wfu_token_" . $sid] != $session_token) {
        echo "Session failed!<br/><br/>Session Data:<br/>";
        print_r(wfu_sanitize($_SESSION));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        die('force_errorabort_code');
    }
    if ($user->user_login != $arr['user_login']) {
        echo "User failed!<br/><br/>User Data:<br/>";
        print_r(wfu_sanitize($user));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        echo "<br/><br/>Params Data:<br/>";
        print_r(wfu_sanitize($arr));
        die('force_errorabort_code');
    }
    //if force_connection_close is set, then the first pass to this callback script is for closing the previous connection
    if (isset($_POST["force_connection_close"]) && $_POST["force_connection_close"] === "1") {
        header("Connection: Close");
        die("success");
    }
    //get the unique id of the upload
    $unique_id = isset($_POST['uniqueuploadid_' . $sid]) ? sanitize_text_field($_POST['uniqueuploadid_' . $sid]) : "";
    if (strlen($unique_id) != 10) {
        die('force_errorabort_code');
    }
    //if upload has finished then perform post upload actions
    if (isset($_POST["upload_finished"]) && $_POST["upload_finished"] === "1") {
        die("success");
    }
    $params_str = get_option('wfu_params_' . $arr['unique_id']);
    $params = wfu_decode_array_from_string($params_str);
    //if this is the first pass of an upload attempt then perform pre-upload actions
    if (!isset($_SESSION['wfu_upload_first_pass_' . $unique_id]) || $_SESSION['wfu_upload_first_pass_' . $unique_id] != 'true') {
        $_SESSION['wfu_upload_first_pass_' . $unique_id] = 'true';
    }
    if (!isset($_POST["subdir_sel_index"])) {
        die;
    }
    $subdir_sel_index = sanitize_text_field($_POST["subdir_sel_index"]);
    $params['subdir_selection_index'] = $subdir_sel_index;
    $_SESSION['wfu_check_refresh_' . $params["uploadid"]] = 'do not process';
    $wfu_process_file_array = wfu_process_files($params, 'ajax');
    // extract safe_output from wfu_process_file_array and pass it as separate part of the response text
    $safe_output = $wfu_process_file_array["general"]['safe_output'];
    unset($wfu_process_file_array["general"]['safe_output']);
    // get javascript code that has been defined in wfu_after_file_upload action
    $js_script = wfu_plugin_encode_string($wfu_process_file_array["general"]['js_script']);
    unset($wfu_process_file_array["general"]['js_script']);
    die("wfu_fileupload_success:" . $js_script . ":" . $safe_output . ":" . wfu_encode_array_to_string($wfu_process_file_array));
}
function wordpress_file_upload_function($incomingfromhandler)
{
    global $post;
    global $blog_id;
    $shortcode_tag = 'wordpress_file_upload';
    $params = wfu_plugin_parse_array($incomingfromhandler);
    $sid = $params["uploadid"];
    $widgetid = $params["widgetid"];
    // store current page and blog id in params array
    $params["pageid"] = $post->ID;
    $params["blogid"] = $blog_id;
    if (!isset($_SESSION['wfu_token_' . $sid]) || $_SESSION['wfu_token_' . $sid] == "") {
        $_SESSION['wfu_token_' . $sid] = uniqid(mt_rand(), TRUE);
    }
    //store the server environment (32 or 64bit) for use when checking file size limits
    $params["php_env"] = wfu_get_server_environment();
    $user = wp_get_current_user();
    $widths = wfu_decode_dimensions($params["widths"]);
    $heights = wfu_decode_dimensions($params["heights"]);
    //additional parameters to pass to visualization routines
    $additional_params = array();
    $additional_params['widths'] = $widths;
    $additional_params['heights'] = $heights;
    $uploadedfile = 'uploadedfile_' . $sid;
    $hiddeninput = 'hiddeninput_' . $sid;
    $adminerrorcodes = 'adminerrorcodes_' . $sid;
    $upload_clickaction = 'wfu_redirect_to_classic(' . $sid . ', \'' . $_SESSION['wfu_token_' . $sid] . '\' , 0, 0);';
    //check if user is allowed to view plugin, otherwise do not generate it
    $uploadroles = explode(",", $params["uploadrole"]);
    foreach ($uploadroles as &$uploadrole) {
        $uploadrole = trim($uploadrole);
    }
    $plugin_upload_user_role = wfu_get_user_role($user, $uploadroles);
    if ($plugin_upload_user_role == 'nomatch') {
        return;
    }
    //activate debug mode only for admins
    if ($plugin_upload_user_role != 'administrator') {
        $params["debugmode"] = "false";
    }
    $params["adminmessages"] = $params["adminmessages"] == "true" && $plugin_upload_user_role == 'administrator';
    // define variable to hold any additional admin errors coming before processing of files (e.g. due to redirection)
    $params["adminerrors"] = "";
    /* Define dynamic upload path from variables */
    $search = array('/%userid%/', '/%username%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/');
    if (is_user_logged_in()) {
        $username = $user->user_login;
    } else {
        $username = "******";
    }
    $replace = array($user->ID, $username, $blog_id, $post->ID, get_the_title($post->ID));
    $params["uploadpath"] = preg_replace($search, $replace, $params["uploadpath"]);
    /* Determine if userdata fields have been defined */
    $userdata_fields = array();
    $userdata_occurrencies = substr_count($params["placements"], "userdata");
    if ($userdata_occurrencies == 0) {
        $userdata_occurrencies = 1;
    }
    if ($params["userdata"] == "true") {
        for ($i = 1; $i <= $userdata_occurrencies; $i++) {
            $userdata_fields2 = wfu_parse_userdata_attribute($params["userdatalabel" . ($i > 1 ? $i : "")]);
            foreach ($userdata_fields2 as $key => $item) {
                $userdata_fields2[$key]["occurrence"] = $i;
            }
            $userdata_fields = array_merge($userdata_fields, $userdata_fields2);
        }
    }
    $params["userdata_fields"] = $userdata_fields;
    /* If medialink or postlink is activated, then subfolders are deactivated */
    if ($params["medialink"] == "true" || $params["postlink"] == "true") {
        $params["askforsubfolders"] = "false";
    }
    /* Generate the array of subfolder paths */
    $params['subfoldersarray'] = wfu_get_subfolders_paths($params);
    //____________________________________________________________________________________________________________________________________________________________________________________
    if ($params['forceclassic'] != "true") {
        //**************section to put additional options inside params array**************
        $params['subdir_selection_index'] = "-1";
        //**************end of section of additional options inside params array**************
        //	below this line no other changes to params array are allowed
        //**************section to save params as Wordpress options**************
        //		every params array is indexed (uniquely identified) by three fields:
        //			- the page that contains the shortcode
        //			- the id of the shortcode instance (because there may be more than one instances of the shortcode inside a page)
        //			- the user that views the plugin (because some items of the params array are affected by the user name)
        //		the wordpress option "wfu_params_index" holds an array of combinations of these three fields, together with a randomly generated string that corresponds to these fields.
        //		the wordpress option "wfu_params_xxx", where xxx is the randomly generated string, holds the params array (encoded to string) that corresponds to this string.
        //		the structure of the "wfu_params_index" option is as follows: "a1||b1||c1||d1&&a2||b2||c2||d2&&...", where
        //			- a is the randomly generated string (16 characters)
        //			- b is the page id
        //			- c is the shortcode id
        //			- d is the user name
        $params_index = wfu_generate_current_params_index($sid, $user->user_login);
        $params_str = wfu_encode_array_to_string($params);
        update_option('wfu_params_' . $params_index, $params_str);
        $ajax_params['shortcode_id'] = $sid;
        $ajax_params['params_index'] = $params_index;
        $ajax_params['debugmode'] = $params["debugmode"];
        $ajax_params['is_admin'] = $plugin_upload_user_role == 'administrator' ? "true" : "false";
        $ajax_params["error_header"] = $params["errormessage"];
        $ajax_params["fail_colors"] = $params["failmessagecolors"];
        $ajax_params_str = wfu_encode_array_to_string($ajax_params);
        $upload_clickaction = 'wfu_HTML5UploadFile(' . $sid . ', \'' . $ajax_params_str . '\', \'' . $_SESSION['wfu_token_' . $sid] . '\')';
    }
    $upload_onclick = ' onclick="' . $upload_clickaction . '"';
    $additional_params['clickaction'] = $upload_clickaction;
    /* Compose the html code for the plugin */
    $wordpress_file_upload_output = "";
    $plugin_style = "";
    if ($widths["plugin"] != "") {
        $plugin_style .= 'width: ' . $widths["plugin"] . '; ';
    }
    if ($heights["plugin"] != "") {
        $plugin_style .= 'height: ' . $heights["plugin"] . '; ';
    }
    if ($plugin_style != "") {
        $plugin_style = ' style="' . $plugin_style . '"';
    }
    $wordpress_file_upload_output .= '<div id="' . $shortcode_tag . '_block_' . $sid . '" class="file_div_clean' . ($params["fitmode"] == "responsive" ? '_responsive_container' : '') . ' wfu_container"' . $plugin_style . '>';
    $wordpress_file_upload_output .= "\n\t" . '<input type="hidden" id="' . $shortcode_tag . '_' . $sid . '_widgetid" value="' . $widgetid . '" />';
    //add visual editor overlay if the current user is administrator
    if (current_user_can('manage_options')) {
        $wordpress_file_upload_output .= wfu_add_visual_editor_button($shortcode_tag, $sid);
    }
    //read indexed component definitions
    $components = wfu_component_definitions();
    $components_indexed = array();
    foreach ($components as $component) {
        $components_indexed[$component['id']] = $component;
        $components_indexed[$component['id']]['occurrencies'] = 0;
    }
    $itemplaces = explode("/", $params["placements"]);
    foreach ($itemplaces as $section) {
        $items_in_section = explode("+", trim($section));
        $section_array = array($params["fitmode"]);
        foreach ($items_in_section as $item_in_section) {
            $item_in_section = strtolower(trim($item_in_section));
            if (isset($components_indexed[$item_in_section]) && ($components_indexed[$item_in_section]['multiplacements'] || $components_indexed[$item_in_section]['occurrencies'] == 0)) {
                $components_indexed[$item_in_section]['occurrencies']++;
                $occurrence_index = $components_indexed[$item_in_section]['multiplacements'] ? $components_indexed[$item_in_section]['occurrencies'] : 0;
                if ($item_in_section == "title") {
                    array_push($section_array, wfu_prepare_title_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "filename") {
                    array_push($section_array, wfu_prepare_textbox_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "selectbutton") {
                    array_push($section_array, wfu_prepare_uploadform_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "uploadbutton" && $params["singlebutton"] != "true") {
                    array_push($section_array, wfu_prepare_submit_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "subfolders") {
                    array_push($section_array, wfu_prepare_subfolders_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "progressbar") {
                    array_push($section_array, wfu_prepare_progressbar_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "message") {
                    array_push($section_array, wfu_prepare_message_block($params, $additional_params, $occurrence_index));
                } elseif ($item_in_section == "userdata" && $params["userdata"] == "true") {
                    array_push($section_array, wfu_prepare_userdata_block($params, $additional_params, $occurrence_index));
                }
            }
        }
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    /* Append mandatory blocks, if have not been included in placements attribute */
    if ($params["userdata"] == "true" && strpos($params["placements"], "userdata") === false) {
        $section_array = array($params["fitmode"]);
        array_push($section_array, wfu_prepare_userdata_block($params, $additional_params, 0));
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    if (strpos($params["placements"], "selectbutton") === false) {
        $section_array = array($params["fitmode"]);
        array_push($section_array, wfu_prepare_uploadform_block($params, $additional_params, 0));
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    /* Pass constants to javascript and run plugin post-load actions */
    $consts = wfu_set_javascript_constants();
    $handler = 'function() { wfu_Initialize_Consts("' . $consts . '"); wfu_plugin_load_action(' . $sid . '); }';
    $wordpress_file_upload_output .= "\n\t" . '<script type="text/javascript">if(window.addEventListener) { window.addEventListener("load", ' . $handler . ', false); } else if(window.attachEvent) { window.attachEvent("onload", ' . $handler . '); } else { window["onload"] = ' . $handler . '; }</script>';
    $wordpress_file_upload_output .= '</div>';
    //	$wordpress_file_upload_output .= '<div>';
    //	$wordpress_file_upload_output .= wfu_test_admin();
    //	$wordpress_file_upload_output .= '</div>';
    //	The plugin uses sessions in order to detect if the page was loaded due to file upload or
    //	because the user pressed the Refresh button (or F5) of the page.
    //	In the second case we do not want to perform any file upload, so we abort the rest of the script.
    if (!isset($_SESSION['wfu_check_refresh_' . $sid]) || $_SESSION['wfu_check_refresh_' . $sid] != "form button pressed") {
        $_SESSION['wfu_check_refresh_' . $sid] = 'do not process';
        $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
        return $wordpress_file_upload_output . "\n";
    }
    $_SESSION['wfu_check_refresh_' . $sid] = 'do not process';
    $params["upload_start_time"] = $_SESSION['wfu_start_time_' . $sid];
    //	The plugin uses two ways to upload the file:
    //		- The first one uses classic functionality of an HTML form (highest compatibility with browsers but few capabilities).
    //		- The second uses ajax (HTML5) functionality (medium compatibility with browsers but many capabilities, like no page refresh and progress bar).
    //	The plugin loads using ajax functionality by default, however if it detects that ajax functionality is not supported, it will automatically switch to classic functionality.
    //	The next line checks to see if the form was submitted using ajax or classic functionality.
    //	If the uploaded file variable stored in $_FILES ends with "_redirected", then it means that ajax functionality is not supported and the plugin must switch to classic functionality.
    if (isset($_FILES[$uploadedfile . '_redirected'])) {
        $params['forceclassic'] = "true";
    }
    if ($params['forceclassic'] != "true") {
        $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
        return $wordpress_file_upload_output . "\n";
    }
    //  The following code is executed in case of non-ajax uploads to process the files.
    //  Consecutive checks are performed in order to verify and approve the upload of files
    $wfu_checkpass = true;
    //  First we test that WP nonce passes the check
    $wfu_checkpass = $wfu_checkpass && isset($_REQUEST["wfu_uploader_nonce"]) && wp_verify_nonce($_REQUEST["wfu_uploader_nonce"], "wfu-uploader-nonce") !== false;
    $unique_id = isset($_POST['uniqueuploadid_' . $sid]) ? sanitize_text_field($_POST['uniqueuploadid_' . $sid]) : "";
    //  Check that upload_id is valid
    $wfu_checkpass = $wfu_checkpass && strlen($unique_id) == 10;
    if ($wfu_checkpass) {
        //process any error messages due to redirection to non-ajax upload
        if (isset($_POST[$adminerrorcodes])) {
            $code = $_POST[$adminerrorcodes];
            if ($code == "") {
                $params['adminerrors'] = "";
            } elseif ($code == "1" || $code == "2" || $code == "3") {
                $params['adminerrors'] = constant('WFU_ERROR_REDIRECTION_ERRORCODE' . $code);
            } else {
                $params['adminerrors'] = WFU_ERROR_REDIRECTION_ERRORCODE0;
            }
        }
        $params['subdir_selection_index'] = -1;
        if (isset($_POST[$hiddeninput])) {
            $params['subdir_selection_index'] = sanitize_text_field($_POST[$hiddeninput]);
        }
        $wfu_process_file_array = wfu_process_files($params, 'no_ajax');
        $safe_output = $wfu_process_file_array["general"]['safe_output'];
        unset($wfu_process_file_array["general"]['safe_output']);
        //javascript code generated from individual wfu_after_upload_filters is not executed in non-ajax uploads
        unset($wfu_process_file_array["general"]['js_script']);
        $wfu_process_file_array_str = wfu_encode_array_to_string($wfu_process_file_array);
        $ProcessUploadComplete_functiondef = 'function(){wfu_ProcessUploadComplete(' . $sid . ', 1, "' . $wfu_process_file_array_str . '", "no-ajax", "", "", "' . $safe_output . '", ["false", "", "false"]);}';
        $wordpress_file_upload_output .= '<script type="text/javascript">window.onload=' . $ProcessUploadComplete_functiondef . '</script>';
    }
    $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
    return $wordpress_file_upload_output . "\n";
}
function wfu_ajax_action_callback()
{
    if (!isset($_REQUEST['session_token'])) {
        die;
    }
    $session_token = sanitize_text_field($_REQUEST["session_token"]);
    if ($session_token == "") {
        die;
    }
    check_ajax_referer('wfu-uploader-nonce', 'wfu_uploader_nonce');
    if (!isset($_REQUEST['params_index'])) {
        die;
    }
    $params_index = sanitize_text_field($_REQUEST["params_index"]);
    if ($params_index == "") {
        die;
    }
    $user = wp_get_current_user();
    $arr = wfu_get_params_fields_from_index($params_index);
    $sid = $arr['shortcode_id'];
    //check referrer using server sessions to avoid CSRF attacks
    if ($_SESSION["wfu_token_" . $sid] != $session_token) {
        echo "Session failed!<br/><br/>Session Data:<br/>";
        print_r(wfu_sanitize($_SESSION));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        die('force_errorabort_code');
    }
    if ($user->user_login != $arr['user_login']) {
        echo "User failed!<br/><br/>User Data:<br/>";
        print_r(wfu_sanitize($user));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        echo "<br/><br/>Params Data:<br/>";
        print_r(wfu_sanitize($arr));
        die('force_errorabort_code');
    }
    //if force_connection_close is set, then the first pass to this callback script is for closing the previous connection
    if (isset($_POST["force_connection_close"]) && $_POST["force_connection_close"] === "1") {
        header("Connection: Close");
        die("success");
    }
    //get the unique id of the upload
    $unique_id = isset($_POST['uniqueuploadid_' . $sid]) ? sanitize_text_field($_POST['uniqueuploadid_' . $sid]) : "";
    if (strlen($unique_id) != 10) {
        die('force_errorabort_code');
    }
    //if before upload actions have been executed and they have rejected the
    //upload, but for some reason (hack attempt) the upload continued, then
    //terminate it
    if (isset($_SESSION["wfu_uploadstatus_" . $unique_id]) && $_SESSION["wfu_uploadstatus_" . $unique_id] == 0) {
        die('force_errorabort_code');
    }
    //if upload has finished then perform post upload actions
    if (isset($_POST["upload_finished"]) && $_POST["upload_finished"] === "1") {
        $echo_str = "";
        //execute after upload filters
        $ret = wfu_execute_after_upload_filters($sid, $unique_id);
        if ($ret["js_script"] != "") {
            $echo_str = "CBUVJS[" . $ret["js_script"] . "]";
        }
        die($echo_str);
    }
    $params_str = get_option('wfu_params_' . $arr['unique_id']);
    $params = wfu_decode_array_from_string($params_str);
    //apply filters to determine if the upload will continue or stop
    $ret = array("status" => "", "echo" => "");
    $attr = array("sid" => $sid, "unique_id" => $unique_id, "params" => $params);
    $ret = apply_filters("_wfu_pre_upload_check", $ret, $attr);
    if ($ret["status"] == "die") {
        die($ret["echo"]);
    }
    //if this is the first pass of an upload attempt then perform pre-upload actions
    if (!isset($_SESSION['wfu_upload_first_pass_' . $unique_id]) || $_SESSION['wfu_upload_first_pass_' . $unique_id] != 'true') {
        $_SESSION['wfu_upload_first_pass_' . $unique_id] = 'true';
    }
    if (!isset($_POST["subdir_sel_index"])) {
        die;
    }
    $subdir_sel_index = sanitize_text_field($_POST["subdir_sel_index"]);
    $params['subdir_selection_index'] = $subdir_sel_index;
    $_SESSION['wfu_check_refresh_' . $params["uploadid"]] = 'do not process';
    $wfu_process_file_array = wfu_process_files($params, 'ajax');
    // extract safe_output from wfu_process_file_array and pass it as separate part of the response text
    $safe_output = $wfu_process_file_array["general"]['safe_output'];
    unset($wfu_process_file_array["general"]['safe_output']);
    // get javascript code that has been defined in wfu_after_file_upload action
    $js_script = wfu_plugin_encode_string($wfu_process_file_array["general"]['js_script']);
    unset($wfu_process_file_array["general"]['js_script']);
    die("wfu_fileupload_success:" . $js_script . ":" . $safe_output . ":" . wfu_encode_array_to_string($wfu_process_file_array));
}
function wordpress_file_upload_function($incomingfromhandler)
{
    global $post;
    global $blog_id;
    $params = wfu_plugin_parse_array($incomingfromhandler);
    $sid = $params["uploadid"];
    // store current page id in params array
    $params["pageid"] = $post->ID;
    if (!isset($_SESSION['wfu_token_' . $sid]) || $_SESSION['wfu_token_' . $sid] == "") {
        $_SESSION['wfu_token_' . $sid] = uniqid(mt_rand(), TRUE);
    }
    //store the server environment (32 or 64bit) for use when checking file size limits
    $params["php_env"] = wfu_get_server_environment();
    $user = wp_get_current_user();
    $widths = wfu_decode_dimensions($params["widths"]);
    $heights = wfu_decode_dimensions($params["heights"]);
    $uploadedfile = 'uploadedfile_' . $sid;
    $hiddeninput = 'hiddeninput_' . $sid;
    $adminerrorcodes = 'adminerrorcodes_' . $sid;
    $upload_clickaction = 'wfu_redirect_to_classic(' . $sid . ', \'' . $_SESSION['wfu_token_' . $sid] . '\' , 0, 0);';
    //check if user is allowed to view plugin, otherwise do not generate it
    $uploadroles = explode(",", $params["uploadrole"]);
    foreach ($uploadroles as &$uploadrole) {
        $uploadrole = strtolower(trim($uploadrole));
    }
    $plugin_upload_user_role = wfu_get_user_role($user, $uploadroles);
    if (!in_array($plugin_upload_user_role, $uploadroles) && $plugin_upload_user_role != 'administrator' && $params["uploadrole"] != 'all') {
        return;
    }
    //activate debug mode only for admins
    if ($plugin_upload_user_role != 'administrator') {
        $params["debugmode"] = "false";
    }
    $params["adminmessages"] = $params["adminmessages"] == "true" && $plugin_upload_user_role == 'administrator';
    // define variable to hold any additional admin errors coming before processing of files (e.g. due to redirection)
    $params["adminerrors"] = "";
    /* Define dynamic upload path from variables */
    $search = array('/%userid%/', '/%username%/', '/%blogid%/', '/%pageid%/', '/%pagetitle%/');
    if (is_user_logged_in()) {
        $username = $user->user_login;
    } else {
        $username = "******";
    }
    $replace = array($user->ID, $username, $blog_id, $post->ID, get_the_title($post->ID));
    $params["uploadpath"] = preg_replace($search, $replace, $params["uploadpath"]);
    /* Determine if userdata fields have been defined */
    $userdata_fields = array();
    if ($params["userdata"] == "true" && $params["userdatalabel"] != "") {
        $userdata_rawfields = explode("/", $params["userdatalabel"]);
        foreach ($userdata_rawfields as $userdata_rawitem) {
            if ($userdata_rawitem != "") {
                $is_required = $userdata_rawitem[0] == "*" ? "true" : "false";
                if ($is_required == "true") {
                    $userdata_rawitem = substr($userdata_rawitem, 1);
                }
                if ($userdata_rawitem != "") {
                    array_push($userdata_fields, array("label" => $userdata_rawitem, "required" => $is_required));
                }
            }
        }
    }
    $params["userdata_fields"] = $userdata_fields;
    /* If medialink or postlink is activated, then subfolders are deactivated */
    if ($params["medialink"] == "true" || $params["postlink"] == "true") {
        $params["askforsubfolders"] = "false";
    }
    /* Prepare information about directory or selection of target subdirectory */
    $subfolders = wfu_prepare_subfolders_block($params, $widths, $heights);
    $subfolders_item = $subfolders['item'];
    $params['subfoldersarray'] = $subfolders['paths'];
    //____________________________________________________________________________________________________________________________________________________________________________________
    if ($params['forceclassic'] != "true") {
        //**************section to put additional options inside params array**************
        $params['subdir_selection_index'] = "-1";
        //**************end of section of additional options inside params array**************
        //	below this line no other changes to params array are allowed
        //**************section to save params as Wordpress options**************
        //		every params array is indexed (uniquely identified) by three fields:
        //			- the page that contains the shortcode
        //			- the id of the shortcode instance (because there may be more than one instances of the shortcode inside a page)
        //			- the user that views the plugin (because some items of the params array are affected by the user name)
        //		the wordpress option "wfu_params_index" holds an array of combinations of these three fields, together with a randomly generated string that corresponds to these fields.
        //		the wordpress option "wfu_params_xxx", where xxx is the randomly generated string, holds the params array (encoded to string) that corresponds to this string.
        //		the structure of the "wfu_params_index" option is as follows: "a1||b1||c1||d1&&a2||b2||c2||d2&&...", where
        //			- a is the randomly generated string (16 characters)
        //			- b is the page id
        //			- c is the shortcode id
        //			- d is the user name
        $params_index = wfu_generate_current_params_index($sid, $user->user_login);
        $params_str = wfu_encode_array_to_string($params);
        update_option('wfu_params_' . $params_index, $params_str);
        $ajax_params['shortcode_id'] = $sid;
        $ajax_params['params_index'] = $params_index;
        $ajax_params['debugmode'] = $params["debugmode"];
        $ajax_params['is_admin'] = $plugin_upload_user_role == 'administrator' ? "true" : "false";
        $ajax_params["error_header"] = $params["errormessage"];
        $ajax_params["fail_colors"] = $params["failmessagecolors"];
        $ajax_params_str = wfu_encode_array_to_string($ajax_params);
        $upload_clickaction = 'wfu_HTML5UploadFile(' . $sid . ', \'' . $ajax_params_str . '\', \'' . $_SESSION['wfu_token_' . $sid] . '\')';
    }
    $upload_onclick = ' onclick="' . $upload_clickaction . '"';
    /* Prepare the title */
    $title_item = wfu_prepare_title_block($params, $widths, $heights);
    /* Prepare the text box showing filename */
    $textbox_item = wfu_prepare_textbox_block($params, $widths, $heights);
    /* Prepare the upload form */
    $additional_params = array();
    $uploadform_item = wfu_prepare_uploadform_block($params, $widths, $heights, $upload_clickaction, $additional_params);
    /* Prepare the submit button */
    $submit_item = wfu_prepare_submit_block($params, $widths, $heights, $upload_clickaction);
    /* Prepare the progress bar */
    $progressbar_item = wfu_prepare_progressbar_block($params, $widths, $heights);
    /* Prepare the message */
    $message_item = wfu_prepare_message_block($params, $widths, $heights);
    /* Prepare user data */
    $userdata_item = wfu_prepare_userdata_block($params, $widths, $heights);
    /* Compose the html code for the plugin */
    $wordpress_file_upload_output = "";
    $wordpress_file_upload_output .= '<div id="wordpress_file_upload_block_' . $sid . '" class="file_div_clean wfu_container">';
    //add visual editor overlay if the current user is administrator
    if (current_user_can('manage_options')) {
        $wordpress_file_upload_output .= "\n\t" . '<div id="wordpress_file_upload_editor_' . $sid . '" class="wfu_overlay_editor">';
        $wordpress_file_upload_output .= "\n\t\t" . '<button class="wfu_overlay_editor_button" title="' . WFU_PAGE_PLUGINEDITOR_BUTTONTITLE . '" onclick="wfu_invoke_shortcode_editor(' . $sid . ', ' . $post->ID . ', \'' . hash('md5', $post->post_content) . '\');"><img src="' . WFU_IMAGE_OVERLAY_EDITOR . '" width="20px" height="20px" /></button>';
        $wordpress_file_upload_output .= "\n\t" . '</div>';
        $wordpress_file_upload_output .= "\n\t" . '<div id="wordpress_file_upload_overlay_' . $sid . '" class="wfu_overlay_container">';
        $wordpress_file_upload_output .= "\n\t\t" . '<table class="wfu_overlay_table"><tbody><tr><td><img src="' . WFU_IMAGE_OVERLAY_LOADING . '" /><label>' . WFU_PAGE_PLUGINEDITOR_LOADING . '</label></td></tr></tbody></table>';
        $wordpress_file_upload_output .= "\n\t\t" . '<div class="wfu_overlay_container_inner"></div>';
        $wordpress_file_upload_output .= "\n\t" . '</div>';
    }
    $itemplaces = explode("/", $params["placements"]);
    foreach ($itemplaces as $section) {
        $items_in_section = explode("+", trim($section));
        $section_array = array();
        foreach ($items_in_section as $item_in_section) {
            $item_in_section = strtolower(trim($item_in_section));
            if ($item_in_section == "title") {
                array_push($section_array, $title_item);
            } elseif ($item_in_section == "filename") {
                array_push($section_array, $textbox_item);
            } elseif ($item_in_section == "selectbutton") {
                array_push($section_array, $uploadform_item);
            } elseif ($item_in_section == "confirmbox" && preg_match("/(^|,)\\s*checkbox\\s*(,|\$)/", $params['security_active']) && $params["singlebutton"] != "true") {
                array_push($section_array, $confirmbox_item);
            } elseif ($item_in_section == "uploadbutton" && $params["singlebutton"] != "true") {
                array_push($section_array, $submit_item);
            } elseif ($item_in_section == "subfolders") {
                array_push($section_array, $subfolders_item);
            } elseif ($item_in_section == "progressbar") {
                array_push($section_array, $progressbar_item);
            } elseif ($item_in_section == "message") {
                array_push($section_array, $message_item);
            } elseif ($item_in_section == "userdata" && $params["userdata"] == "true") {
                array_push($section_array, $userdata_item);
            }
        }
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    /* Append mandatory blocks, if have not been included in placements attribute */
    if ($params["userdata"] == "true" && strpos($params["placements"], "userdata") === false) {
        $section_array = array();
        array_push($section_array, $userdata_item);
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    if (strpos($params["placements"], "selectbutton") === false) {
        $section_array = array();
        array_push($section_array, $uploadform_item);
        $wordpress_file_upload_output .= call_user_func_array("wfu_add_div", $section_array);
    }
    /* Pass constants to javascript and run plugin post-load actions */
    $consts = wfu_set_javascript_constants();
    $handler = 'function() { wfu_Initialize_Consts("' . $consts . '"); wfu_plugin_load_action(' . $sid . '); }';
    $wordpress_file_upload_output .= "\n\t" . '<script type="text/javascript">if(window.addEventListener) { window.addEventListener("load", ' . $handler . ', false); } else if(window.attachEvent) { window.attachEvent("onload", ' . $handler . '); } else { window["onload"] = ' . $handler . '; }</script>';
    $wordpress_file_upload_output .= '</div>';
    //	$wordpress_file_upload_output .= '<div>';
    //	$wordpress_file_upload_output .= wfu_test_admin();
    //	$wordpress_file_upload_output .= '</div>';
    //	The plugin uses sessions in order to detect if the page was loaded due to file upload or
    //	because the user pressed the Refresh button (or F5) of the page.
    //	In the second case we do not want to perform any file upload, so we abort the rest of the script.
    if (!isset($_SESSION['wfu_check_refresh_' . $sid]) || $_SESSION['wfu_check_refresh_' . $sid] != "form button pressed") {
        $_SESSION['wfu_check_refresh_' . $sid] = 'do not process';
        $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
        return $wordpress_file_upload_output . "\n";
    }
    $_SESSION['wfu_check_refresh_' . $sid] = 'do not process';
    $params["upload_start_time"] = $_SESSION['wfu_start_time_' . $sid];
    //	The plugin uses two ways to upload the file:
    //		- The first one uses classic functionality of an HTML form (highest compatibility with browsers but few capabilities).
    //		- The second uses ajax (HTML5) functionality (medium compatibility with browsers but many capabilities, like no page refresh and progress bar).
    //	The plugin loads using ajax functionality by default, however if it detects that ajax functionality is not supported, it will automatically switch to classic functionality.
    //	The next line checks to see if the form was submitted using ajax or classic functionality.
    //	If the uploaded file variable stored in $_FILES ends with "_redirected", then it means that ajax functionality is not supported and the plugin must switch to classic functionality.
    if (isset($_FILES[$uploadedfile . '_redirected'])) {
        $params['forceclassic'] = "true";
    }
    if ($params['forceclassic'] != "true") {
        $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
        return $wordpress_file_upload_output . "\n";
    }
    //	The section below is executed when using classic upload methods
    if (isset($_POST[$adminerrorcodes])) {
        $code = $_POST[$adminerrorcodes];
        if ($code == "") {
            $params['adminerrors'] = "";
        } elseif ($code == "1" || $code == "2" || $code == "3") {
            $params['adminerrors'] = constant('WFU_ERROR_REDIRECTION_ERRORCODE' . $code);
        } else {
            $params['adminerrors'] = WFU_ERROR_REDIRECTION_ERRORCODE0;
        }
    }
    $params['subdir_selection_index'] = -1;
    if (isset($_POST[$hiddeninput])) {
        $params['subdir_selection_index'] = $_POST[$hiddeninput];
    }
    $wfu_process_file_array = wfu_process_files($params, 'no_ajax');
    $safe_output = $wfu_process_file_array["general"]['safe_output'];
    unset($wfu_process_file_array["general"]['safe_output']);
    $wfu_process_file_array_str = wfu_encode_array_to_string($wfu_process_file_array);
    $ProcessUploadComplete_functiondef = 'function(){wfu_ProcessUploadComplete(' . $sid . ', 1, "' . $wfu_process_file_array_str . '", "no-ajax", "", "", "' . $safe_output . '", ["false", "", "false"]);}';
    $wordpress_file_upload_output .= '<script type="text/javascript">window.onload=' . $ProcessUploadComplete_functiondef . '</script>';
    $wordpress_file_upload_output .= wfu_post_plugin_actions($params);
    return $wordpress_file_upload_output . "\n";
}
function wfu_ajax_action_callback()
{
    $user = wp_get_current_user();
    $arr = wfu_get_params_fields_from_index($_POST['params_index']);
    //check referrer using server sessions to avoid CSRF attacks
    if ($_SESSION["wfu_token_" . $arr['shortcode_id']] != $_POST['session_token']) {
        echo "Session failed!<br/><br/>Session Data:<br/>";
        print_r(wfu_sanitize($_SESSION));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        die('force_errorabort_code');
    }
    if ($user->user_login != $arr['user_login']) {
        echo "User failed!<br/><br/>User Data:<br/>";
        print_r(wfu_sanitize($user));
        echo "<br/><br/>Post Data:<br/>";
        print_r(wfu_sanitize($_POST));
        echo "<br/><br/>Params Data:<br/>";
        print_r(wfu_sanitize($arr));
        die('force_errorabort_code');
    }
    //get the unique id of the upload
    $unique_id = isset($_POST['unique_id']) ? $_POST['unique_id'] : "";
    //the first pass to this callback script is for closing the previous connection_aborted
    if (isset($_POST["force_connection_close"]) && $_POST["force_connection_close"] === "1") {
        header("Connection: Close");
        die("success");
    }
    //if upload has finished then perform post upload actions
    if (isset($_POST["upload_finished"]) && $_POST["upload_finished"] === "1") {
        die("success");
    }
    $params_str = get_option('wfu_params_' . $arr['unique_id']);
    $params = wfu_decode_array_from_string($params_str);
    $params['subdir_selection_index'] = $_POST['subdir_sel_index'];
    $_SESSION['wfu_check_refresh_' . $params["uploadid"]] = 'do not process';
    $wfu_process_file_array = wfu_process_files($params, 'ajax');
    // extract safe_output from wfu_process_file_array and pass it as separate part of the response text
    $safe_output = $wfu_process_file_array["general"]['safe_output'];
    unset($wfu_process_file_array["general"]['safe_output']);
    die("wfu_fileupload_success:" . $safe_output . ":" . wfu_encode_array_to_string($wfu_process_file_array));
}