function wfu_upload_plugin_clean($label)
{
    $clean = sanitize_file_name($label);
    if (WFU_VAR("WFU_SANITIZE_FILENAME_MODE") != "loose") {
        $search = array('@[^a-zA-Z0-9._]@');
        $replace = array('-');
        $clean = preg_replace($search, $replace, remove_accents($clean));
    }
    return $clean;
}
function wfu_set_javascript_constants()
{
    $consts = array("nofilemessage" => WFU_ERROR_UPLOAD_NOFILESELECTED, "enable_popups" => WFU_ERROR_ENABLE_POPUPS, "remoteserver_noresult" => WFU_ERROR_REMOTESERVER_NORESULT, "message_header" => WFU_ERRORMESSAGE, "message_failed" => WFU_ERROR_UPLOAD_FAILED_WHILE, "message_cancelled" => WFU_ERROR_UPLOAD_CANCELLED, "message_unknown" => WFU_ERROR_UNKNOWN, "adminmessage_unknown" => WFU_FAILMESSAGE_DETAILS, "message_timelimit" => WFU_ERROR_FILE_PHP_TIME, "message_admin_timelimit" => WFU_ERROR_ADMIN_FILE_PHP_TIME, "cancel_upload_prompt" => WFU_CANCEL_UPLOAD_PROMPT, "file_cancelled" => WFU_ERROR_FILE_CANCELLED, "jsonparse_filemessage" => WFU_ERROR_JSONPARSE_FILEMESSAGE, "jsonparse_message" => WFU_ERROR_JSONPARSE_MESSAGE, "jsonparse_adminmessage" => WFU_ERROR_JSONPARSE_ADMINMESSAGE, "jsonparse_headermessage" => WFU_ERROR_JSONPARSE_HEADERMESSAGE, "jsonparse_headeradminmessage" => WFU_ERROR_JSONPARSE_HEADERADMINMESSAGE, "same_pluginid" => WFU_ERROR_SAME_PLUGINID, "default_colors" => WFU_VAR("WFU_DEFAULTMESSAGECOLORS"), "fail_colors" => WFU_VAR("WFU_FAILMESSAGECOLORS"), "max_time_limit" => WFU_MAX_TIME_LIMIT, "response_url" => WFU_RESPONSE_URL, "ajax_url" => wfu_ajaxurl(), "wfu_pageexit_prompt" => WFU_PAGEEXIT_PROMPT, "wfu_subdir_typedir" => WFU_SUBDIR_TYPEDIR);
    $consts_txt = "";
    foreach ($consts as $key => $val) {
        $consts_txt .= ($consts_txt == "" ? "" : ";") . wfu_plugin_encode_string($key) . ":" . wfu_plugin_encode_string($val);
    }
    return $consts_txt;
}
function wfu_view_log($page = 1, $only_table_rows = false)
{
    global $wpdb;
    $siteurl = site_url();
    $table_name1 = $wpdb->prefix . "wfu_log";
    $table_name2 = $wpdb->prefix . "wfu_userdata";
    $plugin_options = wfu_decode_plugin_options(get_option("wordpress_file_upload_options"));
    if (!current_user_can('manage_options')) {
        return;
    }
    //get log data from database
    $files_total = $wpdb->get_var('SELECT COUNT(idlog) FROM ' . $table_name1);
    $filerecs = $wpdb->get_results('SELECT * FROM ' . $table_name1 . ' ORDER BY date_from DESC' . (WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") > 0 ? ' LIMIT ' . WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") . ' OFFSET ' . ($page - 1) * (int) WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") : ''));
    $echo_str = "";
    if (!$only_table_rows) {
        $echo_str .= "\n" . '<div class="wrap">';
        $echo_str .= "\n\t" . '<h2>Wordpress File Upload Control Panel</h2>';
        $echo_str .= "\n\t" . '<div style="margin-top:20px;">';
        $echo_str .= wfu_generate_dashboard_menu("\n\t\t", "View Log");
        $echo_str .= "\n\t" . '<div style="position:relative;">';
        $echo_str .= wfu_add_loading_overlay("\n\t\t", "historylog");
        $echo_str .= "\n\t\t" . '<div class="wfu_historylog_header" style="width: 100%;">';
        if (WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") > 0) {
            $pages = ceil($files_total / WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS"));
            $echo_str .= wfu_add_pagination_header("\n\t\t\t", "historylog", 1, $pages);
        }
        $echo_str .= "\n\t\t" . '</div>';
        $echo_str .= "\n\t\t" . '<table id="wfu_historylog_table" class="wp-list-table widefat fixed striped">';
        $echo_str .= "\n\t\t\t" . '<thead>';
        $echo_str .= "\n\t\t\t\t" . '<tr>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="5%" style="text-align:center;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>#</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="15%" style="text-align:left;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>Date</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="10%" style="text-align:center;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>Action</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="30%" style="text-align:left;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>File</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="15%" style="text-align:center;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>User</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="25%" style="text-align:left;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<label>Remarks</label>';
        $echo_str .= "\n\t\t\t\t\t" . '</th>';
        $echo_str .= "\n\t\t\t\t" . '</tr>';
        $echo_str .= "\n\t\t\t" . '</thead>';
        $echo_str .= "\n\t\t\t" . '<tbody>';
    }
    $userdatarecs = $wpdb->get_results('SELECT * FROM ' . $table_name2);
    $deletedfiles = array();
    $filecodes = array();
    $time0 = strtotime("0000-00-00 00:00:00");
    $i = ($page - 1) * (int) WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS");
    foreach ($filerecs as $filerec) {
        $remarks = '';
        $filepath = ABSPATH;
        if (substr($filepath, -1) == '/') {
            $filepath = substr($filepath, 0, -1);
        }
        $filepath .= $filerec->filepath;
        $enc_file = wfu_plugin_encode_string($filepath . '[[name]]');
        if ($filerec->action == 'delete') {
            array_push($deletedfiles, $filerec->linkedto);
        } elseif ($filerec->action == 'rename') {
            $prevfilepath = '';
            foreach ($filerecs as $key => $prevfilerec) {
                if ($prevfilerec->idlog == $filerec->linkedto) {
                    $prevfilepath = $prevfilerec->filepath;
                    break;
                }
            }
            if ($prevfilepath != '') {
                $remarks = "\n\t\t\t\t\t\t" . '<label>Previous filepath: ' . $prevfilepath . '</label>';
            }
        } elseif ($filerec->action == 'upload' || $filerec->action == 'modify') {
            foreach ($userdatarecs as $userdata) {
                if ($userdata->uploadid == $filerec->uploadid) {
                    $userdata_datefrom = strtotime($userdata->date_from);
                    $userdata_dateto = strtotime($userdata->date_to);
                    $filerec_datefrom = strtotime($filerec->date_from);
                    if ($filerec_datefrom >= $userdata_datefrom && ($userdata_dateto == $time0 || $filerec_datefrom < $userdata_dateto)) {
                        $remarks .= "\n\t\t\t\t\t\t\t" . '<option>' . $userdata->property . ': ' . $userdata->propvalue . '</option>';
                    }
                }
            }
            if ($remarks != '') {
                $remarks = "\n\t\t\t\t\t\t" . '<select multiple="multiple" style="width:100%; height:40px; background:none; font-size:small;">' . $remarks;
                $remarks .= "\n\t\t\t\t\t\t" . '</select>';
            }
        } elseif ($filerec->action == 'other') {
            $info = $filerec->filepath;
            $filerec->filepath = '';
            $remarks = "\n\t\t\t\t\t\t" . '<textarea style="width:100%; resize:vertical; background:none;" readonly="readonly">' . $info . '</textarea>';
        }
        $i++;
        $otheraction = $filerec->action == 'other';
        $echo_str .= "\n\t\t\t\t" . '<tr>';
        $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:center;">' . $i . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:left;">' . $filerec->date_from . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:center;">' . $filerec->action . '</td>';
        if (!$otheraction) {
            $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:left;">';
            if (in_array($filerec->linkedto, $deletedfiles) || in_array($filerec->idlog, $deletedfiles)) {
                $echo_str .= "\n\t\t\t\t\t\t" . '<span>' . $filerec->filepath . '</span>';
            } else {
                $lid = 0;
                if ($filerec->action == 'upload' || $filerec->action == 'include') {
                    $lid = $filerec->idlog;
                } elseif ($filerec->linkedto > 0) {
                    $lid = $filerec->linkedto;
                }
                if ($lid > 0) {
                    if (!isset($filecodes[$lid])) {
                        $filecodes[$lid] = wfu_safe_store_filepath($filerec->filepath);
                    }
                    $echo_str .= "\n\t\t\t\t\t\t" . '<a class="row-title" href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_details&file=' . $filecodes[$lid] . '" title="View and edit file details" style="font-weight:normal;">' . $filerec->filepath . '</a>';
                } else {
                    $echo_str .= "\n\t\t\t\t\t\t" . '<span>' . $filerec->filepath . '</span>';
                }
            }
            $echo_str .= "\n\t\t\t\t\t" . '</td>';
            $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:center;">' . wfu_get_username_by_id($filerec->userid) . '</td>';
        }
        $echo_str .= "\n\t\t\t\t\t" . '<td style="padding: 5px 5px 5px 10px; text-align:left;"' . ($otheraction ? ' colspan="3"' : '') . '>';
        $echo_str .= $remarks;
        $echo_str .= "\n\t\t\t\t\t" . '</td>';
        $echo_str .= "\n\t\t\t\t" . '</tr>';
    }
    if (!$only_table_rows) {
        $echo_str .= "\n\t\t\t" . '</tbody>';
        $echo_str .= "\n\t\t" . '</table>';
        $echo_str .= "\n\t" . '</div>';
        $echo_str .= "\n" . '</div>';
    }
    return $echo_str;
}
function wfu_post_request($url, $params, $verifypeer = false, $internal_request = false)
{
    $plugin_options = wfu_decode_plugin_options(get_option("wordpress_file_upload_options"));
    if (isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'curl') {
        // POST request using CURL
        $ch = curl_init($url);
        $options = array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($params), CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'), CURLINFO_HEADER_OUT => false, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => $verifypeer);
        //for internal requests to /wp-admin area that is password protected
        //authorization is required
        if ($internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true") {
            $options[CURLOPT_HTTPAUTH] = CURLAUTH_ANY;
            $options[CURLOPT_USERPWD] = WFU_VAR("WFU_DASHBOARD_USERNAME") . ":" . WFU_VAR("WFU_DASHBOARD_PASSWORD");
        }
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    } elseif (isset($plugin_options['postmethod']) && $plugin_options['postmethod'] == 'socket') {
        // POST request using sockets
        $scheme = "";
        $port = 80;
        $timeout = null;
        $errno = 0;
        $errstr = '';
        $url = parse_url($url);
        $host = $url['host'];
        $path = $url['path'];
        if ($url['scheme'] == 'https') {
            $scheme = "ssl://";
            $port = 443;
            $timeout = 30;
        } elseif ($url['scheme'] != 'http') {
            return '';
        }
        $handle = fsockopen($scheme . $host, $port, $errno, $errstr, is_null($timeout) ? ini_get("default_socket_timeout") : $timeout);
        if ($errno !== 0 || $errstr !== '') {
            $handle = false;
        }
        if ($handle !== false) {
            $content = http_build_query($params);
            $request = "POST " . $path . " HTTP/1.1\r\n";
            $request .= "Host: " . $host . "\r\n";
            $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
            //for internal requests to /wp-admin area that is password protected
            //authorization is required
            if ($internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true") {
                $request .= "Authorization: Basic " . base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME") . ":" . WFU_VAR("WFU_DASHBOARD_PASSWORD")) . "\r\n";
            }
            $request .= "Content-length: " . strlen($content) . "\r\n";
            $request .= "Connection: close\r\n\r\n";
            $request .= $content . "\r\n\r\n";
            fwrite($handle, $request, strlen($request));
            $response = '';
            while (!feof($handle)) {
                $response .= fgets($handle, 4096);
            }
            fclose($handle);
            if (0 === strpos($response, 'HTTP/1.1 200 OK')) {
                $parts = preg_split("#\n\\s*\n#Uis", $response);
                return $parts[1];
            }
            return '';
        }
        return '';
    } else {
        // POST request using file_get_contents
        if ($internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true") {
            $url = preg_replace("/^(http|https):\\/\\//", "\$1://" . WFU_VAR("WFU_DASHBOARD_USERNAME") . ":" . WFU_VAR("WFU_DASHBOARD_PASSWORD") . "@", $url);
        }
        $peer_key = version_compare(PHP_VERSION, '5.6.0', '<') ? 'CN_name' : 'peer_name';
        $http_array = array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query($params));
        //for internal requests to /wp-admin area that is password protected
        //authorization is required
        if ($internal_request && WFU_VAR("WFU_DASHBOARD_PROTECTED") == "true") {
            $http_array['header'] .= "Authorization: Basic " . base64_encode(WFU_VAR("WFU_DASHBOARD_USERNAME") . ":" . WFU_VAR("WFU_DASHBOARD_PASSWORD")) . "\r\n";
        }
        if ($verifypeer) {
            $http_array['verify_peer'] = true;
            $http_array[$peer_key] = 'www.google.com';
        }
        $context_params = array('http' => $http_array);
        $context = stream_context_create($context_params);
        return file_get_contents($url, false, $context);
    }
}
Exemple #5
0
function wfu_attribute_definitions()
{
    $defs = array(array("name" => "Widget ID", "attribute" => "widgetid", "type" => "hidden", "listitems" => null, "value" => "", "mode" => "free", "category" => "", "subcategory" => "Basic ", "parent" => "", "dependencies" => null, "variables" => null, "help" => ""), array("name" => "Plugin ID", "attribute" => "uploadid", "type" => "integer", "listitems" => null, "value" => WFU_VAR("WFU_UPLOADID"), "mode" => "free", "category" => "general", "subcategory" => "Basic Functionalities", "parent" => "", "dependencies" => null, "variables" => null, "help" => "The unique id of each shortcode. When you have many shortcodes of this plugin in the same page, then you must use different id for each one."), array("name" => "Single Button Operation", "attribute" => "singlebutton", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_SINGLEBUTTON"), "mode" => "free", "category" => "general", "subcategory" => "Basic Functionalities", "parent" => "", "dependencies" => array("!uploadbutton"), "variables" => null, "help" => "When it is activated, no Upload button will be shown, but upload will start automatically as soon as files are selected."), array("name" => "Upload Path", "attribute" => "uploadpath", "type" => "ltext", "listitems" => null, "value" => WFU_VAR("WFU_UPLOADPATH"), "mode" => "free", "category" => "general", "subcategory" => "Basic Functionalities", "parent" => "", "dependencies" => null, "variables" => array("%userid%", "%username%", "%blogid%", "%pageid%", "%pagetitle%", "%userdataXXX%"), "help" => "This is the folder where the files will be uploaded. The path is relative to wp-contents folder of your Wordpress website. The path can be dynamic by including variables such as %username% or %blogid%. Please check Documentation on how to use variables inside uploadpath."), array("name" => "Plugin Fit Mode", "attribute" => "fitmode", "type" => "radio", "listitems" => array("fixed", "responsive"), "value" => WFU_VAR("WFU_FITMODE"), "mode" => "free", "category" => "general", "subcategory" => "Basic Functionalities", "parent" => "", "dependencies" => null, "variables" => null, "help" => "This defines how the plugin's elements will fit inside the page/post. If it is set to fixed, then the plugin's element positions will remain fixed no matter the width of the container page/post. If it is set to responsive, then the plugin's elements will wrap to fit the width of the container page/post."), array("name" => "Upload Roles", "attribute" => "uploadrole", "type" => "rolelist", "listitems" => array("default_administrator"), "value" => WFU_VAR("WFU_UPLOADROLE"), "mode" => "free", "category" => "general", "subcategory" => "Filters", "parent" => "", "dependencies" => null, "variables" => null, "help" => "Defines the categories (roles) of users allowed to upload files. Multiple selections can be made. If 'Select All' is checked, then all logged users can upload files. If 'Include Guests' is checked, then guests (not logged users) can also upload files. Default value is 'all,guests'."), array("name" => "Allowed File Extensions", "attribute" => "uploadpatterns", "type" => "text", "listitems" => null, "value" => WFU_VAR("WFU_UPLOADPATTERNS"), "mode" => "free", "category" => "general", "subcategory" => "Filters", "parent" => "", "dependencies" => null, "variables" => null, "help" => "Defines the allowed file extensions. Multiple extentions can be defined, separated with comma (,)."), array("name" => "Allowed File Size", "attribute" => "maxsize", "type" => "float", "listitems" => null, "value" => WFU_VAR("WFU_MAXSIZE"), "mode" => "free", "category" => "general", "subcategory" => "Filters", "parent" => "", "dependencies" => null, "variables" => null, "help" => "Defines the allowed file size in MBytes. Files larger than maxsize will not be uploaded. Floating point numbers can be used (e.g. '2.5')."), array("name" => "Create Upload Path", "attribute" => "createpath", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_CREATEPATH"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If activated then the plugin will attempt to create the upload path, if it does not exist."), array("name" => "Do Not Change Filename", "attribute" => "forcefilename", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_FORCEFILENAME"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => null, "variables" => null, "help" => "The plugin by default will modify the filename if it contains invalid or non-english characters. By enabling this attribute the plugin will not change the filename."), array("name" => "Folder Access Method", "attribute" => "accessmethod", "type" => "radio", "listitems" => array("normal", "*ftp"), "value" => WFU_VAR("WFU_ACCESSMETHOD"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => array("ftpinfo", "userftpdomain", "ftppassivemode", "ftpfilepermissions"), "variables" => null, "help" => "Some times files cannot be uploaded to the upload folder because of read/write permissions. A workaround is to use ftp to transfer the files, however ftp credentials must be declared, so use carefully and only if necessary."), array("name" => "FTP Access Credentials", "attribute" => "ftpinfo", "type" => "ltext", "listitems" => null, "value" => WFU_VAR("WFU_FTPINFO"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "accessmethod", "dependencies" => null, "variables" => null, "help" => "If FTP access method is selected, then FTP credentials must be declared here, in the form username:password@ftpdomain."), array("name" => "Use FTP Domain", "attribute" => "useftpdomain", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_USEFTPDOMAIN"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "accessmethod", "dependencies" => null, "variables" => null, "help" => "If FTP access method is selected, then sometimes the FTP domain is different than the domain of your Wordpress installation. In this case, enable this attribute if upload of files is not successful."), array("name" => "FTP Passive Mode", "attribute" => "ftppassivemode", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_FTPPASSIVEMODE"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "accessmethod", "dependencies" => null, "variables" => null, "help" => "If files fail to upload to the ftp domain then switching to passive FTP mode may solve the problem."), array("name" => "Permissions of Uploaded File", "attribute" => "ftpfilepermissions", "type" => "text", "listitems" => null, "value" => WFU_VAR("WFU_FTPFILEPERMISSIONS"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "accessmethod", "dependencies" => null, "variables" => null, "help" => "Force the uploaded files to have specific permissions. This is a 4-digit octal number, e.g. 0777. If left empty, then the ftp server will define the permissions."), array("name" => "Show Upload Folder Path", "attribute" => "showtargetfolder", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_SHOWTARGETFOLDER"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => array("targetfolderlabel"), "variables" => null, "help" => "It defines if a label with the upload directory will be shown."), array("name" => "Select Subfolder", "attribute" => "askforsubfolders", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_ASKFORSUBFOLDERS"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => array("subfoldertree", "subfolderlabel"), "variables" => null, "help" => "If enabled then user can select the upload folder from a drop down list. The list is defined in subfoldertree attribute. The folder paths are relative to the path defined in uploadpath."), array("name" => "List of Subfolders", "attribute" => "subfoldertree", "type" => "folderlist", "listitems" => null, "value" => WFU_VAR("WFU_SUBFOLDERTREE"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "askforsubfolders", "dependencies" => null, "variables" => null, "help" => "The list of folders a user can select. Please see documentation on how to create the list of folders. If 'Auto-populate list' is selected, then the list will be filled automatically with the first-level subfolders inside the directory defined by uploadpath. If 'List is editable' is selected, then the user will have the capability to type the subfolder and filter the subfolder list and/or define a new subfolder."), array("name" => "File Duplicates Policy", "attribute" => "dublicatespolicy", "type" => "radio", "listitems" => array("overwrite", "reject", "*maintain both"), "value" => WFU_VAR("WFU_DUBLICATESPOLICY"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "", "dependencies" => array("uniquepattern"), "variables" => null, "help" => "It determines what happens when an uploaded file has the same name with an existing file. The uploaded file can overwrite the existing one, be rejected or both can be kept by renaming the uploaded file according to a rule defined in uniquepattern attribute."), array("name" => "File Rename Rule", "attribute" => "uniquepattern", "type" => "radio", "listitems" => array("index", "datetimestamp"), "value" => WFU_VAR("WFU_UNIQUEPATTERN"), "mode" => "free", "category" => "general", "subcategory" => "Upload Path and Files", "parent" => "dublicatespolicy", "dependencies" => null, "variables" => null, "help" => "If dublicatespolicy is set to 'maintain both', then this rule defines how the uploaded file will be renamed, in order not to match an existing file. An incremental index number or a datetime stamp can be included in the uploaded file name to make it unique."), array("name" => "Redirect after Upload", "attribute" => "redirect", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_REDIRECT"), "mode" => "free", "category" => "general", "subcategory" => "Redirection", "parent" => "", "dependencies" => array("redirectlink"), "variables" => null, "help" => "If enabled, the user will be redirected to a url defined in redirectlink attribute upon successful upload of all the files."), array("name" => "Redirection URL", "attribute" => "redirectlink", "type" => "ltext", "listitems" => null, "value" => WFU_VAR("WFU_REDIRECTLINK"), "mode" => "free", "category" => "general", "subcategory" => "Redirection", "parent" => "redirect", "dependencies" => null, "variables" => array("%filename%", "%username%"), "help" => "This is the redirect URL. The URL can be dynamic by using variables. Please see Documentation on how to use variables inside attributes."), array("name" => "Show Detailed Admin Messages", "attribute" => "adminmessages", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_ADMINMESSAGES"), "mode" => "free", "category" => "general", "subcategory" => "Other Administrator Options", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then more detailed messages about upload operations will be shown to administrators for debugging or error detection."), array("name" => "Disable AJAX", "attribute" => "forceclassic", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_FORCECLASSIC"), "mode" => "free", "category" => "general", "subcategory" => "Other Administrator Options", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If AJAX is disabled, then upload of files will be performed using HTML forms, meaning that page will refresh to complete the upload. Use it in case that AJAX is causing problems with your page (although the plugin has an auto-detection feature for checking if user's browser supports AJAX or not)."), array("name" => "Test Mode", "attribute" => "testmode", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_TESTMODE"), "mode" => "free", "category" => "general", "subcategory" => "Other Administrator Options", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then the plugin will be shown in test mode, meaning that all selected features will be shown but no upload will be possible. Use it to review how the plugin looks like and style it according to your needs."), array("name" => "Debug Mode", "attribute" => "debugmode", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_DEBUGMODE"), "mode" => "free", "category" => "general", "subcategory" => "Other Administrator Options", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then the plugin will show to administrators any internal PHP warnings and errors generated during the upload process inside the message box."), array("name" => "Plugin Component Positions", "attribute" => "placements", "type" => "placements", "listitems" => null, "value" => WFU_VAR("WFU_PLACEMENTS"), "mode" => "free", "category" => "placements", "subcategory" => "Plugin Component Positions", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the positions of the selected plugin components. Drag the components from the right pane and drop them to the left one to define your own component positions."), array("name" => "Plugin Title", "attribute" => "uploadtitle", "type" => "text", "listitems" => null, "value" => WFU_UPLOADTITLE, "mode" => "free", "category" => "labels", "subcategory" => "Title", "parent" => "", "dependencies" => null, "variables" => null, "help" => "A text representing the title of the plugin."), array("name" => "Select Button Caption", "attribute" => "selectbutton", "type" => "text", "listitems" => null, "value" => WFU_SELECTBUTTON, "mode" => "free", "category" => "labels", "subcategory" => "Buttons", "parent" => "", "dependencies" => null, "variables" => null, "help" => "The caption of the button that selects the files for upload."), array("name" => "Upload Button Caption", "attribute" => "uploadbutton", "type" => "text", "listitems" => null, "value" => WFU_UPLOADBUTTON, "mode" => "free", "category" => "labels", "subcategory" => "Buttons", "parent" => "", "dependencies" => null, "variables" => null, "help" => "The caption of the button that starts the upload."), array("name" => "Upload Folder Label", "attribute" => "targetfolderlabel", "type" => "text", "listitems" => null, "value" => WFU_VAR("WFU_TARGETFOLDERLABEL"), "mode" => "free", "category" => "labels", "subcategory" => "Upload Folder", "parent" => "", "dependencies" => null, "variables" => null, "help" => "This is the label before the upload folder path, if the path is selected to be shown using the showtargetfolder attribute."), array("name" => "Select Subfolder Label", "attribute" => "subfolderlabel", "type" => "text", "listitems" => null, "value" => WFU_VAR("WFU_SUBFOLDERLABEL"), "mode" => "free", "category" => "labels", "subcategory" => "Upload Folder", "parent" => "", "dependencies" => null, "variables" => null, "help" => "This is the label of the subfolder dropdown list. It is active when askforsubfolders attribute is on."), array("name" => "Success Upload Message", "attribute" => "successmessage", "type" => "ltext", "listitems" => null, "value" => WFU_SUCCESSMESSAGE, "mode" => "free", "category" => "labels", "subcategory" => "Upload Messages", "parent" => "", "dependencies" => null, "variables" => array("%filename%", "%filepath%"), "help" => "This is the message that will be shown for every file that has been uploaded successfully."), array("name" => "Warning Upload Message", "attribute" => "warningmessage", "type" => "ltext", "listitems" => null, "value" => WFU_WARNINGMESSAGE, "mode" => "free", "category" => "labels", "subcategory" => "Upload Messages", "parent" => "", "dependencies" => null, "variables" => array("%filename%", "%filepath%"), "help" => "This is the message that will be shown for every file that has been uploaded with warnings."), array("name" => "Error Upload Message", "attribute" => "errormessage", "type" => "ltext", "listitems" => null, "value" => WFU_ERRORMESSAGE, "mode" => "free", "category" => "labels", "subcategory" => "Upload Messages", "parent" => "", "dependencies" => null, "variables" => array("%filename%", "%filepath%"), "help" => "This is the message that will be shown for every file that has failed to upload."), array("name" => "Wait Upload Message", "attribute" => "waitmessage", "type" => "ltext", "listitems" => null, "value" => WFU_WAITMESSAGE, "mode" => "free", "category" => "labels", "subcategory" => "Upload Messages", "parent" => "", "dependencies" => null, "variables" => array("%filename%", "%filepath%"), "help" => "This is the message that will be shown while file is uploading."), array("name" => "Notify by Email", "attribute" => "notify", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_NOTIFY"), "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "", "dependencies" => array("notifyrecipients", "notifysubject", "notifymessage", "notifyheaders", "attachfile"), "variables" => null, "help" => "If activated then email will be sent to inform about successful file uploads."), array("name" => "Email Recipients", "attribute" => "notifyrecipients", "type" => "mtext", "listitems" => null, "value" => WFU_VAR("WFU_NOTIFYRECIPIENTS"), "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "notify", "dependencies" => null, "variables" => array("%useremail%", "%userdataXXX%", "%n%", "%dq%"), "help" => "Defines the recipients of the email notification. Can be dynamic by using variables. Please check Documentation on how to use variables in atributes."), array("name" => "Email Headers", "attribute" => "notifyheaders", "type" => "mtext", "listitems" => null, "value" => WFU_VAR("WFU_NOTIFYHEADERS"), "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "notify", "dependencies" => null, "variables" => array("%n%", "%dq%"), "help" => "Defines additional email headers, in case you want to sent an HTML message, or use Bcc list, or use a different From address and name or other more advanced email options."), array("name" => "Email Subject", "attribute" => "notifysubject", "type" => "ltext", "listitems" => null, "value" => WFU_NOTIFYSUBJECT, "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "notify", "dependencies" => null, "variables" => array("%username%", "%useremail%", "%filename%", "%filepath%", "%blogid%", "%pageid%", "%pagetitle%", "%userdataXXX%", "%dq%"), "help" => "Defines the email subject. Can be dynamic by using variables. Please check Documentation on how to use variables in atributes."), array("name" => "Email Body", "attribute" => "notifymessage", "type" => "mtext", "listitems" => null, "value" => WFU_NOTIFYMESSAGE, "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "notify", "dependencies" => null, "variables" => array("%username%", "%useremail%", "%filename%", "%filepath%", "%blogid%", "%pageid%", "%pagetitle%", "%userdataXXX%", "%n%", "%dq%"), "help" => "Defines the email body. Can be dynamic by using variables. Please check Documentation on how to use variables in atributes."), array("name" => "Attach Uploaded Files", "attribute" => "attachfile", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_ATTACHFILE"), "mode" => "free", "category" => "notifications", "subcategory" => "Email Notifications", "parent" => "notify", "dependencies" => null, "variables" => null, "help" => "If activated, then uploaded files will be included in the notification email as attachments. Please use carefully."), array("name" => "Success Upload Message Color", "attribute" => "successmessagecolor", "type" => "color", "listitems" => null, "value" => WFU_SUCCESSMESSAGECOLOR, "mode" => "free", "category" => "colors", "subcategory" => "Upload Message Colors", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the color of the success message. This attribute has been replaced by successmessagecolors, however it is kept here for backward compatibility."), array("name" => "Success Message Colors", "attribute" => "successmessagecolors", "type" => "color-triplet", "listitems" => null, "value" => WFU_VAR("WFU_SUCCESSMESSAGECOLORS"), "mode" => "free", "category" => "colors", "subcategory" => "Upload Message Colors", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the text, background and border color of the success message."), array("name" => "Warning Message Colors", "attribute" => "warningmessagecolors", "type" => "color-triplet", "listitems" => null, "value" => WFU_VAR("WFU_WARNINGMESSAGECOLORS"), "mode" => "free", "category" => "colors", "subcategory" => "Upload Message Colors", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the text, background and border color of the warning message."), array("name" => "Fail Message Colors", "attribute" => "failmessagecolors", "type" => "color-triplet", "listitems" => null, "value" => WFU_VAR("WFU_FAILMESSAGECOLORS"), "mode" => "free", "category" => "colors", "subcategory" => "Upload Message Colors", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the text, background and border color of the fail (error) message."), array("name" => "Wait Message Colors", "attribute" => "waitmessagecolors", "type" => "color-triplet", "listitems" => null, "value" => WFU_VAR("WFU_WAITMESSAGECOLORS"), "mode" => "free", "category" => "colors", "subcategory" => "Upload Message Colors", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the text, background and border color of the wait message."), array("name" => "Plugin Component Widths", "attribute" => "widths", "type" => "dimensions", "listitems" => null, "value" => WFU_VAR("WFU_WIDTHS"), "mode" => "free", "category" => "dimensions", "subcategory" => "Plugin Component Widths", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the widths of the selected plugin components."), array("name" => "Plugin Component Heights", "attribute" => "heights", "type" => "dimensions", "listitems" => null, "value" => WFU_VAR("WFU_HEIGHTS"), "mode" => "free", "category" => "dimensions", "subcategory" => "Plugin Component Heights", "parent" => "", "dependencies" => null, "variables" => null, "help" => "It defines the heights of the selected plugin components."), array("name" => "Include Additional Data Fields", "attribute" => "userdata", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_USERDATA"), "mode" => "free", "category" => "userdata", "subcategory" => "Additional Data Fields", "parent" => "", "dependencies" => array("userdatalabel"), "variables" => null, "help" => "If enabled, then user can send additional information together with uploaded files (e.g. name, email etc), defined in userdatalabel attribute."), array("name" => "Additional Data Fields", "attribute" => "userdatalabel", "type" => "formfields", "listitems" => wfu_formfield_definitions(), "value" => WFU_USERDATALABEL, "mode" => "free", "category" => "userdata", "subcategory" => "Additional Data Fields", "parent" => "userdata", "dependencies" => null, "variables" => null, "help" => "It defines the labels of the additional data fields and whether they are required or not."), array("name" => "WP Filebase Plugin Connection", "attribute" => "filebaselink", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_FILEBASELINK"), "mode" => "free", "category" => "interoperability", "subcategory" => "Connection With Other Plugins", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then the WP Filebase Plugin will be informed about new file uploads."), array("name" => "Add Uploaded Files To Media", "attribute" => "medialink", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_MEDIALINK"), "mode" => "free", "category" => "interoperability", "subcategory" => "Connection With Other Wordpress Features", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then the uploaded files will be added to the Media library of your Wordpress website. Please note that the upload path must be inside the wp-content/uploads directory (which is the default upload path)."), array("name" => "Attach Uploaded Files To Post", "attribute" => "postlink", "type" => "onoff", "listitems" => null, "value" => WFU_VAR("WFU_POSTLINK"), "mode" => "free", "category" => "interoperability", "subcategory" => "Connection With Other Wordpress Features", "parent" => "", "dependencies" => null, "variables" => null, "help" => "If enabled then the uploaded files will be added to the current post as attachments. Please note that the upload path must be inside the wp-content/uploads directory (which is the default upload path)."), null);
    wfu_array_remove_nulls($defs);
    return $defs;
}
function wfu_prepare_message_block_skeleton($sid, $styles, $test)
{
    /* Prepare header styles for all upload states */
    $header_styles["State0"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE0"));
    $header_styles["State0"]['message'] = WFU_UPLOAD_STATE0;
    $header_styles["State1"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE1"));
    $header_styles["State1"]['message'] = WFU_UPLOAD_STATE1;
    $header_styles["State2"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE2"));
    $header_styles["State2"]['message'] = WFU_UPLOAD_STATE2;
    $header_styles["State3"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE3"));
    $header_styles["State3"]['message'] = WFU_UPLOAD_STATE3;
    $header_styles["State4"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE4"));
    $header_styles["State4"]['message'] = WFU_UPLOAD_STATE4;
    $header_styles["State5"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE5"));
    $header_styles["State5"]['message'] = WFU_UPLOAD_STATE5;
    $header_styles["State5_singlefile"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE5"));
    $header_styles["State5_singlefile"]['message'] = WFU_UPLOAD_STATE5_SINGLEFILE;
    $header_styles["State6"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE6"));
    $header_styles["State6"]['message'] = WFU_UPLOAD_STATE6;
    $header_styles["State7"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE7"));
    $header_styles["State7"]['message'] = WFU_UPLOAD_STATE7;
    $header_styles["State7_singlefile"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE7"));
    $header_styles["State7_singlefile"]['message'] = WFU_UPLOAD_STATE7_SINGLEFILE;
    $header_styles["State8"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE8"));
    $header_styles["State8"]['message'] = WFU_UPLOAD_STATE8;
    $header_styles["State9"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE9"));
    $header_styles["State9"]['message'] = WFU_UPLOAD_STATE9;
    $header_styles["State10"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE10"));
    $header_styles["State10"]['message'] = WFU_UPLOAD_STATE10;
    $header_styles["State11"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE11"));
    $header_styles["State11"]['message'] = WFU_UPLOAD_STATE11;
    $header_styles["State12"] = wfu_prepare_message_colors(WFU_VAR("WFU_HEADERMESSAGECOLORS_STATE12"));
    $header_styles["State12"]['message'] = WFU_UPLOAD_STATE12;
    $ExposedStateIndex = array("0", "1", "2", "3", "4", "5", "5_singlefile", "6", "7", "7_singlefile", "8", "11", "12");
    /* set general variables */
    $messageblock_main = 'wfu_messageblock_' . $sid;
    $messageblock_header = 'wfu_messageblock_header_' . $sid;
    $messageblock_arrow = 'wfu_messageblock_arrow_' . $sid;
    $messageblock_subheader = 'wfu_messageblock_subheader_' . $sid;
    $dlp = "\n\t\t\t\t\t\t\t";
    /* Prepare header HTML template
    	   Variables:
    		[header_safe]: suffix having the value "_safe" in case of State10 upload state, or empty otherwise,
    		[header_color]: text color of header,
    		[header_bgcolor]: background color of header,
    		[header_borcolor]: border color of header,
    		[header_message]: text shown in header */
    $i = 1;
    $messageblock_headers[$i++] = "\t\t\t" . '<div id="' . $messageblock_header . '[header_safe]" class="file_messageblock_header" style="color:[header_color]; background-color:[header_bgcolor]; border:1px solid [header_borcolor];">';
    $messageblock_headers[$i++] = "\t\t\t\t" . '<label id="' . $messageblock_header . '_label[header_safe]" class="file_messageblock_header_label">[header_message]</label>';
    $messageblock_headers[$i++] = "\t\t\t" . '</div>';
    /* Prepare the file block HTML template
    	   Variables:
    		[file_id]: replaced by the id of the file (1, 2, ...),
    		[filenumber_display]: display:none if single file upload, otherwise empty,
    		[fileheader_color], [fileheader_bgcolor], [fileheader_borcolor], [fileheader_message]: replaced by the returned values,
    		[filesubheadermessage_display]: display:none if there is no message, otherwise empty,
    		[filesubheader_message]: replaced by the returned value,
    		[filesubheaderadminmessage_display]: display:none if there is no admin message, otherwise empty,
    		[filesubheader_adminmessage]: replaced by the returned value */
    /* Prepare the files header block HTML template */
    $i = 1;
    $file_count = $test ? 2 : 1;
    for ($ii = 1; $ii <= $file_count; $ii++) {
        if ($test) {
            $file_props = wfu_prepare_message_colors(WFU_VAR("WFU_TESTMESSAGECOLORS"));
            $file_id = $ii;
            $filenumber_display = "";
            $fileheader_color = $file_props['color'];
            $fileheader_bgcolor = $file_props['bgcolor'];
            $fileheader_borcolor = $file_props['borcolor'];
            $fileheader_message = constant('WFU_TESTMESSAGE_FILE' . $ii . '_HEADER');
            $filesubheadermessage_display = "";
            $filesubheader_message = constant('WFU_TESTMESSAGE_FILE' . $ii . '_MESSAGE');
            $filesubheaderadminmessage_display = "";
            $filesubheader_adminmessage = constant('WFU_TESTMESSAGE_FILE' . $ii . '_ADMINMESSAGE');
        } else {
            $file_id = '[file_id]';
            $filenumber_display = '[filenumber_display]';
            $fileheader_color = '[fileheader_color]';
            $fileheader_bgcolor = '[fileheader_bgcolor]';
            $fileheader_borcolor = '[fileheader_borcolor]';
            $fileheader_message = '[fileheader_message]';
            $filesubheadermessage_display = '[filesubheadermessage_display]';
            $filesubheader_message = '[filesubheader_message]';
            $filesubheaderadminmessage_display = '[filesubheaderadminmessage_display]';
            $filesubheader_adminmessage = '[filesubheader_adminmessage]';
        }
        $messageblock_file[$i++] = "\t" . '<tr id="' . $messageblock_main . '_' . $file_id . '" class="file_messageblock_fileheader_tr" style="display:none;">';
        $messageblock_file[$i++] = "\t\t" . '<td id="' . $messageblock_main . '_filenumber_' . $file_id . '" class="file_messageblock_filenumber_td"' . $filenumber_display . '>' . $file_id . '</td>';
        $messageblock_file[$i++] = "\t\t" . '<td id="' . $messageblock_header . '_container_' . $file_id . '" class="file_messageblock_fileheader_td">';
        $messageblock_file[$i++] = "\t\t\t" . '<div id="' . $messageblock_header . '_' . $file_id . '" class="file_messageblock_fileheader" style="color:' . $fileheader_color . '; background-color:' . $fileheader_bgcolor . '; border:1px solid ' . $fileheader_borcolor . ';">';
        $messageblock_file[$i++] = "\t\t\t\t" . '<label id="' . $messageblock_header . '_label_' . $file_id . '" class="file_messageblock_fileheader_label">' . $fileheader_message . '</label>';
        /* The following hidden input holds state of arrow (open or close) */
        $messageblock_file[$i++] = "\t\t\t\t" . '<input id="' . $messageblock_header . '_state_' . $file_id . '" type="hidden" value="none" />';
        $messageblock_file[$i++] = "\t\t\t" . '</div>';
        $messageblock_file[$i++] = "\t\t" . '</td>';
        /* Add a drop down arrow to the file header (file has always details to be shown) */
        $messageblock_file[$i++] = "\t\t" . '<td id="' . $messageblock_arrow . '_' . $file_id . '" class="file_messageblock_filearrow_td" onclick="wfu_filedetails_toggle(' . $sid . ', ' . $file_id . ');">';
        $messageblock_file[$i++] = "\t\t\t" . '<div id="' . $messageblock_arrow . '_up_' . $file_id . '" class="file_messageblock_file_arrow_up" style="display:none;"></div>';
        $messageblock_file[$i++] = "\t\t\t" . '<div id="' . $messageblock_arrow . '_down_' . $file_id . '" class="file_messageblock_file_arrow_down"></div>';
        $messageblock_file[$i++] = "\t\t" . '</td>';
        $messageblock_file[$i++] = "\t" . '</tr>';
        /* Prepare the files subheader block HTML template */
        $messageblock_file[$i++] = "\t" . '<tr id="' . $messageblock_subheader . '_' . $file_id . '" class="file_messageblock_filesubheader_tr" style="display:none;">';
        $messageblock_file[$i++] = "\t\t" . '<td id="' . $messageblock_subheader . '_fileempty_' . $file_id . '" class="file_messageblock_filesubheaderempty_td"' . $filenumber_display . '></td>';
        $messageblock_file[$i++] = "\t\t" . '<td colspan="2" id="' . $messageblock_subheader . '_container_' . $file_id . '" class="file_messageblock_filesubheader_td">';
        $messageblock_file[$i++] = "\t\t\t" . '<div id="' . $messageblock_subheader . '_message_' . $file_id . '" class="file_messageblock_filesubheader_message"' . $filesubheadermessage_display . '>';
        $messageblock_file[$i++] = "\t\t\t\t" . '<label id="' . $messageblock_subheader . '_messagelabel_' . $file_id . '" class="file_messageblock_filesubheader_messagelabel">' . $filesubheader_message . '</label>';
        $messageblock_file[$i++] = "\t\t\t" . '</div>';
        $messageblock_file[$i++] = "\t\t\t" . '<div id="' . $messageblock_subheader . '_adminmessage_' . $file_id . '" class="file_messageblock_filesubheader_adminmessage"' . $filesubheaderadminmessage_display . '>';
        $messageblock_file[$i++] = "\t\t\t\t" . '<label id="' . $messageblock_subheader . '_adminmessagelabel_' . $file_id . '" class="file_messageblock_filesubheader_adminmessagelabel">' . $filesubheader_adminmessage . '</label>';
        $messageblock_file[$i++] = "\t\t\t" . '</div>';
        $messageblock_file[$i++] = "\t\t" . '</td>';
        $messageblock_file[$i++] = "\t" . '</tr>';
    }
    /* Construct the main header block HTML text
    	/* Construct the header block HTML text */
    $i = 1;
    $messageblock["msgblock"]["line" . $i++] = '<table id="' . $messageblock_main . '" class="file_messageblock_table"' . $styles . '><tbody>';
    $messageblock["msgblock"]["line" . $i++] = "\t" . '<tr id="' . $messageblock_header . '" class="file_messageblock_header_tr"' . ($test ? '' : ' style="display:none;"') . '>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '<td colspan="2" id="' . $messageblock_header . '_container" class="file_messageblock_header_td">';
    /* Inside this td element the appropriate upload state HTML block is going to be inserted using Javascript 
       If the plugin is in test mode, then State9 HTML block is inserted now */
    if ($test) {
        foreach ($messageblock_headers as $messageblock_header_part) {
            $messageblock["msgblock"]["line" . $i++] = strtr($messageblock_header_part, array("[header_safe]" => "", "[header_color]" => $header_styles["State9"]["color"], "[header_bgcolor]" => $header_styles["State9"]["bgcolor"], "[header_borcolor]" => $header_styles["State9"]["borcolor"], "[header_message]" => $header_styles["State9"]["message"]));
        }
    }
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '</td>';
    /* Add a drop down arrow to the header */
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '<td id="' . $messageblock_arrow . '" class="file_messageblock_arrow_td"' . ($test ? '' : ' style="display:none;"') . ' onclick="wfu_headerdetails_toggle(' . $sid . ');">';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '<input id="' . $messageblock_header . '_state" type="hidden" value="none" />';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '<div id="' . $messageblock_arrow . '_up" class="file_messageblock_header_arrow_up" style="display:none;"></div>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '<div id="' . $messageblock_arrow . '_down" class="file_messageblock_header_arrow_down"></div>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '</td>';
    $messageblock["msgblock"]["line" . $i++] = "\t" . '</tr>';
    /* Construct the subheader block HTML text if exists */
    $messageblock["msgblock"]["line" . $i++] = "\t" . '<tr id="' . $messageblock_subheader . '" class="file_messageblock_subheader_tr" style="display:none;">';
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '<td colspan="3" id="' . $messageblock_subheader . '_td" class="file_messageblock_subheader_td">';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '<div id="' . $messageblock_subheader . '_message" class="file_messageblock_subheader_message"' . ($test ? '' : ' style="display:none;"') . '>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t\t" . '<label id="' . $messageblock_subheader . '_messagelabel" class="file_messageblock_subheader_messagelabel">' . ($test ? WFU_TESTMESSAGE_MESSAGE : '') . '</label>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '</div>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '<div id="' . $messageblock_subheader . '_adminmessage" class="file_messageblock_subheader_adminmessage"' . ($test ? '' : ' style="display:none;"') . '>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t\t" . '<label id="' . $messageblock_subheader . '_adminmessagelabel" class="file_messageblock_subheader_adminmessagelabel">' . ($test ? WFU_TESTMESSAGE_ADMINMESSAGE : '') . '</label>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t\t" . '</div>';
    $messageblock["msgblock"]["line" . $i++] = "\t\t" . '</td>';
    $messageblock["msgblock"]["line" . $i++] = "\t" . '</tr>';
    /* After the above tr the file blocks are appended by Javascript dynamically as additional tr elements
       If the plugin is in test mode, then two test file blocks are appended now */
    if ($test) {
        foreach ($messageblock_file as $messageblock_file_part) {
            $messageblock["msgblock"]["line" . $i++] = $messageblock_file_part;
        }
    }
    $messageblock["msgblock"]["line" . $i++] = '</tbody></table>';
    /* Construct a div element that will hold the State10 header and use it in case JSON parse fails and upload results cannot be decoded */
    $messageblock["msgblock"]["line" . $i++] = '<div id="' . $messageblock_header . '_safecontainer" style="display:none;">';
    foreach ($messageblock_headers as $messageblock_header_part) {
        $messageblock["msgblock"]["line" . $i++] = strtr($messageblock_header_part, array("[header_safe]" => "_safe", "[header_color]" => $header_styles["State10"]["color"], "[header_bgcolor]" => $header_styles["State10"]["bgcolor"], "[header_borcolor]" => $header_styles["State10"]["borcolor"], "[header_message]" => $header_styles["State10"]["message"]));
    }
    $messageblock["msgblock"]["line" . $i++] = '</div>';
    /* Construct header HTML text for all upload states and save it to hidden input, to be used later on by Javascript to adjust the upload state dynamically */
    $messageblock_header_template = "";
    foreach ($messageblock_headers as $messageblock_header_part) {
        $messageblock_header_template .= $dlp . $messageblock_header_part;
    }
    foreach ($ExposedStateIndex as $ii) {
        $messageblock["header"]["State" . $ii] = strtr($messageblock_header_template, array("[header_safe]" => "", "[header_color]" => $header_styles["State" . $ii]["color"], "[header_bgcolor]" => $header_styles["State" . $ii]["bgcolor"], "[header_borcolor]" => $header_styles["State" . $ii]["borcolor"], "[header_message]" => $header_styles["State" . $ii]["message"]));
    }
    $messageblock_header_str = wfu_encode_array_to_string($messageblock["header"]);
    $messageblock["msgblock"]["line" . $i++] = '<input id="' . $messageblock_header . '_states" type="hidden" value="' . $messageblock_header_str . '" />';
    /* Construct file HTML block template and save it to hidden div to be used later on by Javascript to add file results to the upload message dynamically */
    $messageblock_file_str = "";
    foreach ($messageblock_file as $messageblock_file_part) {
        $messageblock_file_str .= $dlp . $messageblock_file_part;
    }
    $messageblock_file_str = wfu_plugin_encode_string($messageblock_file_str);
    $messageblock["msgblock"]["line" . $i++] = '<input id="' . $messageblock_main . '_filetemplate" type="hidden" value="' . $messageblock_file_str . '" />';
    $messageblock["msgblock"]["line" . $i++] = '<div id="' . $messageblock_main . '_door" style="display:none;"></div>';
    return $messageblock;
}
function wfu_process_files($params, $method)
{
    $sid = $params["uploadid"];
    $sesid = session_id();
    $user = wp_get_current_user();
    if (0 == $user->ID) {
        $user_id = 0;
        $user_login = "******";
        $user_email = "";
        $is_admin = false;
    } else {
        $user_id = $user->ID;
        $user_login = $user->user_login;
        $user_email = $user->user_email;
        $is_admin = current_user_can('manage_options');
    }
    $plugin_options = wfu_decode_plugin_options(get_option("wordpress_file_upload_options"));
    $unique_id = sanitize_text_field($_POST['uniqueuploadid_' . $sid]);
    // determine if this routine is only for checking the file
    $only_check = isset($_POST['only_check']) ? $_POST['only_check'] == "1" : false;
    $suppress_admin_messages = $params["adminmessages"] != "true" || !$is_admin;
    $success_count = 0;
    $warning_count = 0;
    $error_count = 0;
    $default_colors = wfu_prepare_message_colors(WFU_VAR("WFU_DEFAULTMESSAGECOLORS"));
    $notify_only_filename_list = "";
    $notify_target_path_list = "";
    $notify_attachment_list = "";
    $uploadedfile = 'uploadedfile_' . $sid;
    $hiddeninput = 'hiddeninput_' . $sid;
    $allowed_patterns = explode(",", $params["uploadpatterns"]);
    foreach ($allowed_patterns as $key => $allowed_pattern) {
        $allowed_patterns[$key] = trim($allowed_pattern);
    }
    $userdata_fields = $params["userdata_fields"];
    foreach ($userdata_fields as $userdata_key => $userdata_field) {
        $userdata_fields[$userdata_key]["value"] = isset($_POST[$hiddeninput . '_userdata_' . $userdata_key]) ? strip_tags($_POST[$hiddeninput . '_userdata_' . $userdata_key]) : "";
    }
    $params_output_array["version"] = "full";
    $params_output_array["general"]['shortcode_id'] = $sid;
    $params_output_array["general"]['unique_id'] = $unique_id;
    $params_output_array["general"]['state'] = 0;
    $params_output_array["general"]['files_count'] = 0;
    $params_output_array["general"]['update_wpfilebase'] = "";
    $params_output_array["general"]['redirect_link'] = $params["redirect"] == "true" ? $params["redirectlink"] : "";
    $params_output_array["general"]['upload_finish_time'] = 0;
    $params_output_array["general"]['message'] = "";
    $params_output_array["general"]['message_type'] = "";
    $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
    $params_output_array["general"]['admin_messages']['notify'] = "";
    $params_output_array["general"]['admin_messages']['redirect'] = "";
    $params_output_array["general"]['admin_messages']['other'] = "";
    $params_output_array["general"]['errors']['wpfilebase'] = "";
    $params_output_array["general"]['errors']['notify'] = "";
    $params_output_array["general"]['errors']['redirect'] = "";
    $params_output_array["general"]['color'] = $default_colors['color'];
    $params_output_array["general"]['bgcolor'] = $default_colors['bgcolor'];
    $params_output_array["general"]['borcolor'] = $default_colors['borcolor'];
    $params_output_array["general"]['notify_only_filename_list'] = "";
    $params_output_array["general"]['notify_target_path_list'] = "";
    $params_output_array["general"]['notify_attachment_list'] = "";
    $params_output_array["general"]['fail_message'] = "";
    $params_output_array["general"]['fail_admin_message'] = "";
    /* safe_output is a minimized version of params_output_array, that is passed as text, in case JSON parse fails
    	   its data are separated by semicolon (;) and are the following:
    		upload state: the upload state number
    		default colors: the default color, bgcolor and borcolor values, separated by comma(,)
    		file_count: the number of files processed
    		filedata: message type, header, message and admin message of each file, encoded and separated by comma (,) */
    $params_output_array["general"]['safe_output'] = "";
    /* js_script is javascript code that is executed after each file upload and is defined in wfu_after_file_upload action */
    $params_output_array["general"]['js_script'] = "";
    /* adjust $uploadedfile variable (holding file data) if this is a redirection caused because the browser of the user could not handle AJAX upload */
    if (isset($_FILES[$uploadedfile . '_redirected'])) {
        $uploadedfile .= '_redirected';
    }
    /* notify admin if this is a redirection caused because the browser of the user could not handle AJAX upload */
    $params_output_array["general"]['admin_messages']['other'] = $params['adminerrors'];
    if (isset($_FILES[$uploadedfile]['error']) || $only_check) {
        $files_count = 1;
        // in case of checking of file, then the $_FILES variable has not been set because no file has been uploaded,
        // so we set it manually in order to allow the routine to continue
        if ($only_check) {
            $_FILES[$uploadedfile]['name'] = wfu_plugin_decode_string($_POST[$uploadedfile . '_name']);
            $_FILES[$uploadedfile]['type'] = 'any';
            $_FILES[$uploadedfile]['tmp_name'] = 'any';
            $_FILES[$uploadedfile]['error'] = '';
            $_FILES[$uploadedfile]['size'] = $_POST[$uploadedfile . '_size'];
        }
    } else {
        $files_count = 0;
    }
    $params_output_array["general"]['files_count'] = $files_count;
    // index of uploaded file in case of ajax uploads (in ajax uploads only one file is uploaded in every ajax call)
    // the index is used to store any file data in session variables, in case the file is uploaded in two or more passes
    // (like the case were in the first pass it is only checked)
    $single_file_index = isset($_POST[$uploadedfile . '_index']) ? $_POST[$uploadedfile . '_index'] : -1;
    /* append userdata fields to upload path */
    $search = array();
    $replace = array();
    foreach ($userdata_fields as $userdata_key => $userdata_field) {
        $ind = 1 + $userdata_key;
        array_push($search, '/%userdata' . $ind . '%/');
        array_push($replace, $userdata_field["value"]);
    }
    $params["uploadpath"] = preg_replace($search, $replace, $params["uploadpath"]);
    /* append subfolder name to upload path */
    if ($params["askforsubfolders"] == "true") {
        if ($params["subfoldertree"] == "auto+" && $params['subdir_selection_index'] != '') {
            if (substr($params["uploadpath"], -1, 1) == "/") {
                $params["uploadpath"] .= $params['subdir_selection_index'];
            } else {
                $params["uploadpath"] .= '/' . $params['subdir_selection_index'];
            }
        } elseif ($params["subfoldertree"] != "auto+" && $params['subdir_selection_index'] >= 1) {
            if (substr($params["uploadpath"], -1, 1) == "/") {
                $params["uploadpath"] .= $params['subfoldersarray'][$params['subdir_selection_index']];
            } else {
                $params["uploadpath"] .= '/' . $params['subfoldersarray'][$params['subdir_selection_index']];
            }
        }
    }
    if ($files_count == 1) {
        foreach ($_FILES[$uploadedfile] as $key => $prop) {
            $fileprops[$key] = $prop;
        }
        $upload_path_ok = false;
        $allowed_file_ok = false;
        $size_file_ok = false;
        $size_file_phpenv_ok = true;
        $ignore_server_actions = false;
        $file_output['color'] = $default_colors['color'];
        $file_output['bgcolor'] = $default_colors['bgcolor'];
        $file_output['borcolor'] = $default_colors['borcolor'];
        $file_output['header'] = "";
        $file_output['message'] = "";
        $file_output['message_type'] = "";
        $file_output['admin_messages'] = "";
        $file_output['uploaded_file_props'] = "";
        $fileid = -1;
        // determine if file data have been saved to session variables, due to a previous pass of this file
        $file_map = "filedata_" . $unique_id . "_" . $single_file_index;
        // retrieve unique id of the file, used in filter actions for identifying each separate file
        $file_unique_id = isset($_SESSION[$file_map]) ? $_SESSION[$file_map]['file_unique_id'] : '';
        $filedata_previously_defined = $file_unique_id != '';
        /* generate unique id for each file for use in filter actions if it has not been previously defined */
        if (!$filedata_previously_defined) {
            $file_unique_id = wfu_create_random_string(20);
        }
        /* Get uploaded file size in Mbytes */
        // correct file size in case of checking of file otherwise $upload_file_size will be zero and the routine will fail
        if ($only_check) {
            $upload_file_size = $fileprops['size'];
            if ($upload_file_size == 0) {
                $upload_file_size++;
            }
        } else {
            $upload_file_size = filesize($fileprops['tmp_name']);
            if ($upload_file_size == 0 && file_exists($fileprops['tmp_name']) && $fileprops['error'] == 0) {
                $upload_file_size++;
            }
        }
        $upload_file_size_MB = $upload_file_size / 1024 / 1024;
        $only_filename = $fileprops['name'];
        $target_path = wfu_upload_plugin_full_path($params) . $only_filename;
        if ($upload_file_size > 0) {
            /* Section to perform filter action wfu_before_file_check before file is checked in order to perform
               any filename or userdata modifications or reject the upload of the file by setting error_message item
               of $ret_data array to a non-empty value */
            $filter_error_message = '';
            $filter_admin_message = '';
            if ($file_unique_id != '' && !$filedata_previously_defined) {
                /* store file data and upload result to filemap session array 
                   for use by after_upload filters */
                if (!isset($_SESSION["filedata_" . $unique_id])) {
                    $_SESSION["filedata_" . $unique_id] = array();
                }
                $real_file_index = $single_file_index;
                if ($single_file_index == -1) {
                    $real_file_index = $i;
                }
                // get correct file size
                if ($only_check) {
                    $filesize = $fileprops['size'];
                } else {
                    $filesize = filesize($fileprops['tmp_name']);
                }
                $_SESSION["filedata_" . $unique_id][$real_file_index] = array("file_unique_id" => $file_unique_id, "original_filename" => $only_filename, "filesize" => $filesize);
                // prepare parameters for wfu_before_file_check filter
                $changable_data['file_path'] = $target_path;
                $changable_data['user_data'] = $userdata_fields;
                $changable_data['error_message'] = $filter_error_message;
                $changable_data['admin_message'] = $filter_admin_message;
                $additional_data['shortcode_id'] = $sid;
                $additional_data['file_unique_id'] = $file_unique_id;
                $additional_data['file_size'] = $filesize;
                $additional_data['user_id'] = $user->ID;
                $additional_data['page_id'] = $params["pageid"];
                $ret_data = apply_filters('wfu_before_file_check', $changable_data, $additional_data);
                $target_path = $ret_data['file_path'];
                $only_filename = wfu_basename($target_path);
                $userdata_fields = $ret_data['user_data'];
                $filter_error_message = $ret_data['error_message'];
                $filter_admin_message = $ret_data['admin_message'];
                // if this is a file check, which means that a second pass of the file will follow, then we do not want to
                // apply the filters again, so we store the changable data to session variables for this specific file
                if ($only_check) {
                    $_SESSION[$file_map]['file_unique_id'] = $file_unique_id;
                    $_SESSION[$file_map]['filepath'] = $target_path;
                    $_SESSION[$file_map]['userdata'] = $userdata_fields;
                }
            }
            // if this is a second pass of the file, because a first pass with file checking was done before, then retrieve
            // file data that may have previously changed because of application of filters
            if ($filedata_previously_defined) {
                $target_path = $_SESSION[$file_map]['filepath'];
                $only_filename = wfu_basename($target_path);
                $userdata_fields = $_SESSION[$file_map]['userdata'];
            }
            if ($filter_error_message != '') {
                //errorabort flag designates that file will be aborted and no resuming will be attempted
                $file_output['message_type'] = "errorabort";
                $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
                if ($filter_admin_message != '') {
                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
                }
            } else {
                /* generate safe filename by removing invalid characters if forcefilename is deactivated */
                if ($params['forcefilename'] != "true") {
                    $only_filename = wfu_upload_plugin_clean($only_filename);
                    //reconstruct target_path
                    $target_path = wfu_basedir($target_path) . $only_filename;
                }
                /* if medialink or postlink is activated then the target path becomes the current wordpress upload folder */
                if ($params["medialink"] == "true" || $params["postlink"] == "true") {
                    $mediapath = wp_upload_dir();
                    $target_path = $mediapath['path'] . '/' . $only_filename;
                }
                /* Check if upload path exist */
                if (is_dir(wfu_basedir($target_path))) {
                    $upload_path_ok = true;
                } else {
                    if ($params["createpath"] == "true") {
                        $wfu_create_directory_ret = wfu_create_directory(wfu_basedir($target_path), $params["accessmethod"], $params["ftpinfo"]);
                        if ($wfu_create_directory_ret != "") {
                            $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_create_directory_ret);
                        }
                        if (is_dir(wfu_basedir($target_path))) {
                            $upload_path_ok = true;
                        }
                    }
                }
                /* File name control, reject files with .php, .js (and other) extensions for security reasons.
                   This is the first pass of extension control, which only checks the filename.
                   A second pass is performed after the file has completely uploaded, using WP inherent file
                   extension control, which provides better security. */
                if (!wfu_file_extension_restricted(strtolower($only_filename))) {
                    foreach ($allowed_patterns as $allowed_pattern) {
                        if (wfu_upload_plugin_wildcard_match($allowed_pattern, $only_filename)) {
                            $allowed_file_ok = true;
                            break;
                        }
                    }
                }
                /* File size control */
                if ($upload_file_size_MB <= $params["maxsize"]) {
                    if ($params['php_env'] == '32bit' && $upload_file_size > 2147483647) {
                        $size_file_phpenv_ok = false;
                    } else {
                        $size_file_ok = true;
                    }
                }
                if (!$upload_path_ok or !$allowed_file_ok or !$size_file_ok) {
                    //abort the file, no resuming will be attempted
                    $file_output['message_type'] = "errorabort";
                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UPLOAD_FAILED);
                    if (!$upload_path_ok) {
                        $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_EXIST);
                    }
                    if (!$allowed_file_ok) {
                        $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_ALLOW);
                    }
                    if (!$size_file_ok) {
                        if ($size_file_phpenv_ok) {
                            $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_SIZE);
                        } else {
                            $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_PLUGIN_2GBSIZE);
                        }
                    }
                }
            }
        } else {
            // This block is executed when there is an error
            $upload_error = $fileprops['error'];
            if ($upload_error == 1) {
                $message_text = WFU_ERROR_FILE_PHP_SIZE;
                $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_SIZE);
            } elseif ($upload_error == 2) {
                $message_text = WFU_ERROR_FILE_HTML_SIZE;
            } elseif ($upload_error == 3) {
                $message_text = WFU_ERROR_FILE_PARTIAL;
            } elseif ($upload_error == 4) {
                $message_text = WFU_ERROR_FILE_NOTHING;
            } elseif ($upload_error == 6) {
                $message_text = WFU_ERROR_DIR_NOTEMP;
            } elseif ($upload_error == 7) {
                $message_text = WFU_ERROR_FILE_WRITE;
            } elseif ($upload_error == 8) {
                $message_text = WFU_ERROR_UPLOAD_STOPPED;
            } else {
                $upload_time_limit = ini_get("max_input_time");
                $params_output_array["general"]['upload_finish_time'] = $params["upload_start_time"] + $upload_time_limit * 1000;
                $message_text = WFU_ERROR_FILE_PHP_TIME;
                $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_PHP_TIME);
            }
            //error (and not errorabort) flag designates that a resuming of the file may be attempted
            $file_output['message_type'] = "error";
            $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $message_text);
        }
        $message_processed = false;
        //		if ( $upload_path_ok and $allowed_file_ok and $size_file_ok ) {
        if (substr($file_output['message_type'], 0, 5) != "error") {
            if (is_uploaded_file($fileprops['tmp_name']) || $only_check) {
                $source_path = $fileprops['tmp_name'];
                if ($only_check || $ignore_server_actions) {
                    $file_copied = true;
                } else {
                    $file_copied = false;
                    if ($source_path) {
                        $file_exists = file_exists($target_path);
                        if (!$file_exists || $params["dublicatespolicy"] == "" || $params["dublicatespolicy"] == "overwrite") {
                            //redirect echo in internal buffer to receive and process any unwanted warning messages from wfu_upload_file
                            ob_start();
                            ob_clean();
                            /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
                               If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
                               previous filter wfu_before_file_check, corresponding them to the unique file id */
                            if ($file_unique_id != '') {
                                $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
                            }
                            //recalculate $only_filename in case it changed with wfu_before_file_upload filter
                            $only_filename = wfu_basename($target_path);
                            //move the uploaded file to its final destination
                            $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
                            $file_copied = $wfu_upload_file_ret["uploaded"];
                            //process warning messages from wfu_upload_file
                            $echo_message = ob_get_contents();
                            //finish redirecting of echo to internal buffer
                            ob_end_clean();
                            if ($echo_message != "" && !$file_copied) {
                                //error (and not errorabort) flag designates that file may be resumed
                                $file_output['message_type'] = "error";
                                if (stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move")) {
                                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
                                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
                                } else {
                                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
                                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], strip_tags($echo_message));
                                }
                                $message_processed = true;
                            }
                            if ($wfu_upload_file_ret["admin_message"] != "") {
                                $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
                            }
                        } else {
                            if ($file_exists && $params["dublicatespolicy"] == "maintain both") {
                                $full_path = wfu_basedir($target_path);
                                $name_part = $only_filename;
                                $ext_part = "";
                                $dot_pos = strrpos($name_part, ".");
                                if ($dot_pos) {
                                    $ext_part = substr($name_part, $dot_pos);
                                    $name_part = substr($name_part, 0, $dot_pos);
                                }
                                if ($params["uniquepattern"] != "datetimestamp") {
                                    $unique_ind = 1;
                                    do {
                                        $unique_ind += 1;
                                        $only_filename = $name_part . "(" . $unique_ind . ")" . $ext_part;
                                        $target_path = $full_path . $only_filename;
                                    } while (file_exists($target_path));
                                } else {
                                    $current_datetime = gmdate("U") - 1;
                                    do {
                                        $current_datetime += 1;
                                        $only_filename = $name_part . "-" . gmdate("YmdHis", $current_datetime) . $ext_part;
                                        $target_path = $full_path . $only_filename;
                                    } while (file_exists($target_path));
                                }
                                //redirect echo in internal buffer to receive and process any unwanted warning messages from move_uploaded_file
                                ob_start();
                                ob_clean();
                                /* Apply wfu_before_file_upload filter right before the upload, in order to allow the user to change the file name.
                                   If additional data are required, such as user_id or userdata values, they can be retrieved by implementing the
                                   previous filter wfu_before_file_check, corresponding them to the unique file id */
                                if ($file_unique_id != '') {
                                    $target_path = apply_filters('wfu_before_file_upload', $target_path, $file_unique_id);
                                }
                                //recalculate $only_filename in case it changed with wfu_before_file_upload filter
                                $only_filename = wfu_basename($target_path);
                                //move the uploaded file to its final destination
                                $wfu_upload_file_ret = wfu_upload_file($source_path, $target_path, $params["accessmethod"], $params["ftpinfo"], $params["ftppassivemode"], $params["ftpfilepermissions"]);
                                $file_copied = $wfu_upload_file_ret["uploaded"];
                                //process warning messages from move_uploaded_file
                                $echo_message = ob_get_contents();
                                //finish redirecting of echo to internal buffer
                                ob_end_clean();
                                if ($echo_message != "" && !$file_copied) {
                                    //error (and not errorabort) flag designates that file may be resumed
                                    $file_output['message_type'] = "error";
                                    if (stristr($echo_message, "warning") && stristr($echo_message, "permission denied") && stristr($echo_message, "unable to move")) {
                                        $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_DIR_PERMISSION);
                                        $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_DIR_PERMISSION);
                                    } else {
                                        $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_MOVE);
                                        $file_output['admin_messages'] = wfu_join_strings("<br />n", $file_output['admin_messages'], strip_tags($echo_message));
                                    }
                                    $message_processed = true;
                                }
                                if ($wfu_upload_file_ret["admin_message"] != "") {
                                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $wfu_upload_file_ret["admin_message"]);
                                }
                            } else {
                                //abort the file and do not allow resuming
                                $file_output['message_type'] = "errorabort";
                                $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_EXISTS);
                                $message_processed = true;
                                $file_copied = false;
                            }
                        }
                    }
                }
                if ($file_copied) {
                    /* prepare email notification parameters if email notification is enabled */
                    if ($params["notify"] == "true" && !$only_check) {
                        $notify_only_filename_list .= ($notify_only_filename_list == "" ? "" : ", ") . $only_filename;
                        $notify_target_path_list .= ($notify_target_path_list == "" ? "" : ", ") . $target_path;
                        if ($params["attachfile"] == "true") {
                            $notify_attachment_list .= ($notify_attachment_list == "" ? "" : ",") . $target_path;
                        }
                    }
                    /* prepare redirect link if redirection is enabled */
                    if ($params["redirect"] == "true") {
                        /* Define dynamic redirect link from variables */
                        $search = array('/%filename%/', '/%username%/');
                        $replace = array($only_filename, $user_login);
                        $params_output_array["general"]['redirect_link'] = trim(preg_replace($search, $replace, $params["redirectlink"]));
                    }
                    if (!$message_processed) {
                        $file_output['message_type'] = "success";
                    }
                } else {
                    if (!$message_processed) {
                        //abort the file and do not allow resuming
                        $file_output['message_type'] = "errorabort";
                        $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
                    }
                }
                /* Delete temporary file (in tmp directory) */
                //				unlink($source_path);
            } else {
                //abort the file and do not allow resuming
                $file_output['message_type'] = "errorabort";
                $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
            }
        }
        /* last check of output file status */
        if ($file_output['message_type'] == "") {
            if ($file_copied) {
                $file_output['message_type'] = "success";
            } else {
                //abort the file and do not allow resuming
                $file_output['message_type'] = "errorabort";
                $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_UNKNOWN);
            }
        }
        /* suppress any admin messages if user is not administrator or adminmessages is not activated */
        if ($suppress_admin_messages) {
            $file_output['admin_messages'] = "";
        }
        /* set file status to "warning" if the file has been uploaded but there are messages */
        if ($file_output['message_type'] == "success") {
            if ($file_output['message'] != "" || $file_output['admin_messages'] != "") {
                $file_output['message_type'] = "warning";
            }
        }
        /* set success status of the file, to be used for medialink and post actions */
        $file_finished_successfully = !$only_check && ($file_output['message_type'] == "success" || $file_output['message_type'] == "warning");
        /* set non-success status of the file, to be used for medialink and post actions */
        $file_finished_unsuccessfully = substr($file_output['message_type'], 0, 5) == "error";
        /* perform custom actions after file is completely uploaded in order to determine if file is valid ir not */
        if ($file_finished_successfully && !$ignore_server_actions) {
            /* Here the second pass of file extension control is performed after the file has completely
               uploaded, using WP inherent functions that determine the real extension from analyzing the
               data and not from the filename extension. If this check reveals an extension which is not
               permitted then the file will be rejected and erased. If the real extension is different
               than the original one but it is permitted, then the file will remain as it is but a warning
               message will notify the user that the extension of the file does not match its contents. */
            $check = wp_check_filetype_and_ext($target_path, $only_filename, false);
            if ($check['proper_filename'] !== false) {
                $proper_filename = $check['proper_filename'];
                if (wfu_file_extension_restricted(strtolower($only_filename))) {
                    $file_finished_successfully = false;
                    $file_finished_unsuccessfully = true;
                    unlink($target_path);
                    $file_output['message_type'] = "errorabort";
                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_ERROR_FILE_REJECT);
                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_ERROR_ADMIN_FILE_WRONGEXT . $check['proper_filename']);
                } else {
                    $file_output['message_type'] = "warning";
                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], WFU_WARNING_FILE_SUSPICIOUS);
                    $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], WFU_WARNING_ADMIN_FILE_SUSPICIOUS . $check['proper_filename']);
                }
            }
            // run any wfu_after_file_loaded filters to make any last file checks and accept or reject it
            if ($file_finished_successfully) {
                $filter_error_message = '';
                $filter_admin_message = '';
                $changable_data['error_message'] = $filter_error_message;
                $changable_data['admin_message'] = $filter_admin_message;
                $additional_data['file_unique_id'] = $file_unique_id;
                $additional_data['file_path'] = $target_path;
                $additional_data['shortcode_id'] = $sid;
                $ret_data = apply_filters('wfu_after_file_loaded', $changable_data, $additional_data);
                //this is a call to wfu_after_file_complete filters, which is
                //the old name of wfu_after_file_loaded filters, for maintaining
                //backward compatibility
                $ret_data = apply_filters('wfu_after_file_complete', $changable_data, $additional_data);
                $filter_error_message = $ret_data['error_message'];
                $filter_admin_message = $ret_data['admin_message'];
                if ($filter_error_message != '') {
                    $file_finished_successfully = false;
                    $file_finished_unsuccessfully = true;
                    unlink($target_path);
                    $file_output['message_type'] = "errorabort";
                    $file_output['message'] = wfu_join_strings("<br />", $file_output['message'], $filter_error_message);
                    if ($filter_admin_message != '') {
                        $file_output['admin_messages'] = wfu_join_strings("<br />", $file_output['admin_messages'], $filter_admin_message);
                    }
                }
            }
        }
        /* adjust message details and colors according to file result */
        /* FileResult: A */
        $search = array('/%username%/', '/%useremail%/', '/%filename%/', '/%filepath%/');
        $replace = array($user_login, $user_email == "" ? "no email" : $user_email, $only_filename, $target_path);
        if ($file_output['message_type'] == "success") {
            $success_count++;
            $color_array = explode(",", $params['successmessagecolors']);
            $file_output['color'] = $color_array[0];
            $file_output['bgcolor'] = $color_array[1];
            $file_output['borcolor'] = $color_array[2];
            $file_output['header'] = preg_replace($search, $replace, $params['successmessage']);
            /* prepare details of successful file upload, visible only to administrator */
            $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
        } elseif ($file_output['message_type'] == "warning") {
            $warning_count++;
            $color_array = explode(",", $params['warningmessagecolors']);
            $file_output['color'] = $color_array[0];
            $file_output['bgcolor'] = $color_array[1];
            $file_output['borcolor'] = $color_array[2];
            $file_output['header'] = preg_replace($search, $replace, $params['warningmessage']);
            /* prepare and prepend details of successful file upload, visible only to administrator */
            $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_SUCCESSMESSAGE_DETAILS), $file_output['admin_messages']);
        } elseif (substr($file_output['message_type'], 0, 5) == "error") {
            $error_count++;
            $color_array = explode(",", $params['failmessagecolors']);
            $file_output['color'] = $color_array[0];
            $file_output['bgcolor'] = $color_array[1];
            $file_output['borcolor'] = $color_array[2];
            $replace = array($user_login, $user_email == "" ? "no email" : $user_email, $only_filename, $target_path);
            $file_output['header'] = preg_replace($search, $replace, $params['errormessage']);
            /* prepare and prepend details of failed file upload, visible only to administrator */
            $file_output['admin_messages'] = wfu_join_strings("<br />", preg_replace($search, $replace, WFU_FAILMESSAGE_DETAILS), $file_output['admin_messages']);
        }
        /* suppress again any admin messages if user is not administrator or adminmessages is not activated */
        if ($suppress_admin_messages) {
            $file_output['admin_messages'] = "";
        }
        $params_output_array[0] = $file_output;
        if ($file_unique_id != '' && $file_finished_unsuccessfully && !$ignore_server_actions) {
            /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
               If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
               the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
               This actions allows to define custom javascript code to run after each file finishes (either succeeded or failed).
               For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
               still remains. */
            $changable_data['ret_value'] = null;
            $changable_data['js_script'] = '';
            $additional_data['shortcode_id'] = $sid;
            $additional_data['file_unique_id'] = $file_unique_id;
            $additional_data['upload_result'] = $file_output['message_type'];
            $additional_data['error_message'] = $file_output['message'];
            $additional_data['admin_messages'] = $file_output['admin_messages'];
            $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
            $params_output_array["general"]['js_script'] = $ret_data['js_script'];
            //			do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
        }
        if ($file_finished_successfully && !$ignore_server_actions) {
            /* log file upload action if file has finished uploading successfully */
            $fileid = wfu_log_action('upload', $target_path, $user->ID, $unique_id, $params['pageid'], $params['blogid'], $sid, $userdata_fields);
            /* Apply wfu_after_file_upload filter after failed upload, in order to allow the user to perform any post-upload actions.
               If additional data are required, such as user_id or userdata values or filepath, they can be retrieved by implementing
               the previous filters wfu_before_file_check and wfu_before_file_upload, corresponding them to the unique file id.
               This actions allows to define custom javascript code to run after each file finishes (either suceeded or failed).
               For backward compatibility, the wfu_after_file_upload action that was implemented in previous version of the plugin
               still remains. */
            $changable_data['ret_value'] = null;
            $changable_data['js_script'] = '';
            $additional_data['shortcode_id'] = $sid;
            $additional_data['file_unique_id'] = $file_unique_id;
            $additional_data['upload_result'] = $file_output['message_type'];
            $additional_data['error_message'] = $file_output['message'];
            $additional_data['admin_messages'] = $file_output['admin_messages'];
            $ret_data = apply_filters('wfu_after_file_upload', $changable_data, $additional_data);
            $params_output_array["general"]['js_script'] = $ret_data['js_script'];
            //			do_action('wfu_after_file_upload', $file_unique_id, $file_output['message_type'], $file_output['message'], $file_output['admin_messages']);
        }
        /* add file to Media or attach file to current post if any of these options is activated and the file has finished uploading successfully */
        if (($params["medialink"] == "true" || $params["postlink"] == "true") && $file_finished_successfully && !$ignore_server_actions) {
            $pageid = $params["postlink"] == "true" ? $params['pageid'] : 0;
            wfu_process_media_insert($target_path, $pageid);
        }
        /* store final file data and upload result to filemap session array for
           use by after_upload filters */
        $real_file_index = $single_file_index;
        if ($single_file_index == -1) {
            $real_file_index = $i;
        }
        if (($file_finished_successfully || $file_finished_unsuccessfully) && isset($_SESSION["filedata_" . $unique_id][$real_file_index]) && !$ignore_server_actions) {
            $_SESSION["filedata_" . $unique_id][$real_file_index]["filepath"] = $target_path;
            $_SESSION["filedata_" . $unique_id][$real_file_index]["user_data"] = $userdata_fields;
            $_SESSION["filedata_" . $unique_id][$real_file_index]["upload_result"] = $file_output['message_type'];
            $_SESSION["filedata_" . $unique_id][$real_file_index]["message"] = $file_output['message'];
            $_SESSION["filedata_" . $unique_id][$real_file_index]["admin_messages"] = $file_output['admin_messages'];
        }
    }
    // in case of file check set files_count to 0 in order to denote that the file was not really uploaded
    if ($only_check) {
        $params_output_array["general"]['files_count'] = 0;
    }
    $somefiles_Ok = $warning_count + $success_count > 0;
    $allfiles_Ok = $somefiles_Ok && $error_count == 0;
    /* Prepare WPFileBase Plugin update url, if this option has been selected and only if at least one file has been successfully uploaded.
       Execution will happen only if accumulated $params_output_array["general"]['update_wpfilebase'] is not empty */
    if ($params["filebaselink"] == "true") {
        if ($somefiles_Ok) {
            $filebaseurl = site_url();
            if (substr($filebaseurl, -1, 1) == "/") {
                $filebaseurl = substr($filebaseurl, 0, strlen($filebaseurl) - 1);
            }
            /* if the following variable is not empty, then WPFileBase Plugin update must be executed
               and any admin messages must be suppressed */
            $params_output_array["general"]['update_wpfilebase'] = $filebaseurl;
        } else {
            $params_output_array["general"]['admin_messages']['wpfilebase'] = WFU_WARNING_WPFILEBASE_NOTUPDATED_NOFILES;
            $params_output_array["general"]['errors']['wpfilebase'] = "error";
        }
    }
    /* Prepare email notification parameters if email notification is enabled and only if at least one file has been successfully uploaded
       	if $method = "no-ajax" then send the email to the recipients 
       	if $method = "ajax" then return the notification parameters to the handler for further processing
       In case of ajax, execution will happen only if accumulated notify_only_filename_list is not empty */
    if ($params["notify"] == "true") {
        /* verify that there are recipients */
        $notifyrecipients = trim(preg_replace('/%useremail%/', $user_email, $params["notifyrecipients"]));
        if ($notifyrecipients != "") {
            if ($somefiles_Ok) {
                if ($method == 'no_ajax' && !$ignore_server_actions) {
                    $send_error = wfu_send_notification_email($user, $notify_only_filename_list, $notify_target_path_list, $notify_attachment_list, $userdata_fields, $params);
                    if ($send_error != "") {
                        $params_output_array["general"]['admin_messages']['notify'] = $send_error;
                        $params_output_array["general"]['errors']['notify'] = "error";
                    }
                } else {
                    /* if the following variable is not empty, then email notification must be sent
                       and any admin messages must be suppressed */
                    $params_output_array["general"]['notify_only_filename_list'] = $notify_only_filename_list;
                    $params_output_array["general"]['notify_target_path_list'] = $notify_target_path_list;
                    $params_output_array["general"]['notify_attachment_list'] = $notify_attachment_list;
                }
            } else {
                $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NOFILES;
                $params_output_array["general"]['errors']['notify'] = "error";
            }
        } else {
            $params_output_array["general"]['admin_messages']['notify'] = WFU_WARNING_NOTIFY_NOTSENT_NORECIPIENTS;
            $params_output_array["general"]['errors']['notify'] = "error";
        }
    }
    /* Prepare redirect link if redirection is enabled and only if all files have been successfully uploaded
       Execution will happen only if accumulated redirect_link is not empty and accumulated redirect errors are empty */
    if ($params["redirect"] == "true") {
        if ($params_output_array["general"]['redirect_link'] == "") {
            $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_EMPTY;
            $params_output_array["general"]['errors']['redirect'] = "error";
        } elseif (!$allfiles_Ok) {
            $params_output_array["general"]['admin_messages']['redirect'] = WFU_WARNING_REDIRECT_NOTEXECUTED_FILESFAILED;
            $params_output_array["general"]['errors']['redirect'] = "error";
        }
    }
    /* suppress any admin messages if user is not administrator or adminmessages is not activated */
    if ($suppress_admin_messages) {
        $params_output_array["general"]['admin_messages']['wpfilebase'] = "";
        $params_output_array["general"]['admin_messages']['notify'] = "";
        $params_output_array["general"]['admin_messages']['redirect'] = "";
        $params_output_array["general"]['admin_messages']['other'] = "";
    }
    /* Calculate upload state from file results */
    if ($allfiles_Ok && $warning_count == 0) {
        $params_output_array["general"]['state'] = 4;
    } else {
        if ($allfiles_Ok) {
            $params_output_array["general"]['state'] = 5;
        } else {
            if ($somefiles_Ok) {
                $params_output_array["general"]['state'] = 6;
            } else {
                if (!$somefiles_Ok && $error_count > 0) {
                    $params_output_array["general"]['state'] = 7;
                } else {
                    $params_output_array["general"]['state'] = 8;
                }
            }
        }
    }
    /* construct safe output */
    $sout = $params_output_array["general"]['state'] . ";" . WFU_VAR("WFU_DEFAULTMESSAGECOLORS") . ";" . $files_count;
    for ($i = 0; $i < $files_count; $i++) {
        $sout .= ";" . wfu_plugin_encode_string($file_output['message_type']);
        $sout .= "," . wfu_plugin_encode_string($file_output['header']);
        $sout .= "," . wfu_plugin_encode_string($file_output['message']);
        $sout .= "," . wfu_plugin_encode_string($file_output['admin_messages']);
        $sout .= "," . $file_output['uploaded_file_props'];
    }
    $params_output_array["general"]['safe_output'] = $sout;
    return $params_output_array;
}
function wfu_browse_files($basedir_code)
{
    $siteurl = site_url();
    $plugin_options = wfu_decode_plugin_options(get_option("wordpress_file_upload_options"));
    $user = wp_get_current_user();
    //store session variables for use from the downloader
    if (!current_user_can('manage_options')) {
        return;
    }
    //first decode basedir_code
    $basedir = wfu_get_filepath_from_safe($basedir_code);
    //clean session array holding dir and file paths if it is too big
    if (isset($_SESSION['wfu_filepath_safe_storage']) && count($_SESSION['wfu_filepath_safe_storage']) > WFU_VAR("WFU_PHP_ARRAY_MAXLEN")) {
        $_SESSION['wfu_filepath_safe_storage'] = array();
    }
    //extract sort info from basedir
    $sort = "";
    if ($basedir !== false) {
        $ret = wfu_extract_sortdata_from_path($basedir);
        $basedir = $ret['path'];
        $sort = $ret['sort'];
    }
    if ($sort == "") {
        $sort = 'name';
    }
    if (substr($sort, 0, 1) == '-') {
        $order = SORT_DESC;
    } else {
        $order = SORT_ASC;
    }
    //adjust basedir to have a standard format
    if ($basedir !== false) {
        if (substr($basedir, -1) != '/') {
            $basedir .= '/';
        }
        if (substr($basedir, 0, 1) == '/') {
            $basedir = substr($basedir, 1);
        }
        //calculate the absolute path of basedir knowing that basedir is relative to website root
        $basedir = wfu_path_rel2abs($basedir);
        if (!file_exists($basedir)) {
            $basedir = false;
        }
    }
    //set basedit to default value if empty
    if ($basedir === false) {
        $plugin_options = wfu_decode_plugin_options(get_option("wordpress_file_upload_options"));
        $basedir = isset($plugin_options['basedir']) ? $plugin_options['basedir'] : "";
        $temp_params = array('uploadpath' => $basedir, 'accessmethod' => 'normal', 'ftpinfo' => '', 'useftpdomain' => 'false');
        $basedir = wfu_upload_plugin_full_path($temp_params);
    }
    //find relative dir
    $reldir = str_replace(ABSPATH, "root/", $basedir);
    //save dir route to an array
    $parts = explode('/', $reldir);
    $route = array();
    $prev = "";
    foreach ($parts as $part) {
        $part = trim($part);
        if ($part != "") {
            //			if ( $part == 'root' && $prev == "" ) $prev = ABSPATH;
            if ($part == 'root' && $prev == "") {
                $prev = "";
            } else {
                $prev .= $part . '/';
            }
            array_push($route, array('item' => $part, 'path' => $prev));
        }
    }
    //calculate upper directory
    $updir = substr($basedir, 0, -1);
    $delim_pos = strrpos($updir, '/');
    if ($delim_pos !== false) {
        $updir = substr($updir, 0, $delim_pos + 1);
    }
    $echo_str = "\n" . '<div class="wrap">';
    $echo_str .= "\n\t" . '<h2>Wordpress File Upload Control Panel</h2>';
    $echo_str .= "\n\t" . '<div style="margin-top:20px;">';
    $echo_str .= wfu_generate_dashboard_menu("\n\t\t", "File Browser");
    $echo_str .= "\n\t" . '<div>';
    $echo_str .= "\n\t\t" . '<span><strong>Location:</strong> </span>';
    foreach ($route as $item) {
        // store dir path that we need to pass to other functions in session, instead of exposing it in the url
        $dir_code = wfu_safe_store_filepath($item['path']);
        $echo_str .= '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '">' . $item['item'] . '</a>';
        $echo_str .= '<span>/</span>';
    }
    //file browser header
    $echo_str .= "\n\t" . '</div>';
    //	$dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($basedir).'[['.$sort.']]');
    //	$echo_str .= "\n\t".'<a href="'.$siteurl.'/wp-admin/options-general.php?page=wordpress_file_upload&amp;action=create_dir&dir='.$dir_code.'" class="button" title="create folder" style="margin-top:6px">Create folder</a>';
    $echo_str .= "\n\t" . '<div style="margin-top:10px;">';
    $echo_str .= "\n\t\t" . '<table class="wp-list-table widefat fixed striped">';
    $echo_str .= "\n\t\t\t" . '<thead>';
    $echo_str .= "\n\t\t\t\t" . '<tr>';
    $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="30%" style="text-align:left;">';
    $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($basedir) . '[[' . (substr($sort, -4) == 'name' ? $order == SORT_ASC ? '-name' : 'name' : 'name') . ']]');
    $echo_str .= "\n\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '">Name' . (substr($sort, -4) == 'name' ? $order == SORT_ASC ? ' &uarr;' : ' &darr;' : '') . '</a>';
    $echo_str .= "\n\t\t\t\t\t" . '</th>';
    $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="10%" style="text-align:right;">';
    $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($basedir) . '[[' . (substr($sort, -4) == 'size' ? $order == SORT_ASC ? '-size' : 'size' : 'size') . ']]');
    $echo_str .= "\n\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '">Size' . (substr($sort, -4) == 'size' ? $order == SORT_ASC ? ' &uarr;' : ' &darr;' : '') . '</a>';
    $echo_str .= "\n\t\t\t\t\t" . '</th>';
    $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="20%" style="text-align:left;">';
    $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($basedir) . '[[' . (substr($sort, -4) == 'date' ? $order == SORT_ASC ? '-date' : 'date' : 'date') . ']]');
    $echo_str .= "\n\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '">Date' . (substr($sort, -4) == 'date' ? $order == SORT_ASC ? ' &uarr;' : ' &darr;' : '') . '</a>';
    $echo_str .= "\n\t\t\t\t\t" . '</th>';
    $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="10%" style="text-align:center;">';
    $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($basedir) . '[[' . (substr($sort, -4) == 'user' ? $order == SORT_ASC ? '-user' : 'user' : 'user') . ']]');
    $echo_str .= "\n\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '">Uploaded By' . (substr($sort, -4) == 'user' ? $order == SORT_ASC ? ' &uarr;' : ' &darr;' : '') . '</a>';
    $echo_str .= "\n\t\t\t\t\t" . '</th>';
    $echo_str .= "\n\t\t\t\t\t" . '<th scope="col" width="30%" style="text-align:left;">';
    $echo_str .= "\n\t\t\t\t\t\t" . '<label>User Data</label>';
    $echo_str .= "\n\t\t\t\t\t" . '</th>';
    $echo_str .= "\n\t\t\t\t" . '</tr>';
    $echo_str .= "\n\t\t\t" . '</thead>';
    $echo_str .= "\n\t\t\t" . '<tbody>';
    //find contents of current folder
    $dirlist = array();
    $filelist = array();
    if ($handle = opendir($basedir)) {
        $blacklist = array('.', '..');
        while (false !== ($file = readdir($handle))) {
            if (!in_array($file, $blacklist)) {
                $filepath = $basedir . $file;
                $stat = stat($filepath);
                if (is_dir($filepath)) {
                    array_push($dirlist, array('name' => $file, 'fullpath' => $filepath, 'mdate' => $stat['mtime']));
                } else {
                    //find relative file record in database together with user data;
                    //if the file is php, then file record is null meaning that the file can only be viewed
                    //if file record is not found then the file can only be viewed
                    if (preg_match("/\\.php\$/", $filepath)) {
                        $filerec = null;
                    } else {
                        $filerec = wfu_get_file_rec($filepath, true);
                    }
                    //find user who uploaded the file
                    $username = '';
                    if ($filerec != null) {
                        $username = wfu_get_username_by_id($filerec->uploaduserid);
                    }
                    array_push($filelist, array('name' => $file, 'fullpath' => $filepath, 'size' => $stat['size'], 'mdate' => $stat['mtime'], 'user' => $username, 'filedata' => $filerec));
                }
            }
        }
        closedir($handle);
    }
    $dirsort = substr($sort, -4) == 'date' ? 'mdate' : substr($sort, -4);
    $filesort = $dirsort;
    $dirorder = $order;
    if ($dirsort == 'size') {
        $dirsort = 'name';
        $dirorder = SORT_ASC;
    }
    if ($dirsort == 'user') {
        $dirsort = 'name';
        $dirorder = SORT_ASC;
    }
    $dirlist = wfu_array_sort($dirlist, $dirsort, $dirorder);
    $filelist = wfu_array_sort($filelist, $filesort, $order);
    //show subfolders first
    if ($reldir != "root/") {
        $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($updir));
        $echo_str .= "\n\t\t\t\t" . '<tr>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<a class="row-title" href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '" title="go up">..</a>';
        $echo_str .= "\n\t\t\t\t\t" . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:right;"> </td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="20%" style="padding: 5px 5px 5px 10px; text-align:left;"> </td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:center;"> </td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;"> </td>';
        $echo_str .= "\n\t\t\t\t" . '</tr>';
    }
    $ii = 1;
    foreach ($dirlist as $dir) {
        $dir_code = wfu_safe_store_filepath(wfu_path_abs2rel($dir['fullpath']) . '[[' . $sort . ']]');
        $echo_str .= "\n\t\t\t\t" . '<tr onmouseover="var actions=document.getElementsByName(\'wfu_dir_actions\'); for (var i=0; i<actions.length; i++) {actions[i].style.visibility=\'hidden\';} document.getElementById(\'wfu_dir_actions_' . $ii . '\').style.visibility=\'visible\'" onmouseout="var actions=document.getElementsByName(\'wfu_dir_actions\'); for (var i=0; i<actions.length; i++) {actions[i].style.visibility=\'hidden\';}">';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;">';
        $echo_str .= "\n\t\t\t\t\t\t" . '<a class="row-title" href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=' . $dir_code . '" title="' . $dir['name'] . '">' . $dir['name'] . '</a>';
        $echo_str .= "\n\t\t\t\t\t\t" . '<div id="wfu_dir_actions_' . $ii . '" name="wfu_dir_actions" style="visibility:hidden;">';
        $echo_str .= "\n\t\t\t\t\t\t\t" . '<span style="visibility:hidden;">';
        $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=">Noaction</a>';
        $echo_str .= "\n\t\t\t\t\t\t\t\t" . ' | ';
        $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t".'<span>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t\t".'<a href="'.$siteurl.'/wp-admin/options-general.php?page=wordpress_file_upload&action=rename_dir&file='.$dir_code.'" title="Rename this folder">Rename</a>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t\t".' | ';
        //		$echo_str .= "\n\t\t\t\t\t\t\t".'</span>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t".'<span>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t\t".'<a href="'.$siteurl.'/wp-admin/options-general.php?page=wordpress_file_upload&action=delete_dir&file='.$dir_code.'" title="Delete this folder">Delete</a>';
        //		$echo_str .= "\n\t\t\t\t\t\t\t".'</span>';
        $echo_str .= "\n\t\t\t\t\t\t" . '</div>';
        $echo_str .= "\n\t\t\t\t\t" . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:right;"> </td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="20%" style="padding: 5px 5px 5px 10px; text-align:left;">' . date("d/m/Y H:i:s", $dir['mdate']) . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:center;"> </td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;"> </td>';
        $echo_str .= "\n\t\t\t\t" . '</tr>';
        $ii++;
    }
    //show contained files
    foreach ($filelist as $file) {
        if ($file['filedata'] != null) {
            $file_code = wfu_safe_store_filepath(wfu_path_abs2rel($file['fullpath']) . '[[' . $sort . ']]');
        }
        $echo_str .= "\n\t\t\t\t" . '<tr onmouseover="var actions=document.getElementsByName(\'wfu_file_actions\'); for (var i=0; i<actions.length; i++) {actions[i].style.visibility=\'hidden\';} document.getElementById(\'wfu_file_actions_' . $ii . '\').style.visibility=\'visible\'" onmouseout="var actions=document.getElementsByName(\'wfu_file_actions\'); for (var i=0; i<actions.length; i++) {actions[i].style.visibility=\'hidden\';}">';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;">';
        if ($file['filedata'] != null) {
            $echo_str .= "\n\t\t\t\t\t\t" . '<a class="row-title" href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_details&file=' . $file_code . '" title="View and edit file details" style="font-weight:normal;">' . $file['name'] . '</a>';
        } else {
            $echo_str .= "\n\t\t\t\t\t\t" . '<span>' . $file['name'] . '</span>';
        }
        $echo_str .= "\n\t\t\t\t\t\t" . '<div id="wfu_file_actions_' . $ii . '" name="wfu_file_actions" style="visibility:hidden;">';
        if ($file['filedata'] != null) {
            $echo_str .= "\n\t\t\t\t\t\t\t" . '<span>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_details&file=' . $file_code . '" title="View and edit file details">Details</a>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . ' | ';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '<span>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=rename_file&file=' . $file_code . '" title="Rename this file">Rename</a>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . ' | ';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '<span>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=delete_file&file=' . $file_code . '" title="Delete this file">Delete</a>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . ' | ';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '<span>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="javascript:wfu_download_file(\'' . $file_code . '\', ' . $ii . ', \'' . wp_create_nonce('wfu_download_file_invoker') . '\');" title="Download this file">Download</a>';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
        } else {
            $echo_str .= "\n\t\t\t\t\t\t\t" . '<span style="visibility:hidden;">';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . '<a href="' . $siteurl . '/wp-admin/options-general.php?page=wordpress_file_upload&action=file_browser&dir=">Noaction</a>';
            $echo_str .= "\n\t\t\t\t\t\t\t\t" . ' | ';
            $echo_str .= "\n\t\t\t\t\t\t\t" . '</span>';
        }
        $echo_str .= "\n\t\t\t\t\t\t" . '</div>';
        $echo_str .= "\n\t\t\t\t\t\t" . '<div id="wfu_file_download_container_' . $ii . '" style="display: none;"></div>';
        $echo_str .= "\n\t\t\t\t\t" . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:right;">' . $file['size'] . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="20%" style="padding: 5px 5px 5px 10px; text-align:left;">' . date("d/m/Y H:i:s", $file['mdate']) . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="10%" style="padding: 5px 5px 5px 10px; text-align:center;">' . $file['user'] . '</td>';
        $echo_str .= "\n\t\t\t\t\t" . '<td width="30%" style="padding: 5px 5px 5px 10px; text-align:left;">';
        if ($file['filedata'] != null) {
            if (count($file['filedata']->userdata) > 0) {
                $echo_str .= "\n\t\t\t\t\t\t" . '<select multiple="multiple" style="width:100%; height:40px; background:none; font-size:small;">';
                foreach ($file['filedata']->userdata as $userdata) {
                    $echo_str .= "\n\t\t\t\t\t\t\t" . '<option>' . $userdata->property . ': ' . $userdata->propvalue . '</option>';
                }
                $echo_str .= "\n\t\t\t\t\t\t" . '</select>';
            }
        }
        $echo_str .= "\n\t\t\t\t\t" . '</td>';
        $echo_str .= "\n\t\t\t\t" . '</tr>';
        $ii++;
    }
    $echo_str .= "\n\t\t\t" . '</tbody>';
    $echo_str .= "\n\t\t" . '</table>';
    $echo_str .= "\n\t\t" . '<iframe id="wfu_download_frame" style="display: none;"></iframe>';
    $echo_str .= "\n\t" . '</div>';
    $echo_str .= "\n\t" . '</div>';
    $echo_str .= "\n" . '</div>';
    return $echo_str;
}
function wfu_ajax_action_get_historylog_page()
{
    if (!isset($_POST['token']) || !isset($_POST['page'])) {
        die;
    }
    check_ajax_referer('wfu-historylog-page', 'token');
    if (!current_user_can('manage_options')) {
        die;
    }
    if (WFU_VAR("WFU_HISTORYLOG_TABLE_MAXROWS") <= 0) {
        die;
    }
    $page = wfu_sanitize_int($_POST['page']);
    $rows = wfu_view_log($page, true);
    die('wfu_historylog_page_success:' . wfu_plugin_encode_string($rows));
}