<?php

/*

Note, when upgrading to revision 1.21, you will need to add another
field to the table for bbuser. ie.

alter table bbuser add htmlpost tinyint;

Also, when upgrading to revision 1.7, you will need to add another
field to the table for bbuser. ie.

alter table bbuser add unlimited_post_length tinyint;

*/

/*

Copyright © 2001 Nick Gammon.

  Author: Nick Gammon <nick@gammon.com.au>
  Web:    http://www.gammon.com.au/
  Date:   February 2001

  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; either version 2 of the License, 
  or (at your option) any later version. 

  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.


  The Free Software Foundation maintains a web page at: http://www.fsf.org

  See the file gpl.txt for the full GNU General Public License.

*/

require ("config.php");
require ($CONFIG_PATH . "general_config.php");
require ($INCLUDE_DIRECTORY . "common.php");

Init ("Forum registration", "forum, add, edit, user"); 

$forum_name = $control ['forum_name'];

// default action is add new user
if (!$action)
  $action = "add";
  
if ($action == "add" && ($bbuser_id || strlen ($bbuser_id)))
  Problem ("Cannot add if user ID is specified");
  
// load up countries    
$result = mysql_query ("SELECT countryname FROM country "
                     . "ORDER BY countryname") 
  or Problem ("Select of countries failed: " . mysql_error ());
while ($row = mysql_fetch_row ($result))
  $countrylist [$row [0]] = $row [0];  
mysql_free_result ($result);  
    

if ($foruminfo ['admin'])
  {
  $topiclist [0] = '(no topic)';
  // load up topics    
  $result = mysql_query ("SELECT bbtopic_id, concat(section_name, ': ', topic_name) "
                       . "AS description FROM bbtopic, bbsection "
                       . "WHERE bbsection.bbsection_id = bbtopic.bbsection_id  "
                       . "ORDER BY section_name, topic_name") 
    or Problem ("Select of topics failed: " . mysql_error ());
  while ($row = mysql_fetch_array ($result))
    $topiclist [$row ['bbtopic_id']] = $row ['description'];  
  mysql_free_result ($result);  


  // load up sections    
  $result = mysql_query ("SELECT bbsection_id, section_name "
                       . "AS description FROM bbsection "
                       . "ORDER BY section_name") 
    or Problem ("Select of sections failed: " . mysql_error ());
  while ($row = mysql_fetch_array ($result))
    $sectionlist [$row ['bbsection_id']] = $row ['description'];  
  mysql_free_result ($result);  
   }
     
$specials = array
  (
  'username'     => array (
                'input' => 'username',
                'description' => 'Name:',
                'comment' => "This name will be shown on posts and replies in the forum. "
                           . "You will log on to the forum using this name. It doesn't "
                           . "have to be your real name, just a name for the forum.",
                'size' => 30,
                'maxlength' => 30
                ),    // name
  'password'     => array (
                'input' => 'password',
                'description' => 'Password:',
                'comment' => 'Your password, to ensure that only you post under this name.',
                'size' => 20,
                'maxlength' => 20
                ),    // password
  'email'     => array (
                'input' => 'email',
                'description' => 'Email address:',
                'comment' => 'Your email address. eg. yourname@yourdomain.com',                
                'size' => 60,
                'maxlength' => 255
                ),    // email
  'show_email'     => array (
                'input' => 'show_email',
                'type' => 'bool',
                'description' => 'Show email?',
                'comment' => 'If checked, allow other forum users to view your email address.',
                ),    // show_email
  'allow_mail'     => array (
                'input' => 'allow_mail',
                'type' => 'bool',
                'description' => 'Allow mail?',
                'comment' => 'If checked, allow other forum users to send you email (via the forum).',
                ),    // allow_mail
  'use_cookies'     => array (
                'input' => 'use_cookies',
                'type' => 'bool',
                'description' => 'Use cookies?',
                'comment' => 'If checked, use cookies, so you don\'t have to log in every time.',
                ),    // use_cookies
  'country' => array (
                'input' => 'country',
                'type' => 'combo',
                'values' => $countrylist,
                'description' => 'Your country:',
                'comment' => "(optional)\nWhat country you live in.",
                ),    // country
  'icq' => array (
                'input' => 'icq',
                'description' => 'ICQ number:',
                'comment' => "(optional)\nYour ICQ number, if you have one, and wish it to be made public.",
                'size' => 10,
                'maxlength' => 10
                ),    // icq
  'cookie_expiry_days' => array (
                'input' => 'cookie_expiry_days',
                'description' => 'Cookie expires:',
                'comment' => "(optional)\nNumber of days before your cookie expires, after logging on.\n"
                           . "Default if blank is seven days. Can be a fraction, eg. one hour is approx 0.042 days.",
                'size' => 10,
                'maxlength' => 10
                ),    // cookie_expiry_days
  'time_zone' => array (
                'input' => 'time_zone',
                'description' => 'Time correction:',
                'comment' => "(optional)\nNumber of hours time difference between you and UTC.\n"
                           . "Default if blank is UTC (Universal Co-ordinated Time). \n"
                            . "Below are some example time zone corrections:",
                'htmlcomment' => "<ul>\n"
                               . "<li> 0 Dublin, Edinburgh, Lisbon, London, Monrovia, Casablanca\n"
                               . "<li> +1 Amsterdam, Berlin, Rome, Paris, Madrid \n"
                               . "<li> +2 Athens, Helsinki, Istanbul, Cairo, E. Europe \n"
                               . "<li> +3 Baghdad, Kuwait, Nairobi, Moscow \n"
                               . "<li> +4 Abu Dhabi, Kazan, Muscat \n"
                               . "<li> +5 Islamabad, Karachi, Tashkent\n" 
                               . "<li> +6 Almaty, Dhaka \n"
                               . "<li> +7 Bangkok, Jakarta, Hanoi \n"
                               . "<li> +8 Beijing, Hong Kong, Perth, Singapore, Taipei\n"
                               . "<li> +9 Tokyo, Osaka, Sapporto, Seoul, Yakutsk\n"
                               . "<li> +10 Brisbane, Melbourne, Sydney, Guam \n"
                               . "<li> +11 Magadan, Soloman Is., New Caledonia \n"
                               . "<li> +12 Fiji, Kamchatka, Marshall Is., Wellington\n"
                               . "<li> -1 Azores, Cape Verde Is.\n"
                               . "<li> -2 Mid-Atlantic \n"
                               . "<li> -3 Brasilia, Buenos Aires, Georgetown \n"
                               . "<li> -4 Atlantic Time (Canada), Caracas, La Paz \n"
                               . "<li> -5 Eastern Time (US & Canada), Indiana (East) \n"
                               . "<li> -6 Central Time (US & Canada), Mexico city\n"
                               . "<li> -7 Arizona, Mountain Time (US & Canada) \n"
                               . "<li> -8 Pacific Time (US & Canada), Tijuana \n"
                               . "<li> -9 Alaska \n"
                               . "<li> -10 Hawaii \n"
                               . "<li> -11 Midway Island, Samoa\n"
                               . "<li> -12 Eniwetok, Kwajalein\n"
                               . "</ul>",
                'size' => 3,
                'maxlength' => 3
                ),    // time_zone
  'home_page' => array (
                'input' => 'home_page',
                'description' => 'Personal link:',
                'comment' => "(optional)\nA link to your home page, or other favourite page.",
                'size' => 60,
                'maxlength' => 255
                ),    // home_page
  'birth_date'     => array (
                'input' => 'birth_date',
                 'description' => 'Date of birth:',
                'comment' => "(optional)\nEnter your date of birth if you wish your age to be displayed to other forum users.\n"
                            . "Format: YYYY-MM-DD. eg. 1948-12-03\n"
                            . "Hint: If you want to display your approximate age, but not reveal your exact birthdate, just supply "
                            . "the year, eg. 1960-01-01",
                'size' => 10,
                'maxlength' => 10
                 ),    // birth_date
  'bio' => array (
                'input' => 'bio',
                'type' => 'multiline',
                'description' => 'Personal biography:',
                'comment' => "(optional)\nUse this to disclose any information about yourself you want others to see. \n"
                           . "Maximum of 4,000 characters. Text only please, no HTML.",
                'rows' => 10,
                'cols' => 60
                ),    // bio
  'signature' => array (
                'input' => 'signature',
                'description' => 'Signature:',                
                'comment' => "(optional)\nThis will appear at the bottom of each post you make. \n"
                           . "Maximum of 1,000 characters. Text only please, no HTML.",
                'type' => 'multiline',
                'rows' => 5,
                'cols' => 60
                ),    // signature
  'admin'     => array (
                'input' => 'admin',
                'type' => 'bool',
                'description' => 'Administrator?',
                'comment' => 'If checked, user is a forum administrator. USE WITH CARE.',
                ),    // admin
  'htmlpost'     => array (
                'input' => 'htmlpost',
                'type' => 'bool',
                'description' => 'Post in HTML?',
                'comment' => 'If checked, user may make HTML posts.',
                ),    // htmlpost
  'unlimited_post_length'     => array (
                'input' => 'unlimited_post_length',
                'type' => 'bool',
                'description' => 'Unlimited length posts?',
                'comment' => 'If checked, user has no restriction on post length.',
                ),    // unlimited_post_length
  'moderator_topic' => array (
                'input' => 'moderator_topic',
                'type' => 'combo',
                'values' => $topiclist,
                'description' => 'Moderator for:',
                'comment' => "What topic this person is the moderator for.",
                ),    // moderator_topic
  'moderator_section' => array (
                'input' => 'moderator_section',
                'type' => 'combo',
                'values' => $sectionlist,
                'description' => 'Moderator for:',
                'comment' => "What section this person is the moderator for.",
                ),    // moderator_section
  'blocked'     => array (
                'input' => 'blocked',
                'type' => 'bool',
                'description' => 'Blocked?',
                'comment' => 'If checked, user cannot log in or make posts.',
                ),    // blocked
  'bounced'     => array (
                'input' => 'bounced',
                'type' => 'bool',
                'description' => 'Mail bounced?',
                'comment' => 'If checked, mail to this user has bounced.',
                ),    // bounced
  'notify_new_thread'     => array (
                'input' => 'notify_new_thread',
                'type' => 'bool',
                'description' => 'Notify on new subject?',
                'comment' => "If checked, you will be notified by email when a new subject (thread) is started.\n"
                           . "You can then subscribe to it if you want to be notified of further postings to that thread." ,
                ),    // notify_new_thread
  'notify_add'     => array (
                'input' => 'notify_add',
                'type' => 'bool',
                'description' => 'Notify on add?',
                'comment' => 'If checked, user will be notified by email of all new message postings.',
                ),    // notify_add
  'notify_amend'     => array (
                'input' => 'notify_amend',
                'type' => 'bool',
                'description' => 'Notify on amend?',
                'comment' => 'If checked, user will be notified by email of all message amendments.',
                ),    // notify_amend
  'notify_delete'     => array (
                'input' => 'notify_delete',
                'type' => 'bool',
                'description' => 'Notify on delete?',
                'comment' => 'If checked, user will be notified by email of all message deletions.',
                ),    // notify_delete
  'notify_new_user'     => array (
                'input' => 'notify_new_user',
                'type' => 'bool',
                'description' => 'Notify on new user?',
                'comment' => 'If checked, user will be notified by email of all user registrations.',
                ),    // notify_new_user
  'notify_amend_user'     => array (
                'input' => 'notify_amend_user',
                'type' => 'bool',
                'description' => 'Notify on amend user?',
                'comment' => 'If checked, user will be notified by email of all user registration amendments.',
                ),    // notify_amend_user
  );  // end of specials
    
?>

<h1><?php echo $forum_name; ?></h1>

<?php

CheckField ("user identifier", $bbuser_id);
 
if ($action == "amend")
  {
  CheckField ("user identifier", $bbuser_id, false);

  if (!$foruminfo)
    Problem ("You have not logged in");
  
  if ($foruminfo ['bbuser_id'] != $bbuser_id && !$foruminfo ['admin'])
    Problem ("You cannot edit another user's profile");
     
  $query = "SELECT * "
         . "FROM bbuser "
         . "WHERE bbuser_id = $bbuser_id";
    
  // echo $query;
                        
  $result = mysql_query ($query) 
      or Problem ("Select of user failed: " . mysql_error ());
  
  if (!($row = mysql_fetch_array ($result)))
    Problem ("User id $bbuser_id is not on file");
    
  mysql_free_result ($result);

  if ($row ['blocked'])
    Problem ("User $username is not permitted to do this");

  // I'll add the slashes here to be consistent with how they would appear
  // if you amend a page and make an error
  // The slashes will be stripped when the form is redisplayed
  
  $username = addslashes ($row ['username']);
  $email = addslashes ($row ['email']);
  $show_email = $row ['show_email'];
  $allow_mail = $row ['allow_mail'];
  $use_cookies = $row ['use_cookies'];
  $country = addslashes ($row ['country']);
  $icq = $row ['icq'];
  $cookie_expiry_days = $row ['cookie_expiry'] / 86400.0;   // convert to days
  if ($cookie_expiry_days)  // now round to 5 decimal places or it looks silly
    $cookie_expiry_days = round ($cookie_expiry_days * 100000) / 100000.0;
  else
    $cookie_expiry_days = "";   // zero becomes blank
  $time_zone = $row ['time_zone'];
  $home_page = addslashes ($row ['home_page']);
  $birth_date = $row ['birth_date'];
  $bio = addslashes ($row ['bio']);
  $signature = addslashes ($row ['signature']);

  // admin stuff
  $admin = $row ['admin'];
  $htmlpost = $row ['htmlpost'];
  $unlimited_post_length = $row ['unlimited_post_length'];
  $moderator_topic = $row ['moderator_topic'];
  $moderator_section = $row ['moderator_section'];
  $blocked = $row ['blocked'];
  $bounced = $row ['bounced'];
  $notify_new_thread = $row ['notify_new_thread'];
  $notify_add = $row ['notify_add'];
  $notify_amend = $row ['notify_amend'];
  $notify_delete = $row ['notify_delete'];
  $notify_new_user = $row ['notify_new_user'];
  $notify_amend_user = $row ['notify_amend_user'];
      
  $old_email = $email;  // so we know if it changes

  if ($bounced)  
    $specials ['email'] ['error'] = "That email address has bounced. Please choose another one.";
  
  } // end of amending him
  
if ($action == "add" || !$action)
  {
  
  if (!$control ['allow_registrations'])
    Problem ("New registrations are not being processed at present");
    
?>

<hr>
<h2>Forum registration</h2>

<p>Use this form to register as a user of the <?php echo $forum_name; ?>. 
Registration enables us to ensure that forum discussions
occur in an orderly way, however no details will be disclosed to third parties
without your consent.</p>
<p>Your email address is only for our records, unless you indicate that you wish
it to be revealed (so people can discuss topics with you directly). We do not sell
or give away our mailing lists to anyone.</p>
<hr>
<h2>New forum user</h2>
<p>Fields marked &quot;<font color="#FF0000">*</font>&quot; are required, others may be left blank.<br> 
Press the &quot;Save&quot; button when
finished to send your details to our server.</p>
<?php  
  
  $show_email = true;
  $allow_mail = true;
  $use_cookies = true;
  
  } // end of new user

if ($action == "amend")
  if ($foruminfo ['bbuser_id'] != $bbuser_id && $foruminfo ['admin'])
    echo "<hr><h2>Amend other forum user: $username</h2>\n";
  else
    {
  ?>
  
  <hr>
  <h2>Forum registration</h2>
  
  <p>Use this form to amend your forum profile.</p>
  <p>Your email address is only for our records, unless you indicate that you wish
  it to be revealed (so people can discuss topics with you directly). We do not sell
  or give away our mailing lists to anyone.</p>
  <p>You may optionally enter biographic details, your country, ICQ number, birthdate, and signature 
  information. This is designed to help other people to get to know you, however it is
  not required to do so.</p>
  <h3>Password</h3>
  
  <p>If you change your email address a new password will be emailed to you. This is so that
     we can be sure that you have entered your new email address correctly.</p>
  <p>You will need to use this new password next time you log on to the forum.</p>

<?php
  echo "<p>You can ";
  hLink ("change your password", "bbpassword.php", "bbuser_id=$bbuser_id&action=change");
  echo " if you wish.</p>";
?>
     
  <hr>
  <h2>Amend profile for <?php echo $username; ?></h2>
  <p>Fields marked &quot;<font color="#FF0000">*</font>&quot; are required, others may be left blank.<br> 
  Press the &quot;Save&quot; button when
  finished to send your updated details to our server.</p>
  <?php  
    
    } // end of amend user (and not an admin)
    
if ($action == "Save")
  {
?>

<hr>
<h2>Forum user details</h2>
<?php  

  }   // end of save done


if ($action == "Save")
  {
  // don't let them slip in multiple spaces
  while (strstr ($username, "  "))
    $username = str_replace ("  ", " ", trim($username));
  while (strstr ($email, "  "))
    $email = str_replace ("  ", " ", trim($email));
  
  $home_page = trim ($home_page);   // forget excess spaces
  
  // on an add, force user name to proper capitalisation
  //  so we don't get too many john smith or JOHN SMITHs on file
  // however on a modify you can change it, eg. for Archie McDonald
  
  if (!$bbuser_id)
    $username = ucwords ($username);
    
  ValidateOneField ('username', 'text', true, 30, $specials);
//  ValidateOneField ('password', 'text', true, 20, $specials);
  ValidateOneField ('email', 'email', true, 255, $specials);
  ValidateOneField ('icq', 'int', false, 10, $specials);
  ValidateOneField ('cookie_expiry_days', 'real', false, 10, $specials);
  ValidateOneField ('time_zone', 'int', false, 3, $specials);
  ValidateOneField ('home_page', 'text', false, 255, $specials);
  ValidateOneField ('birth_date', 'date', false, 10, $specials);
  ValidateOneField ('bio', 'text', false, 4000, $specials);
  ValidateOneField ('country', 'text', false, 60, $specials);
  ValidateOneField ('signature', 'text', false, 1000, $specials);
  ValidateOneField ('show_email', 'bool', false, 1, $specials);
  ValidateOneField ('allow_mail', 'bool', false, 1, $specials);
  ValidateOneField ('use_cookies', 'bool', false, 1, $specials);

  if (!$specials ['username'] ['error'])
    if (ereg ("[^0-9A-Za-z\._\' \-]", $username))
      {
      $have_error = true;
      $specials ['username'] ['error'] = "The user name contains invalid characters";
      } // end of bad user name

  if (!$specials ['home_page'] ['error'])
    if (ereg ("[^0-9A-Za-z\._\/\~\:\-]", $home_page))
      {
      $have_error = true;
      $specials ['home_page'] ['error'] = "The personal link contains invalid characters";
      } // end of bad home page

  if (!$specials ['email'] ['error'])
if (!eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}$", $email, $check)) 
// old    if (ereg ("[^0-9A-Za-z\\-\\.@_]", $email))
      {
      $have_error = true;
      $specials ['email'] ['error'] = "The email address contains invalid characters";
      } // end of bad email address
        
  if (!$specials ['time_zone'] ['error'] && $time_zone)
    if ($time_zone < -12 || $time_zone > 13)
      {
      $have_error = true;
      $specials ['time_zone'] ['error'] = "Time zone correction must be in range -12 to +13 hours";
    } // end of bad time zone
   
   
  if (!$specials ['email'] ['error'])
    {

    $domain = substr ($email, strpos ($email, '@') + 1);
      
    $query = "SELECT * "
           . "FROM bbbanned "
           . "WHERE banned_address  = '$email' "
           . "OR banned_address = '$domain'";
                             
    $result = mysql_query ($query) 
        or Problem ("Select of banned address failed: " . mysql_error ());

   if ($row = mysql_fetch_array ($result))  
      {
      $have_error = true;
      $specials ['email'] ['error'] = "That email address is not permitted to be registered";
      } // end of a match
      
    mysql_free_result ($result);
         
    } // end of checking email address against banned list

  // we must know their old email, and whether or not it bounced
  if ($bbuser_id)  // only if they amend an existing user
    {
          
    $query = "SELECT * "
           . "FROM bbuser "
           . "WHERE bbuser_id = $bbuser_id";
                                  
    $result = mysql_query ($query) 
        or Problem ("Select of user failed: " . mysql_error ());

    if (!($row = mysql_fetch_array ($result)))
      Problem ("User id $bbuser_id is not on file");
      
    mysql_free_result ($result);
  
    $old_email = $row ['email'];
    $old_bounced = $row ['bounced'];
    
    } // end of saving an existing user

  // see if email address unchanged, and the old one bounced - however let admins get away with it
  if (!$specials ['email'] ['error'])
    if ($old_bounced && $email == $old_email )  
      if (!$foruminfo ['admin'])
        {
        $have_error = true;
        $specials ['email'] ['error'] = "That email address has bounced. Please choose another one.";
        } // end of bounced mail
    
  if (!$bbuser_id)  // adding user
    {
    // don't allow duplicate names or email addresses
    
    $query = "SELECT * "
           . "FROM bbuser "
           . "WHERE username = '$username' "
           . "OR email = '$email'";
                             
    $result = mysql_query ($query) 
        or Problem ("Select of user failed: " . mysql_error ());
    
    if ($row = mysql_fetch_array ($result))  
      {
      $have_error = true;
      if ($row ['username'] == $username)
        $specials ['username'] ['error'] = "That person is already registered - "
                                         . "please choose another name";
      else if ($row ['email'] == $email)
        $specials ['email'] ['error'] = "That email address is already registered - "
                                         . "please choose another email address";
      else  // this shouldn't happen :)
        $specials ['username'] ['error'] = "Duplicate registration.";
      
      } // end of a match
          
    mysql_free_result ($result);
    }   // end of adding (not amending)
  
  } // end of save requested
else if ($action == "add" || $action == "amend")
  {
  // on add, indicate required fields
  $specials ['username'] ['error'] = "*";
  if (!$specials ['email'] ['error'])
    $specials ['email'] ['error'] = "*";
  }  

if ($have_error)
  {
?>
<hr>
<h2>Error in submission</h2>
<p>There were some errors in processing your submission.</p>
<p>Please correct them and re-submit the form (by clicking on &quot;Save&quot;). Thank you.</p> 
  
<?php  
  } // end of error in fields
else
  if ($action == "Save")
    {
    if (!$bbuser_id)  // adding user
      {
      srand ((double) microtime () * 1000000);
      $password = base64_encode (substr (md5 (uniqid (rand ())), 1, 6));
      $date_registered = strftime ("%Y-%m-%d %H:%M:%S", utctime());
      
      // generate a random token - they won't know that one!
      srand ((double) microtime () * 1000000);
      $token = md5 (uniqid (rand ()));
      
      $query = "INSERT INTO bbuser ("
             . "username, password, date_registered, email, show_email, allow_mail, use_cookies, icq, "
             . "home_page, birth_date, bio, country, signature, count_posts, token"
             . ") VALUES ("
             . "'$username', "
             . "'$password', "
             . "'$date_registered', "
             . "'$email', "
             . "'$show_email', "
             . "'$allow_mail', "
             . "'$use_cookies', "
             . ($icq ?        "'$icq', " : "NULL, ")
             . ($home_page ?  "'$home_page', " : "NULL, ")
             . ($birth_date ? "'$birth_date', " : "NULL, ")
             . ($bio ?        "'$bio', " : "NULL, ")
             . ($country ?    "'$country', " : "NULL, ")
             . ($signature ?  "'$signature', " : "NULL, ")
             . "0, "   // count_posts
             . "'$token'"
             . ")";
             
  //    echo $query . "<br>";         
      
      $result = mysql_query ($query) 
        or Problem ("Insert failed: " . mysql_error ());
      if (mysql_affected_rows () == 0)
        Problem ("Could not insert record");
      $bbuser_id = mysql_insert_id ();
        
      MailAdmins ("New user: $username", "joined the forum (email address $email).", 
                  "/bbuseredit.php?action=amend&bbuser_id=$bbuser_id",
                  "notify_new_user");

      echo "<p><b>New user added.</b></p>\n";
      ?>
      
      
      <p>
      Welcome to <?php echo $forum_name; ?>.
      </p>
      
      <p>
      Thanks for registering. You can now post messages, or reply to existing messages.
      </p>
      
      <?php        
        
      } // end of add new user
    else
      { // amending user
      
      CheckField ("user identifier", $bbuser_id, false);
 
      if ($foruminfo ['bbuser_id'] != $bbuser_id && !$foruminfo ['admin'])
        Problem ("You cannot edit another user's profile");
            
      $query = "SELECT * "
             . "FROM bbuser "
             . "WHERE bbuser_id = $bbuser_id";
                                    
      $result = mysql_query ($query) 
          or Problem ("Select of user failed: " . mysql_error ());
      
      if (!($row = mysql_fetch_array ($result)))
        Problem ("User id $bbuser_id is not on file");
        
      mysql_free_result ($result);
    
      $old_email = $row ['email'];

      // need new password?
      if ($email != $old_email)
        {
        srand ((double) microtime () * 1000000);
        $password = base64_encode (substr (md5 (uniqid (rand ())), 1, 6));
        }
      else
        $password = $row ['password'];  // keep existing

      if ($email != $old_email)
        $bounced = false;       // updating email addresses clears the bounced flag
        
      if ($cookie_expiry_days)
        $cookie_expiry = round ($cookie_expiry_days * 86400); // convert back to seconds
      else
        $cookie_expiry = "NULL";
      
      if ($time_zone == "")
        $time_zone = "NULL";
        
      $query = "UPDATE bbuser SET "
             . "username = '$username', "
             . "password = '$password', "
             . "email = '$email', "
             . "show_email = '$show_email', "
             . "allow_mail = '$allow_mail', "
             . "use_cookies = '$use_cookies', "
             . "notify_new_thread = '$notify_new_thread', "
             . "cookie_expiry = $cookie_expiry, "
             . "time_zone = $time_zone, "
             . "icq = " . ($icq ? "'$icq', " : "NULL, ")
             . "home_page = " . ($home_page ? "'$home_page', " : "NULL, ")
             . "birth_date = " . ($birth_date ? "'$birth_date', " : "NULL, ")
             . "bio = " . ($bio ? "'$bio', " : "NULL, ")
             . "country = " . ($country ? "'$country', " : "NULL, ")
             . "signature = " . ($signature ? "'$signature' " : "NULL ");

      // just to make sure, only update these fields if we know an admin is doing it
      
      if ($foruminfo ['admin'])
        $query .= ", admin = '$admin', "
                . "htmlpost = '$htmlpost', "
                . "unlimited_post_length = '$unlimited_post_length', "
                . "moderator_topic = '$moderator_topic', "
                . "moderator_section = '$moderator_section', "
                . "blocked = '$blocked', "
                . "bounced = '$bounced', "
                . "notify_add = '$notify_add', "
                . "notify_amend = '$notify_amend', "
                . "notify_delete = '$notify_delete', "
                . "notify_new_user = '$notify_new_user', "
                . "notify_amend_user = '$notify_amend_user' ";

      // add the WHERE clause
      $query .= "WHERE bbuser_id = $bbuser_id";
  
      $result = mysql_query ($query) 
        or Problem ("Update failed: " . mysql_error ());

      if (mysql_affected_rows () > 0)
        {
        if ($email != $old_email)
          $extra = "\n\nOld email was $old_email, new email is $email";
        else
          $extra = "";
          
        MailAdmins ("Amended user: $username", "amended his/her entry$extra", 
                    "/bbuseredit.php?action=amend&bbuser_id=$bbuser_id",
                    "notify_amend_user");

        echo "<p><b>Registration details updated.</b></p>\n";
        }
      else
        echo "<p><b>No details changed.</b></p>\n";
      
      } // end of modify user


// tell user their new password *if they amended their own record*
//  if ($email != $old_email && $foruminfo ['bbuser_id'] == $bbuser_id)

  // tell user their new password - we do this even if admins change it
  // in case they forget their password, and bugger up their email address
  if ($email != $old_email)
    {  
    
    $forum_url = $control ['forum_url'];
    
    // send mail message
    
    $mailresult = mail ($username . " <" . $email . ">", 
          "$forum_name password",
          "Hi $username,\n\n" 
        . "As requested, here is your $forum_name password.\n\n"
        . "Forum user name: \"$username\"\n\n"
        . "Password       : \"$password\"\n\n"
        . "You can visit the forum at:\n\n  $forum_url/\n\n"
        . $control ['email_signature'],
        // mail header
        "From: " . $control ['email_from'] . "\r\n"
      . "Content-type: text/plain\r\n"
      . "X-mailer: PHP/" . phpversion()
        );
    
    if (!$mailresult)
      Problem ("An error occurred sending the email message");
      
    echo "<p>Your password is now being emailed to <b>" 
          . htmlspecialchars ($email) . "</b></p>\n";
    
    // now update the date we did this 
    
    $today = strftime ("%Y-%m-%d", utctime());   // today's date
    
    $query = "UPDATE bbuser SET "
        . "date_password_mailed = '$today' "
        . "WHERE bbuser_id = $bbuser_id";
      
    $result = mysql_query ($query) 
        or Problem ("Update of date sent failed: " . mysql_error ());

    } // end of email address changing

  
  echo "<hr>\n";
  bList ();
  LI (); hLink ("Go to $forum_name", "bbshowpost.php");
  LI (); hLink ("Edit my profile", "bbuseredit.php", "action=amend&bbuser_id=$bbuser_id");
  LI (); hLink ("View my profile", "bbshowbio.php", "bbuser_id=$bbuser_id");
  LI (); hLink ("View list of registered users", "bbuserlist.php", "", false); 
  
  eList ();
  MessageTail (false);
  die ();
      
  } // end of saving 
  
echo "<form METHOD=post ACTION=\"$PHP_SELF\">\n";
  
$table = array 
  (
  'username' => stripslashes ($username),  
//  'password' => stripslashes ($password),   
  'email' => stripslashes ($email),       
  'show_email' => $show_email,    
  'allow_mail' => $allow_mail,    
  'use_cookies' => $use_cookies,
  );  // end of array

if ($bbuser_id)
  {
  $table ['cookie_expiry_days'] = $cookie_expiry_days;
  $table ['country'] = stripslashes ($country);
  $table ['time_zone'] = $time_zone;
  $table ['icq'] = $icq;
  $table ['home_page'] = stripslashes ($home_page);
  $table ['birth_date'] = $birth_date;
  $table ['bio'] = stripslashes ($bio);
  $table ['signature'] = stripslashes ($signature);
  $table ['notify_new_thread'] = $notify_new_thread;  
  } // end of amending existing
  
if ($foruminfo ['admin'])
  {
  $table ['admin'] = $admin;
  $table ['htmlpost'] = $htmlpost;
  $table ['unlimited_post_length'] = $unlimited_post_length;
  $table ['moderator_section'] = $moderator_section;
  $table ['moderator_topic'] = $moderator_topic;
  $table ['blocked'] = $blocked;  
  $table ['bounced'] = $bounced;  
  $table ['notify_add'] = $notify_add;  
  $table ['notify_amend'] = $notify_amend;  
  $table ['notify_delete'] = $notify_delete;  
  $table ['notify_new_user'] = $notify_new_user;  
  $table ['notify_amend_user'] = $notify_amend_user;      
  }
$params = array
  (
  'LH' => 'valign=top bgcolor="#ADD8E6" align=right',
  'RH' => 'bgcolor="#FAF0E6" align=left'
  );

      
ShowTable ($table, $params, $specials);

?>

<p><b>Save your settings ...</b></p>
<p>
<input Type=submit Name=action Value="Save">
</p>

<input type=hidden name=bbuser_id value=<?php echo ($bbuser_id); ?>>
<?php FormSession (); ?>

</form>
    
<?php

if ($action == "add" || !$action)
  {
?>

<hr>
<h2>Password</h2>
<p>A randomly-generated password will be emailed to you upon completion of this form.
You can use this password to submit discussion topics, and to modify your biographical 
information.</p>
<p>By emailing you the password we are confirming that you have correctly entered your
email address. If you do not get a reply within a couple of minutes please check that
you submitted your correct email address, and if not, resubmit the corrected form.</p>
<h3>Forgotten password</h3>
<p>If you ever forget your password you can request it to be re-emailed to you.</p>

<?php  

}   // end of new user

hLink ("Back to $forum_name", "bbshowpost.php");

MessageTail (false);
?>    
