Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 37.03 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Bulk Password Reset
  4. Plugin URI: http://rubenwoudsma.nl/bulk-password-reset
  5. Description: This plugin makes it possible to execute a bulk password reset for users within a specific group. You can send an activation key to all the users or perform a hard reset of the password.
  6. Author: Ruben Woudsma
  7. Version: 1.3.3
  8. Author URI: http://rubenwoudsma.nl
  9. */
  10. if (!class_exists('bulk_password_reset')) {
  11.     class bulk_password_reset {
  12.         var $hook = 'bulk_password_reset';
  13.         var $longname = 'Bulk Password Reset';
  14.         var $shortname = 'Bulk Password Reset';
  15.         var $optionname = 'bpr_options';      
  16.         //Class Functions
  17.         /**
  18.          * PHP 4 Compatible Constructor
  19.          */
  20.         function bulk_password_reset(){$this->__construct();}
  21.         /**
  22.          * PHP 5 Constructor
  23.          */
  24.         function __construct(){
  25.             //Language Setup
  26.             $locale = get_locale();
  27.             $mo = dirname(__FILE__) . "/languages/" . $this->hook . "-".$locale.".mo";
  28.             load_textdomain($this->hook, $mo);
  29.  
  30.                         //Actions
  31.                         if(is_admin()) {
  32.                             add_action('admin_menu',            array(&$this, 'add_usermenu_item') );
  33.                             add_action('admin_print_scripts',   array(&$this, 'do_script') );
  34.                             add_action('admin_print_styles',    array(&$this, 'do_css') );
  35.                             add_action('admin_head',            array(&$this, 'config_page_head') );
  36.  
  37.                             // admin actions/filters for bulk_actions user menu
  38.                             add_action('admin_footer',          array(&$this, 'bpr_cust_bulk_admin_footer'));
  39.                             add_action('load-edit.php',         array(&$this, 'bpr_cust_bulk_action'));
  40.                             add_action('load-users.php',        array(&$this, 'bpr_cust_bulk_action'));
  41.                             add_action('admin_notices',         array(&$this, 'bpr_cust_bulk_admin_notices'));
  42.                         }
  43.  
  44.             //Filter + set upload folder
  45.             add_filter('upload_dir', array(&$this, 'set_correct_logfolder') );
  46.             $upload = wp_upload_dir();
  47.             remove_filter('upload_dir', array(&$this, 'set_correct_logfolder') );
  48.  
  49.         }
  50.  
  51.         function set_correct_logfolder($upload) {
  52.             $upload['subdir']    = '/bulk-password-reset' . $upload['subdir'];
  53.             $upload['path']        = $upload['basedir'] . $upload['subdir'];
  54.             $upload['url']        = $upload['baseurl'] . $upload['subdir'];
  55.             return $upload;
  56.         }
  57.  
  58.         /**
  59.          * @desc Adds the page to the users sub menu
  60.          */
  61.                 function add_usermenu_item() {
  62.                     add_submenu_page('users.php', $this->longname, $this->shortname, 'administrator', $this->hook, array(&$this, 'bulk_password_reset_page') );
  63.                 }
  64.                
  65.                 /**
  66.                  * @desc Adds some code to the head of the settings/options page
  67.                  */
  68.                 function config_page_head() {
  69.                     if(isset($_GET['page'])) {
  70.                         if ($_GET['page'] == $this->hook) {
  71.                             wp_enqueue_script('jquery');
  72.                             ?>
  73.                              <script type="text/javascript" charset="utf-8">
  74.                                  jQuery(document).ready(function(){
  75.                                     jQuery('#advancedsettings').change(function(){
  76.                                         if (jQuery('#advancedsettings').is(':checked')) {
  77.                                             jQuery('#advancedbprsettings').css("display","block");
  78.                                                 if (jQuery('#uselogfile').is(':checked')) {
  79.                                                     jQuery('#logfilesbpr').css("display","block");
  80.                                                 }
  81.                                         } else {
  82.                                             jQuery('#advancedbprsettings').css("display","none");
  83.                                             jQuery('#logfilesbpr').css("display","none");
  84.                                         }
  85.                                     }).change();
  86.                                     jQuery('#uselogfile').change(function(){
  87.                                         if (jQuery('#uselogfile').is(':checked')) {
  88.                                             jQuery('#logfilesbpr').css("display","block");
  89.                                         } else {
  90.                                             jQuery('#logfilesbpr').css("display","none");
  91.                                         }
  92.                                     }).change();
  93.                                 });
  94.                              </script>
  95.                         <?php
  96.                         }
  97.                     }  
  98.                 }
  99.  
  100.                 /**
  101.                  * @desc Adds settings/options page
  102.                  */
  103.                 function bulk_password_reset_page() {
  104.  
  105.                     $options = get_option($this->optionname);
  106.  
  107.                     if ( (isset($_POST['reset']) && $_POST['reset'] == "true") || !is_array($options) ) {
  108.                         $this->set_defaults();
  109.                         $options    = get_option($this->optionname);
  110.                         echo "<div class=\"updated\"><p>" . __('Bulk Password reset settings reset to default','bulk_password_reset') . "</p></div>\n";
  111.                     }
  112.  
  113.                     if ( isset($_POST['submit']) ) {
  114.                         if (!current_user_can('manage_options')) die(__('You cannot edit the plugin Bulk Password Reset for WordPress options.','bulk_password_reset'));
  115.                         check_admin_referer('bprsettings-config');
  116.  
  117.                         //Text options
  118.                         foreach (array('custommessage', 'customauthkey', 'custompassword') as $option_name) {
  119.                             if (isset($_POST[$option_name]))
  120.                                 $options[$option_name] = $_POST[$option_name];
  121.                             else
  122.                                 $options[$option_name] = '';
  123.                         }
  124.  
  125.                         //Checkbox options
  126.                         foreach (array('sendnotification', 'advancedsettings', 'hardreset', 'passwordnag') as $option_name) {
  127.                             if (isset($_POST[$option_name]))
  128.                                 $options[$option_name] = true;
  129.                             else
  130.                                 $options[$option_name] = false;
  131.                         }
  132.  
  133.                         update_option($this->optionname, $options);
  134.                         echo "<div id=\"updatemessage\" class=\"updated fade\"><p>" . __('Bulk Password Reset settings updated.', 'bulk_password_reset') . "</p></div>\n";
  135.                         echo "<script type=\"text/javascript\">setTimeout(function(){jQuery('#updatemessage').hide('slow');}, 3000);</script>";  
  136.  
  137.                         //Here we need to process al the users within the role groups
  138.                         if (isset($_POST['dobulkreset'])) {
  139.                             $err_msg = '';
  140.  
  141.                             //Validate if roles have been selected
  142.                             if ( !isset($_POST['send_roles']) || !is_array($_POST['send_roles']) || empty($_POST['send_roles']) ) {
  143.                                     $err_msg =  __('No reset has been executed as no group was selected. You need to select at least one group to let the plugin do his work.', 'bulk_password_reset');
  144.                             }
  145.                             else {
  146.                                 $send_roles = $_POST['send_roles'];
  147.  
  148.                                 $user_ID = get_current_user_id();
  149.                                 $recipients = $this->get_recipients_from_roles($send_roles, $user_ID);
  150.  
  151.                                 if (empty($recipients)) {
  152.                                     $err_msg = __('No recipients where found in the selected groups', 'bulk_password_reset');
  153.                                 }
  154.                                 else {
  155.                                     //do mail processing with for each loop
  156.                                     foreach ($recipients as $recipient) {
  157.                                         // no do sending for each recipient
  158.                                         if ( $options['hardreset'] ) {
  159.                                             $errors = $this->reset_password($recipient->id);
  160.                                         } else {
  161.                                             $errors = $this->sent_activation_mail($recipient->id);
  162.                                         }
  163.                                     }
  164.                                    
  165.                                     if ( is_wp_error($errors) ) {
  166.                                         $err_msg = $errors->get_error_message();
  167.                                     }
  168.                                 }
  169.                             }
  170.                            
  171.                             // If error, show error message else show success message
  172.                             if ( $err_msg !='' ) {
  173.                                 // Show error message
  174.                                 echo "<div id=\"errormessage\" class=\"error\"><p>" . $err_msg . "</p></div>\n";
  175.                                 echo "<script type=\"text/javascript\">setTimeout(function(){jQuery('#errormessage').hide('slow');}, 6000);</script>";  
  176.                             } else {
  177.                                 //Show success message
  178.                                 echo "<div id=\"successmessage\" class=\"updated fade\"><p>" . __('Successfully reset the password for the selected role(s).', 'bulk_password_reset') . "</p></div>\n";
  179.                                 echo "<script type=\"text/javascript\">setTimeout(function(){jQuery('#successmessage').hide('slow');}, 6000);</script>";  
  180.                             }
  181.  
  182.                         }
  183.  
  184.                     }
  185.  
  186.                 ?>
  187.                 <div class="wrap">
  188.                     <h2><?php _e('Bulk Password Reset','bulk_password_reset') ?></h2>
  189.                    
  190.                     <!-- Main section -->
  191.                     <div class="postbox-container" style="width:70%;">
  192.                         <div class="metabox-holder">  
  193.                             <div class="meta-box-sortables">
  194.                                 <form action="" method="post" id="bpr-config">
  195.                                     <?php wp_nonce_field('bprsettings-config'); ?>
  196.                                     <div id="bprsettings" class="postbox">
  197.                                         <div class="handlediv" title="Click to toggle"><br /></div>
  198.                                         <h3 class="hndle"><span><?php _e('Bulk Password Reset Settings','bulk_password_reset'); ?> </span></h3>
  199.                                         <div class="bprbox">
  200.                                             <table class="form-table">
  201.                                                 <tr>
  202.                                                     <td colspan="2"><?php _e('With the options down below you can select groups for which you want to do a password reset','bulk_password_reset') ?></td>
  203.                                                 </tr>
  204.                                                 <tr>
  205.                                                     <th scope="row" valign="top"><label for="send_roles"><?php _e('Recipients', 'bulk_password_reset') ?>
  206.                                                     <br/><br/>
  207.                                                     <small><?php _e('You can select multiple groups by pressing the CTRL key.', 'bulk_password_reset') ?></small>
  208.                                                     <br/><br/>
  209.                                                     <small><?php _e('Only the groups having at least one user appear here.', 'bulk_password_reset') ?></small></label></th>
  210.                                                     <td>
  211.                                                         <select id="send_roles" name="send_roles[]" multiple="multiple" size="8" style="width: 554px; height: 150px;">
  212.                                                         <?php
  213.                                                             $roles = $this->get_roles($user_ID);
  214.                                                             foreach ($roles as $key => $value) {
  215.                                                                 $name = translate_user_role($value );
  216.                                                         ?>
  217.                                                             <option value="<?php echo $key; ?>"<?php
  218.                                                                 echo (in_array($key, (array) $send_roles) ? ' selected="selected"' : '');?>>
  219.                                                                 <?php echo __('Role', 'bulk_password_reset') . ' - ' . $name; ?>
  220.                                                             </option>
  221.                                                         <?php
  222.                                                             }
  223.                                                         ?>
  224.                                                         </select>
  225.                                                     </td>
  226.                                                 </tr>
  227.                                                 <tr>
  228.                                                     <th valign="top" scrope="row"><label for="dobulkreset"><?php _e('Do the bulk reset:', 'bulk_password_reset') ?></label><br/><small><?php _e('Activate this check box when you actually would like to do the reset, else only the settings are saved.', 'bulk_password_reset') ?></small></th>
  229.                                                     <td valign="top"><input type="checkbox" id="dobulkreset" name="dobulkreset" /></td>
  230.                                                 </tr>
  231.                                                 <tr>
  232.                                                     <th valign="top" scrope="row"><label for="advancedsettings"><?php _e('Show advanced settings:', 'bulk_password_reset') ?></label><br/><small><?php _e('Only advised for users who want to change the default reset options', 'bulk_password_reset') ?></small></th>
  233.                                                     <td valign="top"><input type="checkbox" id="advancedsettings" name="advancedsettings" <?php echo checked($options['advancedsettings'],true,false); ?>/></td>
  234.                                                 </tr>
  235.                                             </table>
  236.                                         </div>
  237.                                     </div>
  238.  
  239.                                     <!-- Advanced settings -->
  240.                                     <div id="advancedbprsettings" class="postbox">
  241.                                         <div class="handlediv" title="Click to toggle"><br /></div>
  242.                                         <h3 class="hndle"><span><?php _e('Advanced Settings', 'bulk_password_reset') ?></span></h3>
  243.                                         <div class="bprbox">
  244.                                             <table class="form-table">
  245.                                                 <tr>
  246.                                                     <th valign="top" scrope="row"><label for="hardreset"><?php _e('Direct password reset', 'bulk_password_reset') ?>:</label><br/><small><?php _e('Not recommended, as this immediately changes the password of the users.','bulk_password_reset') ?></small></th>
  247.                                                     <td valign="top"><input type="checkbox" id="hardreset" name="hardreset" <?php echo checked($options['hardreset'],true,false); ?> /></td>
  248.                                                 </tr>
  249.                                                 <tr>
  250.                                                     <th valign="top" scrope="row"><label for="sendnotification"><?php _e('E-mail notification', 'bulk_password_reset') ?>:</label><br/><small><?php _e('Not recommended to deactivate, as this change the default reset functionality.','bulk_password_reset') ?></small></th>
  251.                                                     <td valign="top"><input type="checkbox" id="sendnotification" name="sendnotification" <?php echo checked($options['sendnotification'],true,false); ?> /></td>
  252.                                                 </tr>
  253.                                                 <tr>
  254.                                                     <th valign="top" scrope="row"><label for="passwordnag"><?php _e('Password nag', 'bulk_password_reset') ?>:</label><br/><small><?php _e('Not recommended to deactivate, as this will display a note to users to change their password.','bulk_password_reset') ?></small></th>
  255.                                                     <td valign="top"><input type="checkbox" id="passwordnag" name="passwordnag" <?php echo checked($options['passwordnag'],true,false); ?> /></td>
  256.                                                 </tr>
  257.                                                 <tr>
  258.                                                     <th valign="top" scrope="row"><label for="uselogfile"><?php _e('Use logfile?', 'bulk_password_reset') ?>:</label><br/><small><?php _e('Write the result of the password reset to a text log file for track and trace','bulk_password_reset') ?></small></th>
  259.                                                     <td valign="top"><input type="checkbox" id="uselogfile" name="uselogfile" <?php echo checked($options['uselogfile'],true,false); ?> /></td>
  260.                                                 </tr>
  261.                                                 <tr>
  262.                                                     <th valign="top" scrope="row"><label for="custompassword"><?php _e('Set a custom password:', 'bulk_password_reset') ?></label></th>
  263.                                                     <td valign="top"><input type="text" id="custompassword" name="custompassword" size="30" value="<?php echo $options['custompassword']; ?>"/></td>
  264.                                                 </tr>
  265.                                                 <tr>
  266.                                                     <th valign="top" scrope="row"><label for="customauthkey"><?php _e('Set a custom authentication key:', 'bulk_password_reset') ?></label></th>
  267.                                                     <td valign="top"><input type="text" id="customauthkey" name="customauthkey" size="30" value="<?php echo $options['customauthkey']; ?>"/></td>
  268.                                                 </tr>
  269.                                                 <tr>
  270.                                                     <th valign="top" scrope="row"><label for="custommessage"><?php _e('Additional information for in the e-mail body:', 'bulk_password_reset') ?></label></th>
  271.                                                     <td valign="top"><textarea rows="8" cols="70" name="custommessage" id="custommessage"><?php echo $options['custommessage']; ?></textarea></td>
  272.                                                 </tr>
  273.                                             </table>
  274.                                         </div>
  275.                                     </div>
  276.  
  277.                                     <!-- Show logfiles for download -->
  278.                                     <div id="logfilesbpr" class="postbox">
  279.                                         <div class="handlediv" title="Click to toggle"><br /></div>
  280.                                         <h3 class="hndle"><span><?php _e('Bulk Password Reset - Log files', 'bulk_password_reset') ?></span></h3>
  281.                                         <div class="bprbox">
  282.                                             <p><?php _e('Down below you will find an overview of the log files belonging to the earlier resets', 'bulk_password_reset') ?></p>
  283.                                             <?php
  284.                                             //path to directory to scan
  285.                                             $directory = $upload['path'];
  286.  
  287.                                             //get all files with a .log extension.
  288.                                             $logfiles = glob($directory . "*.log");
  289.  
  290.                                             //print each file name
  291.                                             foreach($logfiles as $logfile)
  292.                                             {
  293.                                             echo $logfile;
  294.                                             }
  295.  
  296.                                             ?>
  297.                                         </div>
  298.                                     </div>
  299.                                     <!-- End logfiles section -->
  300.                                    
  301.                                     <div class="submit"><input type="submit" class="button-primary" name="submit" value="<?php _e('Save the bulk Password Reset settings and reset passwords &raquo;', 'bulk_password_reset') ?>" /></div>
  302.  
  303.                                 </form>                                
  304.                                 <form action="" method="post">                                    
  305.                                 <input type="hidden" name="reset" value="true"/>                                    
  306.                                 <div class="submit"><input type="submit" value="<?php _e('Reset Default Settings &raquo;', 'bulk_password_reset'); ?>" />
  307.                                 </div>                                
  308.                                 </form>                            
  309.                                 </div>                        
  310.                                 </div>                    
  311.                                 </div>                    
  312.                                 <div class="postbox-container" style="width:20%;">                        
  313.                                 <div class="metabox-holder">                              
  314.                                 <div class="meta-box-sortables">                                
  315.                                 <?php                                    
  316.                                 $this->plugin_like();                                    
  317.                                 $this->plugin_support();                                    
  318.                                 $this->news();                                
  319.                                 ?>                            
  320.                                 </div>                            
  321.                                 <br/><br/><br/>                        
  322.                                 </div>                    
  323.                                 </div>                              
  324.                                 </div>                
  325.                                 <?php                
  326.                                 }                
  327.                                 /**                
  328.                                 * @desc Set the default options used within the plugin                
  329.                                 */                
  330.                                 function set_defaults() {                    
  331.                                 $options = get_option($this->optionname);                    
  332.                                 $options['custommessage'] = '';                    
  333.                                 $options['customauthkey'] = '';                    
  334.                                 $options['custompassword'] = '';                    
  335.                                 $options['sendnotification'] = true;                    
  336.                                 $options['advancedsettings'] = false;                    
  337.                                 $options['hardreset'] = false;                      
  338.                                 $options['passwordnag'] = true;                      
  339.                                 $options['uselogfile'] = false;                          
  340.                                 update_option($this->optionname,$options);                
  341.                                 }
  342.                                 /**                
  343.                                 * @desc Create a "plugin like" box.                
  344.                                 */                
  345.                                 function plugin_like() {}                  
  346.                                 /**                
  347.                                 * @desc Info box with link to the support forums.                
  348.                                 */                
  349.                                 function plugin_support() {}
  350.                 /**
  351.                  * @desc Box with latest news from rubenwoudsma.nl
  352.                  */
  353.                 function news() {}                
  354.                     /**                
  355.                     * @desc Create a postbox widget                
  356.                     */                
  357.                     function postbox($id, $title, $content) {            
  358.                         }                
  359.                         /**                
  360.                         * @desc Load the plugin related css                
  361.                         */                
  362.                         function do_css() {                
  363.                         if ( isset( $_GET['page'] ) && $_GET['page'] == $this->hook ) {                    
  364.                         wp_enqueue_style('dashboard');                    
  365.                         wp_enqueue_style('thickbox');                    
  366.                         wp_enqueue_style('global');                    
  367.                         wp_enqueue_style('wp-admin');                    
  368.                         wp_enqueue_style('bprextra-admin-css', plugin_dir_url( __FILE__ ) . 'bulk_password_reset.css');                  
  369.                         }                  
  370.                         }                
  371.                         /**                
  372.                         * @desc Load the plugin related javascript                
  373.                         */                
  374.                         function do_script()
  375.                         {                  
  376.                         if ( isset( $_GET['page'] ) && $_GET['page'] == $this->hook )
  377.                         {                    
  378.                     wp_enqueue_script('postbox');                    
  379.                     wp_enqueue_script('dashboard');                    
  380.                     wp_enqueue_script('thickbox');                    
  381.                     wp_enqueue_script('media-upload');                  
  382.                     }                                
  383.                     }                
  384.                     /**                
  385.                     * @desc Retrieve the roles from the users                
  386.                     */                
  387.                     function get_roles( $exclude_id='')
  388.                     {                    
  389.                     $roles = array();                    
  390.                     $wp_roles = new WP_Roles();
  391.                     foreach ($wp_roles->get_names() as $key => $value)
  392.                     {                        
  393.                     $users_in_role = $this->get_recipients_from_roles(array($key), $exclude_id);                        
  394.                     if (!empty($users_in_role))
  395.                     {                            
  396.                 $roles[$key] = $value;                        
  397.                 }                    
  398.                 }                                  
  399.                 return $roles;                
  400.                 }                
  401.                 /**                
  402.                 * @desc Retrieve the users from the roles                
  403.                 */                
  404.                 function get_recipients_from_roles($roles, $exclude_id='')
  405.                 {                    
  406.                 global $wpdb;                                  
  407.                 if (empty($roles)) {                        
  408.                 return array();                    
  409.                 }
  410.                     // Build role filter for the list of roles
  411.                     $role_count = count($roles);
  412.                     $capability_filter = '';
  413.                     for ($i=0; $i<$role_count; $i++) {
  414.                         $capability_filter .= "meta_value like '%" . $roles[$i] . "%'";
  415.                         if ($i!=$role_count-1) {
  416.                             $capability_filter .= ' OR ';
  417.                         }
  418.                     }
  419.                     $users = $wpdb->get_results(
  420.                         "SELECT id, user_login, user_email, display_name "
  421.                         . "FROM $wpdb->usermeta, $wpdb->users "
  422.                         . "WHERE "
  423.                         . " (user_id = id) "
  424.                         . ( $exclude_id!='' ? ' AND (id<>' . $exclude_id . ')' : '' )
  425.                         . " AND (meta_key = '" . $wpdb->prefix . "capabilities') "
  426.                         . " AND (" . $capability_filter . ") " );
  427.                     return $users;
  428.                 }
  429.                 /**
  430.                  * @desc Write message to debug.log based upon wp-config.php WP_DEBUG setting
  431.                  */
  432.                 function log_msg ( $message ) {
  433.                     //Only write to debug.log is WP_DEBUG is set
  434.                     if( WP_DEBUG === true ){
  435.                         //Check to see if array needs to be written, then use print_r
  436.                         if( is_array( $message ) || is_object( $message ) ){
  437.                             error_log( print_r( $message, true ) );
  438.                         } else {
  439.                             error_log( $message );
  440.                         }
  441.                     }
  442.                 }
  443.                 /**
  444.                  * @desc Sent the activation email to the users. Function copied from WP core and adjusted.
  445.                  */
  446.                 function sent_activation_mail($user_id) {
  447.                     global $wpdb, $wp_hasher;
  448.                     $options = get_option($this->optionname);                
  449.                     $user_data = get_user_by('id', $user_id);// redefining user_login ensures we return the right case in the email
  450.                     $user_login = $user_data->user_login;
  451.                     $user_email = $user_data->user_email;
  452.                     //$key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));                    
  453.                     //if ( empty($key) ) {
  454.                         if ( isset($options['customauthkey']) && $options['customauthkey'] != "" )
  455.                         {                            
  456.                     $key = $options['customauthkey'];                        
  457.                     } else {                            // Generate something random for a key...                            
  458.                     $key = wp_generate_password(12, false);                        }
  459.                         // Now insert the key, hashed, into the DB.
  460.                         if ( empty( $wp_hasher ) ) {
  461.                             require_once( ABSPATH . WPINC . '/class-phpass.php' );
  462.                             $wp_hasher = new PasswordHash( 8, true );
  463.                         }
  464.                         $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  465.                         // Now insert the new md5 key into the db
  466.                         $wpdb->update($wpdb->users, array('user_activation_key' => $hashed), array('user_login' => $user_login));
  467.                     //}
  468.                                        
  469.                         if ( $options['sendnotification'] ) {
  470.                         if ( isset($options['custommessage']) && $options['custommessage'] != "" ) {
  471.                             $message = $options['custommessage'] . "\r\n\r\n";
  472.                         } else {
  473.                             $message = '';
  474.                         }
  475.                         $message .= sprintf(__('User name: %s', 'bulk_password_reset'), $user_login) . "\r\n\r\n";
  476.                         $message .= __('To reset your password visit the following address', 'bulk_password_reset') . "\r\n\r\n";
  477.                         $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n";
  478.                         $message .= __('Thank you,', 'bulk_password_reset') . "\r\n\r\n";
  479.                         $message .= __('Administration', 'bulk_password_reset');
  480.                         if ( is_multisite() )
  481.                                 $blogname = $GLOBALS['current_site']->site_name;
  482.                         else
  483.                                 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);                    
  484.                         $title = sprintf(__('[%s] Password Reset Request', 'bulk_password_reset'), $blogname); 
  485.                         if ( $message && !wp_mail($user_email, $title, $message) ) {
  486.                             die('<p>' . __('The email could not be sent.', 'bulk_password_reset') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...', 'bulk_password_reset') . '</p>');
  487.                             $this->log_msg ('ERROR: Not able to sent activation message to ' . $user_login);
  488.                         } else {
  489.                             $this->log_msg ('INFO: Successfully sent activation message to ' . $user_login);
  490.                         }
  491.                                         }
  492.                     return true;                }
  493.                 /**
  494.                  * @desc Reset the users password. Function copied and adjusted from WP core.
  495.                  */
  496.                 function reset_password($user_id) {
  497.                     global $wpdb;
  498.                     $options = get_option($this->optionname);
  499.                     $user = get_user_by('id', $user_id);                  
  500.                     if ( empty( $user ) )                        
  501.                         return new WP_Error('invalid_user', __('Invalid user login supplied', 'bulk_password_reset'));                    
  502.                     if ( isset($options['custompassword']) && $options['custompassword'] != "" ) {                        
  503.                     $new_pass = $options['custompassword'];                    
  504.                     } else {
  505.                         // Generate something random for a password...                        
  506.                         $new_pass = wp_generate_password(12, false);;                    }
  507.                     wp_set_password($new_pass, $user->ID);
  508.                     if ( $options['passwordnag'] ) {                        
  509.                     update_user_meta($user->ID, 'default_password_nag', true); //Set up the Password change nag.                    
  510.                     }
  511.                                         if ( $options['sendnotification'] )
  512.                                         {                                                                  
  513.                                     if ( isset($options['custommessage']) && $options['custommessage'] != "" )
  514.                                     {                          
  515.                                 $message = $options['custommessage'] . "\r\n\r\n";                     
  516.                                 } else {
  517.                                     $message = '';
  518.                                     }                      
  519.                                     $message .= sprintf(__('The site administrator of %s has automatically changed your password.', 'bulk_password_reset'), get_option('siteurl')) . "\r\n\r\n";                       
  520.                                     $message .= sprintf(__('Username: %s', 'bulk_password_reset'), $user->user_login) . "\r\n";                     $message .= sprintf(__('Password: %s', 'bulk_password_reset'), $new_pass) . "\r\n";                    
  521.                                     $message .= network_site_url('wp-login.php', 'login') . "\r\n";                    
  522.                                     $title = sprintf(__('[%s] Your new password', 'bulk_password_reset'), get_option('blogname')); 
  523.                         if ( $message && !wp_mail($user->user_email, $title, $message) ) {
  524.                             die('<p>' . __('The e-mail could not be sent.', 'bulk_password_reset') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...', 'bulk_password_reset') . '</p>');
  525.                             $this->log_msg ('ERROR: Not able to sent reset password message to ' . $user->user_login);
  526.                         } else {                           
  527.                         $this->log_msg ('INFO: Successfully sent reset password message to ' . $user->user_login);                     
  528.                         }                                      
  529.                         }                              
  530.                     return true;
  531.                 }
  532.         /**
  533.          * Step 1: add the custom Bulk Action to the select menus
  534.          */
  535.         function bpr_cust_bulk_admin_footer() {
  536.     $screen = get_current_screen();
  537.     if ( $screen->id != "users" )   // Only add to users.php page
  538.         return;
  539.                 ?>
  540.                     <script type="text/javascript">
  541.                         jQuery(document).ready(function() {
  542.                             jQuery('<option>').val('perform_reset').text('<?php _e('Execute password reset', 'bulk_password_reset')?>').appendTo("select[name='action']");
  543.                             jQuery('<option>').val('perform_reset').text('<?php _e('Execute password reset', 'bulk_password_reset')?>').appendTo("select[name='action2']");
  544.                         });
  545.                     </script>
  546.                 <?php
  547.         }
  548. /**
  549.          * Step 2: handle the custom Bulk Action
  550.          *
  551.          * Based on the post http://wordpress.stackexchange.com/questions/29822/custom-bulk-action
  552.          */
  553.         function bpr_cust_bulk_action() {
  554.                 // get the action
  555.                 $wp_list_table = _get_list_table('WP_Users_List_Table');  // depending on your resource type this could be WP_Posts_List_Table, WP_Comments_List_Table, etc
  556.                 $action = $wp_list_table->current_action();        
  557.                 $allowed_actions = array("perform_reset");
  558.                 if(!in_array($action, $allowed_actions)) return;           
  559.                 // make sure ids are submitted.  depending on the resource type, this may be 'media' or 'ids'              
  560.                 if(isset($_REQUEST['users'])) {
  561.                     $user_ids = array_map('intval', $_REQUEST['users']);
  562.                 }                          
  563.                 if(empty($user_ids)) return;           
  564.                 // this is based on wp-admin/users.php
  565.                 $sendback = remove_query_arg( array('resetted', 'deleted', 'users'), wp_get_referer() ); // ???????
  566.                 if ( ! $sendback )
  567.                     $sendback = admin_url( "users.php" );                              
  568.                 $pagenum = $wp_list_table->get_pagenum();
  569.                 $sendback = add_query_arg( 'paged', $pagenum, $sendback );         
  570.                 switch($action) {                  
  571.                 case 'perform_reset':                  
  572.                         $resetted = 0;
  573.                         foreach( $user_ids as $user_id )
  574.                         {                                                      
  575.                         if ( !$this->reset_password($user_id) )
  576.                                 wp_die( __('Error resetting password of user.') );                                 
  577.                             $resetted++;                       
  578.                         }                  
  579.                         $sendback = add_query_arg( array('resetted' => $resetted, 'ids' => join(',', $user_ids) ), $sendback );
  580.                     break; 
  581.                     default: return;
  582.                 }      
  583.                 $sendback = remove_query_arg( array('action', 'action2', 'new_role', '_status', 'bulk_edit'), $sendback );
  584.                 wp_redirect($sendback);            
  585.                 exit();
  586.         }
  587.         /**
  588.          * Step 3: display an admin notice on the user page after resetting password(s)
  589.          */
  590.         function bpr_cust_bulk_admin_notices() {
  591.             global $pagenow;       
  592.             if($pagenow == 'users.php' && isset($_REQUEST['resetted']) && (int) $_REQUEST['resetted']) {               
  593.             $message = sprintf( _n( 'Password reset has been sent.', '%s password resets have been sent.', $_REQUEST['resetted'] ), number_format_i18n( $_REQUEST['resetted'] ) );
  594.                 echo "<div class=\"updated\"><p>{$message}</p></div>";
  595.             }
  596.         }
  597.   } //End Class
  598. } //End if class exists statement
  599. //instantiate the class
  600. if (class_exists('bulk_password_reset')) {
  601.     $bulk_password_reset_var = new bulk_password_reset();
  602. }
  603. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement