<?php

  /*

      sitesandusers.php

      Sites and Users Admin. Allows the user to administer the sites and
      associated users. [Commented]

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-02 arne_sf: Added tbl_UserTypes.sortorder as the fifth returned field under Attempt 3 of
                            "Retrieve User Mapping Info" for the default action. PostGreSQL raised an error
                            on missing that field in the SQL statement.
        2005-07-02 arne_sf: Replaced all instances of column name 'user' for table tbl_Users with 'username'
        2005-07-02 arne_sf: Replaced all instances of column name 'user' for table tbl_UserSites with 'userid'
        2005-07-02 arne_sf: Replaced all instances of column name 'user' for table tbl_UserDomains with 'userid'
        2005-04-27 arne_sf: Replaced MySQL- and PostgreSQL-specific sequence ID code with call to db_next_id()
                
      ## PAGE CONTAINS HANDYANDY MYSQL MODS ##
      ## Copyright (C) 2005 Andy Deakin (handyandy.org.uk) ##

      ----

      Copyright (C) 2003  Central Manchester CLC
      Copyright (C) 2003  David Thorne (davethorne@gmail.com)

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  // Start session and populate it with data
  session_start();

  // Page Security
  if ($_SESSION['_usertype'] == '' || $_SESSION['_usertype'] == 'Client' || $_SESSION['_restricted'] == '1') {
    require_once 'system/security.php';
    ThrowOut();
  }

  // Page Title
  $ptitle = 'Sites and Users';

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/message.php';
  require_once 'system/global_preferences.php';
  require 'header.php';

  // Language selection
  set_text_domain("sitesandusers");

  // Retrieve Get/Post variables
  $act = $_REQUEST['act'];
  $site = $_POST['site'];
  $sites = $_POST['sites'];
  if ($sites == '') { $sites = array(); }
  $name = $_POST['name'];
  $username = $_POST['username'];
  $password = $_POST['password'];
  $available = $_POST['available'];
  $user = $_POST['user'];
  $users = $_POST['users'];
  $usertype = $_POST['usertype'];
  $support = $_POST['support'];
  $resolve = $_POST['resolve'];
  $email = $_POST['email'];
  $oldusername = $_POST['oldusername'];

  if ($conf_db['dsn']['phptype'] == 'pgsql') {
    $is_pgsql = true;
  }

  // Action: Add a site to the system
  if ($act == 'addsiteaction') {
    $act = 'addsite';
    // Make sure a name has been entered
    if ($site == '') {
      $message = gettext('CORRECTION: You must give this site a name.');
    } elseif (substr(strtolower($site), -9) == '{deleted}') {
      $message = gettext('CORRECTION: You cannot give the site a name that ends in {deleted}');
    } else {
      $sites = array();
      // Insert site into system
      db_send("INSERT INTO tbl_Sites (site,domain) VALUES ('" . $site . "',$_SESSION[_domain])");

      // Add domain administrators to the site
      $domainadmin = 5; // The id of a domain adminstrator
      $sitenum = db_recordset("SELECT id FROM tbl_Sites WHERE site='$site'");
      $sitenum = $sitenum[0]['id'];
      $users = db_recordset("SELECT DISTINCT userid FROM tbl_Sites, tbl_UserSites
                             WHERE usertype=$domainadmin
                               AND tbl_Sites.id = tbl_UserSites.site
                               AND tbl_Sites.domain = {$_SESSION['_domain']}");
      foreach ($users as $user) {
        db_send("INSERT INTO tbl_UserSites (userid, site, usertype)
                 VALUES ({$user['userid']}, $sitenum, $domainadmin)");
      }

      $act = '';
      $message = gettext('NOTE: Site successfully added to system.');
    }
  }

  // Action: Request for details to add a site to the system
  if ($act == 'addsite') {

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('Site Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to add a site')?>:</h2>
  
  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="addsiteaction" />
      <div class="labelfieldpair">
        <div class="name"><label for="site"><?php echo gettext('Site Name')?></label></div>
        <div class="field"><input type="text" name="site" id="site" size="35" maxlength="50" value="<?php echo $site?>" /></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Add Site')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='sitesandusers.php'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Edit a site
  if ($act == 'editsiteaction') {
    $act = 'editsite';
    // Make sure a name has been entered
    if ($site == '') {
      $message = gettext('CORRECTION: You must give this site a name.');
    } elseif (substr(strtolower($site), -9) == '{deleted}') {
      $message = gettext('CORRECTION: You cannot give the site a name that ends in {deleted}');
    } else {
      db_send("UPDATE tbl_Sites SET site='" . $site . "' WHERE ID=$sites[0]");
      $message = gettext('NOTE: Site successfully updated.');
      $act = '';
    }
  }

  // Action: Remove a site
  if ($act == 'removesite') {
    foreach($sites as $siterecord) {
      db_send("DELETE FROM tbl_UserSites WHERE site=$siterecord");
      db_send("UPDATE tbl_Sites SET active=0, site=site||' {deleted}'
               WHERE id=$siterecord");
    }
    $act = '';
    $sites = array();
    $message = gettext('NOTE: Site(s) successfully removed.');
  }

  // Action: Request the details to edit a site
  if ($act == 'editsite') {

    // Retrieve Site information
    $sitesRS = db_recordset("SELECT * FROM tbl_Sites WHERE id=$sites[0]");

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('Site Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to edit a site:')?></h2>
  
  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="editsiteaction" />
      <input type="hidden" name="sites[]" value="<?php echo $sites[0]?>" />
      <div class="labelfieldpair">
        <div class="name"><label for="site"><?php echo gettext('Site Name')?></label></div>
        <div class="field"><input type="text" name="site" id="site" size="35" maxlength="50" value="<?php echo $sitesRS[0][site]?>"></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Submit Changes')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='sitesandusers.php'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Add a user to the system
  if ($act == 'adduseraction') {
    $act = 'adduser';
    // Make sure a name and username has been entered
    $usernamesRS = db_recordset("SELECT username FROM tbl_Users WHERE username='".strtolower($username)."'");
    if ($name == '') {
      $message = gettext('CORRECTION: You must give this user a name.');
    } elseif (substr(strtolower($username), -9) == '{deleted}') {
      $message = gettext('CORRECTION: Usernames cannot end in {deleted}');
    } elseif ($username == '') {
      $message = gettext('CORRECTION: You must give this user a username.');
    } elseif (count($usernamesRS) > 0) {
      $message = gettext('CORRECTION: That username is already taken. You must give this user a different and unique username.');
    } else {
      if ($available == 'true') { $available = '1'; } else { $available = '0'; }
      // Add user
      $user = db_next_id('tbl_Users_id');
      db_send("INSERT INTO tbl_Users (id,name,username,pass,available,email) VALUES ($user, '$name','" . strtolower($username) . "','" . md5($password) . "',$available, '$email')");

      // Add user to the current domain
      db_send("INSERT INTO tbl_UserDomains (userid,domain,defaultflag) VALUES ($user,$_SESSION[_domain],1);");

      $act = '';
      $message = gettext('NOTE: User successfully added to system.');
    }
  }

  // Action: Request the details to add a user to the system
  if ($act == 'adduser') {

    $usertypesRS = db_recordset("SELECT * 
                                 FROM tbl_UserTypes 
                                 WHERE sortorder<$_SESSION[_usertypesortorder]
                                 ORDER BY sortorder");

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('User Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to add a user:')?></h2>

  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="adduseraction" />
      <div class="labelfieldpair">
        <div class="name"><label for="site"><?php echo gettext('Name')?></label></div>
        <div class="field"><input type="text" name="name" id="name" size="35" maxlength="50" value="<?php echo $name?>" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="username"><?php echo gettext('Username')?></label></div>
        <div class="field"><input type="text" name="username" id="username" size="20" maxlength="20" value="<?php echo $username?>" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="password"><?php echo gettext('Password')?></label></div>
        <div class="field"><input type="text" name="password" id="password" size="20" maxlength="20" value="" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="email"><?php echo gettext('Email Address')?></label></div>
        <div class="field"><input type="text" name="email" id="email" size="20" maxlength="40" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="available"><?php echo gettext('Available')?></label></div>
        <div class="field"><input type="checkbox" name="available" id="available" checked="checked" value="true" /></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Add User')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='sitesandusers.php'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Edit a user
  if ($act == 'edituseraction') {
    $act = 'edituser';
    if ($user > 1) {
      $usernamesRS = db_recordset("SELECT username FROM tbl_Users WHERE username='".strtolower($username)."'");
      if ($username == '') {
        $message = gettext('CORRECTION: You must give this user a username.');
        $users = array($user);
      } elseif (substr(strtolower($username), -9) == '{deleted}') {
        $message = gettext('CORRECTION: Usernames cannot end in {deleted}');
        $users = array($user);
      } elseif (count($usernamesRS) > 0 && $username != $oldusername) {
        $message = gettext('CORRECTION: That username is already taken. You must give this user a different and unique username.');
        $users = array($user);
      } elseif ($name == '') {
        $message = gettext('CORRECTION: You must give this user a name.');
        $users = array($user);
      } else {
        $sql = "UPDATE tbl_Users SET name='" . $name . "',username='" . strtolower($username) . "'";
        if ($password <> '') { $sql .= ",pass='" . md5($password) . "'"; }
        $sql .= ",email='$email' WHERE ID=" . $user;
        db_send($sql);
      
        $message = gettext("NOTE: User successfully updated.");
        $users = array($user);
        $act = '';
      }
    }
  }
  
  // Action: Remove a user
  if ($act == 'removeuser') {
    foreach($users as $userrecord) {
      // make sure that don't delete user 'root' or 'unsigned'.
      if ($userrecord > 1) {
        $domainsforuser = db_recordset("SELECT count(*) AS num
                                        FROM tbl_UserDomains
                                        WHERE userid=$userrecord");
        db_send("DELETE FROM tbl_UserDomains WHERE userid=$userrecord AND domain=$_SESSION[_domain]");
        $iud = db_recordset("SELECT id FROM tbl_Sites WHERE domain=$_SESSION[_domain]");
        // prevent SQL Error if there are no sites within the domain,
        if (count($iud)) {
          for($i=0;$i<count($iud);$i++) {
            if ($i) {
              $iuds .= ',';
            }
            $iuds.=$iud[$i]['id'];
          }
          ## echo $iud; print_r($iud);echo $iuds;
          db_send("DELETE FROM tbl_UserSites WHERE userid=$userrecord AND site IN ($iuds)");
        }
        if ($domainsforuser[0][num] == 1) {
          //echo "delete user here {$domainsforuser[0][num]}<br>\n";
          $deleted_user = db_recordset("SELECT username FROM tbl_Users WHERE id=$userrecord");
          db_send("UPDATE tbl_Users SET active=0, username='"
            .substr($deleted_user[0]['username'], 0, 9).
            " {deleted}"."' WHERE id=$userrecord");
        }
      }
    }
    $act = '';
    $message = gettext('NOTE: User(s) successfully removed.');
  }
  
  // Action: Import users from uploaded file
  if ($act == 'importcsvaction') {
    if ($HTTP_POST_FILES['userfile']['size'] == 0) {
      $act = 'importcsv';
      if ($HTTP_POST_FILES['userfile']['type'] == '') {
        $message = sprintf(gettext("CORRECTION: File too large for upload - maximum file size is %s bytes."),$global_prefs['maxupload']);
      } else {
        $message = gettext('CORRECTION: Cannot upload an empty file.');
      }
    } elseif ($HTTP_POST_FILES['userfile']['size']>$global_prefs['maxupload']) {
      $act = 'importcsv';
      $message = sprintf(gettext("CORRECTION: File too large for upload - maximum file size is %s bytes."),$global_prefs['maxupload']);
    } else {
      $act = '';
      $row = 0;
      $skippedrows = array();
      $ignoredrows = array();
      $insertedrows = array();
      $importedrows = array();
      $handle = fopen ($HTTP_POST_FILES['userfile']['tmp_name'],"r");
      while ($data = fgetcsv ($handle, 1000, ",")) {
        $row++;
        $num = count ($data);
        if ($num != 3) {
          $skippedrows[] = $row;
        } elseif (substr(strtolower(trim($data[1])), -9) == '{deleted}') {
          $invalidusernamerows[] = $row;
        } else {
          $usersRS = db_recordset("SELECT * FROM tbl_Users WHERE username='" . addslashes(strtolower(trim($data[1]))) . "'");
          if (count($usersRS) == 0) {
            // Add user
            $user = db_next_id('tbl_Users_id');
            db_send("INSERT INTO tbl_Users (id,name,username,pass,available,email) VALUES ($user, '".trim($data[0])."','" . strtolower(trim($data[1])) . "','" . md5(strtolower(trim($data[1]))) . "',1,'" . trim($data[2]) . "')");
            // Add user to the current domain
            db_send("INSERT INTO tbl_UserDomains (userid,domain,defaultflag) VALUES ($user,$_SESSION[_domain],1);");
            $insertedrows[] = $row;
          } else {
            if ($resolve == 'import') {
              $userdomainsRS = db_recordset("SELECT * FROM tbl_UserDomains WHERE userid='" . $usersRS[0][id] . "' AND domain=$_SESSION[_domain]");
              if (count($userdomainsRS) == 0) {
                db_send("INSERT INTO tbl_UserDomains (userid,domain,defaultflag) VALUES (" . $usersRS[0][id] . ",$_SESSION[_domain],0)");
                $importedrows[] = $row;
              } else {
                $ignoredrows[] = $row;
              }
            } else {
              $ignoredrows[] = $row;
            }
          }
        }
      }
      fclose ($handle);
      if ((count($insertedrows)+count($importedrows))>0) {
        $message = sprintf(gettext("NOTE: %s users successfully imported."),
          (count($insertedrows)+count($importedrows)));
      } else {
        $message = gettext('NOTE: No users imported.');
      }
      $message .= '<br />&rsaquo; <strong> ' . $row . gettext(' records found in file').'</strong>.';
      if (count($skippedrows)>0) {
        $message .= '<br />&rsaquo; <strong> ' . count($skippedrows) . gettext(' malformed records were skipped').'</strong>.';
      }
      if (count($ignoredrows)>0) {
        $message .= '<br />&rsaquo; <strong> ' . count($ignoredrows) . gettext(' duplicate records were ignored').'</strong>.';
      }
      if (count($invalidusernamerows)>0) {
        $message .= '<br />&rsaquo; <strong> ' . count($invalidusernamerows) . 
          gettext(' records with invalid usernames (i.e. with the suffix {deleted}) were skipped').'</strong>.';
      }
    }
  }

  // Action: Import users from a uploaded CSV file
  if ($act == 'importcsv') {

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('Import Users')?></h1>
  <h2><?php echo gettext('Upload a CSV file to import of users.')?></h2>

  <div class="block">
    <p><?php echo gettext('This page allows you to upload a comma delimited text file (.csv) of users in order to add them to the system in bulk. The file must hold each user on seperate lines, with two fields per line. The csv file is of the format <strong><samp>"Full name", "username", "email address"</samp></strong>. The initial password for each user will be the same as the username. If the imported username is already present in the database, then you can choose to either ignore that user or alternatively, if the user does not have access to this domain, grant them access.')?>
    </p>

    <form enctype="multipart/form-data" action="" method="post">
      <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $global_prefs['maxupload']?>" />
      <input type="hidden" name="act" value="importcsvaction" />
      <div class="labelfieldpair">
        <div class="name"><label for="userfile"><?php echo gettext('Use CSV file')?></label></div>
        <div class="field"><input name="userfile" id="userfile" type="file" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <input name="resolve" id="resolveignore" type="radio" value="ignore" checked="checked" />
          <label for="resolveignore"><?php echo gettext('Ignore any clashing usernames.')?></label><br />
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <input name="resolve" id="resolveimport" type="radio" value="import" />
          <label for="resolveimport"><?php echo gettext('Grant any clashing usernames access to this domain.')?></label>
        </div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Import')?>!" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='sitesandusers.php'" />
      </div>
    </form>

  </div>

<?php

  }

  // Action: Import users from other domains
  if ($act == 'importaction') {
    foreach($users as $userrecord) {
      if ($userrecord > 1) {
        db_send("INSERT INTO tbl_UserDomains (userid,domain,defaultflag) VALUES ($userrecord,$_SESSION[_domain],0)");
      } 
    }
    $act = '';
    $message = gettext('NOTE: User(s) successfully imported to this domain.');
  }

  // Action: Import users
  if ($act == 'import') {

    // Retrieve External Users information
    $iud = db_recordset("SELECT userid FROM tbl_UserDomains WHERE domain=$_SESSION[_domain]");

    for($i=0;$i<count($iud);$i++) {
      $iuds .= ",".$iud[$i]['userid'];
    }

    $usersRS = db_recordset("SELECT DISTINCT id,name 
                             FROM tbl_Users 
                             WHERE active=1
                               AND id NOT IN (0,1$iuds) ORDER BY name");

    if ($message) { display($message); }
?>

<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  function mainSubmit (act) {
    document.mainform.act.value=act;
    document.mainform.submit();
  }

//-->
//]]>
</script>

  <h1><?php echo gettext('Import Users')?></h1>
  <h2><?php echo gettext('Please choose the users from the other domains or import from CSV:')?></h2>
        
  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="importaction" />
      <div class="columnleft">
        <div class="labelleft"><label for="users"><?php echo gettext('Users')?></label></div>
        <div class="columnleft">
          <select name="users[]" id="users" size="20" multiple="multiple">
<?php
    $num_users = count($usersRS);
    if (!$users) $users=array($usersRS[0][id]);

    if ($num_users == 0) {
      print ("            <option value=\"0\" selected=\"selected\">[".gettext('No Users')."]</option>\n");
    }
    foreach ($usersRS as $record) {
      // Show as inactive if so
      if ($record[available] == '0') {
        $style = ' class="inactive"';
      } elseif ($record[restricted] == '1') {
        $style = ' class="restricted"';
      } else {
        $style = '';
      }
      print ("            <option value=\"${record[id]}\"${style}>${record[name]}</option>\n");
    }
?>
          </select>
        </div>
        <div class="columnleft">
          <input type="submit" value="<?php echo gettext('Import now')?>" /><br />
          <input type="button" value="<?php echo gettext('From CSV')?>..." onclick="mainSubmit('importcsv')" /><br />
          <input type="button" value="<?php echo gettext('Back')?>" onclick="document.location='sitesandusers.php'" />
        </div>
      </div>
    </form>
    <hr class="hide" />
  </div>

<?php
  }

  // Action: Request the details to edit a user
  if ($act == 'edituser') {

    // Retrieve User information
    $usersRS = db_recordset("SELECT * FROM tbl_Users WHERE id=" . $users[0]);

    if ($message) { display($message); }
?>

  <h1><?php echo gettext('User Admin')?></h1>
  <h2><?php echo gettext('Please enter the following information to edit a user:')?></h2>
        
  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="edituseraction" />
      <input type="hidden" name="oldusername" value="<?php echo $usersRS[0]['username']?>" />
      <input type="hidden" name="user" value="<?php echo $users[0]?>" />
<?php
    foreach ($sites as $record) {
      print "      <input type=\"hidden\" name=\"sites[]\" value=\"" . $record . "\" />\n";
    }
?>
      <div class="labelfieldpair">
        <div class="name"><label for="site"><?php echo gettext('Name')?></label></div>
        <div class="field"><input type="text" name="name" id="name" size="35" maxlength="50" value="<?php echo $usersRS[0][name]?>" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="username"><?php echo gettext('Username')?></label></div>
        <div class="field"><input type="text" name="username" id="username" size="20" maxlength="20" value="<?php echo $usersRS[0][username]?>" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="password"><?php echo gettext('New Password')?></label></div>
        <div class="field"><input type="text" name="password" id="password" size="20" maxlength="20" value="" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="email"><?php echo gettext('Email Address')?></label></div>
        <div class="field"><input type="text" name="email" id="email" size="20" maxlength="40" value="<?php echo $usersRS[0][email]?>" /></div>
      </div>
      <div class="buttonpanel">
        <input name="submit" type="submit" id="submit" value="<?php echo gettext('Submit Changes')?>" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext('Reset')?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext('Cancel')?>" onclick="document.location='sitesandusers.php'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Add the selected member(s) to the selected site(s)
  if ($act == 'add') {

    foreach($users as $userrecord) {
      foreach($sites as $siterecord) {
        db_send("DELETE FROM tbl_UserSites WHERE userid=$userrecord AND site=$siterecord");
        $sql = "INSERT INTO tbl_UserSites (userid,site,usertype) VALUES ($userrecord,$siterecord,$usertype);";
        db_send($sql);
      }
    }
    $act = '';
    $message = gettext('NOTE: Member(s) successfully added to the selected site(s).');
  }

  // Action: Remove the selected member(s) from the selected site(s)
  if ($act == 'remove') {
    foreach($support as $userrecord) {
      $flag = 0;
      $sql = "DELETE FROM tbl_UserSites WHERE userid=$userrecord AND site IN (";
      foreach($sites as $siterecord) {
        if ($flag == 0) {
          $flag = 1;
        } else {
          $sql .= ',';
        }
        $sql .= $siterecord;
      }
      $sql .= ');';
      db_send($sql);

      $sql = '';
    }
    $support = array();
    $act = '';
    $message = gettext('NOTE: Member(s) successfully removed from the selected site(s).');
  }

  // Action: (De)activate the selected member(s)
  if ($act == 'active') {
    foreach($users as $userrecord) {
      $updateuserRS = db_recordset("SELECT * FROM tbl_Users WHERE id=$userrecord;");
      db_send("UPDATE tbl_Users SET available=" . (1 - $updateuserRS[0][available]) . " WHERE id=" . $updateuserRS[0][id] . ";");
    }
    $act = '';
  }

  // Action: (De)restrict the selected member(s)
  if ($act == 'restrict') {
    foreach($users as $userrecord) {
      $updateuserRS = db_recordset("SELECT * FROM tbl_Users WHERE id=$userrecord;");
      db_send("UPDATE tbl_Users SET restricted=" . (1 - $updateuserRS[0][restricted]) . " WHERE id=" . $updateuserRS[0][id] . ";");
    }
    $act = '';
  }

  // Default action: Show sites and user mappings and request action...
  if ($act == '') {
    // Retrieve sites
    if ($is_pgsql) {
      $sql = "SELECT DISTINCT id,site FROM vw_Sites WHERE
      domain=$_SESSION[_domain] AND active=1 ";
      if ($_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
        $sql .= " AND \"user\"=$_SESSION[_id]";
      }
      $sql .= ' ORDER BY site';
    } else {
      $sql = "SELECT DISTINCT tbl_Sites.id,tbl_Sites.site FROM tbl_Sites ";
      if ($_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
        $sql .= ", tbl_UserSites WHERE tbl_UserSites.site = tbl_Sites.id AND tbl_UserSites.site=$_SESSION[_id] AND ";
      } else {
        $sql .=" WHERE ";
      }
      $sql .="tbl_Sites.domain=$_SESSION[_domain] AND tbl_Sites.active=1  ORDER BY tbl_Sites.site";
    }
    
    $sitesRS = db_recordset($sql);
    $num_sites = count($sitesRS);
    // Retrieve user mapping information
    if ($num_sites > 0) {
//       $sql = "SELECT DISTINCT tbl_Users.id,tbl_Users.name,tbl_UserSites.site,tbl_UserSites.usertype 
//     FROM tbl_Users,tbl_UserSites, tbl_UserDomains, tbl_UserTypes, tbl_Sites
//     WHERE tbl_Users.active=1 AND tbl_Users.id > 0 AND tbl_UserDomains.domain=$_SESSION[_domain] 
//     AND tbl_UserTypes.sortorder<$_SESSION[_usertypesortorder]";
//       if ($_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
//         $sql .= " AND site IN (
//     SELECT DISTINCT site FROM tbl_UserDomains, tbl_Users
//     WHERE tbl_UserDomains.domain=$_SESSION[_domain]
//     AND tbl_Users.id=$_SESSION[_id])";
//       }
//       $sql .= " ORDER BY tbl_UserTypes.sortorder,tbl_Users.name";
    ## Attempt 2 (does work)
//     $sql = "SELECT tbl_Users.id,tbl_Users.name, tbl_UserSites.usertype ,tbl_UserSites.site 
//     FROM tbl_Users,tbl_UserSites
//     WHERE tbl_Users.id=tbl_UserSites.userid
//     ORDER BY tbl_UserSites.site";
    ## Attempt 3
      if ($is_pgsql) {
        $sql = "SELECT id,name,site,usertype FROM vw_UserTypes WHERE active=1 AND id > 0 AND domain=$_SESSION[_domain] AND usertypesortorder<$_SESSION[_usertypesortorder]";
        if ($_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
          $sql .= " AND site IN (SELECT DISTINCT site FROM vw_UserTypes WHERE domain=$_SESSION[_domain] AND id=$_SESSION[_id])";
        }
        $sql .= " ORDER BY usertypesortorder,name";
      } else {
        $sql = "SELECT DISTINCT tbl_Users.id,tbl_Users.name, tbl_UserSites.usertype, tbl_UserSites.site, tbl_UserTypes.sortorder
                FROM tbl_Users, tbl_UserSites, tbl_UserDomains, tbl_UserTypes, tbl_Sites
                WHERE tbl_Users.active = 1
                  AND tbl_Users.id > 0
                  AND tbl_UserDomains.domain = $_SESSION[_domain]
                  AND tbl_UserTypes.sortorder < $_SESSION[_usertypesortorder]
                  AND tbl_Users.id = tbl_UserSites.userid";
        if ($_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
          $sql .="  AND tbl_UserSites.site IN (SELECT DISTINCT
                  FROM tbl_UserDomains,tbl_Users WHERE tbl_UserDomains.domain=$_SESSION[_domain]
                    AND tbl_Users.id=$_SESSION[_id])";
        }
        $sql .=" ORDER BY tbl_UserTypes.sortorder, tbl_Users.name";
      }
  
      $usersRS = db_recordset($sql);
    }
    $usertypesRS = db_recordset("SELECT DISTINCT * FROM tbl_UserTypes 
                                 WHERE sortorder<$_SESSION[_usertypesortorder]
                                 ORDER BY sortorder");
    if (!$usertype) $usertype=$usertypesRS[0][id];

    if ($message) { display($message); }
?>

<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

<?php

  /*

      Dynamically create a set of javascript arrays that will be used for the
      client side interface for choosing between the heirarchical mappings of
      sites and usertypes with members.

      The arrays holds the 'children' of each top level category. By choosing
      the appropriate category using two <select> lists the following
      SetupDetails function causes the members list to be rebuilt, on the fly.

  */

    if ($num_sites > 0) {
      $index = 0;
      foreach ($sitesRS as $record) {
        $vindex = 0;
        reset($usertypesRS);
        foreach ($usertypesRS as $vrecord) {
          $current = filter_records(filter_records($usersRS,'site',$record[id]),'usertype',$vrecord[id]);
          $flag = TRUE;
          print ("  var support_${index}_$vindex = new Array('");
          if (count($current) == 0) {
            print ("0','[".gettext('No Support')."]");
          } else {
            foreach ($current as $res_record) {
              if ($flag) {
                $flag = FALSE;
              } else {
                print ("','");
              }
              print ($res_record[id] . "','" . addslashes($res_record[name]));
            }
          }
          print ("');\n");
          $vindex++;
        }
        $index++;
      }
    }
?>

  function SetupDetails () {
    var noDetails = document.mainform.sites.options.length;
    var noTypes = document.mainform.usertype.options.length;
    var DetailsList = document.mainform.support.options;
    var valTemp = 0;
    var oloop=0;
    var flag;
    DetailsList.length = 0;
    for (i=0;i<noDetails;i++) {
     for (j=0;j<noTypes;j++) {
      if (document.mainform.sites.options[i].selected && document.mainform.usertype.options[j].selected && eval('support_' + i + '_' + j + '[0]') != '' && eval('support_' + i + '_' + j + '[0]') != 0) {
  for (loop=0;loop<eval('support_' + i + '_' + j + '.length')/2;loop++) {
          flag = 0;
    valTemp = eval('support_' + i + '_' + j + '[loop*2]');
    textTemp = eval('support_' + i + '_' + j + '[loop*2+1]');
    for (k=0;flag == 0 && k<DetailsList.length;k++) {
      if (DetailsList[k].value == valTemp && DetailsList[k].text == textTemp) {
        flag = 1;
      }
    }
          if (flag == 0) {
            DetailsList[oloop] = new Option(eval('support_' + i + '_' + j + '[loop*2+1]'));
            DetailsList[oloop].value = valTemp;
      oloop++;
          }
  }
      }
     }
    }
    if (document.mainform.support.options.length == 0) {
      DetailsList[0] = new Option('[<?php echo gettext('No Members')?>]');
      DetailsList[0].value = 0;
    }
    DetailsList[0].selected = true;
  }

  function mainSubmit (act) {
    var flag = true;
<?php
    if ($_SESSION['_usertype'] == 'Administrator' || $_SESSION['_usertype'] == 'Root' || $_SESSION['_usertype'] == 'Domain Administrator') {
?>
    if ((act == 'removesite' || act == 'editsite' || act == 'add') && document.mainform.sites.value == 0) {
      alert('<?php echo gettext('There are no sites on which to action your request.')?>');
      flag = false;
    }
    if (act == 'removesite' && flag && !confirm('<?php echo gettext('Are you sure you wish to delete the selected site(s)?')?>')) flag = false;
    if ((act == 'remove' || act == 'edit') && document.mainform.support.value == 0) {
      alert('<?php echo gettext('There are no members on which to action your request.')?>');
      flag = false;
    }
    if (act == 'removeuser' && flag && !confirm('<?php echo gettext('Are you sure you wish to delete the selected user(s)?')?>')) flag = false;
    if ((act == 'removeuser' || act == 'edituser') && document.mainform.users.value == 0) {
      alert('<?php echo gettext('There are no users on which to action your request.')?>');
      flag = false;
    }
<?php
    }
?>
    if (flag) {
      document.mainform.act.value=act;
      document.mainform.submit();
    }
  }

//-->
//]]>
</script>

  <h1><?php echo gettext('Sites and Users')?></h1>
  <h2><?php echo gettext('Please use the lists below to administer sites and users in this system:')?></h2>
        
  <div class="block">
    <form name="mainform" id="mainform" method="post">
      <input type="hidden" name="act" value="" />
<?php
    if ($_SESSION['_usertype'] == 'Root' || $_SESSION['_usertype'] == 'Domain Administrator') {
//  if ($_SESSION['_usertype'] == 'Administrator' || $_SESSION['_usertype'] == 'Root' || $_SESSION['_usertype'] == 'Domain Administrator') {
?>
      <div class="columnleft">
        <div class="labelright"><label for="sites"><?php echo gettext('Sites')?></label></div>
        <div class="columnright">
          <input type="button" value="<?php echo gettext('New')?>..." onclick="mainSubmit('addsite')" /><br />
          <input type="button" value="<?php echo gettext('Edit')?>" onclick="mainSubmit('editsite')" /><br />
          <input type="button" value="<?php echo gettext('Delete')?>" onclick="mainSubmit('removesite')" />
        </div>
        <div class="columnleft">
          <select name="sites[]" id="sites" size="10" onchange="SetupDetails()" multiple="multiple">
<?php
      if ($num_sites == 0) {
        print ("            <option value=\"0\" selected=\"selected\">[".gettext('No Sites')."]</option>\n");
      }
      foreach ($sitesRS as $record) {
        // Set as default if this was previously chosen
        if (count($sites) == 0 || in_array($record[id],$sites)) {$checked = ' selected="selected"';} else {$checked = '';};
          print ("            <option value=\"$record[id]\"$checked>$record[site]</option>\n");
      }
?>
          </select>
        </div>
      </div>
<?php
      if (count($usertypesRS) == 1) {
?>
      <input type="hidden" name="usertype" id="usertype" value="<?php echo $usertypesRS[0][id]?>" />
<?php
      } else {
?>
      <div class="columnleft">
        <div class="labelleft">
          <label for="usertype"><?php echo gettext('Member Type')?></label>
        </div>
        <div class="columnleft">
          <select name="usertype" id="usertype" onchange="SetupDetails()" size="<?php echo count($usertypesRS)?>">
<?php
        $regex = array('/Client/','/Site Contact/','/Support Agent/','/Administrator/','/Domain Administrator/');
        $repl = array(
        gettext('Client'),gettext('Site Contact'),gettext('Support Agent'),gettext('Administrator'),gettext('Domain Administrator'));

        foreach ($usertypesRS as $record) {
          // Set as default if this was previously chosen
          if ($record[id] == $usertype) { $checked = ' selected="selected"'; } else { $checked = ''; }
          print "            <option value=\"$record[id]\"$checked>".
            preg_replace($regex,$repl,$record[type]).
            "</option>\n";
        }
?>
          </select>
        </div>
      </div>
<?php
      }
?>
      <hr class="hide" />
      <div class="columnleft">
        <div class="labelleft"><label for="support"><?php echo gettext('Members')?></label></div>
        <div class="columnleft">
          <select name="support[]" id="support" size="10" multiple="multiple">
            <option selected="selected">[<?php echo gettext('No Support')?>]</option>
          </select>
        </div>
        <div class="columnleft">
          <input type="button" value="< <?php echo gettext('Add')?>" onclick="mainSubmit('add')" /><br />
          <input type="button" value="<?php echo gettext('Remove')?> >" onclick="mainSubmit('remove')" />
        </div>
      </div>
<?php
    }
?>
      <div class="columnleft">
        <div class="labelleft"><label for="users"><?php echo gettext('Available users')?></label></div>
        <div class="columnleft">
          <select name="users[]" id="users" size="10" multiple="multiple">
<?php
    // Retrieve users
    if ($is_pgsql) {
      if ($_SESSION['_usertype'] != 'Administrator' && $_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
        $sql = "SELECT DISTINCT id,name,available,restricted FROM vw_UserTypes WHERE id > 0 AND active=1 AND domain=$_SESSION[_domain] AND usertypesortorder<$_SESSION[_usertypesortorder] AND site IN (SELECT DISTINCT site FROM vw_UserTypes WHERE domain=$_SESSION[_domain] AND id=$_SESSION[_id]) ORDER BY name";
      } else {
        $sql = "SELECT id,name,available,restricted FROM vw_Users WHERE id>0 AND active=1 AND domain=$_SESSION[_domain] AND id NOT IN (SELECT DISTINCT id FROM vw_UserTypes WHERE id > 0 AND domain=$_SESSION[_domain] AND usertypesortorder>=$_SESSION[_usertypesortorder] AND site IN (SELECT DISTINCT site FROM vw_UserTypes WHERE domain=$_SESSION[_domain] AND id=$_SESSION[_id])) ORDER BY name";
      }
    } else {
      if ($_SESSION['_usertype'] != 'Administrator' && $_SESSION['_usertype'] != 'Domain Administrator' && $_SESSION['_usertype'] != 'Root') {
        $sql = "SELECT DISTINCT tbl_Users.id,tbl_Users.name,tbl_Users.available,tbl_Users.tbl_Users.restricted
                FROM tbl_Users, tbl_UserDomains, tbl_UserTypes, tbl_UserSites
                WHERE tbl_Users.id > 0 
                  AND tbl_Users.active=1 
                  AND tbl_UserDomains.domain=$_SESSION[_domain]
                  AND tbl_UserTypes.sortorder<$_SESSION[_usertypesortorder]
                  AND tbl_UserSites.site IN
                   (SELECT DISTINCT tbl_UserSites.site
                    FROM tbl_UserDomains,tbl_Users
                    WHERE tbl_UserDomains.domain=$_SESSION[_domain]
                      AND tbl_Users.id=$_SESSION[_id])
                ORDER BY tbl_Users.name";
      } else {
        $sql = "SELECT tbl_Users.id,tbl_Users.name,tbl_Users.available,tbl_Users.restricted
                FROM tbl_Users, tbl_UserDomains
                WHERE tbl_UserDomains.domain=$_SESSION[_domain]
                  AND tbl_Users.id=tbl_UserDomains.userid
                  AND tbl_Users.id>1
                  AND tbl_Users.active=1
                ORDER BY tbl_Users.name";
      }
    }
    
    $usersRS = db_recordset($sql);
    $num_users = count($usersRS);
    if (!$users) $users=array($usersRS[0][id]);

    if ($num_users == 0) {
      print ("            <option value=\"0\" selected=\"selected\">[".gettext('No Available users')."]</option>\n");
    }
    foreach ($usersRS as $record) {
      // Set as default if this was previously chosen
      if (in_array($record[id],$users)) {$checked = ' selected="selected"';} else {$checked = '';};
      // Show as inactive if so
      if ($record[available] == '0') {
        $style = ' class="inactive"';
      } elseif ($record[restricted] == '1') {
        $style = ' class="restricted"';
      } else {
        $style = '';
      }
      print ("            <option value=\"${record[id]}\"${checked}${style}>${record[name]}</option>\n");
    }
?>
          </select>
        </div>
<?php
    if ($_SESSION['_usertype'] == 'Administrator' || $_SESSION['_usertype'] == 'Root' || $_SESSION['_usertype'] == 'Support Agent' || $_SESSION['_usertype'] == 'Domain Administrator') {
?>
        <div class="columnleft">
<?php
      if ($_SESSION['_usertype'] != 'Support Agent') {
?>
          <input type="button" value="<?php echo gettext('New')?>..." onclick="mainSubmit('adduser')" /><br />
<?php
      }
?>
          <input type="button" value="<?php echo gettext('Edit')?>" onclick="mainSubmit('edituser')" /><br />
<?php
      if ($_SESSION['_usertype'] != 'Support Agent') {
?>
          <input type="button" value="<?php echo gettext('Remove')?>" onclick="mainSubmit('removeuser')" /><br />
<?php
      }
?>
          <input type="button" value="<?php echo gettext('(De)activate')?>" onclick="mainSubmit('active')" /><br />
          <input type="button" value="<?php echo gettext('(De)restrict')?>" onclick="mainSubmit('restrict')" /><br />
<?php
      if ($_SESSION['_usertype'] != 'Support Agent') {
?>
          <input type="button" value="<?php echo gettext('Import')?>..." onclick="mainSubmit('import')" /><br />
<?php
      }
?>
        </div>
<?php
    }
?>
      </div>
    </form>
    <hr class="hide" />
    <p><?php echo gettext("* Italicised names in the 'Available users' list denote inactive (unavailable) users.")?></p>
    <p><?php echo gettext("* Bold, grayed out names in the 'Available users'denotes Restricted users cannot change their details or edit those of other users.")?></p>
  </div>

<?php
    if ($num_sites > 0) {
?>
<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  SetupDetails();

// -->
//]]>
</script>
<?php
    }
  }

  // Include
  require 'footer.php';
?>
