<?php
/*
Plugin Name: Bulk User Access Editor
Description: Change access permissions for many users at once.
Version: 1.00
Requires at least: 2.07
*/

// DON'T UPDATE ANYTHING BELOW THIS LINE

addAction('admin_postlogin', 'bulkUserAccessEditor_dispatch', null, 0);
addAction('plugin_actions',  'bulkUserAccessEditor_addPluginAction');

// dispatch commands
function bulkUserAccessEditor_dispatch() {

  //die(print_r($_REQUEST));
  // only allow admin access
  if (!$GLOBALS['CURRENT_USER']['isAdmin']) {
     return;
  }
  // only run for this plugin
  if (@$_REQUEST['_pluginName'] != 'bulkUserAccessEditor') {
     return;
  }

  require_once $GLOBALS['PROGRAM_DIR'] . '/lib/fieldtypes/accessList.php';
  require_once $GLOBALS['PROGRAM_DIR'] . '/lib/viewer_functions.php';

  // dispatch plugin actions
  $action = @$_REQUEST['_pluginAction'];
  if     ($action == 'showform') {
    bulkUserAccessEditor_showForm();
  }
  elseif ($action == 'update')  {
    bulkUserAccessEditor_update();
  }
  else {
    die(__FUNCTION__ . ": Unknown action");
  }

}

// on plugin_actions: display a "Run" link
function bulkUserAccessEditor_addPluginAction($plugin) {
  $isThisPlugin = preg_match('|/plugins/' .preg_quote($plugin) .'$|', str_replace('\\', '/', __FILE__));
  if (!$isThisPlugin) { return; }

  echo "<a href='?_pluginName=bulkUserAccessEditor&amp;_pluginAction=showform'>Run</a><br />";
}

//
function bulkUserAccessEditor_showForm() {
  global $TABLE_PREFIX;
 // print_r($GLOBALS['APP']);
  showHeader();


  //Setup the section access list form

  $permissionEditor = "";
  $schema = loadSchema("_accesslist");
  $al = new AccessListField($schema);
  $al->label = "Section Access";
  $permissionEditor = $al->getTableRow(null, null, null);


  $form = "


  <div class='content-box'>
    <form method='post' action='?'>
      <input type='hidden' name='_pluginName' value='bulkUserAccessEditor' />
      <input type='hidden' name='_pluginAction' value='update' />

      <div class='content-box-header'>

        <h3>Bulk User Editor</h3>


      </div> <!-- End .content-box-header -->


      <div class='content-box-content'>

        <table cellspacing='1' cellpadding='0' border='0' class='spacedTable bottomBorder'>
        <tr>
        <th width='200px'>&nbsp;</th>
        <th style='text-align: center;'>&nbsp;</th>
        </tr>
        <tr>
        <td class='listRow listRowOdd'>Users To Modify</td>
        <td style='text-align: left;' class='listRow listRowOdd' colspan='2'>
          <label><input type='radio' name='userGroup' value='1' /> All Users</label><br />
          <label><input type='radio' name='userGroup' value='2' /> Administrators</label><br />
          <label><input type='radio' name='userGroup' value='3' /> Non-Administrators</label><br />
         </td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
        $permissionEditor
        </table>
        <script type='text/javascript'>
          $('[name=\"accessList\\[all\\]\\[accessLevel\\]\"]').val('1');
          $('.sectionAccessList').slideDown();
        </script>
        <div align='right'><input type='submit' value='Commit Changes' name='_action=commit' class='button' /></div>
      </div> <!-- End .content-box-content -->
    </form>
  </div> <!-- End .content-box -->  ";




  echo $form;
  showFooter();
  exit;

}
function bulkUserAccessEditor_update() {
  global $TABLE_PREFIX;
  $alert = "";
  $message = "";

  /* Check for selected group of users and make the where condition
    1 - all
    2 - administrators
    3 - non administrators
  */
  if(@$_REQUEST['userGroup'] == 1) {
    $accountsQueryWhere = "num";
  }
  elseif(@$_REQUEST['userGroup'] == 2) {
    $accountsQueryWhere = "isAdmin = 1";
  }
  elseif(@$_REQUEST['userGroup'] == 3) {
    $accountsQueryWhere = "isAdmin = 0";
  }
  else {
    alert("Invalid user group.");
  }

  if(!alert()) {

    if($backupFileName = backupDatabase(NULL, "_accesslist")){
      $message .= "Access List table backed up to " . $backupFileName;
    }
    else {
      alert("Error: Backup failed.");
    }
    if(!alert())
    {
      // Get the applicable user records
      $accountsRecords = mysql_select_query("SELECT num FROM {$TABLE_PREFIX}accounts WHERE $accountsQueryWhere");

      //update each user with the new permissions
      $usersUpdated = 0;
      if($accountsRecords) {
        $usersUpdated = _bulkUserAccessEditor_updateAccessList($accountsRecords);
      }

      $message .= "<br />Account privileges updated for $usersUpdated users.";
      notice($message);
    }
  }

  bulkUserAccessEditor_showForm();

}

/*
  Modification of _updateAccessList() from save.php
  $userNum is now accepted as a paremeter, not from the $_REQUEST varaible

  Copied because save.php runs other code that we don't want.
*/

function _bulkUserAccessEditor_updateAccessList($users) {
  global $TABLE_PREFIX;
  // error checking
  if (!@$_REQUEST['accessList']) { die(__FUNCTION__ . ": No accessList specified!"); }

  // check user num
  if (!$users) {
    die(__FUNCTION__ . ": Couldn't get user number!");
  }

  // create random save id
  $randomSaveId = uniqid('', true);

  $fieldNames   = "userNum, tableName, accessLevel, maxRecords, randomSaveId";
  $insertRows   = "";
  $deleteQueryUserIN = "";
  $userCount = 0;
  foreach($users as $user)
  {
    $userCount++;
    $userNum = (int) $user['num'];

    //Making the IN list for the delete query later
    if($userCount > 1)
    {
      $deleteQueryUserIN .= ",";
    }
    $deleteQueryUserIN .= $userNum;


    // create insert query
    foreach ($_REQUEST['accessList'] as $tableName => $tableValues) {
      if ($tableName != 'all' && $_REQUEST['accessList']['all']['accessLevel'] != '1') { continue; } // don't save section access unless "bySection" is specified for all
      if ($_REQUEST['accessList']['all']['accessLevel'] == '0') { continue; } // skip sections with no access allowed
      if ($insertRows) { $insertRows .= ",\n"; }
      $maxRecords = @$tableValues['maxRecords'] != '' ? "'".mysql_escape($tableValues['maxRecords'])."'" : 'NULL';
      $insertRows .= "('$userNum','" . mysql_escape($tableName) ."','". mysql_escape($tableValues['accessLevel']) .
                     "',$maxRecords,'" . mysql_escape($randomSaveId) . "')";
    }
  }
  $insertQuery  = "INSERT INTO `{$TABLE_PREFIX}_accesslist` ($fieldNames) VALUES $insertRows;";

  // insert new access rights
  if ($insertRows) {
    mysql_query($insertQuery) or die("MySQL Error Inserting New Access Rights: ". htmlencode(mysql_error()) . "\n");
  }

  // delete old access rights
  $deleteQuery = "DELETE FROM `{$TABLE_PREFIX}_accesslist` WHERE userNum IN($deleteQueryUserIN) AND randomSaveId != '" . mysql_escape($randomSaveId) . "'";

  mysql_query($deleteQuery) or die("MySQL Error Deleting Old Access Rights: ". htmlencode(mysql_error()) . "\n");

  return $userCount;
}



?>
