<?php
/*
Plugin Name: Bulk User Access Editor
Description: Change access permissions for many users at once.
Version: 1.02
Requires at least: 3.00
*/

// 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() {
  
  // prepare adminUI() placeholders
  $adminUI = [];
  // page title
  $adminUI['PAGE_TITLE'] = [
    t("Plugins")          => '?menu=admin&action=plugins',
    t("Bulk User Editor") => '?_pluginName=bulkUserAccessEditor&_pluginAction=showform',
  ];
  
  // button
  $adminUI['BUTTONS'] = [
    [ 'name' => 'back_to_plugins', 'label' => 'Back to Plugins &gt;&gt;',  'onclick' => 'window.location="?menu=admin&action=plugins";', 'type' => 'button' ],
  ];
  
  // content
  $adminUI['CONTENT'] = ob_capture(function() {
    global $TABLE_PREFIX;
    // print_r($GLOBALS['APP']);
 
    //Setup the section access list form
    $permissionEditor = "";
    $schema = loadSchema("_accesslist");
    $al = new AccessListField($schema);
    $al->label = "Section Access";
    $permissionEditor = $al->getTableRow(null, null, null);

    ?>
    <input type='hidden' name='_pluginName' value='bulkUserAccessEditor' />
    <input type='hidden' name='_pluginAction' value='update' />
      <div class="col-sm-2">Users To Modify</div>
      <div class="col-sm-9" style="margin-bottom:20px">
        <div class="col-sm-4">
          <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 /><br />
        </div>
        <div class="col-sm-8">
          <?php echo adminUI_button(['type' => 'submit', 'btn-type' => 'default', 'label' => t('Commit Changes'), 'value' => '1']); ?>
        </div>
      </div>
      <?php echo $permissionEditor; ?>
      <script type='text/javascript'>
        $('[name=\"accessList\\[all\\]\\[accessLevel\\]\"]').val('1');
        $('.sectionAccessList').slideDown();
      </script>
  <?php });
  // display content
  adminUI($adminUI);
  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;
}



// EOF
