Advertisement
Guest User

ip-based-login.php

a guest
Mar 30th, 2017
655
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 17.57 KB | None | 0 0
  1. <?php
  2. /**
  3.  * @package ip-based-login
  4.  * @version 1.3.8
  5.  */
  6. /*
  7. Plugin Name: IP Based Login
  8. Plugin URI: http://wordpress.org/extend/plugins/ip-based-login/
  9. Description: IP Based Login is a plugin which allows you to directly login from an allowed IP. You can create ranges and define the IP range which can get access to a particular user. So if you want to allow someone to login but you do not want to share the login details just add their IP using IP Based Login.
  10. Version: 1.3.8
  11. Author: Brijesh Kothari
  12. Author URI: http://www.wpinspired.com/
  13. License: GPLv3 or later
  14. */
  15.  
  16. /*
  17. Copyright (C) 2013  Brijesh Kothari (email : admin@wpinspired.com)
  18. This program is free software: you can redistribute it and/or modify
  19. it under the terms of the GNU General Public License as published by
  20. the Free Software Foundation, either version 3 of the License, or
  21. (at your option) any later version.
  22.  
  23. This program is distributed in the hope that it will be useful,
  24. but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  26. GNU General Public License for more details.
  27.  
  28. You should have received a copy of the GNU General Public License
  29. along with this program.  If not, see <http://www.gnu.org/licenses/>.
  30. */
  31.  
  32. if(!function_exists('add_action')){
  33.     echo 'You are not allowed to access this page directly.';
  34.     exit;
  35. }
  36.  
  37. define('ipbl_version', '1.3.8');
  38.  
  39. // This function adds a link in admin toolbar
  40. function ipbl_admin_bar() {
  41.     global $wp_admin_bar;
  42.     $siteurl = get_option('siteurl');
  43.  
  44.     $wp_admin_bar->add_node(array(
  45.         'id'    => 'ipbl-link',
  46.         'title' => 'Logged in by IP Based Login ('.getip().')',
  47.         'href'  => 'http://www.wpinspired.com/ip-based-login'
  48.     ));
  49.  
  50.     $wp_admin_bar->add_node(array(
  51.         'id'    => 'ipbl-logoff-15',
  52.         'title' => 'Disable auto login for 15 minutes',
  53.         'parent' => 'ipbl-link',
  54.         'href'  => $siteurl.'/wp-admin/options-general.php?page=ip-based-login&no_login=15'
  55.     ));
  56.  
  57.     $wp_admin_bar->add_node(array(
  58.         'id'    => 'ipbl-logoff-30',
  59.         'title' => 'Disable auto login for 30 minutes',
  60.         'parent' => 'ipbl-link',
  61.         'href'  => $siteurl.'/wp-admin/options-general.php?page=ip-based-login&no_login=30'
  62.     ));
  63.  
  64.     $wp_admin_bar->add_node(array(
  65.         'id'    => 'ipbl-logoff-60',
  66.         'title' => 'Disable auto login for 1 hour',
  67.         'parent' => 'ipbl-link',
  68.         'href'  => $siteurl.'/wp-admin/options-general.php?page=ip-based-login&no_login=60'
  69.     ));
  70.  
  71. }
  72.  
  73. // Ok so we are now ready to go
  74. register_activation_hook( __FILE__, 'ip_based_login_activation');
  75.  
  76. function ip_based_login_activation(){
  77.  
  78. global $wpdb;
  79.  
  80. $sql = "
  81. --
  82. -- Table structure for table `".$wpdb->prefix."ip_based_login`
  83. --
  84.  
  85. CREATE TABLE IF NOT EXISTS `".$wpdb->prefix."ip_based_login` (
  86.  `rid` int(10) NOT NULL AUTO_INCREMENT,
  87.  `username` varchar(255) NOT NULL,
  88.  `start` bigint(20) NOT NULL,
  89.  `end` bigint(20) NOT NULL,
  90.  `status` tinyint(2) NOT NULL DEFAULT '1',
  91.  `date` int(10) NOT NULL,
  92.  PRIMARY KEY (`rid`)
  93. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
  94.  
  95. $wpdb->query($sql);
  96.  
  97. add_option('ipbl_version', ipbl_version);
  98.  
  99. }
  100.  
  101. add_action( 'plugins_loaded', 'ip_based_login_update_check' );
  102.  
  103. function ip_based_login_update_check(){
  104.  
  105. global $wpdb;
  106.     // Check if the user wants to set no_login
  107.     if(!empty($_REQUEST['no_login'])){
  108.  
  109.         $current_user = wp_get_current_user();
  110.         $no_login = sanitize_variables($_REQUEST['no_login']);
  111.         $expire_cookie = $no_login * 60;
  112.         setcookie('ipbl_'.$current_user->user_login, 'no_login', time()+$expire_cookie, '/');
  113.         wp_logout();
  114.         wp_redirect(home_url());
  115.         exit;
  116.     }
  117.  
  118.     $sql = array();
  119.     $current_version = get_option('ipbl_version');
  120.  
  121.     if($current_version < 1.3){
  122.         $sql[] = "ALTER TABLE `".$wpdb->prefix."ip_based_login` CHANGE `start` `start` BIGINT( 20 ) NOT NULL ;";
  123.         $sql[] = "ALTER TABLE `".$wpdb->prefix."ip_based_login` CHANGE `end` `end` BIGINT( 20 ) NOT NULL ;";
  124.         $sql[] = "ALTER TABLE `".$wpdb->prefix."ip_based_login` ADD `status` TINYINT( 2 ) NOT NULL DEFAULT '1' AFTER `end` ;";
  125.     }
  126.  
  127.     if($current_version < ipbl_version){
  128.         foreach($sql as $sk => $sv){
  129.             $wpdb->query($sv);
  130.         }
  131.  
  132.         update_option('ipbl_version', ipbl_version);
  133.     }
  134.  
  135. }
  136.  
  137. function triger_login(){
  138.    
  139.     global $wpdb;
  140.    
  141.     $logged_ip = getip();
  142.     $query = "SELECT * FROM ".$wpdb->prefix."ip_based_login WHERE ".ip2long($logged_ip)." BETWEEN `start` AND `end` AND `status` = 1";
  143.     $result = selectquery($query);
  144.     $username = $result['username'];
  145.    
  146.     if(!is_user_logged_in() && !empty($username) && empty($_COOKIE['ipbl_'.$username])){
  147.  
  148.         // What is the user id ?
  149.         $user = get_userdatabylogin($username);
  150.         $user_id = $user->ID;
  151.                
  152.         // Lets login
  153.         wp_set_current_user($user_id, $username);
  154.         wp_set_auth_cookie($user_id);
  155.         do_action('wp_login', $username, $user);
  156.     }
  157.    
  158.     // Did we login the user ?
  159.     if(!empty($username)){
  160.         add_action('wp_before_admin_bar_render', 'ipbl_admin_bar');
  161.     }
  162. }
  163.  
  164. add_action('init', 'triger_login');
  165.  
  166. // Add settings link on plugin page
  167. function ipbl_settings_link($links) {
  168.   $settings_link = '<a href="options-general.php?page=ip-based-login">Settings</a>';
  169.   array_unshift($links, $settings_link);
  170.   return $links;
  171. }
  172.  
  173. $plugin = plugin_basename(__FILE__);
  174. add_filter("plugin_action_links_$plugin", 'ipbl_settings_link' );
  175.  
  176. add_action('admin_menu', 'ip_based_login_admin_menu');
  177.  
  178. function getip(){
  179.     if(isset($_SERVER["REMOTE_ADDR"])){
  180.         return $_SERVER["REMOTE_ADDR"];
  181.     }elseif(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
  182.         return $_SERVER["HTTP_X_FORWARDED_FOR"];
  183.     }elseif(isset($_SERVER["HTTP_CLIENT_IP"])){
  184.         return $_SERVER["HTTP_CLIENT_IP"];
  185.     }
  186. }
  187.  
  188. function selectquery($query){
  189.     global $wpdb;
  190.    
  191.     $result = $wpdb->get_results($query, 'ARRAY_A');
  192.     return current($result);
  193. }
  194.  
  195. function ip_based_login_admin_menu() {
  196.     global $wp_version;
  197.  
  198.     // Modern WP?
  199.     if (version_compare($wp_version, '3.0', '>=')) {
  200.         add_options_page('IP Based Login', 'IP Based Login', 'manage_options', 'ip-based-login', 'ip_based_login_option_page');
  201.         return;
  202.     }
  203.  
  204.     // Older WPMU?
  205.     if (function_exists("get_current_site")) {
  206.         add_submenu_page('wpmu-admin.php', 'IP Based Login', 'IP Based Login', 9, 'ip-based-login', 'ip_based_login_option_page');
  207.         return;
  208.     }
  209.  
  210.     // Older WP
  211.     add_options_page('IP Based Login', 'IP Based Login', 9, 'ip-based-login', 'ip_based_login_option_page');
  212. }
  213.  
  214. function sanitize_variables($variables = array()){
  215.  
  216.     if(is_array($variables)){
  217.         foreach($variables as $k => $v){
  218.             $variables[$k] = trim($v);
  219.             $variables[$k] = escapeshellcmd($v);
  220.             $variables[$k] = esc_sql($v);
  221.         }
  222.     }else{
  223.         $variables = esc_sql(escapeshellcmd(trim($variables)));
  224.     }
  225.    
  226.     return $variables;
  227. }
  228.  
  229. function valid_ip($ip){
  230.  
  231.     if(!ip2long($ip)){
  232.         return false;
  233.     }  
  234.     return true;
  235. }
  236.  
  237. function is_checked($post){
  238.  
  239.     if(!empty($_POST[$post])){
  240.         return true;
  241.     }  
  242.     return false;
  243. }
  244.  
  245. function report_error($error = array()){
  246.  
  247.     if(empty($error)){
  248.         return true;
  249.     }
  250.    
  251.     $error_string = '<b>Please fix the below errors :</b> <br />';
  252.    
  253.     foreach($error as $ek => $ev){
  254.         $error_string .= '* '.$ev.'<br />';
  255.     }
  256.    
  257.     echo '<div id="message" class="error"><p>'
  258.                     . __($error_string, 'ip-based-login')
  259.                     . '</p></div>';
  260. }
  261.  
  262. function ipbl_objectToArray($d){
  263.   if(is_object($d)){
  264.     $d = get_object_vars($d);
  265.   }
  266.  
  267.   if(is_array($d)){
  268.     return array_map(__FUNCTION__, $d); // recursive
  269.   }elseif(is_object($d)){
  270.     return ipbl_objectToArray($d);
  271.   }else{
  272.     return $d;
  273.   }
  274. }
  275.  
  276. function ip_based_login_option_page(){
  277.  
  278.     global $wpdb;
  279.      
  280.     if(!current_user_can('manage_options')){
  281.         wp_die('Sorry, but you do not have permissions to change settings.');
  282.     }
  283.  
  284.     /* Make sure post was from this page */
  285.     if(count($_POST) > 0){
  286.         check_admin_referer('ip-based-login-options');
  287.     }
  288.    
  289.     if(isset($_GET['users_dropdown'])){    
  290.         $users_dropdown = (int) sanitize_variables($_GET['users_dropdown']);
  291.         if(!empty($users_dropdown)){
  292.             update_option('ipbl_dropdown', '1');
  293.         }else{
  294.             update_option('ipbl_dropdown', '');        
  295.         }
  296.     }
  297.    
  298.     if(isset($_GET['delid'])){
  299.        
  300.         $delid = (int) sanitize_variables($_GET['delid']);
  301.        
  302.         $wpdb->query("DELETE FROM ".$wpdb->prefix."ip_based_login WHERE `rid` = '".$delid."'");
  303.         echo '<div id="message" class="updated fade"><p>'
  304.             . __('IP range has been deleted successfully', 'ip-based-login')
  305.             . '</p></div>';
  306.     }
  307.    
  308.     if(isset($_GET['statusid'])){
  309.        
  310.         $statusid = (int) sanitize_variables($_GET['statusid']);
  311.         $setstatus = sanitize_variables($_GET['setstatus']);
  312.         $_setstatus = ($setstatus == 'disable' ? 0 : 1);
  313.        
  314.         $wpdb->query("UPDATE ".$wpdb->prefix."ip_based_login SET `status` = '".$_setstatus."' WHERE `rid` = '".$statusid."'");
  315.         echo '<div id="message" class="updated fade"><p>'
  316.             . __('IP range has been '.$setstatus.'d successfully', 'ip-based-login')
  317.             . '</p></div>';
  318.     }
  319.    
  320.     if(isset($_POST['add_iprange'])){
  321.         global $ip_based_login_options;
  322.  
  323.         $ip_based_login_options['username'] = trim($_POST['username']);
  324.         $ip_based_login_options['start'] = trim($_POST['start_ip']);
  325.         $ip_based_login_options['end'] = trim($_POST['end_ip']);
  326.  
  327.         $ip_based_login_options = sanitize_variables($ip_based_login_options);
  328.        
  329.         $user = get_user_by('login', $ip_based_login_options['username']);
  330.        
  331.         if(empty($user)){
  332.             $error[] = 'The username does not exist.';
  333.         }
  334.        
  335.         if(!valid_ip($ip_based_login_options['start'])){
  336.             $error[] = 'Please provide a valid start IP';
  337.         }
  338.        
  339.         if(!valid_ip($ip_based_login_options['end'])){
  340.             $error[] = 'Please provide a valid end IP';        
  341.         }
  342.        
  343.         // This is to check if there is any other range exists with the same Start or End IP
  344.         $ip_exists_query = "SELECT * FROM ".$wpdb->prefix."ip_based_login WHERE
  345.         `start` BETWEEN '".ip2long($ip_based_login_options['start'])."' AND '".ip2long($ip_based_login_options['end'])."'
  346.         OR `end` BETWEEN '".ip2long($ip_based_login_options['start'])."' AND '".ip2long($ip_based_login_options['end'])."';";
  347.         $ip_exists = $wpdb->get_results($ip_exists_query);
  348.         //print_r($ip_exists);
  349.        
  350.         if(!empty($ip_exists)){
  351.             $error[] = 'The Start IP or End IP submitted conflicts with an existing IP range!';
  352.         }
  353.        
  354.         // This is to check if there is any other range exists with the same Start IP
  355.         $start_ip_exists_query = "SELECT * FROM ".$wpdb->prefix."ip_based_login WHERE
  356.         '".ip2long($ip_based_login_options['start'])."' BETWEEN `start` AND `end`;";
  357.         $start_ip_exists = $wpdb->get_results($start_ip_exists_query);
  358.         //print_r($start_ip_exists);
  359.        
  360.         if(!empty($start_ip_exists)){
  361.             $error[] = 'The Start IP is present in an existing range!';
  362.         }
  363.        
  364.         // This is to check if there is any other range exists with the same End IP
  365.         $end_ip_exists_query = "SELECT * FROM ".$wpdb->prefix."ip_based_login WHERE
  366.         '".ip2long($ip_based_login_options['end'])."' BETWEEN `start` AND `end`;";
  367.         $end_ip_exists = $wpdb->get_results($end_ip_exists_query);
  368.         //print_r($end_ip_exists);
  369.        
  370.         if(!empty($end_ip_exists)){
  371.             $error[] = 'The End IP is present in an existing range!';
  372.         }
  373.        
  374.         if(ip2long($ip_based_login_options['start']) > ip2long($ip_based_login_options['end'])){
  375.             $error[] = 'The end IP cannot be smaller than the start IP';           
  376.         }
  377.        
  378.         if(empty($error)){
  379.            
  380.             $options['username'] = $ip_based_login_options['username'];
  381.             $options['start'] = ip2long($ip_based_login_options['start']);
  382.             $options['end'] = ip2long($ip_based_login_options['end']);
  383.             $options['status'] = (is_checked('status') ? 1 : 0);
  384.             $options['date'] = date('Ymd');
  385.            
  386.             $wpdb->insert($wpdb->prefix.'ip_based_login', $options);
  387.            
  388.             if(!empty($wpdb->insert_id)){
  389.                 echo '<div id="message" class="updated fade"><p>'
  390.                     . __('IP range added successfully', 'ip-based-login')
  391.                     . '</p></div>';
  392.             }else{
  393.                 echo '<div id="message" class="updated fade"><p>'
  394.                     . __('There were some errors while adding IP range', 'ip-based-login')
  395.                     . '</p></div>';        
  396.             }
  397.            
  398.         }else{
  399.             report_error($error);
  400.         }
  401.     }
  402.    
  403.     $ipranges = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ip_based_login;", 'ARRAY_A');
  404.    
  405.     // A list of all users
  406.     $_users = get_users();
  407.     $users_dropdown = get_option('ipbl_dropdown');
  408.    
  409.     $show_popup = 0;
  410.     $donate_popup = get_option('ipbl_donate_popup');
  411.     if(!empty($donate_popup)){
  412.         if($donate_popup <= date('Ymd', strtotime('-1 month'))){
  413.             $show_popup = 1;
  414.             update_option('ipbl_donate_popup', date('Ymd'));
  415.         }
  416.     }else{
  417.         $show_popup = 1;
  418.         update_option('ipbl_donate_popup', date('Ymd'));
  419.     }
  420.    
  421.     echo '<script>
  422.     var donate_popup = '.$show_popup.';
  423.     if(donate_popup == 1){
  424.         if(confirm("Donate $5 for IP Based Login to support the development")){
  425.             window.location.href =  "http://www.wpinspired.com/ip-based-login";
  426.         }
  427.     }
  428.     </script>';
  429.    
  430.     ?>
  431.     <div class="wrap">
  432.       <h2><?php echo __('IP Based Login Settings','ip-based-login'); ?></h2>
  433.       <form action="options-general.php?page=ip-based-login" method="post">
  434.         <?php wp_nonce_field('ip-based-login-options'); ?>
  435.         <table class="form-table">
  436.           <tr>
  437.             <th scope="row" valign="top"><label for="username"><?php echo __('Username','ip-based-login'); ?></label></th>
  438.             <td>
  439.                 <?php
  440.                
  441.                     if(!empty($users_dropdown)){
  442.                         echo '<select name="username">';
  443.                        
  444.                         foreach($_users as $uk => $uv){
  445.                             $_users[$uk] = ipbl_objectToArray($uv);
  446.                             echo '<option value="'.$_users[$uk]['data']['user_login'].'" '.($ip_based_login_options['username'] == $_users[$uk]['data']['user_login'] ? 'selected="selected"' : '').'>'.$_users[$uk]['data']['user_login'].'</option>';
  447.                         }
  448.                        
  449.                         echo '</select>&nbsp;&nbsp;';
  450.                     }else{
  451.                         echo '<input type="text" size="25" value="'.((isset($_POST['username']) ? trim($_POST['username']) : '')).'" name="username" id="username" />';
  452.                     }
  453.                    
  454.                 ?>
  455.                
  456.               <?php echo __('Username to be logged in as when accessed from the below IP range','ip-based-login'); ?> <br />
  457.                 <?php
  458.                
  459.                     if(empty($users_dropdown)){
  460.                         echo __('<a class="submitdelete" href="options-general.php?page=ip-based-login&users_dropdown=1">Show the list of users in a drop down</a>','ip-based-login');
  461.                     }else{                     
  462.                         echo __('<a class="submitdelete" href="options-general.php?page=ip-based-login&users_dropdown=0">Don\'t show the list of users in a drop down</a>','ip-based-login');
  463.                     }
  464.                    
  465.                 ?> <br />
  466.             </td>
  467.           </tr>
  468.           <tr>
  469.             <th scope="row" valign="top"><label for="start_ip"><?php echo __('Start IP','ip-based-login'); ?></label></th>
  470.             <td>
  471.               <input type="text" size="25" value="<?php echo((isset($_POST['start_ip']) ? trim($_POST['start_ip']) : '')); ?>" name="start_ip" id="start_ip" /> <?php echo __('Start IP of the range','ip-based-login'); ?> <br />
  472.             </td>
  473.           </tr>
  474.           <tr>
  475.             <th scope="row" valign="top"><label for="end_ip"><?php echo __('End IP','ip-based-login'); ?></label></th>
  476.             <td>
  477.               <input type="text" size="25" value="<?php echo((isset($_POST['end_ip']) ? trim($_POST['end_ip']) : '')); ?>" name="end_ip" id="end_ip" /> <?php echo __('End IP of the range','ip-based-login'); ?> <br />
  478.             </td>
  479.           </tr>
  480.           <tr>
  481.             <th scope="row" valign="top"><?php echo __('Active','ip-based-login'); ?></th>
  482.             <td>
  483.               <input type="checkbox" <?php if(!isset($_POST['add_iprange']) || is_checked('status')) echo 'checked="checked"'; ?> name="status" /> <?php echo __('Select the checkbox to set this range as active','ip-based-login'); ?> <br />
  484.             </td>
  485.           </tr>
  486.         </table><br />
  487.         <input name="add_iprange" class="button action" value="<?php echo __('Add IP range','ip-based-login'); ?>" type="submit" />    
  488.       </form>
  489.     </div> 
  490.     <?php
  491.    
  492.     if(!empty($ipranges)){
  493.         ?>
  494.         <br /><br />
  495.         <table class="wp-list-table widefat fixed users">
  496.             <tr>
  497.                 <th scope="row" valign="top"><?php echo __('Username','ip-based-login'); ?></th>
  498.                 <th scope="row" valign="top"><?php echo __('Start IP','ip-based-login'); ?></th>
  499.                 <th scope="row" valign="top"><?php echo __('End IP','ip-based-login'); ?></th>
  500.                 <th scope="row" valign="top"><?php echo __('Options','ip-based-login'); ?></th>
  501.             </tr>
  502.             <?php
  503.                
  504.                 foreach($ipranges as $ik => $iv){
  505.                     $status_button = (!empty($iv['status']) ? 'disable' : 'enable');
  506.                     echo '
  507.                     <tr>
  508.                         <td>
  509.                             '.$iv['username'].'
  510.                         </td>
  511.                         <td>
  512.                             '.long2ip($iv['start']).'
  513.                         </td>
  514.                         <td>
  515.                             '.long2ip($iv['end']).'
  516.                         </td>
  517.                         <td>
  518.                             <a class="submitdelete" href="options-general.php?page=ip-based-login&delid='.$iv['rid'].'" onclick="return confirm(\'Are you sure you want to delete this IP range ?\')">Delete</a>&nbsp;&nbsp;
  519.                             <a class="submitdelete" href="options-general.php?page=ip-based-login&statusid='.$iv['rid'].'&setstatus='.$status_button.'" onclick="return confirm(\'Are you sure you want to '.$status_button.' this IP range ?\')">'.ucfirst($status_button).'</a>
  520.                         </td>
  521.                     </tr>';
  522.                 }
  523.             ?>
  524.         </table>
  525.         <?php
  526.     }
  527.    
  528.     echo '<br /><br /><br /><br /><hr />
  529.     IP Based Login v'.ipbl_version.' is developed by <a href="http://wpinspired.com" target="_blank">WP Inspired</a>.
  530.     You can report any bugs <a href="http://wordpress.org/support/plugin/ip-based-login" target="_blank">here</a>.
  531.     You can provide any valuable feedback <a href="http://www.wpinspired.com/contact-us/" target="_blank">here</a>.
  532.     <a href="http://www.wpinspired.com/ip-based-login" target="_blank">Donate</a>';
  533. }  
  534.  
  535. // Sorry to see you going
  536. register_uninstall_hook( __FILE__, 'ip_based_login_deactivation');
  537.  
  538. function ip_based_login_deactivation(){
  539.  
  540. global $wpdb;
  541.  
  542. $sql = "DROP TABLE ".$wpdb->prefix."ip_based_login;";
  543. $wpdb->query($sql);
  544.  
  545. delete_option('ipbl_version');
  546. delete_option('ipbl_dropdown');
  547. delete_option('ipbl_donate_popup');
  548.  
  549. }
  550. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement