<?php

  // load viewer library
  $libraryPath = 'cmsAdmin/lib/viewer_functions.php';
  $dirsToCheck = array('','../','../../','../../../','../../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  // error checking
  if (!@$GLOBALS['WEBSITE_MEMBERSHIP_PLUGIN']) { die("You must activate the Website Membership plugin before you can access this page."); }

  //
  $showSignupForm = true;

  // error checking
  if (@$CURRENT_USER) {
    $errorsAndAlerts = "You are already signed up! <a href='{$GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL']}'>Click here to continue</a>.";
    $showSignupForm = false;
  }

  // process form
  if (@$_REQUEST['save']) {


    // error checking
    $errorsAndAlerts = "";
    if (!@$_REQUEST['fullname'])                { $errorsAndAlerts .= "You must enter your full name!<br/>\n"; }
    if (!@$_REQUEST['email'])                   { $errorsAndAlerts .= "You must enter your email!<br/>\n"; }
    else if(!isValidEmail(@$_REQUEST['email'])) { $errorsAndAlerts .= "Please enter a valid email (example: user@example.com)<br/>\n"; }
    if (!@$_REQUEST['username'])                { $errorsAndAlerts .= "You must choose a username!<br/>\n"; }

    // check for duplicate usernames and emails
    if (!$errorsAndAlerts) {
      $count = mysql_count($GLOBALS['WSM_ACCOUNTS_TABLE'], "`username` = '".mysql_escape(@$_REQUEST['username'])."'");
      if ($count > 0 && @$_REQUEST['username']) { $errorsAndAlerts .= "That username is already in use, please choose another!<br/>\n"; }

      $count = mysql_count($GLOBALS['WSM_ACCOUNTS_TABLE'], "'".mysql_escape($_REQUEST['email'])."' IN (email, username)");
      if ($count > 0) { $errorsAndAlerts .= "That email is already in use, please choose another!<br/>\n"; }
    }

    // turn off strict mysql error checking for: STRICT_ALL_TABLES
    mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)

    // add user
    if (!$errorsAndAlerts) {

      // generate password
      $password     = substr(md5(uniqid(mt_rand(), true)), 15); // example output: c5560251ef0b3eef9
      if (@$SETTINGS['advanced']['encryptPasswords']) { $passwordHash = getPasswordDigest($password); }
      else                                            { $passwordHash = $password; }

      //
      mysql_query("INSERT INTO `{$TABLE_PREFIX}" . @$GLOBALS['WSM_ACCOUNTS_TABLE'] . "` SET
                      fullname         = '".mysql_escape( $_REQUEST['fullname'] )."',
                      email            = '".mysql_escape( $_REQUEST['email'] )."',
                      username         = '".mysql_escape( $_REQUEST['username'] )."',
                      password         = '".mysql_escape( $passwordHash )."',
                      
                      disabled         = '0',
                      isAdmin          = '0',
                      expiresDate      = '0000-00-00 00:00:00',
                      neverExpires     = '1',
                      createdDate      = NOW(),
                      updatedDate      = NOW(),
                      createdByUserNum = '0',
                      updatedByUserNum = '0'")
      or die("MySQL Error Creating Record:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      $userNum = mysql_insert_id();

      // If a table other than the standard accounts table has been set for this
      // plugin, do not update the accesslist table
      if (@$GLOBALS['WSM_ACCOUNTS_TABLE']=="accounts") {
        // create accesslist entry
        // replace '_sample' with the table you want the user to access
        // replace '6' with the access level they should have: 0=none, 6=author, 9=editor
        // replace '1' with the max listings they are allowed
        mysql_query("INSERT INTO `{$TABLE_PREFIX}_accesslist`
                                 (userNum,  tableName,        accessLevel, maxRecords, randomSaveId)
                          VALUES ($userNum, 'all',            '1',         NULL,       '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890'),
                                 ($userNum, '_sample',        '6',         1,          '1234567890')") or die("MySQL Error Creating Access List:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      }

      // send message
      $emailTemplate = "emails/user-new-signup.php";
      $emailHeaders  = emailTemplate_load(array(
                        'template'     => websiteLogin_pluginDir() . "/$emailTemplate",
                        'subject'      => '', // set in template
                        'from'         => '', // set in template
                        'to'           => $_REQUEST['email'],
                        'placeholders' => array(
                        'username' => array_key_exists('username', $_REQUEST) ? $_REQUEST['username'] : $_REQUEST['email'], // if using email as username then show that instead
                        'password' => $password,
                        'loginUrl' => "http://" . $_SERVER['HTTP_HOST'] . $GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL'],
                        ),
                      ));
      $mailErrors   = sendMessage($emailHeaders);
      if ($mailErrors) { die("Mail Error: $mailErrors"); }

      // show thanks
      $errorsAndAlerts  = "Thanks, We've created an account for you and emailed you your password.<br/><br/>\n";
      $errorsAndAlerts .= "If you don't receive an email from us within a few minutes check your spam filter for messages from {$emailHeaders['from']}<br/><br/>\n";
      $errorsAndAlerts .= "<a href='{$GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL']}'>Click here to login</a>.";

      
      //If the user has successfully signed up, login them in.
      redirectBrowserToURL('scratch.php?action=login&username='.$_REQUEST['username'].'&password='.$password);


    }
  }

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
  body, td { font-family: arial; font-size: 14px; }
</style>
</head>
<body>

<h1>Sample User Signup Form</h1>

<!-- USER SIGNUP FORM -->
  <?php if (@$errorsAndAlerts): ?>
    <div style="color: #C00; font-weight: bold; font-size: 14px; font-family: arial;"><br/>
      <?php echo $errorsAndAlerts; ?><br/>
    </div>
  <?php endif ?>

<?php if ($showSignupForm): ?>
  <form method="post" action="?">
  <input type="hidden" name="save" value="1" />

  <table border="0" cellspacing="0" cellpadding="2">
   <tr>
    <td>Full Name</td>
    <td><input type="text" name="fullname" value="<?php echo htmlspecialchars(@$_REQUEST['fullname']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>Email</td>
    <td><input type="text" name="email" value="<?php echo htmlspecialchars(@$_REQUEST['email']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>Username</td>
    <td><input type="text" name="username" value="<?php echo htmlspecialchars(@$_REQUEST['username']); ?>" size="50" /></td>
   </tr>

   <tr>
    <td colspan="2" align="center">
      <br/><input class="button" type="submit" name="submit" value="Sign up &gt;&gt;" />
    </td>
   </tr>
  </table>

  </form>
<?php endif ?>
<!-- /USER SIGNUP FORM -->

</body>
</html>
