API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wtMembership.php

<?php
/**
 *  WebTemplate Core
 *
 *  @version 2.0
 *  @module WebTemplate Core
 */


// paths to notifications in the WT Tree
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"] = Array();
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["welcome"] = Array("path" => "Membership/Welcome/Welcome", "name" => "Welcome", "description" => "This email is sent to users when they become active members", "tags" => "[First Name] = First Name, [Last Name] = Last Name, [Username] = Username, [Password] = Password");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["registration success"] = Array("path" => "Membership/Welcome/Registration Success", "name" => "Registration Success", "description" => "This message is displayed to the user upon successful registration");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["activation instructions"] = Array("path" => "Membership/Activation/Activation Instructions", "name" => "Activation Instructions", "description" => "This message is displayed to the user after they have registered and is intended to give them instructions on how to activate their membership", "tags" => "[Activation Url] = The Activation Url, [First Name] = First Name, [Last Name] = Last Name, [Username] = Username, [Password] = Password");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["activation"] = Array("path" => "Membership/Activation/Activation Email", "name" => "Activation Email", "description" => "This is the email which gets sent to a user after they register. It contains a link they can click to activate their membership", "tags" => "[Activation Url] = The Activation Url, [First Name] = First Name, [Last Name] = Last Name, [Username] = Username, [Password] = Password");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["application received"] = Array("path" => "Membership/Approval/Application Received", "name" => "Application Received Message", "description" => "This message is displayed to the user after they have registered. It is intended this message will inform them their membership application has been received and will be processed");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["application received email"] = Array("path" => "Membership/Approval/Application Received Email", "name" => "Application Received Email", "description" => "This message is emailed to the user after they have registered to inform them their application has been received and is being processed");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["application received admin email"] = Array("path" => "Membership/Approval/Application Received Admin Email", "name" => "Application Received Admin Email", "description" => "This message is sent to the administrator to inform them of a new application");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["approve"] = Array("path" => "Membership/Approval/Approve", "name" => "Approved Email", "description" => "This message is emailed to a member when their membership application has been approved");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["on hold"] = Array("path" => "Membership/Approval/On Hold", "name" => "On Hold Email", "description" => "This message is emailed to a member when they are put on hold");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["off hold"] = Array("path" => "Membership/Approval/Off Hold", "name" => "Off Hold Email", "description" => "This message is emailed to a member when they are taken off hold");

$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["reject"] = Array("path" => "Membership/Approval/Reject", "name" => "Rejected Email", "description" => "This message is emailed to a member when their membership application has been rejected");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["first warning"] = Array("path" => "Membership/Expiry/First Warning", "name" => "Expiry First Warning Email", "description" => "This message is emailed to a member to notify them their membership is about to expire");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["second warning"] = Array("path" => "Membership/Expiry/Second Warning", "name" => "Expiry Second Warning Email", "description" => "This message is emailed to a member as a second warning their membership is about to expire");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["expired"] = Array("path" => "Membership/Expiry/Expired", "name" => "Expired Email", "description" => "This message is emailed to a member to notify them their membership has expired");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["forgotten password instructions"] = Array("path" => "Membership/Forgotten Password/Forgotten Password Instructions", "name" => "Forgotten Password Instructions", "description" => "This message is displayed to the user after they click the forgotten password link");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["password link sent"] = Array("path" => "Membership/Forgotten Password/Password Link Sent", "name" => "Password Link Sent", "description" => "This message is displayed to the user to inform them an email has been sent to them containing a link they can use to reset their password");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["forgotten password"] = Array("path" => "Membership/Forgotten Password/Forgotten Password", "name" => "Forgotten Password Email", "description" => "This message is emailed to the user and contains a link they can click to reset their password");

$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["membership selection"] = Array("path" => "Membership/Membership Selection/Membership Selection", "name" => "Membership Selection Instructions", "description" => "This message is displayed to the user when they are given the choice of membership type");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["registration details"] = Array("path" => "Membership/Registration Details", "name" => "Registration Details Instructions", "description" => "This message is displayed to users when they are asked to enter their registration details");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["credit card payment"] = Array("path" => "Membership/Member Fees/Credit Card Payment", "name" => "Credit Card Payment Instructions", "description" => "This message is displayed to a user when they are asked to pay for their membership by credit card");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["credit card payment successful"] = Array("path" => "Membership/Member Fees/Credit Card Payment Successful", "name" => "Credit Card Payment Successful Message", "description" => "This message is displayed to the user upon a successful credit card payment");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["payment receipt email"] = Array("path" => "Membership/Member Fees/Payment Receipt Email", "name" => "Payment Receipt Email", "description" => "This email is sent to members after a successful credit card payment");
$GLOBALS["WTMEMBERSHIPNOTIFICATIONS"]["terms and conditions"] = Array("path" => "Membership/Terms and Conditions/Terms and Conditions", "name" => "Terms and Conditions", "description" => "These are the terms and conditions of membership");


/**
 *  The class containing functions relating to membership
 *
 *  @class WTMembership
 *  @extends WTNode
 */
class WTMembership
{

  /**
   *  Process a URI beginning with __membership<br/>
   *  Possible URIs: __membership/activate, __membership/resetpassword, __membership/payment
   *
   *  @method processMembershipURI
   *  @static
   *  @param {String} path The URI to process
   */
  public static function processMembershipURI($path) {
    $pathParts = explode("/", $path);
    if(count($pathParts) > 1) {
      $cmd = $pathParts[1];
      switch($cmd) {
        case 'activate':
        case 'resetpassword':
          if(count($pathParts) > 3) {
            $guid = $pathParts[2];
            $key = $pathParts[3];
            WTMembership::memberKey($guid, $key, $cmd);
          }
          break;
        case 'payment':
          WTMembership::processPayment();
          break;
      }
/*      print "cmd = $cmd, guid = $guid, key = $key<br>";
      print "path = $path";*/
    }
    exit("");
  
  }

  /**
   * Return the HTML for an account page depending on the value of the request variable "cmd":<br/>
   * "changepassword", "passwordset", "editdetails", "detailsset", "vieworders", "vieworder", "membershippayments", "paymembership", "successfulpayment", "viewpayment", "viewinvoice"
   *
   *  @method account
   *  @static
   *  @return {String} The HTML for the appropriate member page
   */
  static function account($args = Array()) 
  {
    $cmd = $GLOBALS["WT"]->getRequestValue("cmd");
    switch($cmd) {
      case 'changepassword':
      case 'passwordset':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/changepassword.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
        break;
      case 'editdetails':
      case 'detailsset':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/editdetails.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'vieworders':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/vieworders.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'vieworder':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/vieworder.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'membershippayments':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/membershippayments.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'paymembership':
      case 'successfulpayment':
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/ccpayment.wt";
        $templateSource = WTTemplate::load($templatePath);
        $orderGuid = $GLOBALS["WT"]->getRequestValue("id");
        $order = $GLOBALS["WT"]->getNode($orderGuid);

        $transactionGuid = WTSession::get("WTTRANSACTIONGUID");
        $transactionError = "";
        if($transactionGuid) {
          $transaction = $GLOBALS["WT"]->getNode($transactionGuid);
          $transactionError = $transaction->getAttribute("Description");
        }
            
        $data["orderID"] = $orderGuid;
        $data["Amount Due"] = $order->getAttribute("Order Total");
        $data["Description"]= $order->getAttribute("Notes");
        $data["Transaction Error"] = $transactionError;
       
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'viewpayment':
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/viewpayment.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'renewmembership':
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/renewmembership.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      case 'viewinvoice':
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/viewinvoice.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
      default:
        $data = Array();
        $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/membership/account.wt";
        $templateSource = WTTemplate::load($templatePath);
        return WTTemplate::compileAndEvaluate($templateSource, $data);
    }
  
  }


  /**
   *  Process a membership payment
   *
   *  @method processPayment
   *
   */
  static function processPayment() 
  {
    $orderGuid = (int)$GLOBALS["WT"]->getRequestValue("orderID");
    if($orderGuid) {
      $order = $GLOBALS["WT"]->getNode($orderGuid);
      $paid = $order->getAttribute("Paid");
      if($paid != "Yes") {
        $args = Array();
        if(WTConfig::get("Ctel/Debug") == "Yes") {
          $args["Debug"] = 1;
        }
        $uri = $GLOBALS["WT"]->getRequestValue("uri");
        $args["Amount"] = $order->getAttribute("Order Total");
        $args["CardHolderName"] = $GLOBALS["WT"]->getRequestValue("cardHolderName");
        $args["CardNumber"] = $GLOBALS["WT"]->getRequestValue("cardNumber");
        $args["CardExpiry"] = $GLOBALS["WT"]->getRequestValue("expMonth") . $GLOBALS["WT"]->getRequestValue("expYear");
        $args["CardSecurityNumber"] = $GLOBALS["WT"]->getRequestValue("cardSecNum");
        $args["CustomerReference"] = "Membership Payment #" . $order->getAttribute("Order Number");

        $transaction = WTTransaction::ccPayment($args);
        $GLOBALS["WT"]->linkNodes($order, $transaction);       
        WTSession::set("WTTRANSACTIONGUID", '');
 
        if($transaction->getAttribute("Successful ID") == 1) {
          $order->setAttributes(Array("Paid" => "Yes", "Paid Date" => date("Y-m-d H:i:s")));
          $contact = $GLOBALS["WT"]->getCurrentUser();
          WTMembership::sendNotification("payment receipt email", $contact);
          $uri = $GLOBALS["WT"]->getRequestValue("uri");
          $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "successfulpayment");
          if(WTConfig::get("Cleverbooks") == "Yes") {
            $username = WTConfig::get("Cleverbooks/Username");
            $password = WTConfig::get("Cleverbooks/Password");

            $description = $order->getAttribute("Notes");

            include_once($GLOBALS["WTDIRECTORY"] . "include/cleverbooks/cleverbooks.php");

            if($GLOBALS["WTSITEID"] == 11264 || $GLOBALS["WTSITEID"] == 11362) {
              $contactID = $order->getAttribute("Contact ID");
              if($contactID) {
                $contact = $GLOBALS["WT"]->getNode($contactID);
                if($contact) {
                  $description .= " - " . $contact->getAttribute("Business Name");
                }
              }
              wtLogCleverbooksTransaction($username, $password, -$order->getAttribute("Order Total"), $description, "186", "100");
            } else {           
              wtLogCleverbooksTransaction($username, $password, -$order->getAttribute("Order Total"));
            }
          }

          header("Location: $uri");
          exit("");
        } else {


          WTSession::set("WTTRANSACTIONGUID", $transaction->m_guid);
          header("Location: $uri");
          exit("");
        }

        
        
      }
    } else {
    $paymentGuid = WTSession::get("WTMEMBERPAYMENTGUID");
    $memberGuid = WTSession::get("WTNEWMEMBERGUID");
    $memberGroupGuid = WTSession::get("WTNEWMEMBERGROUPGUID");
  

    $payment = $GLOBALS["WT"]->getNode($paymentGuid);
    $contact = $GLOBALS["WT"]->getNode($memberGuid);
    $group = $GLOBALS["WT"]->getNode($memberGroupGuid);

    if($payment && $contact) {
      $paid = $payment->getAttribute("Paid");
      if($paid != "Yes") {
        $cardType = $GLOBALS["WT"]->getRequestValue("cardType");
    
        $args = Array();
        if(WTConfig::get("Ctel/Debug") == "Yes") {
          $args["Debug"] = 1;
        }
        $uri = $GLOBALS["WT"]->getRequestValue("uri");
        $args["Amount"] = $payment->getAttribute("Amount");
        $args["CardHolderName"] = $GLOBALS["WT"]->getRequestValue("cardHolderName");
        $args["CardNumber"] = $GLOBALS["WT"]->getRequestValue("cardNumber");
        $args["CardExpiry"] = $GLOBALS["WT"]->getRequestValue("expMonth") . $GLOBALS["WT"]->getRequestValue("expYear");
        $args["CardSecurityNumber"] = $GLOBALS["WT"]->getRequestValue("cardSecNum");
        $args["CustomerReference"] = "Membership Payment #" . $payment->getAttribute("Reference Number");

        $transaction = WTTransaction::ccPayment($args);
        $GLOBALS["WT"]->linkNodes($payment, $transaction);
        if($transaction->getAttribute("Successful ID") == 1) {
          $payment->setAttributes(Array("Paid" => "Yes", "Paid Date" => date("Y-m-d H:i:s")));
          $contact->setAttributes(Array("Status" => "Active"));
          $feeType = $group->getAttribute("Fee Type");
          switch($feeType) {
            case 'Joining Fee Only':
              $contact->setAttributes(Array("Expires" => "No"));
              break;
            case 'Joining and Recurring Fee':
            case 'Recurring Fee Only':
              $period = $group->getAttribute("Recurring Fee Period");
              switch($period) {
                case 'Weekly':
                  $expiryDate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 7, date("Y")));
                  break;
                case 'Monthly':
                  $expiryDate = date("Y-m-d", mktime(0, 0, 0, date("m") + 1, date("d"), date("Y")));
                  break;
                case 'Annually':
                  $expiryDate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1));
                  break;
              }
              $contact->setAttributes(Array("Expires" => "Yes", "Expiry Date" => $expiryDate));
              break;
          }

          $subject = $group->getAttribute("Welcome Email Subject");
          $message = $group->getAttribute("Welcome Email Message");

          $fromName = WTConfig::get("Membership/Notifications From Name");
          $fromAddress = WTConfig::get("Membership/Notifications From Address");

          $formdata = WTSession::get("WTNEWMEMBERFORMLABELDATA");

          $formdata["Email Address"] = $contact->getAttribute("Email Address");
          $formdata["Username"] = $contact->getAttribute("Username");

          foreach($formdata as $k => $v) {
            $subject = str_replace('[' . $k . ']', $v, $subject);
            $message = str_replace('[' . $k . ']', $v, $message);
          }

          $mail = new WTMail();
          $mail->setFrom($fromAddress, $fromName);
          $mail->setTo($formdata["Email Address"]);
          $mail->setReplyTo($formdata["Email Address"]);
          $mail->setContent($subject, $message, true);
          $mail->send();

          $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "accepted");
          header("Location: $uri");
          exit("");
        } else {
          WTSession::set("WTTRANSACTIONGUID", $transaction->m_guid);
          header("Location: $uri");
          exit("");
        }

        print_r($transaction->getAttributes());
      } else {
        print "Already Paid!";
      }
    }
    }
exit("");
  }

  /**
   *  Change a password in response to the form action "changepassword"
   *
   *  @method processChangePassword
   *  @static
   *  @param {String} action The action of the form, should be "changepassword"
   *  @param {Array} data The data from the form submission
   *
   */
  static function processChangePassword($action, $data) 
  {
    $form = $GLOBALS["WT"]->getNode($data["formGuid"]);
    $data = $form->getFormDataFromRequest(true);

//print_r($data); 
    $currentUser = $GLOBALS["WT"]->getCurrentUser();

    $passwordok = true;
    if(array_key_exists("New Password", $data)) {
      $passwordok = strlen($data["New Password"]) >= 6;
    }

    $confirmfieldsok = $form->checkConfirmFields();
    if(!$confirmfieldsok || !$passwordok) {
      $GLOBALS["WTFORMERROR"] = "There was a problem, please check the form and resubmit";
      return true;
    }

    if($data["i"] != "" && $data["k"] != "") {
      $contact = $GLOBALS["WT"]->getNode($data["i"]);
      if($contact && $contact->m_typeName == "Contact") {
        $key = $contact->getAttribute("Key");
        if($key == $data["k"]) {
          $contact->setAttributes(Array("Key" => "", "Key Action" => "", "Password" => $data["New Password"]));
          $accountPage = WTConfig::get("Membership/Member Account Page");
          if($accountPage == "") {
            $accountPage = "account";
          }
          
          header("Location: $accountPage?cmd=passwordset");
          exit("");
        }
      }
    } else {
      if($currentUser) {
        $password = $currentUser->getAttribute("Password");
        $username = $currentUser->getAttribute("Username");
        $md5password = md5($username . WTSYSTEMSALT . $data["Current Password"]);
        if($md5password == $password) {
          $currentUser->setAttributes(Array("Password" => $data["New Password"]));

          $accountPage = WTConfig::get("Membership/Member Account Page");
          if($accountPage == "") {
            $accountPage = "account";
          }

          header("Location: $accountPage?cmd=passwordset");
          exit("");
        } else {
          $GLOBALS["WTFORMERROR"] = "Old password is incorrect";
          return true;
        }
        
      }
    }

    exit("");

  }

  /**
   *  Set member details in response to the form action "setmemberdetails"
   *
   *  @method processSetMemberDetails
   *  @static 
   *  @param {String} action Should be "setmemberdetails" 
   *  @param {Array} data The data from the form submission
   *
   */
  static function processSetMemberDetails($action, $data) 
  {
    $form = $GLOBALS["WT"]->getNode($data["formGuid"]);
    if($form) {
      $contactData = $form->getContactDataFromRequest(Array("Add Files To Library" => true, "Files Path" => "/Files/Images/Contact Images"));


      $currentUser = $GLOBALS["WT"]->getCurrentUser();
      if($currentUser) {
        $currentUser->setAttributes($contactData);
      }
      $accountPage = WTConfig::get("Membership/Member Account Page");
      if($accountPage == "") {
        $accountPage = "account";
      }

      header("Location: $accountPage?cmd=detailsset");
      exit("");
    }
  }

  static function signup($args)
  {
    $html = "";
    $cmd = $GLOBALS["WT"]->getRequestValue("cmd");
    switch($cmd) {
      case 'payment':
        $transactionGuid = WTSession::get("WTTRANSACTIONGUID");
        WTSession::set("WTTRANSACTIONGUID", "");
        $orderGuid = WTSession::get("WTMEMBERPAYMENTGUID");
        $memberGuid = WTSession::get("WTNEWMEMBERGUID");

        $order = $GLOBALS["WT"]->getNode($orderGuid);
        $paymentAmount = $order->getAttribute("Order Total");
        $paymentDescription = $order->getAttribute("Notes");
        $referenceNumber = $order->getAttribute("Order Number");
        $contact = $GLOBALS["WT"]->getNode($memberGuid);

        $transactionError = "";
        if($transactionGuid) {
          $transaction = $GLOBALS["WT"]->getNode($transactionGuid);
          $transactionError = $transaction->getAttribute("Description"); 
        }
        $templateData = Array("Amount Due" => $paymentAmount, "Description" => $paymentDescription, "Reference Number" => $referenceNumber, "Transaction Error" => $transactionError);
        $ccTemplate = WTTemplate::load($GLOBALS["WTDIRECTORY"] . "templates/membership/ccpayment.wt");
        $html .= WTTemplate::compileAndEvaluate($ccTemplate, $templateData);
        return $html;
        break;
    }
  }


  /**
   *  Create a member in response to the form action "register" or "cartregister"
   *
   *  @method processSignupForm
   *  @static
   *  @param {String} action Should be either "register" or "cartregister"
   *  @param {Array} The data from the form
   */
  static function processSignupForm($action, $data) 
  {
    $contact = WTMembership::processSignup($action, $data);

    if($contact) {
      
      $uri = $GLOBALS["WT"]->getRequestURI();
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "accepted");
      header("Location: $uri");
      exit("");
    } else {

      // form has been processed, so return true
      return true;
    }
  
  }


  /**
   *  Process a submission of a member signup form
   *
   *  @method processSignup
   *  @static
   *  @param {String} action Should be either "register" or "cartregister"
   *  @param {Array} The data from the form
   */ 
  static function processSignup($action, $data)
  {
    $form = $GLOBALS["WT"]->getNode($data["formGuid"]);
    if($form) {

      $activation = WTConfig::get("Membership/Activation");
      $approval = WTConfig::get("Membership/Approval");
      $expiry = WTConfig::get("Membership/Expiry");
      $welcome = WTConfig::get("Membership/Welcome");
      $siteUrl = WTConfig::get("Site Details/Site URL");
      $usernameIsEmail = WTConfig::get("Membership/Username Is Email Address");

      $formdata = $form->getFormDataFromRequest(true);
      $contactData = $form->getContactDataFromRequest();
      $contact = null;

      if($usernameIsEmail == "Yes") {
        $contactData["Username"] = $contactData["Email Address"];

      }

      $usernameok = true;
      if(array_key_exists("Username", $contactData)) {
        $usernameok = WTMembership::checkUsername($contactData["Username"]);
      }

      $emailok = true;
      if(array_key_exists("Email Address", $contactData)) {
        $emailok = WTMembership::checkEmail($contactData["Email Address"]) && WTForm::checkEmail($contactData["Email Address"]);
      }

      $passwordok = true;
      if(array_key_exists("Password", $contactData)) {
        $passwordok = strlen($contactData["Password"]) >= 6;
      }

      $confirmfieldsok = $form->checkConfirmFields();

      if(!$usernameok || !$emailok || !$confirmfieldsok) {
        $GLOBALS["WTFORMERROR"] = "There was a problem with your submission, please check your values and resubmit";

        if(!$usernameok) {
          $GLOBALS["WTFORMERROR"] = "There was a problem with your submission: the username you have chosen is already in use";
        }
        return null;
      }
      
      $feeType == "Free";
      $memberGroup = null;

      if(array_key_exists("Membership Type", $formdata) && $formdata["Membership Type"]) {
        $memberGroup = $GLOBALS["WT"]->getNode("/Groups/" . $formdata["Membership Type"]);
        if(!$memberGroup) {
          $GLOBALS["WTFORMERROR"] = "There was a problem with your submission";

  //        return null;
        } else {
        
          $feeType = $memberGroup->getAttribute("Fee Type");
        }

      }

      
      // need to get contact data again and this time add in images
      if($GLOBALS["WTSITEID"] == 11293) {
        $contactData = $form->getContactDataFromRequest(Array("Add Files To Library" => true, "Files Path" => "/Files/Documents/Resumes"));
      } else {
        $contactData = $form->getContactDataFromRequest(Array("Add Files To Library" => true, "Files Path" => "/Files/Images/Contact Images"));
      }

      
      if($usernameIsEmail == "Yes") {
        $contactData["Username"] = $contactData["Email Address"];

      }

      $member = $GLOBALS["WT"]->getNode("/Config/Options/Contact Types/Member");
      $contactData["Type"] = "Member";
      $contactData["Type IDs"] = $member->m_guid;


      $contacts = $GLOBALS["WT"]->getNode("/Contacts");


      if($approval == "Yes" && $memberGroup) {
        $autoApproveGroups = WTConfig::get("Membership/Approval/Auto Approve Groups");
        if($autoApproveGroups) {
          $groups = array_map("trim", explode(",", $autoApproveGroups));
          if(in_array($memberGroup->getName(), $groups)) {
            $approval = "No";
          }
        }
      }




      if($approval == "Yes") {
        // members need to be approved
        $contactData["Status"] = "Awaiting Approval";
        $annualStartDate = WTConfig::get("Membership/Annual Start Date");
        if($annualStartDate == "Yes") {
          $currentPeriod = WTMembership::getCurrentPeriod();
          if($currentPeriod) {
            $periodEnds = $currentPeriod->getAttribute("To");
            $contactData["Expiry Date"] = $currentPeriod->getAttribute("To");
          }
          $contactData["Expires"] = "Yes";
        }

        if(!array_key_exists("Password", $contactData) || $contactData["Password"] == "") {
          $contactData["Password"] = WTMembership::generatePassword();
        }

        $contact = $contacts->createChild("Contact", $contactData);

        if(array_key_exists("Password", $contactData)) {
          // hack to save password until approved
          $sql = "UPDATE
                    Contact
                  SET
                    Password = '" . mysql_escape_string($contactData["Password"]) . "'
                  WHERE
                    __guid = " . $contact->m_guid;
          mysql_query($sql);
        }

        if($memberGroup) {
          $GLOBALS["WT"]->linkNodes($memberGroup, $contact);
        }

        WTMembership::sendNotification("application received email", $contact);
        WTMembership::sendNotification("application received admin email", $contact);

        $_SESSION["WTLASTMEMBER"] = $contact->m_guid;
      } else if($feeType && $feeType != "Free") {

        $contactData["Status"] = "Inactive";
        
        $fee = 0;
        $contact = $contacts->createChild("Contact", $contactData);
        if($memberGroup) {
          $GLOBALS["WT"]->linkNodes($memberGroup, $contact);        

          $fee = 0;
          switch($feeType) {
            case 'Joining Fee Only':
              $fee = $memberGroup->getAttribute("Joining Fee");
              $contact->setAttributes(Array("Expires" => "No"));
              break;
            case 'Joining and Recurring Fee':
              $fee = $memberGroup->getAttribute("Joining Fee");
              $contact->setAttributes(Array("Expires" => "Yes", "Expiry Date" => date("Y-m-d")));
              break;
            case 'Recurring Fee Only':
              $contact->setAttributes(Array("Expires" => "Yes", "Expiry Date" => date("Y-m-d")));
              $fee = $memberGroup->getAttribute("Recurring Fee");
              break;
          }
        }

        $paymentData = Array();
        $paymentData["Paid"] = "No";
        $paymentData["Amount"] = $fee;
        $paymentData["Reason"] = "Join";
        $paymentData["Description"] = "Joining: " . $memberGroup->getName();
        $paymentData["Member ID"] = $contact->m_guid;
        $membershipPayments = $GLOBALS["WT"]->getNode("/Membership/Membership Payments");
        $payment = $membershipPayments->createChild("wtMembershipPayment", $paymentData);
        $payment->setAttributes(Array("Reference Number" => $payment->m_guid));

        $contactPayments = $GLOBALS["WT"]->getNode($contact->m_guid . "/Membership Payments");
        if(!$memberPayments) {
          $contactPayments = $contact->createChild("wtNode", Array("Node Name" => "Membership Payments"));    
        }
//        $contactPaymentRecord = $contact->createChild("wtNode", Array("Node Name" => "Membership Payments"));


        $GLOBALS["WT"]->linkNodes($contactPayments, $payment);


        WTSession::set("WTMEMBERPAYMENTGUID", $payment->m_guid);
        WTSession::set("WTNEWMEMBERGUID", $contact->m_guid);

        if($memberGroup) {
          WTSession::set("WTNEWMEMBERGROUPGUID", $memberGroup->m_guid);
        } else {
          WTSession::set("WTNEWMEMBERGROUPGUID", "");
        }

        WTSession::set("WTNEWMEMBERFORMDATA", $data);
        WTSession::set("WTNEWMEMBERFORMLABELDATA", $formdata);

        $uri = $GLOBALS["WT"]->getRequestURI();
        $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "payment");
        $uri = $GLOBALS["WT"]->setURIParameter($uri, "type", "");

        header("Location: $uri");
        exit("");                        
      } else if($activation == "Yes") {
        $contactData["Expires"] = "No";
        $contactData["Status"] = "Inactive";
        $contactData["Key"] = md5(uniqid(rand(),1));
        $contactData["Key Date"] = date("Y-m-d H:i:s");
        $contactData["Key Action"] = serialize(Array("cmd" => "activate"));
        $contact = $contacts->createChild("Contact", $contactData);
        if($memberGroup) {
          $GLOBALS["WT"]->linkNodes($memberGroup, $contact);
        }        

        // hack to save password until activated
        $sql = "UPDATE
                  Contact
                SET
                  Password = '" . mysql_escape_string($contactData["Password"]) . "'
                WHERE
                  __guid = " . $contact->m_guid;
        mysql_query($sql);

        // have to refresh the contacts attributes
        $contact->m_dirty = true;
        $contact->getAttributes();

        print mysql_error();


        if($action != "cartregister") {
          $activationUrl = $siteUrl . "__membership/activate/" . $contact->m_guid . "/" . $contactData["Key"];

          $activationUrl = '<a href="' . $activationUrl . '">' . $activationUrl . '</a>';
          WTMembership::sendNotification("activation", $contact, Array("Activation Url" => $activationUrl));
        } else {


          WTMembership::activate($contact);
          $username = $contact->getAttribute("Username");
          $GLOBALS["WT"]->setUser($username);


        }


      } else if($approval == "Yes") {
        // members need to be approved
        $contactData["Status"] = "Awaiting Approval";

        $contact = $contacts->createChild("Contact", $contactData);

        if(array_key_exists("Password", $contactData)) {        
          // hack to save password until approved
          $sql = "UPDATE
                    Contact
                  SET
                    Password = '" . mysql_escape_string($contactData["Password"]) . "'
                  WHERE
                    __guid = " . $contact->m_guid;
          mysql_query($sql);
        }

        WTMembership::sendNotification("application received email", $contact);
        WTMembership::sendNotification("application received admin email", $contact);


        $_SESSION["WTLASTMEMBER"] = $contact->m_guid;        
      } else if($welcome == "Yes") {

        $contactData["Status"] = "Active";
        if(!array_key_exists("Password", $contactData) || $contactData["Password"] == "") {
          $contactData["Password"] = WTMembership::generatePassword();
        }


        $contact = $contacts->createChild("Contact", $contactData);

        if($memberGroup) {
          $GLOBALS["WT"]->linkNodes($memberGroup, $contact);
          $contactData["Group ID"] = $memberGroup->m_guid;
          WTMembership::sendNotification("group welcome email", $contact, $contactData);
        } else { 
          WTMembership::sendNotification("welcome", $contact, $contactData);
        }

        $username = $contact->getAttribute("Username");
        $GLOBALS["WT"]->setUser($username);


      } else {


        $contactData["Status"] = "Active";
        if(!array_key_exists("Password", $contactData) || $contactData["Password"] == "") {
          $contactData["Password"] = WTMembership::generatePassword();
        }


        $contact = $contacts->createChild("Contact", $contactData);

        if($GLOBALS["WTSITEID"] == 11293) {
          sendCandidateSubmission($contact->m_guid);
        }
      
        if($memberGroup) {
          $GLOBALS["WT"]->linkNodes($memberGroup, $contact);

          $contactData["Group ID"] = $memberGroup->m_guid;
          WTMembership::sendNotification("group welcome email", $contact, $contactData);


          
          $GLOBALS["WT"]->setUser($contactData["Username"]);
        }


      }

/*      $uri = $GLOBALS["WT"]->getRequestURI();
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "accepted");
      header("Location: $uri");
      exit("");
*/
      return $contact;
    }

    return null;
  }


  /**
   *  Generate a random password
   *
   *  @method generatePassword
   *  @static
   *  @param {int} [length=7] The length of the password to return
   *  @return The generated password
   */
  static function generatePassword($length = 7) 
  {
    $password = '';
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    for($i = 0; $i < $length; $i++) {
      $password .= $chars[rand(0, strlen($chars) - 1)];
    }

    return $password;
  }


  /**
   *  Approve a member
   *
   *  @method approve
   *  @static
   *  @param {int} guid The guid of the member to approve
   *
   */
  static function approve($guid, $data = Array()) 
  {
    $contact = $GLOBALS["WT"]->getNode($guid);

    $memberGroups = $contact->getGroups("Member Group");


    if(array_key_exists("Joining Fee", $data)) {
      $groupName = "";
      if(is_numeric($memberGroups)) {
        $groupNode = $GLOBALS["WT"]->getNode($memberGroups);
        $groupName = $groupNode->getName();
      }

      $membershipPayments = $GLOBALS["WT"]->getNode("/Membership/Membership Payments");

      $payment = $membershipPayments->createChild("wtMembershipPayment", Array("Amount" => $data["Joining Fee"], "Description" => "Joining " . $groupName, "Paid" => "No", "Reason" => "Join", "Member ID" => $contact->m_guid ) );
      $payment->setAttributes(Array("Reference Number" => $payment->m_guid));



      $orders = $GLOBALS["WT"]->getNode("/Orders");
      $order = $orders->createChild("wtOrder", Array("wtOrder", "Order Date" => date("Y-m-d H:i:s"), "Paid" => "No", "Notes" => "Joining " . $groupName, "Contact ID" => $contact->m_guid, "Status" => "", "Order Total" => $data["Joining Fee"]));
      $order->setAttributes(Array("Order Number" => $order->m_guid));
      $orderItem = $order->createChild("wtOrderItem", Array("Code" => "", "Name" => "Joining " . $groupName, "Description" => "", "Price" => $data["Joining Fee"], "Quantity" => 1));

      $contactPayments = $GLOBALS["WT"]->getNode($contact->m_guid . "/Membership Payments");
      if(!$memberPayments) {
        $contactPayments = $contact->createChild("wtNode", Array("Node Name" => "Membership Payments"));
      }
      $GLOBALS["WT"]->linkNodes($contactPayments, $payment);
    }

    $member = $GLOBALS["WT"]->getNode("/Config/Options/Contact Types/Member");
 
    $password = $contact->getAttribute("Password");
    if(trim($password) == "") {
      $password = WTMembership::generatePassword();
    }
    $data["Status"] = "Active";
    $data["Type IDs"] = $member->m_guid;
    $data["Password"] = $password;
    $contact->setAttributes($data);

    $sendGroupWelcome = is_numeric($memberGroups);
    if($sendGroupWelcome) {
      $message = "";
      $group = $GLOBALS["WT"]->getNode($memberGroups);
      if($group) {
        $subject = $group->getAttribute("Welcome Email Subject");
        $message = $group->getAttribute("Welcome Email Message");
      }
      if(!$message) {
        $sendGroupWelcome = false;
      }
    }

    if($sendGroupWelcome) {
      $data["Group ID"] = $memberGroups;
      WTMembership::sendNotification("group welcome email", $contact, $data);
    } else {    
      WTMembership::sendNotification("approve", $contact, $data);
    }
  }

  /**
   *  Reject a member
   *
   *  @method reject
   *  @param {int} The guid of the member to reject
   */
  static function reject($guid) 
  {
    $contact = $GLOBALS["WT"]->getNode($guid);
    if($contact) {
      WTMembership::sendNotification("reject", $contact);
      $contact->deleteNode();
    }
  }

  static function checkMemberField($type, $value) 
  {
    switch($type) {
      case "password":
      if(strlen($value) < 6) {
        return '<span class="formerror">Your password needs to be 6 or more characters</span>';
      } else {
        return '<span class="formsuccess">Password is OK!</span>';
      }
      break;
    case "passwordconfirm":
      if($value != "ok") {
        return '<span class="formerror">The password fields do not match</span>';
      } else {
        return '<span class="formsuccess">Passwords match</span>';
      }
    case "email":
      if(!WTForm::checkEmail($value)) {
        return '<span class="formerror">Please enter a valid email address</span>';
      }
/*
      $q = Array();
      $q["Node Type"] = "Contact";
      $q["Criteria"] = "`Email Address` = '" . mysql_escape_string($value) . "' AND Type LIKE '%Member%'";
      $q["Select"] = "COUNT(*)";
      $count = $GLOBALS["WT"]->query($q, "singleValueCallback");
*/
      
      if(WTMembership::checkEmail($value)) {
        return '<span class="formsuccess">Email Address OK!</span>';
      } else {
        return '<span class="formerror">' . $value . ' is already associated with a member</span>';
      }
      break;
    case "emailconfirm":
      if($value != "ok") {
        return '<span class="formerror">The email address fields do not match</span>';
      } else {
        return '<span class="formsuccess">Email Addresses match</span>';
      }
      break;
    case "username":
      if(trim($value) == "") {
        return '<span class="formerror">Please enter a value for username</span>';
      }

      if(WTMembership::checkUsername($value)) {
        return '<span class="formsuccess">The username '. $value .' is available</span>';
      } else {
        return '<span class="formerror"> The username ' . $value . ' is already in use. Please log in or choose a different username</span>';
      }

      break;

    }
  }


  /**
   *  Check if a username is available
   *
   *  @method checkUsername
   *  @static
   *  @param {String} username The username to check
   *  @param {int} [contactGuid=0] Set to a contact guid to check the username for a particular contact
   *  @return {boolean} returns true if the username is ok
   */
  static function checkUsername($username, $contactguid = 0) 
  {
    $q = Array();
    $q["Node Type"] = "Contact";
    $q["Criteria"] = "Username = '" . mysql_escape_string($username) . "' AND (Type LIKE '%Member%' OR Type LIKE '%Admin%') AND Status <> 'Inactive'";
    if($contactguid != 0) {
      $q["Criteria"] .= " AND Contact.__guid <> " . $contactguid;
    }
    $q["Select"] = "COUNT(*)";
    $count = $GLOBALS["WT"]->query($q, "singleValueCallback");
    return $count == 0;

  }

  /**
   *  Check if an email address is available
   *
   *  @method checkEmail
   *  @static
   *  @param {String} emai The email address to check
   *  @param {int} [contactGuid=0] Set to a contact guid the check the email address for a particular contact
   *  @return {booelan} returns true if the email address is ok
   */
  static function checkEmail($email, $contactguid = 0) 
  {
    $q = Array();
    $q["Node Type"] = "Contact";
    $q["Criteria"] = "`Email Address` = '" . mysql_escape_string($email) . "' AND Type LIKE '%Member%' AND Status <> 'Inactive'";
    if($contactguid != 0) {
      $q["Criteria"] .= " AND Contact.__guid <> " . $contactguid ;
    }
    
    
    $q["Select"] = "COUNT(*)";
    $count = $GLOBALS["WT"]->query($q, "singleValueCallback");
    return $count == 0;  
  }


  /**
   *  Send a forgotten password email
   *  
   *  @method forgottenPassword
   *  @static
   */
  //Revisions: 1.0.
  //           1.1 //Need to send 'Password Reset URL' as an anchor.
  static function forgottenPassword() 
  {
    $username = $GLOBALS["WT"]->getRequestValue("username");

    $q = Array();
    $q["Criteria"] = "(Username = '" . mysql_escape_string($username) . "' OR `Email Address` = '" . mysql_escape_string($username) . "') AND Status = 'Active' AND `Type` LIKE '%Member%'";
    $q["Limit"] = "1";
    $q["Select"] = "Contact.__guid";
    $q["Node Type"] = "Contact";
    $guid = $GLOBALS["WT"]->query($q, "singleValueCallback");
    if($guid) {
      print "guid = $guid";
      $contact = $GLOBALS["WT"]->getNode($guid);
      if(!$contact) {
//        return;
      }

      $key = md5(uniqid(rand(),1));
      $keyAction = Array("cmd" => "passwordreset");
      $contact->setAttributes(Array("Key" => $key, "Key Date" => date("Y-m-d H:i:s"), "Key Action" => serialize($keyAction)));
      $data = Array();
     
     // $data["Password Reset URL"] = WTConfig::get("Site Details/Site URL") . "?wtc=o24rnd5kgtlsdf3&i=$guid&k=$key";
      $data["Password Reset URL"] = "<a href='";
      $data["Password Reset URL"] .= WTConfig::get("Site Details/Site URL") . "__membership/resetpassword/$guid/$key";
      $data["Password Reset URL"] .= "'>".WTConfig::get("Site Details/Site URL") . "__membership/resetpassword/$guid/$key"."</a>";
      //$data["Password Reset URL"] = "<a href='"+WTConfig::get("Site Details/Site URL") . "__membership/resetpassword/$guid/$key"+"'>Test Link</a>";

      WTMembership::sendNotification("forgotten password", $contact, $data);
      $_SESSION["WTLASTMEMBER"] = $contact->m_guid;

      $uri = $GLOBALS["WT"]->getRequestURI();
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "emailsent");

      
      header("Location: $uri");

//      header("Location: password-link-sent");
      exit("");
    } else {
      $uri = $GLOBALS["WT"]->getRequestURI();
      $uri = $GLOBALS["WT"]->setURIParameter($uri, "cmd", "notfound");
      header("Location: $uri");
      exit("");
//      print "couldn't find contact";
    }
  }

  static function setNotification($type, $subject, $message)
  {
    $subjectPath = $GLOBALS["WTMEMBERSHIPNOTIFICATIONS"][$type]["path"] . " Subject";
    $messagePath = $GLOBALS["WTMEMBERSHIPNOTIFICATIONS"][$type]["path"] . " Message";

    WTConfig::set($subjectPath, $subject);
    WTConfig::set($messagePath, $message);
  }


  static function getNotificationInfo($type, $element) 
  {
    return $GLOBALS["WTMEMBERSHIPNOTIFICATIONS"][$type][$element];
  }

  static function getNotificationSubject($type) 
  {
    $subjectPath = $GLOBALS["WTMEMBERSHIPNOTIFICATIONS"][$type]["path"] . " Subject";
    if(WTSession::get("WTLANGUAGEID") && WTConfig::get("Multilingual") == "Yes") {
      $subjectNode = $GLOBALS["WT"]->getNode("/Config/Settings/" . $subjectPath);
      if($subjectNode) {
        $subjectTranslationNode = $subjectNode->getTranslationNode(WTSession::get("WTLANGUAGEID"));
        if($subjectTranslationNode) {
          return $subjectTranslationNode->getAttribute("Value");
        }
      }
    }
    return WTConfig::get($subjectPath);
  }

  static function getNotificationMessage($type) 
  {
    $messagePath = $GLOBALS["WTMEMBERSHIPNOTIFICATIONS"][$type]["path"] . " Message";

    if(WTSession::get("WTLANGUAGEID") && WTConfig::get("Multilingual") == "Yes") {

      $messageNode = $GLOBALS["WT"]->getNode("/Config/Settings/" . $messagePath);
      if($messageNode) {


        $messageTranslationNode = $messageNode->getTranslationNode(WTSession::get("WTLANGUAGEID"));
        if($messageTranslationNode) {
          return $messageTranslationNode->getAttribute("Value");
        }
      } 
    } 


    return WTConfig::get($messagePath);   
  }

  static function sendNotification($type, $contact, $data = Array())
  {
    $type = strtolower($type);
    if(!is_object($contact)) {
      $contact = $GLOBALS["WT"]->getNode($contact);
    }
    if(!$contact) {
      return false;
    }

    $emailAddress = $contact->getAttribute("Email Address");
    $fromName = WTConfig::get("Membership/Notifications From Name");
    $fromAddress = WTConfig::get("Membership/Notifications From Address");


    if($type == "group welcome email") {
      $groupID = $data["Group ID"];
      $group = $GLOBALS["WT"]->getNode($groupID);
      $subject = $group->getAttribute("Welcome Email Subject");
      $message = $group->getAttribute("Welcome Email Message");

      if($subject == "" && $message == "") {
        $subject = WTMembership::getNotificationSubject("welcome");
        $message = WTMembership::getNotificationMessage("welcome");
      }


    } else {
      $subject = WTMembership::getNotificationSubject($type);
      $message = WTMembership::getNotificationMessage($type);
    }

    foreach($data as $key => $value) {
      $subject = str_replace("[$key]", $value, $subject);
      $message = str_replace("[$key]", $value, $message);
    }
    $attributes = $contact->getAttributes();
    foreach($attributes as $key => $value) {
      $subject = str_replace("[$key]", $value, $subject);
      $message = str_replace("[$key]", $value, $message);
    }

    $templateNode = $GLOBALS["WT"]->getNode("/Templates/Emails/General");
    if($templateNode) {
      $templateData = Array("Content" => $message);
      $message = $templateNode->evaluate($templateData);
     
    } else {
      $message = '<html><head></head><body>' . $message . '</body></html>';
    }

    if($type == "application received admin email") {
      $emailAddress = WTConfig::get("Membership/Admin Notifications To Address");
    }

    $mail = new WTMail();
    $mail->setFrom($fromAddress, $fromName);
    $mail->setReplyTo($fromAddress);
    $mail->setTo($emailAddress);
    $mail->setContent($subject, $message, true);
    $mail->send();

    $sendToAdmin = $type == "group welcome email" || $type == "payment receipt email";
    if($type == "welcome") {
      if(WTConfig::get("Membership/Welcome/Send Copy To Admin") == "Yes") {
        $sendToAdmin = true;
      }
    }

    if($sendToAdmin) { 
//$type == "group welcome email" || $type == "payment receipt email") {
      $emailAddress = WTConfig::get("Membership/Admin Notifications To Address");
      $mail = new WTMail();
      $mail->setFrom($fromAddress, $fromName);
      $mail->setReplyTo($fromAddress);
      $mail->setTo($emailAddress);
      $mail->setContent($subject, $message, true);
      $mail->send();
    }
  }


  /**
   *  Activate a member
   *
   *  @method activate
   *  @static 
   *  @param {Object} The contact object to activate
   */
  static function activate($contact) {
    $contactData = Array("Key" => "", "Key Action" => "", "Status" => "Active");
    $username = $contact->getAttribute("Username");
    $password = $contact->getAttribute("Password");

    $contactData["Password"] = trim($password);

    if($contactData["Password"] == "") {
      $contactData["Password"] = WTMembership::generatePassword();
    }
    $contact->setAttributes($contactData);


    $memberGroups = $contact->getGroups("Member Group");

    if(is_numeric($memberGroups)) {
      $contactData["Group ID"] = $memberGroups;
      WTMembership::sendNotification("group welcome email", $contact, $contactData);
    } else {
      WTMembership::sendNotification("welcome", $contact, $contactData);
    }

  }

  static function memberKey($id, $key, $cmd = "") 
  {
    if(is_numeric($id) && strlen($key) == 32) {
      $q = Array();
      $q["Node Type"] = "Contact";
      $q["Criteria"] = "Contact.__guid = " . (int)$id . " AND `Key` = '" . mysql_escape_string($key) . "'";
      $q["Limit"] = 1;
      $q["Select"] = "Contact.__guid";
      $guid = $GLOBALS["WT"]->query($q, "singleValueCallback");
      if($guid) {
        $contact = $GLOBALS["WT"]->getNode($guid);
        $keyDate = $contact->getAttribute("Key Date");
        $keyAction = unserialize($contact->getAttribute("Key Action"));
        $cmd = $keyAction["cmd"];

        switch($cmd) {
//          case 'resetpassword':
          case 'passwordreset':
          case 'resetpassword':
            $username = $contact->getAttribute("Username");
            $GLOBALS["WT"]->setUser($username);
            $base = $GLOBALS["WT"]->getSiteSetting("Site Base"); 

            $accountPage = WTConfig::get("Membership/Member Account Page");
            if($accountPage == "") {
              $accountPage = "account";
            }

            header("Location: {$base}$accountPage?cmd=changepassword&i=$id&k=$key");
            exit("");
            break;
          case 'activate':
            if(!WTMembership::checkUsername($contact->getAttribute("Username"))) {
              $inUseURI = WTConfig::get("Membership/Activation/Username In Use URI");
              if($inUseURI) {
                WTSession::set("WTACTIVATEUSERNAME", $contact->getAttribute("Username"));
                $inUseURI = WTConfig::get("Site Details/Site URL") . $inUseURI;
                header("Location: $inUseURI");
                exit("");
              }
            }

            if(!WTMembership::checkEmail($contact->getAttribute("Email Address"))) {
              $inUseURI = WTConfig::get("Membership/Activation/Email In Use URI");
              if($inUseURI) {
                WTSession::set("WTACTIVATEEMAIL", $contact->getAttribute("Email Address"));
                $inUseURI = WTConfig::get("Site Details/Site URL") . $inUseURI;
                header("Location: $inUseURI");
                exit("");
              }
            }

            WTMembership::activate($contact);
            $username = $contact->getAttribute("Username");
/* 
            $contactData = Array("Key" => "", "Key Action" => "", "Status" => "Active");
            $username = $contact->getAttribute("Username");
            $password = $contact->getAttribute("Password");

            $contactData["Password"] = trim($password);

            if($contactData["Password"] == "") {
              $contactData["Password"] = WTMembership::generatePassword();
            }
            $contact->setAttributes($contactData);


            $memberGroups = $contact->getGroups("Member Group");

            if(is_numeric($memberGroups)) {
              $contactData["Group ID"] = $memberGroups;
              WTMembership::sendNotification("group welcome email", $contact, $contactData);
            } else {
              WTMembership::sendNotification("welcome", $contact, $contactData);
            }

            $GLOBALS["WT"]->setUser($username);
*/
            $GLOBALS["WT"]->setUser($username);

            $accountPage = WTConfig::get("Membership/Member Account Page");
            if($accountPage == "") {
              $accountPage = "account";
            }

            $url = WTConfig::get("Site Details/Site URL") . "$accountPage?cmd=activated";
            header("Location: $url");
            exit("");
            break;
        }


//        $contact->setAttributes(Array("Key" => "", "Key Action" => ""));
      } else {
        switch($cmd) {
          case 'activate':
            $url = WTConfig::get("Site Details/Site URL") . "website-member-signup?cmd=alreadyactive";
            header("Location: $url");
            exit("");
            break;
          case 'resetpassword':
            print "The reset password link has expired";
            break;
        }
      }
    }
  }


  static function getCurrentPeriod() {
    $q = Array();
    $q["Node Type"] = "wtMembershipPeriod";
    $q["Path"] = "/Membership/Membership Periods/*";
    $q["Criteria"] = "`From` <= NOW() AND `To` > NOW()";
    $q["Select"] = "wtMembershipPeriod.__guid";
    $periodGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
    if($periodGuid) {
      return $GLOBALS["WT"]->getNode($periodGuid);
    }
    return null;
  }

  static function getPeriodFee($groupID, $periodID = 0) {
    if($periodID == 0) {
      $currentPeriod = WTMembership::getCurrentPeriod();
      if($currentPeriod) {
        $periodID = $currentPeriod->m_guid;
      }
    }

    $q["Node Type"] = "wtMembershipPeriodFee";
    $q["Path"] = "$periodID/*";
    $q["Criteria"] = "`Group ID` = $groupID";
    $feeGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
    if($feeGuid) {
      $feeNode = $GLOBALS["WT"]->getNode($feeGuid);
      return $feeNode->getAttribute("Fee");
    }
  }

  static function getValue($pathElements)
  {
    $activation = $GLOBALS["WT"]->getWTValue("wt.settings.Membership.Activation");
    $approval = $GLOBALS["WT"]->getWTValue("wt.settings.Membership.Approval");
    $memberfees = $GLOBALS["WT"]->getWTValue("wt.settings.Membership.Member Fees");
    $contact = null;
    $attributes = null;
    if(array_key_exists("WTLASTMEMBER", $_SESSION)) {
      $contact = $GLOBALS["WT"]->getNode($_SESSION["WTLASTMEMBER"]);
      $attributes = $contact->getAttributes();

    }
   
    if(count($pathElements) >= 4) {
      if($pathElements[2] == 'registerthanks') {
        if($pathElements[3] == 'subject') {
          if($approval == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Approval/Application Received Subject");
          } else if($activation == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Activation/Activation Instructions Subject");
          } else if($memberfees == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Member Fees/Credit Card Payment Successful Subject");
          } else {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Welcome/Welcome Subject");
          }
          if(count($pathElements) == 5 && $pathElements[4] == "guid") {
            return $node->m_guid;
          } else {
            return $node->getAttribute("Value");
          }
        } else {
          if($approval == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Approval/Application Received Message");
          } else if($activation == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Activation/Activation Instructions Message");
          } else if($memberfees == "Yes") {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Member Fees/Credit Card Payment Successful Message");
          } else {
            $node = $GLOBALS["WT"]->getNode("/Config/Settings/Membership/Welcome/Welcome Message");
          }

          if(count($pathElements) == 5 && $pathElements[4] == "guid") {
            return $node->m_guid;
          } else {
            return $node->getAttribute("Value");
          }
        }
      } else if($pathElements[2] == 'passwordlinksent') {
        if($pathElements[3] == 'subject') {
          $value = WTMembership::getNotificationSubject('password link sent');
        } else {
          $value = WTMembership::getNotificationMessage('password link sent');
        }

        foreach($attributes as $k => $v) {
          $value = str_replace("[$k]", $v, $value);
        }
        return $value;
        
      }
    }
    
  }


}

WTForm::registerFormHandler("register", Array("WTMembership", "processSignupForm"));
WTForm::registerFormHandler("cartregister", Array("WTMembership", "processSignupForm"));

WTForm::registerFormHandler("changepassword", Array("WTMembership", "processChangePassword"));
WTForm::registerFormHandler("setmemberdetails", Array("WTMembership", "processSetMemberDetails"));

$GLOBALS["WT"]->registerURIHandler("__membership", Array("WTMembership", "processMembershipURI"));

?>