static function check_user_exists($username)
 {
     global $wpdb;
     //if username is empty just return false
     if ($username == '') {
         return false;
     }
     //If multisite
     if (AIOWPSecurity_Utility::is_multisite_install()) {
         $blog_id = get_current_blog_id();
         $admin_users = get_users('blog_id=' . $blog_id . 'orderby=login&role=administrator');
         $acct_name_exists = false;
         foreach ($admin_users as $user) {
             if ($user->user_login == $username) {
                 $acct_name_exists = true;
                 break;
             }
         }
         return $acct_name_exists;
     }
     //check users table
     $user = $wpdb->get_var("SELECT user_login FROM `" . $wpdb->users . "` WHERE user_login='******';");
     $userid = $wpdb->get_var("SELECT ID FROM `" . $wpdb->users . "` WHERE ID='" . sanitize_text_field($username) . "';");
     if ($user == $username || $userid == $username) {
         return true;
     } else {
         return false;
     }
 }
 function prepare_items()
 {
     //First, lets decide how many records per page to show
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     //$this->process_bulk_action();
     global $wpdb;
     global $aio_wp_security;
     $logged_in_users = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('users_online') : get_transient('users_online');
     if ($logged_in_users !== FALSE) {
         foreach ($logged_in_users as $key => $val) {
             $userdata = get_userdata($val['user_id']);
             $username = $userdata->user_login;
             $val['username'] = $username;
             $logged_in_users[$key] = $val;
         }
     } else {
         $logged_in_users = array();
         //If no transient found set to empty array
     }
     $data = $logged_in_users;
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 function aiowps_validate_registration_with_captcha($errors, $sanitized_user_login, $user_email)
 {
     global $aio_wp_security;
     $locked = $aio_wp_security->user_login_obj->check_locked_user();
     if ($locked == null) {
         //user is not locked continue
     } else {
         $errors->add('authentication_failed', __('<strong>ERROR</strong>: You are not allowed to register because your IP address is currently locked!', 'all-in-one-wp-security-and-firewall'));
         return $errors;
     }
     if (array_key_exists('aiowps-captcha-answer', $_POST)) {
         isset($_POST['aiowps-captcha-answer']) ? $captcha_answer = strip_tags(trim($_POST['aiowps-captcha-answer'])) : ($captcha_answer = '');
         $captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
         $submitted_encoded_string = base64_encode($_POST['aiowps-captcha-temp-string'] . $captcha_secret_string . $captcha_answer);
         $trans_handle = sanitize_text_field($_POST['aiowps-captcha-string-info']);
         $captcha_string_info_trans = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('aiowps_captcha_string_info_' . $trans_handle) : get_transient('aiowps_captcha_string_info_' . $trans_handle);
         if ($submitted_encoded_string !== $captcha_string_info_trans) {
             //This means a wrong answer was entered
             //return new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Your answer was incorrect - please try again.', 'all-in-one-wp-security-and-firewall'));
             $errors->add('authentication_failed', __('<strong>ERROR</strong>: Your answer was incorrect - please try again.', 'all-in-one-wp-security-and-firewall'));
             return $errors;
         }
     }
     return $errors;
 }
 function prepare_items()
 {
     //First, lets decide how many records per page to show
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     //$this->process_bulk_action();
     global $wpdb;
     global $aio_wp_security;
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     $orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'user_id';
     $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : 'DESC';
     $logged_in_users = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('users_online') : get_transient('users_online');
     foreach ($logged_in_users as $key => $val) {
         $userdata = get_userdata($val['user_id']);
         $username = $userdata->user_login;
         $val['username'] = $username;
         $logged_in_users[$key] = $val;
     }
     $data = $logged_in_users;
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 function generate_maths_question()
 {
     global $aio_wp_security;
     //For now we will only do plus, minus, multiplication
     $equation_string = '';
     $operator_type = array('&#43;', '&#8722;', '&#215;');
     $operand_display = array('word', 'number');
     //let's now generate an equation
     $operator = $operator_type[rand(0, 2)];
     if ($operator === '&#215;') {
         //Don't make the question too hard if multiplication
         $first_digit = rand(1, 5);
         $second_digit = rand(1, 5);
     } else {
         $first_digit = rand(1, 20);
         $second_digit = rand(1, 20);
     }
     if ($operand_display[rand(0, 1)] == 'word') {
         $first_operand = $this->number_word_mapping($first_digit);
     } else {
         $first_operand = $first_digit;
     }
     if ($operand_display[rand(0, 1)] == 'word') {
         $second_operand = $this->number_word_mapping($second_digit);
     } else {
         $second_operand = $second_digit;
     }
     //Let's caluclate the result and construct the equation string
     if ($operator === '&#43;') {
         //Addition
         $result = $first_digit + $second_digit;
         $equation_string .= $first_operand . ' ' . $operator . ' ' . $second_operand . ' = ';
     } else {
         if ($operator === '&#8722;') {
             //Subtraction
             //If we are going to be negative let's swap operands around
             if ($first_digit < $second_digit) {
                 $equation_string .= $second_operand . ' ' . $operator . ' ' . $first_operand . ' = ';
                 $result = $second_digit - $first_digit;
             } else {
                 $equation_string .= $first_operand . ' ' . $operator . ' ' . $second_operand . ' = ';
                 $result = $first_digit - $second_digit;
             }
         } elseif ($operator === '&#215;') {
             //Multiplication
             $equation_string .= $first_operand . ' ' . $operator . ' ' . $second_operand . ' = ';
             $result = $first_digit * $second_digit;
         }
     }
     //Let's encode correct answer
     $captcha_secret_string = $aio_wp_security->configs->get_value('aiowps_captcha_secret_key');
     $current_time = time();
     $enc_result = base64_encode($current_time . $captcha_secret_string . $result);
     $random_str = AIOWPSecurity_Utility::generate_alpha_numeric_random_string(10);
     AIOWPSecurity_Utility::is_multisite_install() ? set_site_transient('aiowps_captcha_string_info_' . $random_str, $enc_result, 30 * 60) : set_transient('aiowps_captcha_string_info_' . $random_str, $enc_result, 30 * 60);
     $equation_string .= '<input type="hidden" name="aiowps-captcha-string-info" id="aiowps-captcha-string-info" value="' . $random_str . '" />';
     $equation_string .= '<input type="hidden" name="aiowps-captcha-temp-string" id="aiowps-captcha-temp-string" value="' . $current_time . '" />';
     $equation_string .= '<input type="text" size="2" id="aiowps-captcha-answer" name="aiowps-captcha-answer" value="" />';
     return $equation_string;
 }
 function get_bulk_actions()
 {
     if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
         //Suppress the block link if site is a multi site AND not the main site
         $actions = array();
         //blank array
     } else {
         $actions = array('block' => 'Block');
     }
     return $actions;
 }
 function prepare_items()
 {
     /**
      * First, lets decide how many records per page to show
      */
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     $this->process_bulk_action();
     global $wpdb;
     $failed_logins_table_name = AIOWPSEC_TBL_FAILED_LOGINS;
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
     isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
     $orderby = !empty($orderby) ? esc_sql($orderby) : 'failed_login_date';
     $order = !empty($order) ? esc_sql($order) : 'DESC';
     $orderby = AIOWPSecurity_Utility::sanitize_value_by_array($orderby, $sortable);
     $order = AIOWPSecurity_Utility::sanitize_value_by_array($order, array('DESC' => '1', 'ASC' => '1'));
     $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$failed_logins_table_name} WHERE id > %d ORDER BY {$orderby} {$order}", -1), ARRAY_A);
     //Note: had to deliberately introduce WHERE clause because you need at least 2 arguments in prepare statement. Cannot use order/orderby
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
    function render_tab1()
    {
        echo '<div class="aio_grey_box">';
        echo '<p>' . __('For information, updates and documentation, please visit the', 'aiowpsecurity') . ' <a href="https://www.tipsandtricks-hq.com/wordpress-security-and-firewall-plugin" target="_blank">' . __('AIO WP Security & Firewall Plugin', 'aiowpsecurity') . '</a> ' . __('Page', 'aiowpsecurity') . '</p>';
        echo '<p><a href="https://www.tipsandtricks-hq.com/development-center" target="_blank">' . __('Follow us', 'aiowpsecurity') . '</a> on ' . __('Twitter, Google+ or via Email to stay up to date about the new security features of this plugin.', 'aiowpsecurity') . '</p>';
        echo '</div>';
        echo "<script type='text/javascript' src='https://www.google.com/jsapi'></script>";
        //Include the google chart library
        global $aiowps_feature_mgr;
        global $aio_wp_security;
        $feature_mgr = $aiowps_feature_mgr;
        $total_site_security_points = $feature_mgr->get_total_site_points();
        $total_security_points_achievable = $feature_mgr->get_total_achievable_points();
        ?>
        <div id="aiowps_dashboard_widget_content">
            
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Security Strength Meter', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">

        <script type='text/javascript'>
          google.load('visualization', '1', {packages:['gauge']});
          google.setOnLoadCallback(drawChart);
          function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Label', 'Value'],
              ['Strength', <?php 
        echo $total_site_security_points;
        ?>
]
            ]);

            var options = {
              width: 320, height: 200, max: <?php 
        echo $total_security_points_achievable;
        ?>
,
              greenColor: '8EFA9B', yellowColor: 'F5EE90', redColor: 'FA7373',
              redFrom: 0, redTo: 10,
              yellowFrom:10, yellowTo: 50,
              greenFrom:50, greenTo: <?php 
        echo $total_security_points_achievable;
        ?>
,
              minorTicks: 5
            };

            var chart = new google.visualization.Gauge(document.getElementById('security_strength_chart_div'));
            chart.draw(data, options);
          }
        </script>
        <div id='security_strength_chart_div'></div>

        <div class="aiowps_dashboard_widget_footer">
        <?php 
        _e('Total Achievable Points: ', 'aiowpsecurity');
        echo '<strong>' . $total_security_points_achievable . '</strong><br />';
        _e('Current Score of Your Site: ', 'aiowpsecurity');
        echo '<strong>' . $total_site_security_points . '</strong>';
        ?>
        </div>
        
        </div></div>
        </div><!-- aiowps_dashboard_box -->
        
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Security Points Breakdown', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">
        
        <?php 
        $feature_items = $feature_mgr->feature_items;
        $pt_src_chart_data = "";
        $pt_src_chart_data .= "['Feature Name', 'Points'],";
        foreach ($feature_items as $item) {
            if ($item->feature_status == $feature_mgr->feature_active) {
                $pt_src_chart_data .= "['" . $item->feature_name . "', " . $item->item_points . "],";
            }
        }
        ?>
        <script type="text/javascript">
              google.load("visualization", "1", {packages:["corechart"]});
              google.setOnLoadCallback(drawChart);
              function drawChart() {
                var data = google.visualization.arrayToDataTable([
                  <?php 
        echo $pt_src_chart_data;
        ?>
                ]);

                var options = {
                  height: '250',
                  width: '320',
                  backgroundColor: 'F6F6F6'
                };

                var chart = new google.visualization.PieChart(document.getElementById('points_source_breakdown_chart_div'));
                chart.draw(data, options);
              }
        </script>
        <div id='points_source_breakdown_chart_div'></div>

        </div></div>
        </div><!-- aiowps_dashboard_box -->
        
        <div class="aiowps_dashboard_box_small aiowps_spread_the_word_widget">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Spread the Word', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">
        
        <p><?php 
        _e('We are working hard to make your WordPress site more secure. Please support us, here is how:', 'aiowpsecurity');
        ?>
</p>
        <p>
            <a href="https://plus.google.com/+Tipsandtricks-hq/" target="_blank">Follow us on Google+</a>
        </p>
        <p>
            <a href="http://twitter.com/intent/tweet?url=https://www.tipsandtricks-hq.com/wordpress-security-and-firewall-plugin&text=I love the All In One WP Security and Firewall plugin!" target="_blank" class="aio_tweet_link">Post to Twitter</a>
        </p>
        <p>
            <a href="http://wordpress.org/support/view/plugin-reviews/all-in-one-wp-security-and-firewall/" target="_blank" class="aio_rate_us_link">Give us a Good Rating</a>
        </p>
        
        </div></div>
        </div><!-- aiowps_dashboard_box -->   
        
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Critical Feature Status', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">

        <?php 
        _e('Below is the current status of the critical features that you should activate on your site to achieve a minimum level of recommended security', 'aiowpsecurity');
        $feature_items = $feature_mgr->feature_items;
        $username_admin_feature = $feature_mgr->get_feature_item_by_id("user-accounts-change-admin-user");
        echo '<div class="aiowps_feature_status_container">';
        echo '<div class="aiowps_feature_status_name">' . __('Admin Username', 'aiowpsecurity') . '</div>';
        echo '<a href="admin.php?page=' . AIOWPSEC_USER_ACCOUNTS_MENU_SLUG . '">';
        echo '<div class="aiowps_feature_status_bar">';
        if ($username_admin_feature->feature_status == $feature_mgr->feature_active) {
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_on">On</div>';
            echo '<div class="aiowps_feature_status_label">Off</div>';
        } else {
            echo '<div class="aiowps_feature_status_label">On</div>';
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_off">Off</div>';
        }
        echo '</div></div></a>';
        echo '<div class="aio_clear_float"></div>';
        $login_lockdown_feature = $feature_mgr->get_feature_item_by_id("user-login-login-lockdown");
        echo '<div class="aiowps_feature_status_container">';
        echo '<div class="aiowps_feature_status_name">' . __('Login Lockdown', 'aiowpsecurity') . '</div>';
        echo '<a href="admin.php?page=' . AIOWPSEC_USER_LOGIN_MENU_SLUG . '">';
        echo '<div class="aiowps_feature_status_bar">';
        if ($login_lockdown_feature->feature_status == $feature_mgr->feature_active) {
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_on">On</div>';
            echo '<div class="aiowps_feature_status_label">Off</div>';
        } else {
            echo '<div class="aiowps_feature_status_label">On</div>';
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_off">Off</div>';
        }
        echo '</div></div></a>';
        echo '<div class="aio_clear_float"></div>';
        $filesystem_feature = $feature_mgr->get_feature_item_by_id("filesystem-file-permissions");
        echo '<div class="aiowps_feature_status_container">';
        echo '<div class="aiowps_feature_status_name">' . __('File Permission', 'aiowpsecurity') . '</div>';
        echo '<a href="admin.php?page=' . AIOWPSEC_FILESYSTEM_MENU_SLUG . '">';
        echo '<div class="aiowps_feature_status_bar">';
        if ($filesystem_feature->feature_status == $feature_mgr->feature_active) {
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_on">On</div>';
            echo '<div class="aiowps_feature_status_label">Off</div>';
        } else {
            echo '<div class="aiowps_feature_status_label">On</div>';
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_off">Off</div>';
        }
        echo '</div></div></a>';
        echo '<div class="aio_clear_float"></div>';
        $basic_firewall_feature = $feature_mgr->get_feature_item_by_id("firewall-basic-rules");
        echo '<div class="aiowps_feature_status_container">';
        echo '<div class="aiowps_feature_status_name">' . __('Basic Firewall', 'aiowpsecurity') . '</div>';
        echo '<a href="admin.php?page=' . AIOWPSEC_FIREWALL_MENU_SLUG . '">';
        echo '<div class="aiowps_feature_status_bar">';
        if ($basic_firewall_feature->feature_status == $feature_mgr->feature_active) {
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_on">On</div>';
            echo '<div class="aiowps_feature_status_label">Off</div>';
        } else {
            echo '<div class="aiowps_feature_status_label">On</div>';
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_off">Off</div>';
        }
        echo '</div></div></a>';
        echo '<div class="aio_clear_float"></div>';
        ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->        

        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Last 5 Logins', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">        
        <?php 
        global $wpdb;
        $login_activity_table = AIOWPSEC_TBL_USER_LOGIN_ACTIVITY;
        /* -- Ordering parameters -- */
        //Parameters that are going to be used to order the result
        isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
        isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
        $orderby = !empty($orderby) ? $orderby : 'login_date';
        $order = !empty($order) ? $order : 'DESC';
        $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$login_activity_table} ORDER BY login_date DESC LIMIT %d", 5), ARRAY_A);
        //Get the last 5 records
        if ($data == NULL) {
            echo '<p>' . __('No data found!', 'aiowpsecurity') . '</p>';
        } else {
            $login_summary_table = '';
            echo '<p>' . __('Last 5 logins summary:', 'aiowpsecurity') . '</p>';
            $login_summary_table .= '<table class="widefat">';
            $login_summary_table .= '<thead>';
            $login_summary_table .= '<tr>';
            $login_summary_table .= '<th>' . __('User', 'aiowpsecurity') . '</th>';
            $login_summary_table .= '<th>' . __('Date', 'aiowpsecurity') . '</th>';
            $login_summary_table .= '<th>' . __('IP', 'aiowpsecurity') . '</th>';
            $login_summary_table .= '</tr>';
            $login_summary_table .= '</thead>';
            foreach ($data as $entry) {
                $login_summary_table .= '<tr>';
                $login_summary_table .= '<td>' . $entry['user_login'] . '</td>';
                $login_summary_table .= '<td>' . $entry['login_date'] . '</td>';
                $login_summary_table .= '<td>' . $entry['login_ip'] . '</td>';
                $login_summary_table .= '</tr>';
            }
            $login_summary_table .= '</table>';
            echo $login_summary_table;
        }
        echo '<div class="aio_clear_float"></div>';
        ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->
        
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Maintenance Mode Status', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">        
        <?php 
        if ($aio_wp_security->configs->get_value('aiowps_site_lockout') == '1') {
            echo '<p>' . __('Maintenance mode is currently enabled. Remember to turn it off when you are done', 'aiowpsecurity') . '</p>';
        } else {
            echo '<p>' . __('Maintenance mode is currently off.', 'aiowpsecurity') . '</p>';
        }
        echo '<div class="aiowps_feature_status_container">';
        echo '<div class="aiowps_feature_status_name">' . __('Maintenance Mode', 'aiowpsecurity') . '</div>';
        echo '<a href="admin.php?page=' . AIOWPSEC_MAINTENANCE_MENU_SLUG . '">';
        echo '<div class="aiowps_feature_status_bar">';
        if ($aio_wp_security->configs->get_value('aiowps_site_lockout') == '1') {
            //Maintenance mode is enabled
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_off">On</div>';
            //If enabled show red by usign the "off" class
            echo '<div class="aiowps_feature_status_label">Off</div>';
        } else {
            echo '<div class="aiowps_feature_status_label">On</div>';
            echo '<div class="aiowps_feature_status_label aiowps_feature_status_on">Off</div>';
        }
        echo '</div></div></a>';
        echo '<div class="aio_clear_float"></div>';
        ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->

        <?php 
        //Insert Cookie Based Brute Force feature box if this feature is active
        if ($aio_wp_security->configs->get_value('aiowps_enable_brute_force_attack_prevention') == '1') {
            ?>
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
            _e('Cookie Based Brute Prevention', 'aiowpsecurity');
            ?>
</label></h3>
        <div class="inside">        
        <?php 
            $brute_force_login_feature_link = '<a href="admin.php?page=' . AIOWPSEC_BRUTE_FORCE_MENU_SLUG . '&tab=tab2" target="_blank">' . __('Cookie-Based Brute Force', 'aiowpsecurity') . '</a>';
            $brute_force_feature_secret_word = $aio_wp_security->configs->get_value('aiowps_brute_force_secret_word');
            echo '<div class="aio_yellow_box">';
            echo '<p>' . sprintf(__('The %s feature is currently active.', 'aiowpsecurity'), $brute_force_login_feature_link) . '</p>';
            echo '<p>' . __('Your new WordPress login URL is now:', 'aiowpsecurity') . '</p>';
            echo '<p><strong>' . AIOWPSEC_WP_URL . '/?' . $brute_force_feature_secret_word . '=1</strong></p>';
            echo '</div>';
            //yellow box div
            echo '<div class="aio_clear_float"></div>';
            ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->
        <?php 
        }
        //End if statement for Cookie Based Brute Prevention box
        //Insert Rename Login Page feature box if this feature is active
        if ($aio_wp_security->configs->get_value('aiowps_enable_rename_login_page') == '1') {
            ?>
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
            _e('Rename Login Page', 'aiowpsecurity');
            ?>
</label></h3>
        <div class="inside">        
        <?php 
            if (get_option('permalink_structure')) {
                $home_url = trailingslashit(home_url());
            } else {
                $home_url = trailingslashit(home_url()) . '?';
            }
            $rename_login_feature_link = '<a href="admin.php?page=' . AIOWPSEC_BRUTE_FORCE_MENU_SLUG . '&tab=tab1" target="_blank">' . __('Rename Login Page', 'aiowpsecurity') . '</a>';
            echo '<div class="aio_yellow_box">';
            echo '<p>' . sprintf(__('The %s feature is currently active.', 'aiowpsecurity'), $rename_login_feature_link) . '</p>';
            echo '<p>' . __('Your new WordPress login URL is now:', 'aiowpsecurity') . '</p>';
            echo '<p><strong>' . $home_url . $aio_wp_security->configs->get_value('aiowps_login_page_slug') . '</strong></p>';
            echo '</div>';
            //yellow box div
            echo '<div class="aio_clear_float"></div>';
            ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->
        <?php 
        }
        //End if statement for Rename Login box
        if ($aio_wp_security->configs->get_value('aiowps_enable_automated_fcd_scan') == '1') {
            echo '<div class="aiowps_dashboard_box_small">';
            echo '<div class="postbox">';
            echo '<h3><label for="title">File Change Detection</label></h3>';
            echo '<div class="inside">';
            if ($aio_wp_security->configs->get_value('aiowps_fcds_change_detected')) {
                echo '<div class="aio_red_box aio_padding_10">File change detected!</div>';
                echo '<p>Please review the changes from the <a href="admin.php?page=' . AIOWPSEC_FILESCAN_MENU_SLUG . '">scanner menu</a></p>';
            } else {
                echo '<div class="aio_green_box aio_padding_10">No recent file changes detected.</div>';
            }
            echo '</div></div>';
            echo '</div>';
            //<!-- aiowps_dashboard_box -->
        }
        //End if statement for automated scan box
        ?>
        
        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Logged In Users', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">        
        <?php 
        $users_online_link = '<a href="admin.php?page=' . AIOWPSEC_USER_LOGIN_MENU_SLUG . '&tab=tab5">Logged In Users</a>';
        if (AIOWPSecurity_Utility::is_multisite_install()) {
            $logged_in_users = get_site_transient('users_online');
            $num_users = count($logged_in_users);
            if ($num_users > 1) {
                echo '<div class="aio_red_box"><p>' . __('Number of users currently logged in site-wide is:', 'aiowpsecurity') . ' <strong>' . $num_users . '</strong></p>';
                $info_msg = '<p>' . sprintf(__('Go to the %s menu to see more details', 'aiowpsecurity'), $users_online_link) . '</p>';
                echo $info_msg . '</div>';
            } else {
                echo '<div class="aio_green_box"><p>' . __('There are no other site-wide users currently logged in.', 'aiowpsecurity') . '</p></div>';
            }
        } else {
            $logged_in_users = get_transient('users_online');
            if ($logged_in_users === false || $logged_in_users == NULL) {
                $num_users = 0;
            } else {
                $num_users = count($logged_in_users);
            }
            if ($num_users > 1) {
                echo '<div class="aio_red_box"><p>' . __('Number of users currently logged into your site (including you) is:', 'aiowpsecurity') . ' <strong>' . $num_users . '</strong></p>';
                $info_msg = '<p>' . sprintf(__('Go to the %s menu to see more details', 'aiowpsecurity'), $users_online_link) . '</p>';
                echo $info_msg . '</div>';
            } else {
                echo '<div class="aio_green_box"><p>' . __('There are no other users currently logged in.', 'aiowpsecurity') . '</p></div>';
            }
        }
        ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->

        <div class="aiowps_dashboard_box_small">
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Locked IP Addresses', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">        
        <?php 
        $locked_ips_link = '<a href="admin.php?page=' . AIOWPSEC_MAIN_MENU_SLUG . '&tab=tab3">Locked IP Addresses</a>';
        $locked_ips = AIOWPSecurity_Utility::get_locked_ips();
        if ($locked_ips === FALSE) {
            echo '<div class="aio_green_box"><p>' . __('There are no IP addresses currently locked out.', 'aiowpsecurity') . '</p></div>';
        } else {
            $num_ips = count($locked_ips);
            echo '<div class="aio_red_box"><p>' . __('Number of temporarily locked out IP addresses: ', 'aiowpsecurity') . ' <strong>' . $num_ips . '</strong></p>';
            $info_msg = '<p>' . sprintf(__('Go to the %s menu to see more details', 'aiowpsecurity'), $locked_ips_link) . '</p>';
            echo $info_msg . '</div>';
        }
        ?>
        </div></div>
        </div><!-- aiowps_dashboard_box -->        

        <div class="aio_clear_float"></div>
        
        </div>
<!-- Masonry stuff -->
<?php 
        //wp_enqueue_script('masonry');
        echo '<script type="text/javascript" src="' . AIO_WP_SECURITY_URL . '/js/masonry.pkgd.min.js?ver=' . AIO_WP_SECURITY_VERSION . '"></script>';
        ?>
<style>
.aiowps_dashboard_box_small { 
    width: 350px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var container = document.querySelector('#aiowps_dashboard_widget_content');
var msnry = new Masonry( container, {
  // options
  columnWidth: 100,
  itemSelector: '.aiowps_dashboard_box_small'
});
}
</script>
<!-- End Masonry stuff -->
        
        <?php 
    }
    function render_tab2()
    {
        global $aio_wp_security;
        global $aiowps_feature_mgr;
        if (isset($_POST['aiowpsec_save_registration_captcha_settings'])) {
            $error = '';
            $nonce = $_REQUEST['_wpnonce'];
            if (!wp_verify_nonce($nonce, 'aiowpsec-registration-captcha-settings-nonce')) {
                $aio_wp_security->debug_logger->log_debug("Nonce check failed on registration captcha settings save!", 4);
                die("Nonce check failed on registration captcha settings save!");
            }
            //Save all the form values to the options
            $random_20_digit_string = AIOWPSecurity_Utility::generate_alpha_numeric_random_string(20);
            //Generate random 20 char string for use during captcha encode/decode
            $aio_wp_security->configs->set_value('aiowps_captcha_secret_key', $random_20_digit_string);
            $aio_wp_security->configs->set_value('aiowps_enable_registration_page_captcha', isset($_POST["aiowps_enable_registration_page_captcha"]) ? '1' : '');
            $aio_wp_security->configs->save_config();
            //Recalculate points after the feature status/options have been altered
            $aiowps_feature_mgr->check_feature_status_and_recalculate_points();
            $this->show_msg_settings_updated();
        }
        ?>
        <div class="aio_blue_box">
            <?php 
        echo '<p>' . __('This feature allows you to add a captcha form on the WordPress registration page.', 'all-in-one-wp-security-and-firewall') . '
            <br />' . __('Users who attempt to register will also need to enter the answer to a simple mathematical question - if they enter the wrong answer, the plugin will not allow them to register.', 'all-in-one-wp-security-and-firewall') . '
            <br />' . __('Therefore, adding a captcha form on the registration page is another effective yet simple SPAM registration prevention technique.', 'all-in-one-wp-security-and-firewall') . '
            </p>';
        ?>
        </div>
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Registration Page Captcha Settings', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
        <?php 
        if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
            //Hide config settings if MS and not main site
            $special_msg = '<div class="aio_yellow_box">';
            $special_msg .= '<p>' . __('The core default behaviour for WordPress Multi Site regarding user registration is that all users are registered via the main site.', 'all-in-one-wp-security-and-firewall') . '</p>';
            $special_msg .= '<p>' . __('Therefore, if you would like to add a captcha form to the registration page for a Multi Site, please go to "Registration Captcha" settings on the main site.', 'all-in-one-wp-security-and-firewall') . '</p>';
            $special_msg .= '</div>';
            echo $special_msg;
        } else {
            //Display security info badge
            global $aiowps_feature_mgr;
            $aiowps_feature_mgr->output_feature_details_badge("user-registration-captcha");
            ?>

            <form action="" method="POST">
        <?php 
            wp_nonce_field('aiowpsec-registration-captcha-settings-nonce');
            ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php 
            _e('Enable Captcha On Registration Page', 'all-in-one-wp-security-and-firewall');
            ?>
:</th>
                    <td>
                    <input name="aiowps_enable_registration_page_captcha" type="checkbox"<?php 
            if ($aio_wp_security->configs->get_value('aiowps_enable_registration_page_captcha') == '1') {
                echo ' checked="checked"';
            }
            ?>
 value="1"/>
                    <span class="description"><?php 
            _e('Check this if you want to insert a captcha form on the WordPress user registration page (if you allow user registration).', 'all-in-one-wp-security-and-firewall');
            ?>
</span>
                    </td>
                </tr>            
            </table>
            <input type="submit" name="aiowpsec_save_registration_captcha_settings" value="<?php 
            _e('Save Settings', 'all-in-one-wp-security-and-firewall');
            ?>
" class="button-primary" />
            </form>
            </div></div>        
        <?php 
        }
    }
 static function add_option_values()
 {
     global $aio_wp_security;
     $blog_email_address = get_bloginfo('admin_email');
     //Get the blog admin email address - we will use as the default value
     //WP Generator Meta Tag feature
     $aio_wp_security->configs->add_value('aiowps_remove_wp_generator_meta_info', '');
     //Checkbox
     //Prevent Image Hotlinks
     $aio_wp_security->configs->add_value('aiowps_prevent_hotlinking', '');
     //Checkbox
     //General Settings Page
     //User password feature
     //Lockdown feature
     $aio_wp_security->configs->add_value('aiowps_enable_login_lockdown', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_allow_unlock_requests', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_max_login_attempts', '3');
     $aio_wp_security->configs->add_value('aiowps_retry_time_period', '5');
     $aio_wp_security->configs->add_value('aiowps_lockout_time_length', '60');
     $aio_wp_security->configs->add_value('aiowps_set_generic_login_msg', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_email_notify', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_email_address', $blog_email_address);
     //text field
     $aio_wp_security->configs->add_value('aiowps_enable_forced_logout', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_logout_time_period', '60');
     $aio_wp_security->configs->add_value('aiowps_enable_invalid_username_lockdown', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_unlock_request_secret_key', AIOWPSecurity_Utility::generate_alpha_numeric_random_string(20));
     //Hidden secret value which will be used to do some unlock request processing. This will be assigned a random string generated when lockdown settings saved
     //Login Whitelist feature
     $aio_wp_security->configs->add_value('aiowps_enable_whitelisting', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_allowed_ip_addresses', '');
     //Captcha feature
     $aio_wp_security->configs->add_value('aiowps_enable_login_captcha', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_captcha_secret_key', AIOWPSecurity_Utility::generate_alpha_numeric_random_string(20));
     //Hidden secret value which will be used to do some captcha processing. This will be assigned a random string generated when captcha settings saved
     //User registration
     $aio_wp_security->configs->add_value('aiowps_enable_manual_registration_approval', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_registration_page_captcha', '');
     //Checkbox
     //DB Security feature
     //$aio_wp_security->configs->add_value('aiowps_new_manual_db_pefix',''); //text field
     $aio_wp_security->configs->add_value('aiowps_enable_random_prefix', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_automated_backups', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_db_backup_frequency', '4');
     $aio_wp_security->configs->add_value('aiowps_db_backup_interval', '2');
     //Dropdown box where (0,1,2) => (hours,days,weeks)
     $aio_wp_security->configs->add_value('aiowps_backup_files_stored', '2');
     $aio_wp_security->configs->add_value('aiowps_send_backup_email_address', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_backup_email_address', $blog_email_address);
     //Filesystem Security feature
     $aio_wp_security->configs->add_value('aiowps_disable_file_editing', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_prevent_default_wp_file_access', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_system_log_file', 'error_log');
     //Blacklist feature
     $aio_wp_security->configs->add_value('aiowps_enable_blacklisting', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_banned_ip_addresses', '');
     //Firewall features
     $aio_wp_security->configs->add_value('aiowps_enable_basic_firewall', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_pingback_firewall', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_disable_index_views', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_disable_trace_and_track', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_forbid_proxy_comments', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_deny_bad_query_strings', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_advanced_char_string_filter', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_5g_firewall', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_brute_force_attack_prevention', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_brute_force_secret_word', '');
     $aio_wp_security->configs->add_value('aiowps_cookie_based_brute_force_redirect_url', 'http://127.0.0.1');
     $aio_wp_security->configs->add_value('aiowps_brute_force_attack_prevention_pw_protected_exception', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_brute_force_attack_prevention_ajax_exception', '');
     //Checkbox
     //404 detection
     $aio_wp_security->configs->add_value('aiowps_enable_404_logging', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_404_IP_lockout', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_404_lockout_time_length', '60');
     $aio_wp_security->configs->add_value('aiowps_404_lock_redirect_url', 'http://127.0.0.1');
     //Brute Force features
     $aio_wp_security->configs->add_value('aiowps_enable_rename_login_page', '');
     //Checkbox
     //Maintenance menu - Visitor lockout feature
     $aio_wp_security->configs->add_value('aiowps_site_lockout', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_site_lockout_msg', '');
     //Text area/msg box
     //SPAM Prevention menu
     $aio_wp_security->configs->add_value('aiowps_enable_spambot_blocking', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_enable_comment_captcha', '');
     //Checkbox
     //Filescan features
     //File change detection feature
     $aio_wp_security->configs->add_value('aiowps_enable_automated_fcd_scan', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_fcd_scan_frequency', '4');
     $aio_wp_security->configs->add_value('aiowps_fcd_scan_interval', '2');
     //Dropdown box where (0,1,2) => (hours,days,weeks)
     $aio_wp_security->configs->add_value('aiowps_fcd_exclude_filetypes', '');
     $aio_wp_security->configs->add_value('aiowps_fcd_exclude_files', '');
     $aio_wp_security->configs->add_value('aiowps_send_fcd_scan_email', '');
     //Checkbox
     $aio_wp_security->configs->add_value('aiowps_fcd_scan_email_address', $blog_email_address);
     $aio_wp_security->configs->add_value('aiowps_fcds_change_detected', FALSE);
     //used to display a global alert on site when file change detected
     //TODO - keep adding default options for any fields that require it
     //Save it
     $aio_wp_security->configs->save_config();
 }
 function do_additional_plugins_loaded_tasks()
 {
     if (isset($_GET['aiowpsec_do_log_out'])) {
         wp_logout();
         if (isset($_GET['after_logout'])) {
             $after_logout_url = esc_url($_GET['after_logout']);
             AIOWPSecurity_Utility::redirect_to_url($after_logout_url);
         }
         if (isset($_GET['al_additional_data'])) {
             $payload = strip_tags($_GET['al_additional_data']);
             $decoded_payload = base64_decode($payload);
             parse_str($decoded_payload);
             if (!empty($redirect_to)) {
                 $login_url = AIOWPSecurity_Utility::add_query_data_to_url(wp_login_url(), 'redirect_to', $redirect_to);
             }
             if (!empty($msg)) {
                 $login_url .= '&' . $msg;
             }
             if (!empty($login_url)) {
                 AIOWPSecurity_Utility::redirect_to_url($login_url);
             }
         }
     }
 }
    function render_tab5()
    {
        $logged_in_users = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('users_online') : get_transient('users_online');
        global $aio_wp_security;
        include_once 'wp-security-list-logged-in-users.php';
        //For rendering the AIOWPSecurity_List_Table
        $user_list = new AIOWPSecurity_List_Logged_In_Users();
        if (isset($_REQUEST['action'])) {
            if ($_REQUEST['action'] == 'force_user_logout') {
                //Force Logout link was clicked for a row in list table
                $user_list->force_user_logout(strip_tags($_REQUEST['logged_in_id']), strip_tags($_REQUEST['ip_address']));
            }
        }
        if (isset($_POST['aiowps_refresh_logged_in_user_list'])) {
            $nonce = $_REQUEST['_wpnonce'];
            if (!wp_verify_nonce($nonce, 'aiowpsec-logged-in-users-nonce')) {
                $aio_wp_security->debug_logger->log_debug("Nonce check failed for users logged in list!", 4);
                die(__('Nonce check failed for users logged in list!', 'all-in-one-wp-security-and-firewall'));
            }
            $user_list->prepare_items();
        }
        ?>
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Refresh Logged In User Data', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
        <form action="" method="POST">
        <?php 
        wp_nonce_field('aiowpsec-logged-in-users-nonce');
        ?>
        <input type="submit" name="aiowps_refresh_logged_in_user_list" value="<?php 
        _e('Refresh Data', 'all-in-one-wp-security-and-firewall');
        ?>
" class="button-primary" />
        </form>
        </div></div>
        
        <div class="aio_blue_box">
            <?php 
        echo '<p>' . __('This tab displays all users who are currently logged into your site.', 'all-in-one-wp-security-and-firewall') . '
                <br />' . __('If you suspect there is a user or users who are logged in which should not be, you can block them by inspecting the IP addresses from the data below and adding them to your blacklist.', 'all-in-one-wp-security-and-firewall') . '
                <br />' . __('You can also instantly log them out by clicking on the "Force Logout" link when you hover over the row in the User Id column.', 'all-in-one-wp-security-and-firewall') . '
            </p>';
        ?>
        </div>
        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Currently Logged In Users', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
            <?php 
        //Fetch, prepare, sort, and filter our data...
        $user_list->prepare_items();
        //echo "put table of locked entries here";
        ?>
            <form id="tables-filter" method="get" onSubmit="return confirm('Are you sure you want to perform this bulk operation on the selected entries?');">
            <!-- For plugins, we also need to ensure that the form posts back to our current page -->
            <input type="hidden" name="page" value="<?php 
        echo esc_attr($_REQUEST['page']);
        ?>
" />
            <input type="hidden" name="tab" value="<?php 
        echo esc_attr($_REQUEST['tab']);
        ?>
" />
            <!-- Now we can render the completed list table -->
            <?php 
        $user_list->display();
        ?>
            </form>
        </div></div>
        <?php 
    }
 function change_db_prefix($table_old_prefix, $table_new_prefix)
 {
     global $wpdb, $aio_wp_security;
     $old_prefix_length = strlen($table_old_prefix);
     $error = 0;
     //Config file path
     $config_file = AIOWPSecurity_Utility_File::get_wp_config_file_path();
     //Get the table resource
     //$result = mysql_list_tables(DB_NAME);
     $result = $this->get_mysql_tables(DB_NAME);
     //Fix for deprecated php mysql_list_tables function
     //Count the number of tables
     if (is_array($result) && count($result) > 0) {
         $num_rows = count($result);
     } else {
         echo '<div class="aio_red_box"><p>' . __('Error - Could not get tables or no tables found!', 'all-in-one-wp-security-and-firewall') . '</p></div>';
         return;
     }
     $table_count = 0;
     $info_msg_string = '<p class="aio_info_with_icon">' . __('Starting DB prefix change operations.....', 'all-in-one-wp-security-and-firewall') . '</p>';
     $info_msg_string .= '<p class="aio_info_with_icon">' . sprintf(__('Your WordPress system has a total of %s tables and your new DB prefix will be: %s', 'all-in-one-wp-security-and-firewall'), '<strong>' . $num_rows . '</strong>', '<strong>' . $table_new_prefix . '</strong>') . '</p>';
     echo $info_msg_string;
     //Do a back of the config file
     if (!AIOWPSecurity_Utility_File::backup_and_rename_wp_config($config_file)) {
         echo '<div class="aio_red_box"><p>' . __('Failed to make a backup of the wp-config.php file. This operation will not go ahead.', 'all-in-one-wp-security-and-firewall') . '</p></div>';
         return;
     } else {
         echo '<p class="aio_success_with_icon">' . __('A backup copy of your wp-config.php file was created successfully!', 'all-in-one-wp-security-and-firewall') . '</p>';
     }
     //Get multisite blog_ids if applicable
     if (AIOWPSecurity_Utility::is_multisite_install()) {
         $blog_ids = AIOWPSecurity_Utility::get_blog_ids();
     }
     //Rename all the table names
     foreach ($result as $db_table) {
         //Get table name with old prefix
         $table_old_name = $db_table;
         if (strpos($table_old_name, $table_old_prefix) === 0) {
             //Get table name with new prefix
             $table_new_name = $table_new_prefix . substr($table_old_name, $old_prefix_length);
             //Write query to rename tables name
             $sql = "RENAME TABLE `" . $table_old_name . "` TO `" . $table_new_name . "`";
             //$sql = "RENAME TABLE %s TO %s";
             //Execute the query
             if (false === $wpdb->query($sql)) {
                 $error = 1;
                 echo '<p class="aio_error_with_icon">' . sprintf(__('%s table name update failed', 'all-in-one-wp-security-and-firewall'), '<strong>' . $table_old_name . '</strong>') . '</p>';
                 $aio_wp_security->debug_logger->log_debug("DB Security Feature - Unable to change prefix of table " . $table_old_name, 4);
             } else {
                 $table_count++;
             }
         } else {
             continue;
         }
     }
     if ($error == 1) {
         echo '<p class="aio_error_with_icon">' . sprintf(__('Please change the prefix manually for the above tables to: %s', 'all-in-one-wp-security-and-firewall'), '<strong>' . $table_new_prefix . '</strong>') . '</p>';
     } else {
         echo '<p class="aio_success_with_icon">' . sprintf(__('%s tables had their prefix updated successfully!', 'all-in-one-wp-security-and-firewall'), '<strong>' . $table_count . '</strong>') . '</p>';
     }
     //Get wp-config.php file contents and modify it with new info
     $config_contents = file($config_file);
     $prefix_match_string = '$table_prefix=';
     //this is our search string for the wp-config.php file
     foreach ($config_contents as $line_num => $line) {
         $no_ws_line = preg_replace('/\\s+/', '', $line);
         //Strip white spaces
         if (strpos($no_ws_line, $prefix_match_string) !== FALSE) {
             $config_contents[$line_num] = str_replace($table_old_prefix, $table_new_prefix, $line);
             break;
         }
     }
     //Now let's modify the wp-config.php file
     if (AIOWPSecurity_Utility_File::write_content_to_file($config_file, $config_contents)) {
         echo '<p class="aio_success_with_icon">' . __('wp-config.php file was updated successfully!', 'all-in-one-wp-security-and-firewall') . '</p>';
     } else {
         echo '<p class="aio_error_with_icon">' . sprintf(__('The "wp-config.php" file was not able to be modified. Please modify this file manually using your favourite editor and search 
                 for variable "$table_prefix" and assign the following value to that variable: %s', 'all-in-one-wp-security-and-firewall'), '<strong>' . $table_new_prefix . '</strong>') . '</p>';
         $aio_wp_security->debug_logger->log_debug("DB Security Feature - Unable to modify wp-config.php", 4);
     }
     //Now let's update the options table
     $update_option_table_query = "UPDATE " . $table_new_prefix . "options \r\r\n                                                                  SET option_name = '" . $table_new_prefix . "user_roles' \r\r\n                                                                  WHERE option_name = '" . $table_old_prefix . "user_roles' \r\r\n                                                                  LIMIT 1";
     if (false === $wpdb->query($update_option_table_query)) {
         echo '<p class="aio_error_with_icon">' . sprintf(__('Update of table %s failed: unable to change %s to %s', 'all-in-one-wp-security-and-firewall'), $table_new_prefix . 'options', $table_old_prefix . 'user_roles', $table_new_prefix . 'user_roles') . '</p>';
         $aio_wp_security->debug_logger->log_debug("DB Security Feature - Error when updating the options table", 4);
         //Log the highly unlikely event of DB error
     } else {
         echo '<p class="aio_success_with_icon">' . sprintf(__('The options table records which had references to the old DB prefix were updated successfully!', 'all-in-one-wp-security-and-firewall')) . '</p>';
     }
     //Now let's update the options tables for the multisite subsites if applicable
     if (AIOWPSecurity_Utility::is_multisite_install()) {
         if (!empty($blog_ids)) {
             foreach ($blog_ids as $blog_id) {
                 if ($blog_id == 1) {
                     continue;
                 }
                 //skip main site
                 $new_pref_and_site_id = $table_new_prefix . $blog_id . '_';
                 $old_pref_and_site_id = $table_old_prefix . $blog_id . '_';
                 $update_ms_option_table_query = "UPDATE " . $new_pref_and_site_id . "options\r\r\n                                                                            SET option_name = '" . $new_pref_and_site_id . "user_roles'\r\r\n                                                                            WHERE option_name = '" . $old_pref_and_site_id . "user_roles'\r\r\n                                                                            LIMIT 1";
                 if (false === $wpdb->query($update_ms_option_table_query)) {
                     echo '<p class="aio_error_with_icon">' . sprintf(__('Update of table %s failed: unable to change %s to %s', 'all-in-one-wp-security-and-firewall'), $new_pref_and_site_id . 'options', $old_pref_and_site_id . 'user_roles', $new_pref_and_site_id . 'user_roles') . '</p>';
                     $aio_wp_security->debug_logger->log_debug("DB change prefix feature - Error when updating the subsite options table: " . $new_pref_and_site_id . 'options', 4);
                     //Log the highly unlikely event of DB error
                 } else {
                     echo '<p class="aio_success_with_icon">' . sprintf(__('The %s table records which had references to the old DB prefix were updated successfully!', 'all-in-one-wp-security-and-firewall'), $new_pref_and_site_id . 'options') . '</p>';
                 }
             }
         }
     }
     //Now let's update the user meta table
     $custom_sql = "SELECT user_id, meta_key \r\r\n                        FROM " . $table_new_prefix . "usermeta \r\r\n                        WHERE meta_key \r\r\n                        LIKE '" . $table_old_prefix . "%'";
     $meta_keys = $wpdb->get_results($custom_sql);
     $error_update_usermeta = '';
     //Update all meta_key field values which have the old table prefix in user_meta table
     foreach ($meta_keys as $meta_key) {
         //Create new meta key
         $new_meta_key = $table_new_prefix . substr($meta_key->meta_key, $old_prefix_length);
         $update_user_meta_sql = "UPDATE " . $table_new_prefix . "usermeta \r\r\n                                                            SET meta_key='" . $new_meta_key . "' \r\r\n                                                            WHERE meta_key='" . $meta_key->meta_key . "'\r\r\n                                                            AND user_id='" . $meta_key->user_id . "'";
         if (false === $wpdb->query($update_user_meta_sql)) {
             $error_update_usermeta .= '<p class="aio_error_with_icon">' . sprintf(__('Error updating user_meta table where new meta_key = %s, old meta_key = %s and user_id = %s.', 'all-in-one-wp-security-and-firewall'), $new_meta_key, $meta_key->meta_key, $meta_key->user_id) . '</p>';
             echo $error_update_usermeta;
             $aio_wp_security->debug_logger->log_debug("DB Security Feature - Error updating user_meta table where new meta_key = " . $new_meta_key . " old meta_key = " . $meta_key->meta_key . " and user_id = " . $meta_key->user_id, 4);
             //Log the highly unlikely event of DB error
         }
     }
     echo '<p class="aio_success_with_icon">' . __('The usermeta table records which had references to the old DB prefix were updated successfully!', 'all-in-one-wp-security-and-firewall') . '</p>';
     //Display tasks finished message
     $tasks_finished_msg_string = '<p class="aio_info_with_icon">' . __('DB prefix change tasks have been completed.', 'all-in-one-wp-security-and-firewall') . '</p>';
     echo $tasks_finished_msg_string;
 }
 function do_additional_plugins_loaded_tasks()
 {
     global $aio_wp_security;
     if (isset($_GET['aiowpsec_do_log_out'])) {
         wp_logout();
         if (isset($_GET['after_logout'])) {
             $after_logout_url = esc_url($_GET['after_logout']);
             AIOWPSecurity_Utility::redirect_to_url($after_logout_url);
         }
         $additional_data = strip_tags($_GET['al_additional_data']);
         if (isset($additional_data)) {
             $login_url = '';
             //Check if rename login feature enabled
             if ($aio_wp_security->configs->get_value('aiowps_enable_rename_login_page') == '1') {
                 if (get_option('permalink_structure')) {
                     $home_url = trailingslashit(home_url());
                 } else {
                     $home_url = trailingslashit(home_url()) . '?';
                 }
                 $login_url = $home_url . $aio_wp_security->configs->get_value('aiowps_login_page_slug');
             } else {
                 $login_url = wp_login_url();
             }
             //Inspect the payload and do redirect to login page with a msg and redirect url
             $logout_payload = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('aiowps_logout_payload') : get_transient('aiowps_logout_payload');
             if (!empty($logout_payload['redirect_to'])) {
                 $login_url = AIOWPSecurity_Utility::add_query_data_to_url($login_url, 'redirect_to', $logout_payload['redirect_to']);
             }
             if (!empty($logout_payload['msg'])) {
                 $login_url .= '&' . $logout_payload['msg'];
             }
             if (!empty($login_url)) {
                 AIOWPSecurity_Utility::redirect_to_url($login_url);
             }
         }
     }
 }
 function validate_change_username_form()
 {
     global $wpdb;
     global $aio_wp_security;
     $errors = '';
     $nonce = $_REQUEST['_wpnonce'];
     if (!wp_verify_nonce($nonce, 'aiowpsec-change-admin-nonce')) {
         $aio_wp_security->debug_logger->log_debug("Nonce check failed on admin username change operation!", 4);
         die(__('Nonce check failed on admin username change operation!', 'aiowpsecurity'));
     }
     if (!empty($_POST['aiowps_new_user_name'])) {
         $new_username = sanitize_text_field($_POST['aiowps_new_user_name']);
         if (validate_username($new_username)) {
             if (AIOWPSecurity_Utility::check_user_exists($new_username)) {
                 $errors .= __('Username ', 'aiowpsecurity') . $new_username . __(' already exists. Please enter another value. ', 'aiowpsecurity');
             } else {
                 //let's check if currently logged in username is 'admin'
                 global $user_login;
                 get_currentuserinfo();
                 if (strtolower($user_login) == 'admin') {
                     $username_is_admin = TRUE;
                 } else {
                     $username_is_admin = FALSE;
                 }
                 //Now let's change the username
                 $result = $wpdb->query("UPDATE `" . $wpdb->users . "` SET user_login = '******' WHERE user_login='******';");
                 if (!$result) {
                     //There was an error updating the users table
                     $user_update_error = __('The database update operation of the user account failed!', 'aiowpsecurity');
                     //TODO## - add error logging here
                     $return_msg = '<div id="message" class="updated fade"><p>' . $user_update_error . '</p></div>';
                     return $return_msg;
                 }
                 //multisite considerations
                 if (AIOWPSecurity_Utility::is_multisite_install()) {
                     //process sitemeta if we're in a multi-site situation
                     $oldAdmins = $wpdb->get_var("SELECT meta_value FROM `" . $wpdb->sitemeta . "` WHERE meta_key = 'site_admins'");
                     $newAdmins = str_replace('5:"admin"', strlen($new_username) . ':"' . esc_sql($new_username) . '"', $oldAdmins);
                     $wpdb->query("UPDATE `" . $wpdb->sitemeta . "` SET meta_value = '" . esc_sql($newAdmins) . "' WHERE meta_key = 'site_admins'");
                 }
                 //If user is logged in with username "admin" then log user out and send to login page so they can login again
                 if ($username_is_admin) {
                     //Lets logout the user
                     $aio_wp_security->debug_logger->log_debug("Logging User Out with login " . $user_login . " because they changed their username.");
                     $after_logout_url = AIOWPSecurity_Utility::get_current_page_url();
                     $after_logout_payload = 'redirect_to=' . $after_logout_url . '&msg=' . $aio_wp_security->user_login_obj->key_login_msg . '=admin_user_changed';
                     //Place the handle for the login screen message in the URL
                     $encrypted_payload = base64_encode($after_logout_payload);
                     $logout_url = AIOWPSEC_WP_URL . '?aiowpsec_do_log_out=1';
                     $logout_url = AIOWPSecurity_Utility::add_query_data_to_url($logout_url, 'al_additional_data', $encrypted_payload);
                     AIOWPSecurity_Utility::redirect_to_url($logout_url);
                 }
             }
         } else {
             //An invalid username was entered
             $errors .= __('You entered an invalid username. Please enter another value. ', 'aiowpsecurity');
         }
     } else {
         //No username value was entered
         $errors .= __('Please enter a value for your username. ', 'aiowpsecurity');
     }
     if (strlen($errors) > 0) {
         //We have some validation or other error
         $return_msg = '<div id="message" class="error"><p>' . $errors . '</p></div>';
     } else {
         $return_msg = '<div id="message" class="updated fade"><p>' . __('Username Successfully Changed!', 'aiowpsecurity') . '</p></div>';
     }
     return $return_msg;
 }
    function render_tab2()
    {
        global $aio_wp_security;
        global $aiowps_feature_mgr;
        if (isset($_POST['aiowps_disable_file_edit'])) {
            $nonce = $_REQUEST['_wpnonce'];
            if (!wp_verify_nonce($nonce, 'aiowpsec-disable-file-edit-nonce')) {
                $aio_wp_security->debug_logger->log_debug("Nonce check failed on disable PHP file edit options save!", 4);
                die("Nonce check failed on disable PHP file edit options save!");
            }
            if (isset($_POST['aiowps_disable_file_editing'])) {
                $res = AIOWPSecurity_Utility::disable_file_edits();
                //$this->disable_file_edits();
            } else {
                $res = AIOWPSecurity_Utility::enable_file_edits();
                //$this->enable_file_edits();
            }
            if ($res) {
                //Save settings if no errors
                $aio_wp_security->configs->set_value('aiowps_disable_file_editing', isset($_POST["aiowps_disable_file_editing"]) ? '1' : '');
                $aio_wp_security->configs->save_config();
                //Recalculate points after the feature status/options have been altered
                $aiowps_feature_mgr->check_feature_status_and_recalculate_points();
                $this->show_msg_updated(__('Your PHP file editing settings were saved successfully.', 'aiowpsecurity'));
            } else {
                $this->show_msg_error(__('Operation failed! Unable to modify or make a backup of wp-config.php file!', 'aiowpsecurity'));
            }
            //$this->show_msg_settings_updated();
        }
        ?>
        <h2><?php 
        _e('File Editing', 'aiowpsecurity');
        ?>
</h2>
        <div class="aio_blue_box">
            <?php 
        echo '<p>' . __('The Wordpress Dashboard by default allows administrators to edit PHP files, such as plugin and theme files.', 'aiowpsecurity') . '
            <br />' . __('This is often the first tool an attacker will use if able to login, since it allows code execution.', 'aiowpsecurity') . '
            <br />' . __('This feature will disable the ability for people to edit PHP files via the dashboard.', 'aiowpsecurity') . '    
            </p>';
        ?>
        </div>

        <div class="postbox">
        <h3><label for="title"><?php 
        _e('Disable PHP File Editing', 'aiowpsecurity');
        ?>
</label></h3>
        <div class="inside">
        <?php 
        //Display security info badge
        global $aiowps_feature_mgr;
        $aiowps_feature_mgr->output_feature_details_badge("filesystem-file-editing");
        ?>

        <form action="" method="POST">
        <?php 
        wp_nonce_field('aiowpsec-disable-file-edit-nonce');
        ?>
            
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><?php 
        _e('Disable Ability To Edit PHP Files', 'aiowpsecurity');
        ?>
:</th>                
                <td>
                <input name="aiowps_disable_file_editing" type="checkbox"<?php 
        if ($aio_wp_security->configs->get_value('aiowps_disable_file_editing') == '1') {
            echo ' checked="checked"';
        }
        ?>
 value="1"/>
                <span class="description"><?php 
        _e('Check this if you want to remove the ability for people to edit PHP files via the WP dashboard', 'aiowpsecurity');
        ?>
</span>
                </td>
            </tr>            
        </table>
        <input type="submit" name="aiowps_disable_file_edit" value="<?php 
        _e('Save Settings', 'aiowpsecurity');
        ?>
" class="button-primary" />
        </form>
        </div></div>
    <?php 
    }
    function render_tab3()
    {
        global $aio_wp_security;
        global $aiowps_feature_mgr;
        if (isset($_POST['aiowpsec_save_captcha_settings'])) {
            $error = '';
            $nonce = $_REQUEST['_wpnonce'];
            if (!wp_verify_nonce($nonce, 'aiowpsec-captcha-settings-nonce')) {
                $aio_wp_security->debug_logger->log_debug("Nonce check failed on captcha settings save!", 4);
                die("Nonce check failed on captcha settings save!");
            }
            //Save all the form values to the options
            $random_20_digit_string = AIOWPSecurity_Utility::generate_alpha_numeric_random_string(20);
            //Generate random 20 char string for use during captcha encode/decode
            $aio_wp_security->configs->set_value('aiowps_captcha_secret_key', $random_20_digit_string);
            $aio_wp_security->configs->set_value('aiowps_enable_login_captcha', isset($_POST["aiowps_enable_login_captcha"]) ? '1' : '');
            $aio_wp_security->configs->set_value('aiowps_enable_custom_login_captcha', isset($_POST["aiowps_enable_custom_login_captcha"]) ? '1' : '');
            $aio_wp_security->configs->set_value('aiowps_enable_lost_password_captcha', isset($_POST["aiowps_enable_lost_password_captcha"]) ? '1' : '');
            $aio_wp_security->configs->save_config();
            //Recalculate points after the feature status/options have been altered
            $aiowps_feature_mgr->check_feature_status_and_recalculate_points();
            $this->show_msg_settings_updated();
        }
        ?>
        <div class="aio_blue_box">
            <?php 
        echo '<p>' . __('This feature allows you to add a captcha form on the WordPress login page.', 'all-in-one-wp-security-and-firewall') . '
            <br />' . __('Users who attempt to login will also need to enter the answer to a simple mathematical question - if they enter the wrong answer, the plugin will not allow them login even if they entered the correct username and password.', 'all-in-one-wp-security-and-firewall') . '
                <br />' . __('Therefore, adding a captcha form on the login page is another effective yet simple "Brute Force" prevention technique.', 'all-in-one-wp-security-and-firewall') . '
            </p>';
        ?>
        </div>
        <form action="" method="POST">
        <div class="postbox">
        <h3 class="hndle"><label for="title"><?php 
        _e('Login Form Captcha Settings', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
        <?php 
        //Display security info badge
        global $aiowps_feature_mgr;
        $aiowps_feature_mgr->output_feature_details_badge("user-login-captcha");
        ?>

        <?php 
        wp_nonce_field('aiowpsec-captcha-settings-nonce');
        ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><?php 
        _e('Enable Captcha On Login Page', 'all-in-one-wp-security-and-firewall');
        ?>
:</th>
                <td>
                <input name="aiowps_enable_login_captcha" type="checkbox"<?php 
        if ($aio_wp_security->configs->get_value('aiowps_enable_login_captcha') == '1') {
            echo ' checked="checked"';
        }
        ?>
 value="1"/>
                <span class="description"><?php 
        _e('Check this if you want to insert a captcha form on the login page', 'all-in-one-wp-security-and-firewall');
        ?>
</span>
                </td>
            </tr>            
        </table>
        </div></div>        
        <div class="postbox">
        <h3 class="hndle"><label for="title"><?php 
        _e('Custom Login Form Captcha Settings', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
        <?php 
        //Display security info badge
        global $aiowps_feature_mgr;
        $aiowps_feature_mgr->output_feature_details_badge("custom-login-captcha");
        ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><?php 
        _e('Enable Captcha On Custom Login Form', 'all-in-one-wp-security-and-firewall');
        ?>
:</th>
                <td>
                <input name="aiowps_enable_custom_login_captcha" type="checkbox"<?php 
        if ($aio_wp_security->configs->get_value('aiowps_enable_custom_login_captcha') == '1') {
            echo ' checked="checked"';
        }
        ?>
 value="1"/>
                <span class="description"><?php 
        _e('Check this if you want to insert captcha on a custom login form generated by the following WP function: wp_login_form()', 'all-in-one-wp-security-and-firewall');
        ?>
</span>
                </td>
            </tr>            
        </table>
        </div></div>        
        <div class="postbox">
        <h3 class="hndle"><label for="title"><?php 
        _e('Lost Password Form Captcha Settings', 'all-in-one-wp-security-and-firewall');
        ?>
</label></h3>
        <div class="inside">
        <?php 
        //Display security info badge
        global $aiowps_feature_mgr;
        $aiowps_feature_mgr->output_feature_details_badge("lost-password-captcha");
        ?>

        <table class="form-table">
            <tr valign="top">
                <th scope="row"><?php 
        _e('Enable Captcha On Lost Password Page', 'all-in-one-wp-security-and-firewall');
        ?>
:</th>
                <td>
                <input name="aiowps_enable_lost_password_captcha" type="checkbox"<?php 
        if ($aio_wp_security->configs->get_value('aiowps_enable_lost_password_captcha') == '1') {
            echo ' checked="checked"';
        }
        ?>
 value="1"/>
                <span class="description"><?php 
        _e('Check this if you want to insert a captcha form on the lost password page', 'all-in-one-wp-security-and-firewall');
        ?>
</span>
                </td>
            </tr>            
        </table>
        </div></div>        
        <input type="submit" name="aiowpsec_save_captcha_settings" value="<?php 
        _e('Save Settings', 'all-in-one-wp-security-and-firewall');
        ?>
" class="button-primary" />
        </form>
        <?php 
    }
 /**
  * This function will perform a database backup
  */
 function execute_backup()
 {
     global $wpdb, $aio_wp_security;
     $is_multi_site = false;
     @ini_set('auto_detect_line_endings', true);
     if (function_exists('is_multisite') && is_multisite()) {
         //Let's get the current site's table prefix
         $site_pref = esc_sql($wpdb->prefix);
         $db_query = "SHOW TABLES LIKE '" . $site_pref . "%'";
         $tables = $wpdb->get_results($db_query, ARRAY_N);
         $is_multi_site = true;
     } else {
         //get all of the tables
         $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
     }
     $return = '';
     //cycle through each table
     foreach ($tables as $table) {
         $result = $wpdb->get_results('SELECT * FROM `' . $table[0] . '`;', ARRAY_N);
         $num_fields = sizeof($wpdb->get_results('DESCRIBE `' . $table[0] . '`;'));
         $return .= 'DROP TABLE IF EXISTS `' . $table[0] . '`;';
         $row2 = $wpdb->get_row('SHOW CREATE TABLE `' . $table[0] . '`;', ARRAY_N);
         $return .= PHP_EOL . PHP_EOL . $row2[1] . ";" . PHP_EOL . PHP_EOL;
         foreach ($result as $row) {
             $return .= 'INSERT INTO `' . $table[0] . '` VALUES(';
             for ($j = 0; $j < $num_fields; $j++) {
                 $row[$j] = addslashes($row[$j]);
                 //$row[$j] = ereg_replace( PHP_EOL, "\n", $row[$j] ); //deprecated!
                 $row[$j] = preg_replace("/" . PHP_EOL . "/", "\n", $row[$j]);
                 if (isset($row[$j])) {
                     $return .= '"' . $row[$j] . '"';
                 } else {
                     $return .= '""';
                 }
                 if ($j < $num_fields - 1) {
                     $return .= ',';
                 }
             }
             $return .= ");" . PHP_EOL;
         }
         $return .= PHP_EOL . PHP_EOL;
     }
     $return .= PHP_EOL . PHP_EOL;
     //Check to see if the main "backups" directory exists - create it otherwise
     $aiowps_backup_dir = WP_CONTENT_DIR . '/' . AIO_WP_SECURITY_BACKUPS_DIR_NAME;
     $aiowps_backup_url = content_url() . '/' . AIO_WP_SECURITY_BACKUPS_DIR_NAME;
     if (!AIOWPSecurity_Utility_File::create_dir($aiowps_backup_dir)) {
         $aio_wp_security->debug_logger->log_debug("Creation of DB backup directory failed!", 4);
         return false;
     }
     //Generate a random prefix for more secure filenames
     $random_prefix = $random_prefix = AIOWPSecurity_Utility::generate_alpha_numeric_random_string(14);
     if ($is_multi_site) {
         global $current_blog;
         $blog_id = $current_blog->blog_id;
         //Get the current site name string for use later
         $site_name = get_bloginfo('name');
         $site_name = strtolower($site_name);
         //make alphaunermic
         $site_name = preg_replace("/[^a-z0-9_\\s-]/", "", $site_name);
         //Cleanup multiple instances of dashes or whitespaces
         $site_name = preg_replace("/[\\s-]+/", " ", $site_name);
         //Convert whitespaces and underscore to dash
         $site_name = preg_replace("/[\\s_]/", "-", $site_name);
         $file = $random_prefix . '-database-backup-site-name-' . $site_name . '-' . current_time('timestamp');
         //We will create a sub dir for the blog using its blog id
         $dirpath = $aiowps_backup_dir . '/blogid_' . $blog_id . '/';
         //Create a subdirectory for this blog_id
         if (!AIOWPSecurity_Utility_File::create_dir($dirpath)) {
             $aio_wp_security->debug_logger->log_debug("Creation failed of DB backup directory for the following multisite blog ID: " . $blog_details->blog_id, 4);
             return false;
         }
         $fileName = $dirpath . '/' . $file . '.sql';
         $handle = @fopen($fileName, 'w+');
     } else {
         $dirpath = $aiowps_backup_dir;
         $file = $random_prefix . '-database-backup-' . current_time('timestamp');
         $fileName = $dirpath . '/' . $file . '.sql';
         $handle = @fopen($fileName, 'w+');
     }
     /*** Try upping the memory limit before gzipping */
     if (function_exists('memory_get_usage') && (int) @ini_get('memory_limit') < 64) {
         @ini_set('memory_limit', '64M');
     }
     if (!file_exists($fileName)) {
         echo "FILE DOES NOT EXISTS";
         exit;
         $handle = @fopen($fileName, 'w+');
     }
     $fw_res = @fwrite($handle, $return);
     if (!$fw_res) {
         return false;
     }
     @fclose($handle);
     //zip the file
     /*if ( class_exists( 'ZipArchive' ) ) 
             {
                 $zip = new ZipArchive();
                 $archive = $zip->open($dirpath . '/' . $file . '.zip', ZipArchive::CREATE);
                 $zip->addFile($dirpath . '/' . $file . '.sql', $file . '.sql' );
                 $zip->close();
     
                 //delete .sql and keep zip
                 @unlink( $dirpath . '/' . $file . '.sql' );
                 $fileext = '.zip';
             } else 
             {
                 $fileext = '.sql';
             }*/
     $fileext = '.sql';
     $this->last_backup_file_name = $file . $fileext;
     //database-backup-1367644822.zip or database-backup-1367644822.sql
     $this->last_backup_file_path = $dirpath . '/' . $file . $fileext;
     if ($is_multi_site) {
         $this->last_backup_file_dir_multisite = $aiowps_backup_dir . '/blogid_' . $blog_id;
     }
     $this->aiowps_send_backup_email();
     //Send backup file via email if applicable
     $this->aiowps_delete_backup_files();
     return true;
 }
 function block_ip($entries, $username = '')
 {
     global $wpdb;
     $events_table = AIOWPSEC_TBL_LOGIN_LOCKDOWN;
     if (is_array($entries)) {
         //lock multiple records
         $ip_list = "(" . implode(",", $entries) . ")";
         //Create comma separate list for DB operation
         //TODO
     } elseif ($entries != NULL) {
         //Block single record
         AIOWPSecurity_Utility::lock_IP($entries, '404', $username);
     }
 }
 function check_404_event()
 {
     if (is_404()) {
         //This means a 404 event has occurred - let's log it!
         AIOWPSecurity_Utility::event_logger('404');
     }
 }
 function prepare_items()
 {
     /**
      * First, lets decide how many records per page to show
      */
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     $this->process_bulk_action();
     global $wpdb;
     $block_table_name = AIOWPSEC_TBL_PERM_BLOCK;
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
     isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
     $orderby = !empty($orderby) ? esc_sql($orderby) : 'id';
     $order = !empty($order) ? esc_sql($order) : 'DESC';
     $orderby = AIOWPSecurity_Utility::sanitize_value_by_array($orderby, $sortable);
     $order = AIOWPSecurity_Utility::sanitize_value_by_array($order, array('DESC' => '1', 'ASC' => '1'));
     if (isset($_POST['s'])) {
         $search_term = trim($_POST['s']);
         $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $block_table_name . " WHERE `blocked_ip` LIKE '%%%s%%' OR `block_reason` LIKE '%%%s%%' OR `country_origin` LIKE '%%%s%%' OR `blocked_date` LIKE '%%%s%%'", $search_term, $search_term, $search_term, $search_term), ARRAY_A);
     } else {
         $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $block_table_name . " WHERE id > %d ORDER BY {$orderby} {$order}", -1), ARRAY_A);
     }
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 function check_user_accounts_display_name_feature($item)
 {
     if (AIOWPSecurity_Utility::check_identical_login_and_nick_names()) {
         $item->set_feature_status($this->feature_inactive);
     } else {
         $item->set_feature_status($this->feature_active);
     }
 }
 static function create_htaccess_logs_dir()
 {
     global $aio_wp_security;
     $aiowps_log_dir = AIO_WP_SECURITY_PATH . '/logs';
     $server_type = AIOWPSecurity_Utility::get_server_type();
     //Only create .htaccess if server is the right type
     if ($server_type == 'apache' || $server_type == 'litespeed') {
         $file = $aiowps_log_dir . '/.htaccess';
         if (!file_exists($file)) {
             //Write some rules which will stop people from viewing the log files publicly
             $rules = '';
             $rules .= 'order deny,allow' . PHP_EOL;
             $rules .= 'deny from all' . PHP_EOL;
             $write_result = file_put_contents($file, $rules);
             if ($write_result === false) {
                 $aio_wp_security->debug_logger->log_debug("Creation of .htaccess file in " . $aiowps_log_dir . " directory failed!", 4);
             }
         }
     }
 }
 function prepare_items()
 {
     /**
      * First, lets decide how many records per page to show
      */
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     $this->process_bulk_action();
     global $wpdb;
     $lockdown_table_name = AIOWPSEC_TBL_LOGIN_LOCKDOWN;
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
     isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
     $orderby = !empty($orderby) ? esc_sql($orderby) : 'lockdown_date';
     $order = !empty($order) ? esc_sql($order) : 'DESC';
     $orderby = AIOWPSecurity_Utility::sanitize_value_by_array($orderby, $sortable);
     $order = AIOWPSecurity_Utility::sanitize_value_by_array($order, array('DESC' => '1', 'ASC' => '1'));
     $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$lockdown_table_name} WHERE (lock_reason=%s OR lock_reason=%s) AND release_date > now() ORDER BY {$orderby} {$order}", 'login_fail', '404'), ARRAY_A);
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 static function getrules_blacklist()
 {
     global $aio_wp_security;
     $aiowps_server = AIOWPSecurity_Utility::get_server_type();
     $rules = '';
     if ($aio_wp_security->configs->get_value('aiowps_enable_blacklisting') == '1') {
         //Let's do the list of blacklisted IPs first
         $hosts = explode(PHP_EOL, $aio_wp_security->configs->get_value('aiowps_banned_ip_addresses'));
         if (!empty($hosts) && !(sizeof($hosts) == 1 && trim($hosts[0]) == '')) {
             if ($aiowps_server == 'apache' || $aiowps_server == 'litespeed') {
                 $rules .= AIOWPSecurity_Utility_Htaccess::$ip_blacklist_marker_start . PHP_EOL;
                 //Add feature marker start
                 $rules .= "Order allow,deny" . PHP_EOL . "Allow from all" . PHP_EOL;
             }
             $phosts = array();
             foreach ($hosts as $host) {
                 $host = trim($host);
                 if (!in_array($host, $phosts)) {
                     if (strstr($host, '*')) {
                         $parts = array_reverse(explode('.', $host));
                         $netmask = 32;
                         foreach ($parts as $part) {
                             if (strstr(trim($part), '*')) {
                                 $netmask = $netmask - 8;
                             }
                         }
                         $dhost = trim(str_replace('*', '0', implode('.', array_reverse($parts))) . '/' . $netmask);
                         if (strlen($dhost) > 4) {
                             if ($aiowps_server == 'apache' || $aiowps_server == 'litespeed') {
                                 $trule = "Deny from " . $dhost . PHP_EOL;
                                 if (trim($trule) != 'Deny From') {
                                     $rules .= $trule;
                                 }
                             } else {
                                 $rules .= "\tdeny " . $dhost . ';' . PHP_EOL;
                             }
                         }
                     } else {
                         $dhost = trim($host);
                         if (strlen($dhost) > 4) {
                             if ($aiowps_server == 'apache' || $aiowps_server == 'litespeed') {
                                 $rules .= "Deny from " . $dhost . PHP_EOL;
                             } else {
                                 $rules .= "\tdeny " . $dhost . ";" . PHP_EOL;
                             }
                         }
                     }
                 }
                 $phosts[] = $host;
             }
             $rules .= AIOWPSecurity_Utility_Htaccess::$ip_blacklist_marker_end . PHP_EOL;
             //Add feature marker end
         }
         //Now let's do the user agent list
         $user_agents = explode(PHP_EOL, $aio_wp_security->configs->get_value('aiowps_banned_user_agents'));
         if (!empty($user_agents) && !(sizeof($user_agents) == 1 && trim($user_agents[0]) == '')) {
             if ($aiowps_server == 'apache' || $aiowps_server == 'litespeed') {
                 $rules .= AIOWPSecurity_Utility_Htaccess::$user_agent_blacklist_marker_start . PHP_EOL;
                 //Add feature marker start
                 //Start mod_rewrite rules
                 $rules .= "<IfModule mod_rewrite.c>" . PHP_EOL . "RewriteEngine On" . PHP_EOL . PHP_EOL;
                 $count = 1;
                 foreach ($user_agents as $agent) {
                     $agent_escaped = quotemeta($agent);
                     $pattern = '/\\s/';
                     //Find spaces in the string
                     $replacement = '\\s';
                     //Replace spaces with \s so apache can understand
                     $agent_sanitized = preg_replace($pattern, $replacement, $agent_escaped);
                     $rules .= "RewriteCond %{HTTP_USER_AGENT} ^" . trim($agent_sanitized);
                     if ($count < sizeof($user_agents)) {
                         $rules .= " [NC,OR]" . PHP_EOL;
                         $count++;
                     } else {
                         $rules .= " [NC]" . PHP_EOL;
                     }
                 }
                 $rules .= "RewriteRule ^(.*)\$ - [F,L]" . PHP_EOL . PHP_EOL;
             } else {
                 $count = 1;
                 $alist = '';
                 foreach ($user_agents as $agent) {
                     $alist .= trim($agent);
                     if ($count < sizeof($user_agents)) {
                         $alist .= '|';
                         $count++;
                     }
                 }
                 $rules .= "\tif (\$http_user_agent ~* " . $alist . ") { return 403; }" . PHP_EOL;
             }
         }
         //close mod_rewrite
         if (strlen($aio_wp_security->configs->get_value('aiowps_banned_user_agents')) > 0) {
             if ($aiowps_server == 'apache' || $aiowps_server == 'litespeed') {
                 $rules .= "</IfModule>" . PHP_EOL;
                 $rules .= AIOWPSecurity_Utility_Htaccess::$user_agent_blacklist_marker_end . PHP_EOL;
                 //Add feature marker end
             }
         }
     }
     return implode(PHP_EOL, array_diff(explode(PHP_EOL, $rules), array('Deny from ', 'Deny from')));
 }
 function aiowps_scheduled_db_cleanup_handler()
 {
     global $aio_wp_security;
     $aio_wp_security->debug_logger->log_debug_cron("DB Cleanup - checking if a cleanup needs to be done now...");
     //Check the events table because this can grow quite large especially when 404 events are being logged
     $events_table_name = AIOWPSEC_TBL_EVENTS;
     $max_rows_event_table = '5000';
     //Keep a max of 5000 rows in the events table
     $max_rows_event_table = apply_filters('aiowps_max_rows_event_table', $max_rows_event_table);
     AIOWPSecurity_Utility::cleanup_table($events_table_name, $max_rows_event_table);
     //Check the failed logins table
     $failed_logins_table_name = AIOWPSEC_TBL_FAILED_LOGINS;
     $max_rows_failed_logins_table = '5000';
     //Keep a max of 5000 rows in the events table
     $max_rows_failed_logins_table = apply_filters('aiowps_max_rows_failed_logins_table', $max_rows_failed_logins_table);
     AIOWPSecurity_Utility::cleanup_table($failed_logins_table_name, $max_rows_failed_logins_table);
     //Check the login activity table
     $login_activity_table_name = AIOWPSEC_TBL_USER_LOGIN_ACTIVITY;
     $max_rows_login_activity_table = '5000';
     //Keep a max of 5000 rows in the events table
     $max_rows_login_activity_table = apply_filters('aiowps_max_rows_login_attempts_table', $max_rows_login_activity_table);
     AIOWPSecurity_Utility::cleanup_table($login_activity_table_name, $max_rows_login_activity_table);
     //Check the global meta table
     $global_meta_table_name = AIOWPSEC_TBL_GLOBAL_META_DATA;
     $max_rows_global_meta_table = '5000';
     //Keep a max of 5000 rows in this table
     $max_rows_global_meta_table = apply_filters('aiowps_max_rows_global_meta_table', $max_rows_global_meta_table);
     AIOWPSecurity_Utility::cleanup_table($global_meta_table_name, $max_rows_global_meta_table);
     //Keep adding other DB cleanup tasks as they arise...
 }
 function create_admin_menus()
 {
     $menu_icon_url = AIO_WP_SECURITY_URL . '/images/plugin-icon.png';
     $this->main_menu_page = add_menu_page(__('WP Security', 'aiowpsecurity'), __('WP Security', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_MAIN_MENU_SLUG, array(&$this, 'handle_dashboard_menu_rendering'), $menu_icon_url);
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Dashboard', 'aiowpsecurity'), __('Dashboard', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_MAIN_MENU_SLUG, array(&$this, 'handle_dashboard_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Settings', 'aiowpsecurity'), __('Settings', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_SETTINGS_MENU_SLUG, array(&$this, 'handle_settings_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('User Accounts', 'aiowpsecurity'), __('User Accounts', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_USER_ACCOUNTS_MENU_SLUG, array(&$this, 'handle_user_accounts_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('User Login', 'aiowpsecurity'), __('User Login', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_USER_LOGIN_MENU_SLUG, array(&$this, 'handle_user_login_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('User Registration', 'aiowpsecurity'), __('User Registration', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_USER_REGISTRATION_MENU_SLUG, array(&$this, 'handle_user_registration_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Database Security', 'aiowpsecurity'), __('Database Security', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_DB_SEC_MENU_SLUG, array(&$this, 'handle_database_menu_rendering'));
     if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
         //Suppress the Filesystem Security menu if site is a multi site AND not the main site
     } else {
         add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Filesystem Security', 'aiowpsecurity'), __('Filesystem Security', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_FILESYSTEM_MENU_SLUG, array(&$this, 'handle_filesystem_menu_rendering'));
     }
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('WHOIS Lookup', 'aiowpsecurity'), __('WHOIS Lookup', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_WHOIS_MENU_SLUG, array(&$this, 'handle_whois_menu_rendering'));
     if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
         //Suppress the Blacklist Manager menu if site is a multi site AND not the main site
     } else {
         add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Blacklist Manager', 'aiowpsecurity'), __('Blacklist Manager', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_BLACKLIST_MENU_SLUG, array(&$this, 'handle_blacklist_menu_rendering'));
     }
     if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
         //Suppress the firewall menu if site is a multi site AND not the main site
     } else {
         add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Firewall', 'aiowpsecurity'), __('Firewall', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_FIREWALL_MENU_SLUG, array(&$this, 'handle_firewall_menu_rendering'));
     }
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Brute Force', 'aiowpsecurity'), __('Brute Force', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_BRUTE_FORCE_MENU_SLUG, array(&$this, 'handle_brute_force_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('SPAM Prevention', 'aiowpsecurity'), __('SPAM Prevention', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_SPAM_MENU_SLUG, array(&$this, 'handle_spam_menu_rendering'));
     if (AIOWPSecurity_Utility::is_multisite_install() && get_current_blog_id() != 1) {
         //Suppress the filescan menu if site is a multi site AND not the main site
     } else {
         add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Scanner', 'aiowpsecurity'), __('Scanner', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_FILESCAN_MENU_SLUG, array(&$this, 'handle_filescan_menu_rendering'));
     }
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Maintenance', 'aiowpsecurity'), __('Maintenance', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_MAINTENANCE_MENU_SLUG, array(&$this, 'handle_maintenance_menu_rendering'));
     add_submenu_page(AIOWPSEC_MAIN_MENU_SLUG, __('Miscellaneous', 'aiowpsecurity'), __('Miscellaneous', 'aiowpsecurity'), AIOWPSEC_MANAGEMENT_PERMISSION, AIOWPSEC_MISC_MENU_SLUG, array(&$this, 'handle_misc_menu_rendering'));
     do_action('aiowpsecurity_admin_menu_created');
 }
 /**
  * This will clean up the "users_online" transient entry for the current user. 
  *
  */
 function update_user_online_transient($user_id, $ip_addr)
 {
     global $aio_wp_security;
     $logged_in_users = AIOWPSecurity_Utility::is_multisite_install() ? get_site_transient('users_online') : get_transient('users_online');
     //$logged_in_users = get_transient('users_online');
     if ($logged_in_users === false || $logged_in_users == NULL) {
         return;
     }
     $j = 0;
     foreach ($logged_in_users as $value) {
         if ($value['user_id'] == $user_id && strcmp($value['ip_address'], $ip_addr) == 0) {
             unset($logged_in_users[$j]);
             break;
         }
         $j++;
     }
     //Save the transient
     AIOWPSecurity_Utility::is_multisite_install() ? set_site_transient('users_online', $logged_in_users, 30 * 60) : set_transient('users_online', $logged_in_users, 30 * 60);
     //set_transient('users_online', $logged_in_users, 30 * 60); //Set transient with the data obtained above and also set the expiry to 30min
     return;
 }
 function prepare_items()
 {
     /**
      * First, lets decide how many records per page to show
      */
     $per_page = 100;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     $this->process_bulk_action();
     global $wpdb;
     $events_table_name = AIOWPSEC_TBL_EVENTS;
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
     isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
     $orderby = !empty($orderby) ? esc_sql($orderby) : 'id';
     $order = !empty($order) ? esc_sql($order) : 'DESC';
     $orderby = AIOWPSecurity_Utility::sanitize_value_by_array($orderby, $sortable);
     $order = AIOWPSecurity_Utility::sanitize_value_by_array($order, array('DESC' => '1', 'ASC' => '1'));
     if (isset($_POST['s'])) {
         $search_term = trim($_POST['s']);
         $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $events_table_name . " WHERE `ip_or_host` LIKE '%%%s%%' OR `url` LIKE '%%%s%%' OR `referer_info` LIKE '%%%s%%'", $search_term, $search_term, $search_term), ARRAY_A);
     } else {
         $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$events_table_name} WHERE event_type=%s ORDER BY {$orderby} {$order}", '404'), ARRAY_A);
     }
     $new_data = array();
     foreach ($data as $row) {
         //lets insert an empty "status" column - we will use later
         $row['status'] = '';
         $new_data[] = $row;
     }
     $current_page = $this->get_pagenum();
     $total_items = count($new_data);
     $new_data = array_slice($new_data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $new_data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 function prepare_items()
 {
     //First, lets decide how many records per page to show
     $per_page = 20;
     $columns = $this->get_columns();
     $hidden = array();
     $sortable = $this->get_sortable_columns();
     $this->_column_headers = array($columns, $hidden, $sortable);
     $this->process_bulk_action();
     global $wpdb;
     global $aio_wp_security;
     $minimum_comments_per_ip = $aio_wp_security->configs->get_value('aiowps_spam_ip_min_comments');
     if (empty($minimum_comments_per_ip)) {
         $minimum_comments_per_ip = 5;
     }
     /* -- Ordering parameters -- */
     //Parameters that are going to be used to order the result
     isset($_GET["orderby"]) ? $orderby = strip_tags($_GET["orderby"]) : ($orderby = '');
     isset($_GET["order"]) ? $order = strip_tags($_GET["order"]) : ($order = '');
     $orderby = !empty($orderby) ? esc_sql($orderby) : 'amount';
     $order = !empty($order) ? esc_sql($order) : 'DESC';
     $orderby = AIOWPSecurity_Utility::sanitize_value_by_array($orderby, $sortable);
     $order = AIOWPSecurity_Utility::sanitize_value_by_array($order, array('DESC' => '1', 'ASC' => '1'));
     $sql = $wpdb->prepare("SELECT   comment_author_IP, COUNT(*) AS amount\n                FROM     {$wpdb->comments} \n                WHERE    comment_approved = 'spam'\n                GROUP BY comment_author_IP\n                HAVING   amount >= %d\n                ORDER BY {$orderby} {$order}\n                ", $minimum_comments_per_ip);
     $data = $wpdb->get_results($sql, ARRAY_A);
     //Get all permamnetly blocked IP addresses
     $block_list = AIOWPSecurity_Blocking::get_list_blocked_ips();
     if (!empty($block_list)) {
         foreach ($data as $key => $value) {
             if (in_array($value['comment_author_IP'], $block_list)) {
                 $data[$key]['status'] = 'blocked';
             }
         }
     }
     $current_page = $this->get_pagenum();
     $total_items = count($data);
     $data = array_slice($data, ($current_page - 1) * $per_page, $per_page);
     $this->items = $data;
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }