<?php
/*
Plugin Name: Website Membership
Description: Website membership functions for user sign-up, password reminder, login, user specific content, and login only content
Version: 1.01
Requires at least: 2.01
*/

// UPDATE THESE VALUES

$GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL']  = '/member_login.php';    // url to login form
$GLOBALS['WEBSITE_LOGIN_SIGNUP_URL']      = '/member_signup.php';   // signup url linked to from the login page
$GLOBALS['WEBSITE_LOGIN_REMINDER_URL']    = '/member_reminder.php'; // password reminder url linked to from the login page
$GLOBALS['WEBSITE_LOGIN_PROFILE_URL']     = '/member_profile.php';  // url to "edit my profile" page

$GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL']  = '/access_menu.php';    // user gets redirected here after login
$GLOBALS['WEBSITE_LOGIN_POST_LOGOFF_URL'] = '/index.php';    // user gets redirected here after logoff



// DON'T UPDATE ANYTHING BELOW THIS LINE

$GLOBALS['WEBSITE_MEMBERSHIP_PLUGIN']  = true;
if (!defined('START_SESSION')) { define('START_SESSION', true); }
addAction('viewer_postinit', '_websiteLogin_init', null, 0);

//
function _websiteLogin_init() {
  if (defined('IS_CMS_ADMIN')) { return; } // only run this form website viewers, not CMS admin pages

  // load current user
  $GLOBALS['CURRENT_USER'] = _websiteLogin_getCurrentUser(); //

  // perform website login actions
  if (@$_REQUEST['action'] == 'logoff')               { _websiteLogin_logoff(); }
  if (@$_REQUEST['action'] == 'login')                { _websiteLogin_login(); }
  if (@$_REQUEST['action'] == 'sendPasswordReminder') { _websiteLogin_sendPasswordReminder(); }
 if (@$_REQUEST['action'] == 'pastInformation') { _websiteLogin_pastInformation(); }
}



// if (!$CURRENT_USER) { websiteLogin_redirectToLogin(); }
function websiteLogin_redirectToLogin() {

  // remember page they're trying to access
  $thisUrl = thisPageUrl();
  $_SESSION['lastUrl'] = $thisUrl;

  // redirect to login
  redirectBrowserToURL("{$GLOBALS['WEBSITE_LOGIN_LOGIN_FORM_URL']}?loginRequired=1");
  exit;
}


// load user from database with cookie login details
function _websiteLogin_getCurrentUser() {

  // check for login cookies
  if (!@$_SESSION['username'] || !@$_SESSION['passwordHash']) { return false; }

  // lookup user
  $tablename = $GLOBALS['TABLE_PREFIX'] . 'accounts';
  $query     = "SELECT * FROM `$tablename`";
  $query    .= " WHERE username = '" .mysql_escape( @$_SESSION['username'] ). "'";
  $query    .= " LIMIT 1";
  $result    = mysql_query($query);
  if (!$result) {
    die("Error: Unable to load accounts database table.<br/>\nMysql Error: ". htmlspecialchars(mysql_error()) . "\n");
  }
  $currentUser = mysql_fetch_assoc($result);
  if (is_resource($result)) { mysql_free_result($result); }

  //
  $isValidLogin = $currentUser && (md5($currentUser['password']) == @$_SESSION['passwordHash']);

  // remove cookies on invalid login
  if (!$isValidLogin) {
    unset($_SESSION['username']);
    unset($_SESSION['passwordHash']);
    unset($_SESSION['lastUrl']);

    // unset current user
    $GLOBALS['CURRENT_USER'] = false;
  }

  // logoff user if they've been disabled
  if (@$currentUser['disabled']) { _websiteLogin_logoff(); }

  // update lastLoginDate if it exists
  if ($isValidLogin && array_key_exists('lastLoginDate', $currentUser)) {
    $loggingInteral = 1 * 60; // 1 minute
    $lastLoginTime  = strtotime($currentUser['lastLoginDate']);
    $updateLog      = ($lastLoginTime + $loggingInteral) <= time();

    if ($updateLog) {
      $query  = "UPDATE `$tablename` SET `lastLoginDate` = NOW() WHERE username = '" .mysql_escape( @$_SESSION['username'] ). "'";
      $result = mysql_query($query) or die("Mysql error updating lastLoginDate: ". htmlspecialchars(mysql_error()) . "\n");
      if (is_resource($result)) { mysql_free_result($result); }
    }
  }

  //
  if ($isValidLogin) { return $currentUser; }
  else               { return false; }

}


//
function _websiteLogin_login() {
  global $CURRENT_USER;

  // set cookies
  // header line must be first or other cookies won't be set.
  // HttpOnly is only supported in PHP 5.2 so we do this manually
  $_SESSION['username']     = @$_REQUEST['username']; //
  $_SESSION['passwordHash'] = md5(@$_REQUEST['password']);

  // check for valid login
  $CURRENT_USER = _websiteLogin_getCurrentUser();

  // error checking
  if      (!@$_REQUEST['username']) { alert("Please enter a username!<br/>\n"); }
  else if (!@$_REQUEST['password']) { alert("Please enter a password!<br/>\n"); }
  else if (!$CURRENT_USER)          { alert("Invalid username or password!<br/>\n"); }
  else if ($CURRENT_USER['disabled']) { alert("Your account has been disabled!<br/>\n"); }
  if (alert()) { return; }

  // clear form values
  $_REQUEST['username'] = '';
  $_REQUEST['password'] = '';

  // redirect on success
  if      ($GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL']) { $postLoginUrl = $GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL']; }
  else if (@$_SESSION['lastUrl'])                    { $postLoginUrl = @$_SESSION['lastUrl']; }
  else                                               { $postLoginUrl = thisPageUrl(); }
  $redirectUrl = $GLOBALS['WEBSITE_LOGIN_POST_LOGIN_URL'];

  unset($_SESSION['lastUrl']);
  redirectBrowserToURL("$postLoginUrl");
  exit;

}


// remove login cookies
function _websiteLogin_logoff() {
  global $CURRENT_USER;

  // remove login cookies
  $_SESSION = array();
  session_destroy();

  // unset current user
  $CURRENT_USER = false;

  // redirect after logoff
  if ($GLOBALS['WEBSITE_LOGIN_POST_LOGOFF_URL']) {
    $logoffUrl = $GLOBALS['WEBSITE_LOGIN_POST_LOGOFF_URL'];
  }
  else {
    $logoffUrl = thisPageUrl();
    $logoffUrl = preg_replace('/\baction=logoff\b/', '', $logoffUrl); // prevent redirect loop
  }

  //
  redirectBrowserToURL($logoffUrl);
  exit;

}

//
function _websiteLogin_pastInformation() {
  global $SETTINGS, $TABLE_PREFIX;

//  REQUEST	FOR PAST INFORMATION

// display errors
  if (array_key_exists('pastInformation', $_REQUEST) && @$_REQUEST['pastInformation'] == $user['email']) {
    alert("<span class='heading-text-yellow'>Congratulations!!!<br />Your Account Exists</span><br/><span class='body-text-yellow'>You do not need to create a new account.</span>\n");
  }
  }
  function _websiteLogin_sendPasswordReminder() {
  global $SETTINGS, $TABLE_PREFIX;

  // display errors
  if (array_key_exists('usernameOrEmail', $_REQUEST) && @$_REQUEST['usernameOrEmail'] == '') {
    alert("<span class='heading-text-yellow'>Please enter your information before you submit the form.</span><br/><span class='body-text-yellow'>Click the back button on your browser to continue.</span>\n");
  }
  // Lookup username or email
  if (@$_REQUEST['usernameOrEmail']) {

    $escapedNameOrEmail = mysql_escape($_REQUEST['usernameOrEmail']);
    $query = "SELECT * FROM `{$TABLE_PREFIX}accounts` WHERE '$escapedNameOrEmail' IN (`username`,`email`)";
    $users = mysql_query_fetch_all_assoc($query);

    // send emails
    foreach ($users as $user) {

      // send email
      $to        = $user['email'];
      $subject   = "{$_SERVER['HTTP_HOST']} Password Reminder";
      $message   = "Hi {$user['email']},\n"
                 . "\n"
                 . "You requested your username and password for {$_SERVER['HTTP_HOST']}.\n"
                 . "\n"
                 . "Your username is: {$user['username']}\n"
                 . "Your password is: {$user['password']}\n\n"
                 . "Your information was requested from the IP address {$_SERVER['REMOTE_ADDR']}.\n"
                 . "If you've received this email and you didn't request this information,\n"
                 . "don't worry, none of this information has been\n"
                 . "sent to anyone else.\n";
      $mailResult = @mail($to, $subject, $message, "From: {$SETTINGS['adminEmail']}");
      if (!$mailResult) { die("Mail Error: $php_errormsg"); }

      //
      alert("<span class='body-text-bold'>Thanks, we've emailed your information to you.<br/><br/>

      If you don't receive an email within a few minutes, check your
      spam filter for messages from {$SETTINGS['adminEmail']}</span>");

      // clear form
      $_REQUEST['usernameOrEmail'] = '';
    }

    //
    if (!$users) {
      alert("<span class='heading-text-yellow'>Sorry, no matching information was found!</span><br /><span class='body-text-yellow'>Click</span> <a class='special' href'artistsofpalmbeachcounty.org/becomeamember2.php'>HERE</a> <span class='body-text-yellow'>to continue</span>");
    }

  }

}


//
function _websiteLogin_sendSignupMessage() {
  global $SETTINGS, $TABLE_PREFIX;

  // if using email as username then show that instead
  $username = array_key_exists('username', $_REQUEST) ? $_REQUEST['username'] : $_REQUEST['email'];

  // send email
  $to        = $_REQUEST['email'];
  $subject   = "{$_SERVER['HTTP_HOST']} Membership Application";
  $message   = "Hi {$_REQUEST['email']},\n"
             . "\n"
             . "Thanks for your interest in becoming a member of {$_SERVER['HTTP_HOST']}.\n"
             . "\n"
             . "As soon as your membership has been successfully processed you'll receive a confirmation email with a link to our login page.\n"
			  . "\n"
			  . "Only your name, Web Site address, the artisitic medium(s) in which you work, and an email address (encrypted from spam bots) will be viewable by the public in our on-line Member Directory.\n"
			 . "\n"
			 . "Remember, your application can't be processed if you haven't paid your first year's dues.\n"
             . "\n"
             . "You can pay your dues on-line using PayPal here:\n"
             . "http://www.artistsofpalmbeachcounty.org/paypal3.php\n"
             . "\n"
             . "Thanks and Welcome!\n"
			  . "\n"
			  . "The Membership Committee\n";

  $mailResult = @mail($to, $subject, $message, "From: {$SETTINGS['adminEmail']}");
  if (!$mailResult) { die("Mail Error: $php_errormsg"); }

}


?>
