<?php 
/**
  Plugin Name: WP File Manager - PRO
  Plugin URI: https://filemanagerpro.io/product/file-manager/
  Description: Manage your WP files.
  Author: mndpsingh287
  Version: 5.4
  Author URI: https://profiles.wordpress.org/mndpsingh287
  License: GPLv2
 **/
if (!defined('FILEMANEGERPROPATH')) {
    define('FILEMANEGERPROPATH', plugin_dir_path(__FILE__));
}
if (!defined('FILEMANAGERPROURL')) {
    define('FILEMANAGERPROURL', plugins_url('', __FILE__));
}
if (!defined('fm_file_path')):
    define('fm_file_path', dirname(__FILE__));
  endif;
if (!defined('fm_plugin_url')):
    define('fm_plugin_url', plugins_url('wp-file-manager-pro'));
  endif;
if (!class_exists('mk_file_folder_manager')):
    class mk_file_folder_manager
    {
        const FILE_MANAGER_VERSION = '5.4';

        /* Auto Load Hooks */
        public function __construct()
        {
            if (!function_exists('wp_get_current_user')) {
                include ABSPATH.'wp-includes/pluggable.php';
            }
            if (is_admin()) {
                include 'controller/fm_controller.php';
                $fm_controller = new mk_fm_controller();
            }
            $opt = get_option('wp_file_manager_pro');
            $folder = basename(dirname(__FILE__));
            $file = basename(__FILE__);
            add_action('init', array(&$this, 'check_fm_updates'));
            add_action('admin_menu', array(&$this, 'ffm_menu_page'));
            add_action('admin_enqueue_scripts', array(&$this, 'ffm_admin_things'));
            add_action('wp_ajax_mk_file_folder_manager', array(&$this, 'mk_file_folder_manager_action_callback'));
            /*add_action('wp_ajax_nopriv_mk_file_folder_manager', array(&$this, 'mk_file_folder_manager_action_callback'));*/
            add_action('wp_ajax_mk_file_folder_manager_shortcode', array(&$this, 'mk_file_folder_manager_action_callback_shortcode'));
            add_action('wp_ajax_nopriv_mk_file_folder_manager_shortcode', array(&$this, 'mk_file_folder_manager_action_callback_shortcode'));
            add_shortcode('wp_file_manager', array(&$this, 'wp_file_manager_front_view'));
            add_shortcode('wp_file_manager_admin', array(&$this, 'wp_file_manager_front_view_admin_control'));
            if (isset($opt['ispro']) && !empty($opt['ispro']) && $opt['ispro'] == 'yes') {
                $this->load_packed_extensions();
                do_action('load_filemanager_extensions');
            }
            add_action('plugins_loaded', array(&$this, 'filemanager_pro_load_text_domain'));
            if ($this->allow_shortocode_btn()) {
                add_action('media_buttons_context', array(
                        $this,
                        'filemanager_pro_btn',
                     ));
            }
            /* New Feature */
            add_action('init', array(&$this, 'create_auto_directory'));
            // Install vendor
            add_action('wp_ajax_mk_file_folder_manager_install_vendor',
            array(&$this, 'mk_file_folder_manager_install_vendor_callback'));
            // php syntax
            add_action('wp_ajax_mk_check_filemanager_php_syntax', array(&$this, 'mk_check_filemanager_php_syntax_callback'));
            add_action('wp_ajax_nopriv_mk_check_filemanager_php_syntax', array(&$this, 'mk_check_filemanager_php_syntax_callback'));
            add_action('admin_init', array(&$this, 'remove_fm_temp_file'));
        }
        /*
        * File Manager Load pre-packed extensions
        */
        public function load_packed_extensions()
        {
            $dir = dirname(__FILE__).'/extensions';
            if (is_dir($dir)) {
                $extensions = glob($dir.'/*');
                foreach ($extensions as $extension) {
                    if (is_dir($extension)) {
                        include $extension.'/'.basename($extension).'.php';
                    }
                }
            }
        }

        //install vendor
        public function mk_file_folder_manager_install_vendor_callback()
        {
            $vendor_url = 'https://webdesi9.com/filemanager_vendor/vendor.zip';
            $destination = FILEMANEGERPROPATH.'lib';
            $newZip = $destination.'/vendor.zip';
            $f = file_put_contents($newZip, fopen($vendor_url, 'r'), LOCK_EX);
            if (false === $f) {
                die("Couldn't write to file.");
            }
            $zip = new ZipArchive();
            $res = $zip->open($newZip);
            if ($res === true) {
                $zip->extractTo($destination);
                $zip->close();
                echo 'Required libraries installed successfully.';
                unlink($newZip);
            } else {
                echo 'Unable to install Required libraries.';
            }
            die;
        }

        /* Allow Shortcode Button */
        public function allow_shortocode_btn()
        {
            $opt = get_option('wp_filemanager_options');
            if (isset($opt['allow_shortcode_btn_editor']) && $opt['allow_shortcode_btn_editor'] == 'yes') {
                return true;
            } else {
                return false;
            }
        }

        /* Auto Directory */
        public function create_auto_directory()
        {
            $upload_dir = wp_upload_dir();
            if (is_user_logged_in()) {
                $current_user = wp_get_current_user();                
                if (isset($current_user->user_login) && !empty($upload_dir['basedir'])) {
                    $user_dirname = $upload_dir['basedir'].'/wp-file-manager-pro/users/'.$current_user->user_login;
                    if (!file_exists($user_dirname)) {
                        wp_mkdir_p($user_dirname);
                    }
                }
            }
            /* BackUp - Folder, since 6.0 */
            $backup_dirname = $upload_dir['basedir'].'/wp-file-manager-pro/backup';
            if (!file_exists($backup_dirname)) {
                wp_mkdir_p($backup_dirname);
            }
        }

        /* File Manager */
        public function filemanager_pro_load_text_domain()
        {
            $domain = dirname(plugin_basename(__FILE__));
            $locale = apply_filters('plugin_locale', get_locale(), $domain);
            load_textdomain($domain, trailingslashit(WP_LANG_DIR).'plugins'.'/'.$domain.'-'.$locale.'.mo');
            load_plugin_textdomain($domain, false, basename(dirname(__FILE__)).'/languages/');
        }

        /* Menu Page */
        public function ffm_menu_page()
        {
            $permissions = $this->permissions();
            add_menu_page(
            __('WP File Manager', 'wp-file-manager-pro'),
            __('WP File Manager', 'wp-file-manager-pro'),
            $permissions,
            'wp_file_manager',
            array(&$this, 'ffm_settings_callback'),
            plugins_url('images/wp_file_manager.png', __FILE__)
            );           
            /* Only for admin */
            add_submenu_page('wp_file_manager', __('Settings', 'wp-file-manager-pro'), __('Settings', 'wp-file-manager-pro'), 'manage_options', 'wp_file_manager_settings', array(&$this, 'wp_file_manager_settings'));
             /* Only for admin */
             add_submenu_page('wp_file_manager', __('Preferences', 'wp-file-manager'), __('Preferences', 'wp-file-manager'), 'manage_options', 'wp_file_manager_root', array(&$this, 'wp_file_manager_root'));
            /* Only for admin */
            add_submenu_page('wp_file_manager', __('Email', 'wp-file-manager-pro'), __('Email', 'wp-file-manager-pro'), 'manage_options', 'wpfm-emails', array(&$this, 'wp_file_manager_email_notifications'));
            /* Only for admin */
            add_submenu_page('wp_file_manager', __('Shortcode', 'wp-file-manager-pro'), __('Shortcode', 'wp-file-manager-pro'), 'manage_options', 'wp_file_manager_shortcode_doc', array(&$this, 'wp_file_manager_shortcode_doc'));
            if (class_exists('wp_file_manager_googledrive')) {
                add_submenu_page('wp_file_manager', __('Google Drive', 'wp-file-manager-pro'), __('Google Drive', 'wp-file-manager-pro'), 'manage_options', 'wp_file_manager_gdrive_settings', array('wp_file_manager_googledrive', 'wp_file_manager_gdrive_settings'));
            }
            if (class_exists('wp_file_manager_mobile')) {
                add_submenu_page('wp_file_manager', __('Mobile', 'wp-file-manager-pro'), __('Mobile', 'wp-file-manager-pro'), 'manage_options', 'wp_file_manager_mobile_settings', array('wp_file_manager_mobile', 'wp_file_manager_mobile_settings'));
            }
            add_submenu_page('wp_file_manager', __('Addons', 'wp-file-manager-pro'), __('Addons', 'wp-file-manager-pro'), 'manage_options', 'wpfm-addons', array(&$this, 'wp_file_manager_extension'));

        }

        /* Main Role */
        public function ffm_settings_callback()
        {
            $this->render('lib', 'wpfilemanager', true);
        }

        /*Settings */
        public function wp_file_manager_settings()
        {
            $this->render('inc', 'settings', true);
        }

        /* Shortcode Doc */
        public function wp_file_manager_shortcode_doc()
        {
            $this->render('inc', 'shortcode_docs', true);
        }

        /* Extesions - Show */
        public function wp_file_manager_extension()
        {
            $this->render('inc', 'extensions', true);
        }

        /* Email Notifications */
        public function wp_file_manager_email_notifications()
        {
            $this->render('inc', 'email', true);
        }

        /*
         Root
        */
        public function wp_file_manager_root()
        {
            $this->render('inc', 'root', true);
        }

        /* Admin  Things */
        public function ffm_admin_things()
        {
            $opt = get_option('wp_filemanager_options');
            $getPage = isset($_GET['page']) ? $_GET['page'] : '';
            $allowedPages = array(
                                      'wp_file_manager',
                                      'wp_file_manager_settings',
                                      );

            if (!empty($getPage) && in_array($getPage, $allowedPages)):
                        wp_enqueue_style('jquery-ui', plugins_url('css/jquery-ui.css', __FILE__));
            wp_enqueue_style('elfinder.min', plugins_url('lib/css/elfinder.min.css', __FILE__));
            wp_enqueue_style('theme', plugins_url('lib/css/theme.css', __FILE__));
            wp_enqueue_script('jquery_min', plugins_url('js/jquery-ui.min.js', __FILE__));
            wp_enqueue_script('elfinder_min', plugins_url('lib/js/elfinder.full.js', __FILE__));
            wp_enqueue_style('wp_file_manager', plugins_url('css/wp_file_manager_pro.css', __FILE__));
            if (isset($opt['lang']) && !empty($opt['lang'])):
                         if ($opt['lang'] != 'en') {
                             wp_enqueue_script('fm_lang', plugins_url('lib/js/i18n/elfinder.'.$opt['lang'].'.js', __FILE__));
                         }
            endif;
            if (isset($opt['theme']) && !empty($opt['theme'])) {
                if ($opt['theme'] != 'default') {
                    wp_enqueue_style('theme-latest', plugins_url('lib/themes/'.$opt['theme'].'/css/theme.css', __FILE__));
                }
            }
            endif;
            if (!empty($getPage) && $getPage == 'wp_file_manager_settings') {
                wp_enqueue_style('jquery-multiselect-css', plugins_url('css/jquery.multiselect.css', __FILE__));
                wp_enqueue_script('jquery-multiselect-js', plugins_url('js/jquery.multiselect.js', __FILE__));
                wp_enqueue_script('mkapp', plugins_url('js/app.js', __FILE__));
            }
        }

        /*
        * Ajax request handler
        * Run File Manager
        */
        public function mk_file_folder_manager_action_callback()
        {
            require 'lib/php/autoload.php';
            elFinder::$netDrivers['ftp'] = 'FTP';
            $current_user = wp_get_current_user();
            $userLogin = $current_user->user_login;
            $user = new WP_User($current_user->ID);
            $file_operations = array();
            if (!empty($user->roles) && is_array($user->roles)) {
                foreach ($user->roles as $role):
                    $role;
                endforeach;
            }

            // allowing vendor for gdrive || Dropbox
            if (class_exists('wp_file_manager_dropbox') || class_exists('wp_file_manager_googledrive')) {
                if (file_exists(FILEMANEGERPROPATH.'lib/vendor/autoload.php')) {
                    require 'lib/vendor/autoload.php';
                }
            }

            $thirdParty = get_option('wp_file_manager_pro_3rd_party');

            /* Drop Box Addon Support Code */
            $dropbox = array();

            if (class_exists('wp_file_manager_dropbox')) {
                /* DROP BOX Integrations Start */
                $dropbox_int = get_option('wp_file_manager_dropbox');
                //print_r($dropbox_int); die;
                /* DROP BOX */
                $enable_dropbox = false;
                if (isset($dropbox_int['enable_fm_dropbox']) && $dropbox_int['enable_fm_dropbox'] == 1) {
                    $enable_dropbox = true;
                }
                if ($enable_dropbox) {
                    $dropbox_accessfolder = '';
                    if (isset($dropbox_int['private_folder_access']) && !empty($dropbox_int['private_folder_access'])):
               $dropbox_accessfolder = $dropbox_int['private_folder_access'];
                    endif;
                    $folderRestricted = array();
                    $fileRestricted = array();
                    /* According To Username */
                    $selected_user = (isset($dropbox_int['select_users']) && !empty($dropbox_int['select_users'])) ? $dropbox_int['select_users'] : array();
                    $select_user_roles = (isset($dropbox_int['select_user_roles']) && !empty($dropbox_int['select_user_roles'])) ? $dropbox_int['select_user_roles'] : array();
                    if (in_array($userLogin, $selected_user)):
                    $key = array_search($userLogin, $selected_user);
                    /* Seperate Folder access */
                    if (!empty($dropbox_int['user_seprate_folder'][$key])):
                      $dropbox_accessfolder = $dropbox_int['user_seprate_folder'][$key];
                    endif;
                    /* File Operations */
                    $file_operations = $dropbox_int['users_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $restrictedFolders = explode('|', $dropbox_int['restrict_user_folders'][$key]);
                    if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $folderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                       $folderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $restrictedfiles = explode('|', $dropbox_int['restrict_user_files'][$key]);
                    if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
                    $fileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $fileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    /* According to userroles */
                    elseif (in_array($role, $select_user_roles)):
                    $key = array_search($role, $select_user_roles);
                    /* Seperate Folder access */
                    if (!empty($dropbox_int['seprate_folder'][$key])):
                      $dropbox_accessfolder = $dropbox_int['seprate_folder'][$key];
                    endif;
                    /* File Operations */
                    $file_operations = $dropbox_int['userrole_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $restrictedFolders = explode('|', $dropbox_int['restrict_folders'][$key]);
                    if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $folderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                        $folderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $restrictedfiles = explode('|', $dropbox_int['restrict_files'][$key]);
                    if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
                    $fileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $fileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif; else:
                    $folderRestricted[] = array('hidden' => 'false');
                    $fileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    $mime_allowed = array('all');
                    $mime_denied = array('');
                    /* Path View */
                    $mk_restrictions = array();

                    $cc = count($restrictedFolders);

                    if (count($fileRestricted) > $cc) {
                        $cc = count($fileRestricted);
                    }
                    for ($mu = 0; $mu <= $cc; ++$mu) {
                        $mk_restrictions[$mu] = $fileRestricted[$mu];
                        $mk_restrictions[$mu] = $folderRestricted[$mu];
                    }
                    /* End According To User */
                    if (!$file_operations && empty($file_operations)) {
                        $file_operations = array('help', 'empty');
                    }
                    elFinder::$netDrivers['dropbox2'] = 'Dropbox2';
                    $ELFINDER_DROPBOX_APPKEY = isset($dropbox_int['ELFINDER_DROPBOX_APPKEY']) ? $dropbox_int['ELFINDER_DROPBOX_APPKEY'] : '';
                    $ELFINDER_DROPBOX_APPSECRET = isset($dropbox_int['ELFINDER_DROPBOX_APPSECRET']) ? $dropbox_int['ELFINDER_DROPBOX_APPSECRET'] : '';
                    $ELFINDER_ACCESS_TOKEN = isset($dropbox_int['ELFINDER_ACCESS_TOKEN']) ? $dropbox_int['ELFINDER_ACCESS_TOKEN'] : '';
                    $path = '/';
                    if (!empty($dropbox_accessfolder)) {
                        $path = '/'.$dropbox_accessfolder;
                    }
                    if (!empty($ELFINDER_DROPBOX_APPKEY) && !empty($ELFINDER_DROPBOX_APPSECRET) && !empty($ELFINDER_ACCESS_TOKEN)) {
                        define('ELFINDER_DROPBOX_APPKEY', $ELFINDER_DROPBOX_APPKEY);
                        define('ELFINDER_DROPBOX_APPSECRET', $ELFINDER_DROPBOX_APPSECRET);
                        $dropbox = array(
                            'driver' => 'Dropbox2',
                            'path' => $path,
                            'access_token' => $ELFINDER_ACCESS_TOKEN,
                            'disabled' => $file_operations,
                            'attributes' => $mk_restrictions,
                        );
                    }
                }
            }
            /* END DROP BOX */
            $gdrive = array();
            if (class_exists('wp_file_manager_googledrive')) {
                $gdrive = get_option('wp_file_manager_google_drive');
                $gdriveTokenjson = get_option('gdriveToken');
                $gdriveToken = json_decode($gdriveTokenjson, true);
                $enable_google_drive = false;
                if (isset($gdrive['ELFINDER_ENABLE_GOOGLE_DRIVE']) && $gdrive['ELFINDER_ENABLE_GOOGLE_DRIVE'] == 1) {
                    $enable_google_drive = true;
                }
                if ($enable_google_drive) {
                    $ELFINDER_GOOGLEDRIVE_CLIENTID = isset($gdrive['ELFINDER_GOOGLEDRIVE_CLIENTID']) ? $gdrive['ELFINDER_GOOGLEDRIVE_CLIENTID'] : '';
                    $ELFINDER_GOOGLEDRIVE_CLIENTSECRET = isset($gdrive['ELFINDER_GOOGLEDRIVE_CLIENTSECRET']) ? $gdrive['ELFINDER_GOOGLEDRIVE_CLIENTSECRET'] : '';
                    elFinder::$netDrivers['googledrive'] = 'GoogleDrive';
                    if (!empty($ELFINDER_GOOGLEDRIVE_CLIENTID) && !empty($ELFINDER_GOOGLEDRIVE_CLIENTSECRET)) {
                        define('ELFINDER_GOOGLEDRIVE_CLIENTID', $ELFINDER_GOOGLEDRIVE_CLIENTID);
                        define('ELFINDER_GOOGLEDRIVE_CLIENTSECRET', $ELFINDER_GOOGLEDRIVE_CLIENTSECRET);
                    }
                    $gdrive = array(
                            'driver' => 'GoogleDrive',
                            'refresh_token' => $gdriveToken['refresh_token'],
                            'access_token' => $gdriveToken['access_token'],
                        );
                }
            }
            /*
            Box Integration Start
            */
            $box = array();

            if (class_exists('wp_file_manager_dropbox')) {
                $box_settings = get_option('wp_file_manager_box');
                $enable_box = false;
                if (isset($box_settings['enable_fm_box']) && $box_settings['enable_fm_box'] == 1) {
                    $enable_box = true;
                }
                if ($enable_box) {
                    /* Premissions System Start */

                    $box_accessfolder = '';
                    $box_private_folder_access_type = '';
                    if (isset($box_settings['private_folder_access']) && !empty($box_settings['private_folder_access'])):
                   $box_accessfolder = $box_settings['private_folder_access'];
                    $box_private_folder_access_type = $box_settings['box_private_folder_access_type'];
                    endif;
                    $boxfolderRestricted = array();
                    $boxfileRestricted = array();
                    /* According To Username */
                    $selected_user = (isset($box_settings['select_users']) && !empty($box_settings['select_users'])) ? $box_settings['select_users'] : array();
                    $select_user_roles = (isset($box_settings['select_user_roles']) && !empty($box_settings['select_user_roles'])) ? $box_settings['select_user_roles'] : array();
                    if (in_array($userLogin, $selected_user)):
                    $key = array_search($userLogin, $selected_user);
                    /* Seperate Folder access */
                    if (!empty($box_settings['user_seprate_folder'][$key])):
                      $box_accessfolder = $box_settings['user_seprate_folder'][$key];
                    $box_private_folder_access_type = $box_settings['user_box_private_folder_access_type'][$key];
                    endif;
                    /* File Operations */
                    $box_file_operations = $box_settings['users_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $restrictedFolders = explode('|', $box_settings['restrict_user_folders'][$key]);
                    if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $boxfolderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                       $boxfolderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $restrictedfiles = explode('|', $box_settings['restrict_user_files'][$key]);
                    if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
                    $boxfileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $boxfileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    /* According to userroles */
                    elseif (in_array($role, $select_user_roles)):
                    $key = array_search($role, $select_user_roles);
                    /* Seperate Folder access */
                    if (!empty($box_settings['seprate_folder'][$key])):
                      $box_accessfolder = $box_settings['seprate_folder'][$key];
                    $box_private_folder_access_type = $box_settings['userrole_box_private_folder_access_type'][$key];
                    endif;
                    /* File Operations */
                    $box_file_operations = $box_settings['userrole_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $restrictedFolders = explode('|', $box_settings['restrict_folders'][$key]);
                    if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $boxfolderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                        $boxfolderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $restrictedfiles = explode('|', $box_settings['restrict_files'][$key]);
                    if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
                    $boxfileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $boxfileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif; else:
                    $boxfolderRestricted[] = array('hidden' => 'false');
                    $boxfileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    $mime_allowed = array('all');
                    $mime_denied = array('');
                    /* Path View */
                    $mk_box_restrictions = array();

                    $cc = count($boxfolderRestricted);

                    if (count($boxfileRestricted) > $cc) {
                        $cc = count($boxfileRestricted);
                    }
                    for ($mu = 0; $mu <= $cc; ++$mu) {
                        $mk_box_restrictions[$mu] = $boxfileRestricted[$mu];
                        $mk_box_restrictions[$mu] = $boxfolderRestricted[$mu];
                    }
                    /* End According To User */
                    if (!$box_file_operations && empty($box_file_operations)) {
                        $box_file_operations = array('help', 'empty');
                    }

                    /* Premissions System End */
                    $ELFINDER_BOX_CLIENT_ID = isset($box_settings['ELFINDER_BOX_CLIENT_ID']) && !empty($box_settings['ELFINDER_BOX_CLIENT_ID']) ? $box_settings['ELFINDER_BOX_CLIENT_ID'] : '';
                    $ELFINDER_BOX_CLIENT_SECRET = isset($box_settings['ELFINDER_BOX_CLIENT_SECRET']) && !empty($box_settings['ELFINDER_BOX_CLIENT_SECRET']) ? $box_settings['ELFINDER_BOX_CLIENT_SECRET'] : '';
                    $r = array();
                    $box_access_token = get_option('wp_file_manager_pro_box_token');
                    if (!empty($box_accessfolder)) {
                        if (!empty($box_private_folder_access_type)) {
                            if ($box_private_folder_access_type == 1) {
                                $paths = explode(',', $box_accessfolder);
                                foreach ($paths as $path) {
                                    $r[] = $this->get_box_folder_id($path, $box_access_token);
                                }
                            } elseif ($box_private_folder_access_type == 2) {
                                $paths = explode(',', $box_accessfolder);
                                foreach ($paths as $path) {
                                    $r[] = $path;
                                }
                            }
                        }
                    }
                    if (!empty($r)) {
                        foreach ($r as $k => $v) {
                            $box[] = array(
                                        'driver' => 'Box',
                                        'client_id' => $ELFINDER_BOX_CLIENT_ID,
                                        'client_secret' => $ELFINDER_BOX_CLIENT_SECRET,
                                        'accessToken' => $box_access_token,
                                        'path' => '/'.$v,
                                        'disabled' => $box_file_operations,
                                        'attributes' => $mk_box_restrictions,
                                     );
                        }
                    } else {
                        $box[] = array(
                                        'driver' => 'Box',
                                        'client_id' => $ELFINDER_BOX_CLIENT_ID,
                                        'client_secret' => $ELFINDER_BOX_CLIENT_SECRET,
                                        'accessToken' => $box_access_token,
                                        'path' => '/',
                                        'disabled' => $box_file_operations,
                                        'attributes' => $mk_box_restrictions,
                                     );
                    }
                }
            }
            /*
            Box Integration end
            */

            /*
            One Drive Integration start
            */
            $onedrive = array();

            if (class_exists('wp_file_manager_onedrive')) {
                $onedrive_opt = get_option('wp_file_manager_onedrive');
                $enable_one_drive = false;
                if (isset($onedrive_opt['ELFINDER_ENABLE_ONE_DRIVE']) && $onedrive_opt['ELFINDER_ENABLE_ONE_DRIVE'] == 1) {
                    $enable_one_drive = true;
                }
                if ($enable_one_drive) {
                    /* Permissions System Start */

                    $onedrive_accessfolder = '';
                    $onedrive_private_folder_access_type = '';
                    if (isset($onedrive_opt['private_folder_access']) && !empty($onedrive_opt['private_folder_access'])):
                   $onedrive_accessfolder = $onedrive_opt['private_folder_access'];
                    $onedrive_private_folder_access_type = $onedrive_opt['box_private_folder_access_type'];
                    endif;
                    $onedrivefolderRestricted = array();
                    $onedrivefileRestricted = array();
                    /* According To Username */
                    $onedrive_selected_user = (isset($onedrive_opt['select_users']) && !empty($onedrive_opt['select_users'])) ? $onedrive_opt['select_users'] : array();
                    $onedrive_select_user_roles = (isset($onedrive_opt['select_user_roles']) && !empty($onedrive_opt['select_user_roles'])) ? $onedrive_opt['select_user_roles'] : array();
                    if (in_array($userLogin, $onedrive_selected_user)):
                    $key = array_search($userLogin, $onedrive_selected_user);
                    /* Seperate Folder access */
                    if (!empty($onedrive_opt['user_seprate_folder'][$key])):
                      $onedrive_accessfolder = $onedrive_opt['user_seprate_folder'][$key];
                    $onedrive_private_folder_access_type = $onedrive_opt['user_onedrive_private_folder_access_type'][$key];
                    endif;
                    /* File Operations */
                    $onedrive_file_operations = $onedrive_opt['users_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $obedriverestrictedFolders = explode('|', $onedrive_opt['restrict_user_folders'][$key]);
                    if (!empty($onedriverestrictedFolders[0]) && is_array($onedriverestrictedFolders)):
                      foreach ($onedriverestrictedFolders as $onedriverestrictedFolder):
                        $onedrivefolderRestricted[] = array('pattern' => '!^/'.$onedriverestrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                       $onedrivefolderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $onedriverestrictedfiles = explode('|', $onedrive_opt['restrict_user_files'][$key]);
                    if (!empty($onedriverestrictedfiles[0]) && is_array($onedriverestrictedfiles)):
                      foreach ($onedriverestrictedfiles as $onedriverestrictedFile):
                       $pattern = '/'.$onedriverestrictedFile.'$/';
                    $onedrivefileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $onedrivefileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    /* According to userroles */
                    elseif (in_array($role, $onedrive_select_user_roles)):
                    $key = array_search($role, $onedrive_select_user_roles);
                    /* Seperate Folder access */
                    if (!empty($onedrive_opt['seprate_folder'][$key])):
                      $onedrive_accessfolder = $onedrive_opt['seprate_folder'][$key];
                    $onedrive_private_folder_access_type = $onedrive_opt['userrole_onedrive_private_folder_access_type'][$key];
                    endif;
                    /* File Operations */
                    $onedrive_file_operations = $onedrive_opt['userrole_fileoperations_'.$key];
                    /* Folder Restrictions */
                    $onedriverestrictedFolders = explode('|', $onedrive_opt['restrict_folders'][$key]);
                    if (!empty($onedriverestrictedFolders[0]) && is_array($onedriverestrictedFolders)):
                      foreach ($onedriverestrictedFolders as $restrictedFolder):
                        $onedrivefolderRestricted[] = array('pattern' => '!^/'.$onedriverestrictedFolder.'!', 'hidden' => true);
                    endforeach; else:
                        $onedrivefolderRestricted[] = array('hidden' => 'false');
                    endif;
                    /* File Restrictions */
                    $onedriverestrictedfiles = explode('|', $onedrive_opt['restrict_files'][$key]);
                    if (!empty($onedriverestrictedfiles[0]) && is_array($onedriverestrictedfiles)):
                      foreach ($onedriverestrictedfiles as $onedriverestrictedFile):
                       $pattern = '/'.$onedriverestrictedFile.'$/';
                    $onedrivefileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
                    endforeach; else:
                       $onedrivefileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif; else:
                    $onedrivefolderRestricted[] = array('hidden' => 'false');
                    $onedrivefileRestricted[] = array('pattern' => '', 'locked' => false);
                    endif;
                    $mime_allowed = array('all');
                    $mime_denied = array('');
                    /* Path View */
                    $mk_onedrive_restrictions = array();

                    $cc = count($onedrivefolderRestricted);

                    if (count($onedrivefileRestricted) > $cc) {
                        $cc = count($onedrivefileRestricted);
                    }
                    for ($mu = 0; $mu <= $cc; ++$mu) {
                        $mk_onedrive_restrictions[$mu] = $onedrivefileRestricted[$mu];
                        $mk_onedrive_restrictions[$mu] = $onedrivefolderRestricted[$mu];
                    }
                    /* End According To User */
                    if (!$onedrive_file_operations && empty($onedrive_file_operations)) {
                        $onedrive_file_operations = array('help', 'empty');
                    }

                    /* Permissions System End  */
                    $ELFINDER_ONE_DRIVE_CLIENT_ID = isset($onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_ID']) && !empty($onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_ID']) ? $onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_ID'] : '';
                    $ELFINDER_ONE_DRIVE_CLIENT_SECRET = isset($onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_SECRET']) && !empty($onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_SECRET']) ? $onedrive_opt['ELFINDER_ONE_DRIVE_CLIENT_SECRET'] : '';
                    //elFinder::$netDrivers['onedrive'] = 'OneDrive';
                    define('ELFINDER_ONEDRIVE_CLIENTID', $ELFINDER_ONE_DRIVE_CLIENT_ID);
                    define('ELFINDER_ONEDRIVE_CLIENTSECRET', $ELFINDER_ONE_DRIVE_CLIENT_SECRET);

                    // path system start
                    $od = array();
                    $one_drive_access_token = get_option('wp_file_manager_pro_one_drive_token');
                    if (!empty($onedrive_accessfolder)) {
                        if (!empty($onedrive_private_folder_access_type)) {
                            if ($onedrive_private_folder_access_type == 1) {
                                $onedrivepaths = explode(',', $onedrive_accessfolder);
                                foreach ($onedrivepaths as $onedrivepath) {
                                    $od[] = $this->get_one_drive_id($onedrivepath, $one_drive_access_token);
                                }
                            } elseif ($onedrive_private_folder_access_type == 2) {
                                $onedrivepaths = explode(',', $onedrive_accessfolder);
                                foreach ($onedrivepaths as $onedrivepath) {
                                    $od[] = $onedrivepath;
                                }
                            }
                        }
                    }
                    //print_r ($od); die;
                    if (!empty($od)) {
                        foreach ($od as $k => $v) {
                            $onedrive[] = array(
                                        'driver' => 'OneDrive',
                                        'client_id' => $ELFINDER_ONE_DRIVE_CLIENT_ID,
                                        'client_secret' => $ELFINDER_ONE_DRIVE_CLIENT_SECRET,
                                        'accessToken' => $one_drive_access_token,
                                        'path' => '/'.$v,
                                        'disabled' => $onedrive_file_operations,
                                        'attributes' => $mk_onedrive_restrictions,
                                     );
                        }
                    } else {
                        $onedrive[] = array(
                                        'driver' => 'OneDrive',
                                        'client_id' => $ELFINDER_ONE_DRIVE_CLIENT_ID,
                                        'client_secret' => $ELFINDER_ONE_DRIVE_CLIENT_SECRET,
                                        'accessToken' => $one_drive_access_token,
                                        'path' => '/',
                                        'disabled' => $onedrive_file_operations,
                                        'attributes' => $mk_onedrive_restrictions,
                                     );
                    }
                }
            }
            /*
              One Drive Integration end
            */
            $opt = get_option('wp_filemanager_options');
            $accessfolder = '';
            $absolute_path = ABSPATH;
            $settings = get_option('wp_file_manager_pro_settings');
            if (isset($settings['public_path']) && !empty($settings['public_path'])) {
                $absolute_path = $settings['public_path'];
            }
            if (isset($opt['private_folder_access']) && !empty($opt['private_folder_access'])):
               $accessfolder = $opt['private_folder_access'];
            endif;
            $folderRestricted = array();
            $fileRestricted = array();
            $file_operations = array();
            /* According To Username */
            $selected_user = (isset($opt['select_users']) && !empty($opt['select_users'])) ? $opt['select_users'] : array();
            $select_user_roles = (isset($opt['select_user_roles']) && !empty($opt['select_user_roles'])) ? $opt['select_user_roles'] : array();
            if (in_array($userLogin, $selected_user)):
                    $key = array_search($userLogin, $selected_user);
            /* Seperate Folder access */
            if (!empty($opt['user_seprate_folder'][$key])):
                      $accessfolder = $opt['user_seprate_folder'][$key];
            endif;
            /* File Operations */
            $file_operations = $opt['users_fileoperations_'.$key];
            /* Folder Restrictions */
            $restrictedFolders = explode('|', $opt['restrict_user_folders'][$key]);
            if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $folderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
            endforeach; else:
                        $folderRestricted[] = array('hidden' => 'false');
            endif;
            /* File Restrictions */
            $restrictedfiles = explode('|', $opt['restrict_user_files'][$key]);
            if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
            $fileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
            endforeach; else:
                       $fileRestricted[] = array('pattern' => '', 'locked' => false);
            endif;
            /* According to userroles */
            elseif (in_array($role, $select_user_roles)):
                    $key = array_search($role, $select_user_roles);
            /* Seperate Folder access */
            if (!empty($opt['seprate_folder'][$key])):
                      $accessfolder = $opt['seprate_folder'][$key];
            endif;
            /* File Operations */
            $file_operations = $opt['userrole_fileoperations_'.$key];
            /* Folder Restrictions */
            $restrictedFolders = explode('|', $opt['restrict_folders'][$key]);
            if (!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
                      foreach ($restrictedFolders as $restrictedFolder):
                        $folderRestricted[] = array('pattern' => '!^/'.$restrictedFolder.'!', 'hidden' => true);
            endforeach; else:
                        $folderRestricted[] = array('hidden' => 'false');
            endif;
            /* File Restrictions */
            $restrictedfiles = explode('|', $opt['restrict_files'][$key]);
            if (!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
                      foreach ($restrictedfiles as $restrictedFile):
                       $pattern = '/'.$restrictedFile.'$/';
            $fileRestricted[] = array('pattern' => $pattern, 'write' => false, 'locked' => true);
            endforeach; else:
                       $fileRestricted[] = array('pattern' => '', 'locked' => false);
            endif; else:
                    $folderRestricted[] = array('hidden' => 'false');
            $fileRestricted[] = array('pattern' => '', 'locked' => false);
            endif;
            //$mime_allowed = array('text', 'image', 'application','audio/mpeg','video/mp4','application/x-shockwave-flash');
            $mime_allowed = array('all');
            $mime_denied = array('');
            /* Path View */
            $siteUrl = site_url();
            if (!empty($accessfolder)) {
                $siteUrl .= '/'.$accessfolder;
            }
            $mk_restrictions = array();
            /* Limit To 100 */
            $cc = count($restrictedFolders);
            if (count($fileRestricted) > $cc) {
                $cc = count($fileRestricted);
            }
            for ($mu = 0; $mu <= $cc; ++$mu) {
                $mk_restrictions[$mu] = $fileRestricted[$mu];
                $mk_restrictions[$mu] = $folderRestricted[$mu];
            }

            $mk_restrictions[] = array(
                                  'pattern' => '/.tmb/',
                                   'read' => false,
                                   'write' => false,
                                   'hidden' => true,
                                   'locked' => false,
                                );
            $mk_restrictions[] = array(
                                  'pattern' => '/.quarantine/',
                                   'read' => false,
                                   'write' => false,
                                   'hidden' => true,
                                   'locked' => false,
                                );
            /* End According To User */
            if (!$file_operations && empty($file_operations)) {
                $file_operations = array('help', 'empty', 'preference');
            }
            if (!isset($opt['diable_local_file_system_fm']) && $opt['diable_local_file_system_fm'] != 'yes') {
                // trash
                if (isset($settings['fm_enable_trash']) && $settings['fm_enable_trash'] == '1') {
                    $mkTrash = array(
                         'id' => '1',
                         'driver' => 'Trash',
                         'path' => FILEMANEGERPROPATH.'lib/files/.trash/',
                         'tmbURL' => site_url().'/lib/files/.trash/.tmb/',
                         'winHashFix' => DIRECTORY_SEPARATOR !== '/',
                         'uploadDeny' => array(''),
                         'uploadAllow' => array(''),
                         'uploadOrder' => array('deny', 'allow'),
                         'accessControl' => 'access',
                        //'attributes' => $mk_restrictions,
                     );
                    $mkTrashHash = 't1_Lw';
                } else {
                    $mkTrash = array();
                    $mkTrashHash = '';
                }
                /* Local File System */
                $local_file_system = array(
                            'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
                            'path' => $absolute_path.$accessfolder, // path to files (REQUIRED)
                            'URL' => $siteUrl, // URL to files (REQUIRED)
                            'trashHash' => $mkTrashHash,
                            'winHashFix' => DIRECTORY_SEPARATOR !== '/',
                            'uploadDeny' => $mime_denied, // All Mimetypes not allowed to upload
                            'uploadAllow' => $mime_allowed,
                            'uploadOrder' => array('deny', 'allow'),
                            'accessControl' => 'access', // disable and hide dot starting files (OPTIONAL)
                            'acceptedName' => 'validName',
                            'uploadMaxSize' => !empty($opt['fm_max_upload_size']) ? $opt['fm_max_upload_size'].'M' : '2'.'M',
                            'disabled' => $file_operations,
                            'attributes' => $mk_restrictions,
                        );
            } else {
                $local_file_system = array();
                $mkTrash = array();
            }
            $roots = array();
           
            array_push($roots, $local_file_system, $mkTrash,$dropbox, $gdrive);
            if (!empty($box) && is_array($box) && count($box) > 0) {
                foreach ($box as $key => $val) {
                    array_push($roots, $val);
                }
            }
            // onedrive
            if (!empty($onedrive) && is_array($onedrive) && count($onedrive) > 0) {
                foreach ($onedrive as $key => $val) {
                    array_push($roots, $val);
                }
            }
            $opts = array(
                           'debug' => false,
                           'roots' => $roots,
               );
            $connector = new elFinderConnector(new elFinder($opts));
            $connector->run();
            die;
        }

        /* Get One Drive Id from folder name */
        public function get_one_drive_id($name, $token)
        {
            $t = json_decode($token, true);
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://graph.microsoft.com/v1.0/users/me/drive/root:/'.$name,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'authorization: bearer '.$t['data']['access_token'],
                'cache-control: no-cache',
            ),
        ));
            $response = curl_exec($curl);
            $res = json_decode($response, true);
            if (isset($res['id'])) {
                return $res['id'];
            } else {
                return 0;
            }
            curl_close($curl);
        }

        /* Get Box ID from folder name */
        public function get_box_folder_id($name, $token)
        {
            $t = json_decode($token, true);
            $url = 'https://api.box.com/2.0/search';
            $dataArray = array(
                'query' => $name,
                'type' => 'folder',
                );
            $ch = curl_init();
            $data = http_build_query($dataArray);
            $getUrl = $url.'?'.$data;
            $headers = array(
              'Authorization: Bearer '.$t['data']['access_token'],
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_URL, $getUrl);
            curl_setopt($ch, CURLOPT_TIMEOUT, 80);
            $response = curl_exec($ch);
            $res = json_decode($response, true);
            if (isset($res)) {
                return $res['entries'][0]['id'];
            } else {
                return 0;
            }
            curl_close($ch);
        }

        /*
        Access permissions
        */
        public function permissions()
        {
            $opt = get_option('wp_filemanager_options');
            $allowedroles = isset($opt['fm_user_roles']) ? $opt['fm_user_roles'] : '';
            if (empty($allowedroles)) {
                $allowedroles = array();
            }
            $current_user = wp_get_current_user();
            $userLogin = $current_user->user_login;
            $permissions = 'manage_options';
            $userID = $current_user->ID;
            $user = new WP_User($userID);
            if (!empty($user->roles) && is_array($user->roles)) {
                foreach ($user->roles as $role):
                    $role;
                endforeach;
            }
            $mk_count_u_roles = array_intersect($user->roles,$allowedroles);          
            if ($role == 'administrator'):
             $permissions = 'manage_options'; 
             elseif(count($mk_count_u_roles) > 0):
                $permissions = 'read';
             endif;
            return $permissions;
        }

        /*
        render
        */
        public function render($folder, $page, $restrictions)
        {
            if ($restrictions) {
                if (is_admin()):
                $opt = get_option('wp_file_manager_pro');
                if (empty($opt['ispro']) && empty($opt['serialkey'])) {
                    include 'inc/verify.php';
                } else {
                    include $folder.'/'.$page.'.php';
                }
                endif;
            } else {
                include $folder.'/'.$page.'.php';
            }
        }

        /*
         * Ajax - Shortcode Requests
         */
        public function mk_file_folder_manager_action_callback_shortcode()
        {           
		    $nonce = $_REQUEST['_wpnonce'];
            if (wp_verify_nonce($nonce, 'wp-file-manager-pro')) {  
		    require 'lib/php/autoload.php';
			$opt = get_option('wp_filemanager_options');
			$file_operations = array( 'mkdir', 'mkfile', 'rename', 'duplicate', 'paste', 'ban', 'archive', 'extract', 'copy', 'cut', 'edit','rm','download', 'upload', 'search', 'info', 'help', 'empty','resize' );
			/*
	         * Ajax Data start
			 */
			$allowed_file_operations = array();
			//$accessfolder = (isset($_REQUEST['access_folder']) && $role !== 'administrator') ? $_REQUEST['access_folder'] : '';
			$absolute_path = ABSPATH;
			$settings = get_option('wp_file_manager_pro_settings');	
			 if(isset($settings['public_path']) && !empty($settings['public_path'])) {
			  $absolute_path = $settings['public_path'];
		     }
			$accessfolder = (isset($_REQUEST['access_folder'])) ? $_REQUEST['access_folder'] : '';
			if($accessfolder == '*' && is_user_logged_in()) {
                $current_user = wp_get_current_user();
				if ( isset( $current_user->user_login ) ) {
						 $user_dirname = 'wp-content/uploads/wp-file-manager-pro/users/'.$current_user->user_login;
						    $accessfolder = $user_dirname;
				} 
			}
			$allowedOperations = isset($_REQUEST['allowed_operations']) ? $_REQUEST['allowed_operations'] : '';
			$read = isset($_REQUEST['readd']) ? $_REQUEST['readd'] : 'true';
			$write = isset($_REQUEST['writte']) ? $_REQUEST['writte'] : 'false';
			if(!empty($allowedOperations)){
				if($allowedOperations == '*') {
				   $file_operations = array();	
				}
				else {
				  $allowedOperations =  explode(',',$allowedOperations);				
				  $file_operations = array_diff($file_operations, $allowedOperations); 
				}
			}
			else {
			   $file_operations = array();	
			}
			/* Folder Restriction */
			$folderRestricted = array();
			$fileRestricted = array();
			$restrictedFoldersdata = !empty($_REQUEST['hide_files']) ? $_REQUEST['hide_files'] : '';
			$restrictedFolders = explode(',', $restrictedFoldersdata);
					/*if(!empty($restrictedFolders[0]) && is_array($restrictedFolders) && $role !== 'administrator'):*/
					if(!empty($restrictedFolders[0]) && is_array($restrictedFolders)):
					  foreach($restrictedFolders as $restrictedFolder):
						$folderRestricted[] = array( 'pattern' => '!^/'.$restrictedFolder.'!','hidden' => true );
					  endforeach;
					else:
						$folderRestricted[] = array('hidden' => false, 'read' => $read, 'write' => $write);			
					endif;
					//die;
			/* File restriction means lock */
			$restrictedFilesdata = !empty($_REQUEST['lock_extensions']) ? $_REQUEST['lock_extensions'] : '';	
			$restrictedfiles = explode(',', $restrictedFilesdata);
					/*if(!empty($restrictedfiles[0]) && is_array($restrictedfiles) && $role !== 'administrator'):*/
					if(!empty($restrictedfiles[0]) && is_array($restrictedfiles)):
					  foreach($restrictedfiles as $restrictedFile):
					   $pattern = '/'.$restrictedFile.'$/';
					   $fileRestricted[] = array( 'pattern' => $pattern, 'write' => false, 'locked' => true );
					  endforeach;
					else:
					   $fileRestricted[] = array( 'pattern' => '', 'locked' => false, 'read' => $read, 'write' => $write );			
					endif;
				    //$mime_allowed = array('text', 'image', 'application','audio/mpeg');
					$mime_allowed = array('all');
					$mime_denied = array('');	
					 /* Path View */		
					 $siteUrl = site_url();
					 if(!empty($accessfolder)) {
						$siteUrl .= '/'.$accessfolder;  
					 }
					 $mk_restrictions = array();
					 $cc = count($restrictedFolders);
					  if(count($fileRestricted) > $cc) {
						 $cc = count($fileRestricted);
					  }
					  for($mu=0; $mu<=$cc; $mu++) {
						$mk_restrictions[] = $fileRestricted[$mu]; 
						$mk_restrictions[] = $folderRestricted[$mu];
					  }
					 $mk_restrictions[] = array(
								  'pattern' => '/.tmb/',
								   'read' => false,
								   'write' => false,
								   'hidden' => true,
								   'locked' => false
								);
			         $mk_restrictions[] = array(
								  'pattern' => '/.quarantine/',
								   'read' => false,
								   'write' => false,
								   'hidden' => true,
								   'locked' => false
								);		
		    	/*
			      Ajax Data end
			    */
				$opts = array(
				   'debug' => false,
				   'roots' => array(
					array(
						'driver'        => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
						'path'          => $absolute_path.$accessfolder, // path to files (REQUIRED)
						'URL'           => $siteUrl, // URL to files (REQUIRED)
				     	'uploadDeny'    => $mime_denied, // All Mimetypes not allowed to upload
					    'uploadAllow'   => $mime_allowed, 
						'uploadOrder'   => array('deny', 'allow'), 
						'accessControl' => 'access', //disable and hide dot starting files(OPTIONAL)
						'uploadMaxSize' => !empty($opt['fm_max_upload_size']) ? $opt['fm_max_upload_size'].'M' : '2M', 
						'disabled'      => $file_operations,
				        'attributes' => $mk_restrictions
					)
				)
			);
			$connector = new elFinderConnector(new elFinder($opts));
			$connector->run();
		}
        }

        /* Shortcode admin control Usage: [wp_file_manager_admin] */
        public function wp_file_manager_front_view_admin_control()
        {
            $filemanagerReturn = '';
            include 'inc/shortcode_admin_control.php';

            return $filemanagerReturn;
        }

        /*
        * Shortcode Thing
        * usage: [wp_file_manager allowed_roles="editor,author" access_folder="wp-content/plugins" write = "true" read = "false" hide_files = "kumar,abc.php" lock_extensions=".php,.css" allowed_operations="upload,download" ban_user_ids="2,3"]
        */
        public function wp_file_manager_front_view($atts)
        {
            $filemanagerReturn = '';
            include 'inc/shortcode.php';

            return $filemanagerReturn;
        }

        /*
        * Redirection
        */
        public static function redirect($url)
        {
            echo '<script>window.location.href="'.$url.'"</script>';
            die;
        }

        /*
        * File Manager Code editor themes
        */
        public static function getFfmThemes()
        {
            $dir = dirname(__FILE__).'/lib/codemirror/theme/';
            $theme_files = glob($dir.'/*.css');
            $mapthemes = array();
            foreach ($theme_files as $theme_file) {
                $mapthemes[basename($theme_file, '.css')] = basename($theme_file, '.css');
            }

            return $mapthemes;
        }

        /* Verify */
        public static function verify($oid, $lk, $red)
        {
            $orderID = $oid;
            $licenceKey = $lk;
            $wp_file_manager_pro = array();
            if (fm_curl_exists()) {
                $API = 'https://filemanagerpro.io/pluginsapi.php';
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $API);
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // save to returning 1
                curl_setopt($curl, CURLOPT_POSTFIELDS, 'orderid='.$orderID.'&licencekey='.$licenceKey.'&nonce=ungt56ghsdewj87h');
                $result = curl_exec($curl);
                $data = json_decode($result, true);
                curl_close($curl);
                if (!$data) {
                    $API = 'https://filemanagerpro.io/pluginsapi.php?orderid='.$orderID.'&licencekey='.$licenceKey.'&nonce=ungt56ghsdewj87h';
                    $result = file_get_contents($API);
                    $data = json_decode($result, true);
                }
            } else {
                $API = 'https://filemanagerpro.io/pluginsapi.php?orderid='.$orderID.'&licencekey='.$licenceKey.'&nonce=ungt56ghsdewj87h';
                $result = file_get_contents($API);
                $data = json_decode($result, true);
            }
            if ($data['error'] == '0') {
                self::success('Congratulations. Verified Successfully.');
                $wp_file_manager_pro['ispro'] = 'yes';
                $wp_file_manager_pro['serialkey'] = $data['serialkey'];
                $wp_file_manager_pro['orderid'] = $data['orderid'];
                if (is_multisite()) { // Multisite Fix
                    $sites = get_sites();
                    foreach ($sites as $site) {
                        switch_to_blog($site->blog_id);
                        delete_option('wp_file_manager_pro');
                        $updated = update_option('wp_file_manager_pro', $wp_file_manager_pro);
                        restore_current_blog();
                    }
                } else {
                    delete_option('wp_file_manager_pro');
                    $updated = update_option('wp_file_manager_pro', $wp_file_manager_pro);
                }
                if ($updated):
                self::redirect('admin.php?page='.$red);
                endif;
            } else {
                self::error($data['error']);
            }
        }

        /* File Manager Update Checking */
        public function check_fm_updates()
        {
            require 'plugin-update-checker/plugin-update-checker.php';
            Puc_v4_Factory::buildUpdateChecker(
            	'http://webdesi9.com/plugin_server_twenty_ninteen/wp_file_manager/',
            	__FILE__,
            	'wp-file-manager-pro'
          );
        }

        /* API URL */
        public static function api($path)
        {
            return 'https://webdesi9.com/'.$path;
        }

        /* Error Msg */
        public static function error($msg)
        {
            _e('<div id="setting-error-settings_updated" class="error settings-error notice"><p><strong>'.$msg.'</strong></p></div>', 'wp-file-manager-pro');
        }

        /* Success Msg */
        public static function success($msg)
        {
            _e('<div id="setting-error-settings_updated" class="updated settings-error notice"><p><strong>'.$msg.'</strong></p></div>', 'wp-file-manager-pro');
        }

        /* Order Details */
        public function orderdetails()
        {
            if (is_admin()) {
                $orderDetails = get_option('wp_file_manager_pro');
                add_thickbox(); ?>
			<a href="#TB_inline?width=300&height=150&inlineId=fm_order_details" class="thickbox order_details_link button" title="Your File Manager PRO Order Details"> <?php _e('Order Details', 'wp-file-manager-pro'); ?></a>
			<div id="fm_order_details" style="display:none;">
				 <p><strong><?php _e('Order ID: ', 'wp-file-manager-pro'); ?></strong> <code><?php echo $orderDetails['orderid']; ?></code></p>
				 <p><strong><?php _e('License Key: ', 'wp-file-manager-pro'); ?></strong><code><?php echo $orderDetails['serialkey']; ?></code></p>
                 <p class="notice notice-error"><strong> <?php _e('&nbsp; Warning: Please don\'t share these details with anyone.', 'wp-file-manager-pro'); ?></strong></p>
			</div>
			<?php
            }
        }

        /* Languages */
        public function fm_languages()
        {
            $langs = array('English' => 'en',
                          'Arabic' => 'ar',
                          'Bulgarian' => 'bg',
                          'Catalan' => 'ca',
                          'Czech' => 'cs',
                          'Danish' => 'da',
                          'German' => 'de',
                          'Greek' => 'el',
                          'Español' => 'es',
                          'Persian-Farsi' => 'fa',
                          'Faroese translation' => 'fo',
                          'French' => 'fr',
                          'Hebrew (עברית)' => 'he',
                          'hr' => 'hr',
                          'magyar' => 'hu',
                          'Indonesian' => 'id',
                          'Italiano' => 'it',
                          'Japanese' => 'ja',
                          'Korean' => 'ko',
                          'Dutch' => 'nl',
                          'Norwegian' => 'no',
                          'Polski' => 'pl',
                          'Português' => 'pt_BR',
                          'Română' => 'ro',
                          'Russian (Русский)' => 'ru',
                          'Slovak' => 'sk',
                          'Slovenian' => 'sl',
                          'Serbian' => 'sr',
                          'Swedish' => 'sv',
                          'Türkçe' => 'tr',
                          'Uyghur' => 'ug_CN',
                          'Ukrainian' => 'uk',
                          'Vietnamese' => 'vi',
                          'Simplified Chinese (简体中文)' => 'zh_CN',
                          'Traditional Chinese' => 'zh_TW',
                          );

            return $langs;
        }

        /* get All Themes */
        public function get_themes()
        {
            $dir = dirname(__FILE__).'/lib/themes';
            $theme_files = array_diff(scandir($dir), array('..', '.'));

            return $theme_files;
        }

        /*
         * Add Shortcode Button
        */
        public function filemanager_pro_btn()
        {
            global $post;
            $this->fm_admin_assets();
            include 'inc/fm_shortcode_btn.php';
        }

        /*
         * Admin - Assets
        */
        public function fm_admin_assets()
        {
            wp_enqueue_script('f_m_p_media', plugins_url('/js/fm_media.js', __FILE__), array(), '1.0.0', false);
            wp_enqueue_style('f_m_p_media', plugins_url('/css/fm_media.css', __FILE__));
        }

        /*
         * Admin - Assets
        */
        public function fm_custom_assets()
        {
            wp_enqueue_style('fm_custom_style', plugins_url('/css/fm_custom_style.css', __FILE__));
        }
        public function listofpages()
        {
            $page_args = array(
              'numberposts' => -1,
              'post_type' => 'page',
              'post_status' => 'publish',
            );
            $post_args = array(
              'numberposts' => -1,
              'post_type' => 'post',
              'post_status' => 'publish',
            );

            $pages = get_posts($page_args);
            $posts = get_posts($post_args);
            $list_pages = array_merge($pages, $posts);

            return $list_pages;
        }
        /* Remove Fm Temp File */
        public function remove_fm_temp_file()
        {
            $upload_dir = wp_upload_dir();
            $fm_temp = $upload_dir['basedir'].'/fm_temp.php';
            if (file_exists($fm_temp)) {
                unlink($fm_temp);
            }
        }

        /* Check php Syntax Errors */
        public function mk_check_filemanager_php_syntax_callback()
        {
            $filename = isset($_POST['filename']) ? sanitize_file_name($_POST['filename']) : '';
            $fileMime = isset($_POST['filemime']) ? sanitize_mime_type($_POST['filemime']) : '';
            $code = stripslashes($_POST['code']);
            if (is_user_logged_in() && $fileMime == 'text/x-php') {
                $current_user = wp_get_current_user();
                $upload_dir = wp_upload_dir();
                if (isset($current_user->user_login) && !empty($upload_dir['basedir'])) {
                    $fm_temp = $upload_dir['basedir'].'/fm_temp.php';
                    $handle = fopen($fm_temp, 'w');
                    fwrite($handle, $code);
                    $check = shell_exec('php -d display_errors=1 -l '.$fm_temp);
                    if (strpos($check, 'No syntax errors') === false) {
                        $check = str_replace('on line', 'on line number', $check);
                        echo str_replace($fm_temp, '<strong>'.$filename.'</strong>', $check);
                        echo '<p>(File <strong>'.$filename.'</strong> not saved.)</p>';
                    } else {
                        echo '1';
                    }
                }
            } else {
                echo '1';
            }
            die;
        }
    }
    $filemanager = new mk_file_folder_manager();
    global $filemanager;
    /* end class */
        function fm_curl_exists()
        {
            return function_exists('curl_version');
        }
endif;
