<?php
/**
 * Process.php
 * 
 * The Process class is meant to simplify the task of processing
 * user submitted forms, redirecting the user to the correct
 * pages if errors are found, or if form is successful, either
 * way. Also handles the logout procedure.
 *
 * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
 * Last Updated: August 19, 2004
 */
include("include/session.php");

class Process
{
   /* Class constructor */
   function Process(){
      global $session;
      /* User submitted login form */
      if(isset($_POST['sublogin'])){
	     $retval = $session->logout(); // makes sure all cookies are cleared before attempting login
         $this->procLogin();
      }
      /* User submitted registration form */
      else if(isset($_POST['subjoin'])){
         $this->procRegister();
      }
      /* User submitted forgot password form */
      else if(isset($_POST['subforgot'])){
         $this->procForgotPass();
      }
      /* User submitted edit account form */
      else if(isset($_POST['subedit'])){
         $this->procEditAccount();
      }
      /* User submitted delete request */
      else if(isset($_POST['subdelete'])){
         $this->procDeleteAccount();
      }
      /* User has removed a buddy from the buddy list */
      else if(isset($_POST['removebuddy'])){
		 $this->procRemoveBuddy();
      }
      /* User has removed a buddy request from the buddy list */
      else if(isset($_POST['cancelbuddyrequest'])){
		 $this->procCancelBuddyRequest();
      }
      /* User has sent a buddy request */
      else if(isset($_POST['addbuddy'])){
		 $this->procAddBuddy();
      }
      /* User has approved / denied a buddy request */
      else if(isset($_POST['buddyacceptdeny'])){
		 $this->procAcceptDenyBuddyRequest();
      }
	  else if(isset($_POST['sendpm'])){
		 $this->procSendPM();
      }
	  else if($session->isQueryAdmin() && isset($_POST['adminquerysubmit'])){
		 $this->procQuerySubmit();
      }
	  else if($session->isQueryAdmin() && isset($_POST['adminactionssubmit'])){
		 $this->procActionsSubmit();
      }
	  else if($session->isAdmin() && isset($_POST['addserversubmit'])){
		 $this->procAddServer();
      }
	  else if($session->isAdmin() && isset($_POST['editserversubmit'])){
		 $this->procEditServer();
      }
	  else if($session->isAdmin() && isset($_POST['adminsearchsubmit'])){
		 $this->procSearchSubmit();
      }
	  else if($session->isAdmin() && isset($_POST['subadminedit'])){
	     $this->procAdminEditAccount();
	  }
	  else if($session->isAdmin() && isset($_POST['subadmindelete'])){
	     $this->procAdminDeleteAccount();
	  }

      /**
       * The only other reason user should be directed here
       * is if he wants to logout, which means user is
       * logged in currently.
       */
      else if($session->logged_in){
         $this->procLogout();
      }
      /**
       * Should not get here, which means user is viewing this page
       * by mistake and therefore is redirected.
       */
       else{
          header("Location: index.php");
		  return;
       }
   }

   /**
    * procLogin - Processes the user submitted login form, if errors
    * are found, the user is redirected to correct the information,
    * if not, the user is effectively logged in to the system.
    */
   function procLogin(){
      global $session, $form;
	  
	  $user = $_POST['user'];
	  $pass = $_POST['pass'];
	  
	  $user = mysql_real_escape_string(trim($user));
	  $pass = mysql_real_escape_string(trim($pass));
	  
      /* Login attempt */
      $retval = $session->login($user, $pass, isset($_POST['remember']));
      
      /* Login successful */
      if($retval){
         header("Location: ".$session->referrer);
		 return;
      }
      /* Login failed */
      else{
         $_SESSION['value_array'] = $_POST;
         $_SESSION['error_array'] = $form->getErrorArray();
         header("Location: ".$session->referrer);
		 return;
      }
   }
   
   /**
    * procLogout - Simply attempts to log the user out of the system
    * given that there is no logout form to process.
    */
   function procLogout(){
      global $session;
      $retval = $session->logout();
      header("Location: index.php");
	  return;
   }
   
   /**
    * procRegister - Processes the user submitted registration form,
    * if errors are found, the user is redirected to correct the
    * information, if not, the user is effectively registered with
    * the system and an email is (optionally) sent to the newly
    * created user.
    */
   function procRegister(){
      global $session, $form;

	  $user = $_POST['user'];
	  $pass = $_POST['pass'];
	  $email = $_POST['email'];
	  $secretq = $_POST['secretq'];
	  $answerq = $_POST['answerq'];
	    
	  $user = mysql_real_escape_string(trim($user));
	  $pass = mysql_real_escape_string(trim($pass));
	  $email = mysql_real_escape_string(trim($email));
	  $secretq = mysql_real_escape_string(trim($secretq));
	  $answerq = mysql_real_escape_string(trim($answerq));
	  
      /* Registration attempt */
      $retval = $session->register($user, $pass, $email, $secretq, $answerq);
      
      /* Registration Successful */
      if($retval == 0){
         $_SESSION['reguname'] = $user;
         $_SESSION['regsuccess'] = true;
         header("Location: ".$session->referrer);
		 return;
      }
      /* Error found with form */
      else if($retval == 1){
         $_SESSION['value_array'] = $_POST;
         $_SESSION['error_array'] = $form->getErrorArray();
         header("Location: ".$session->referrer);
		 return;
      }
      /* Registration attempt failed */
      else if($retval == 2){
         $_SESSION['reguname'] = $user;
         $_SESSION['regsuccess'] = false;
         header("Location: ".$session->referrer);
		 return;
      }
   }
   
   /* procRemoveBuddy */
   function procRemoveBuddy(){
      global $database, $session;
	  
	  $buddyid = $_POST['buddyid'];
	    
	  if(strlen($buddyid) == 0)
	  {
	    header("Location: ".$session->referrer);
		 return;
	  }
		
	  $buddyid = mysql_real_escape_string($buddyid);
	  
	  $database->removeFromBuddyList($session->userDBid,$buddyid);
      header("Location: ".$session->referrer);
	  return;
   }
   
   /* procCancelBuddyRequest */
   function procCancelBuddyRequest(){
      global $database, $session;

	  $buddyid = $_POST['buddyid'];
	    
	  $buddyid = mysql_real_escape_string($buddyid);
	  
	  $database->RemoveFromBuddyRequestList($session->userDBid,$buddyid);
	  
	  $_SESSION['errormsg'] = "Buddy request cancelled successfully!";
      header("Location: " . $session->referrer);
	  return;
   }
   
   /* procAddBuddy */
   function procAddBuddy(){
      global $database, $session;
	  
	  $buddysearchresults = $_POST['buddysearchresults'];

	  $buddysearchresults = mysql_real_escape_string($buddysearchresults);
 
	  if(strlen($buddysearchresults) == 0)
	  {
	    header("Location: ".$session->referrer);
		 return;
	  }
	  else if($buddysearchresults == $session->userDBid)
	  {
		$_SESSION['errormsg'] = "You cannot add yourself as a buddy.";
	    header("Location: ".$session->referrer);
		return;
	  }
	  $result = $database->AddToBuddyList($session->userDBid,$buddysearchresults);
	  
	  if($result)
	  {
		$_SESSION['errormsg'] = $result;
	  }
      header("Location: " . $session->referrer);
	  return;
   }
   
   function procSendPM(){
	  global $database, $session;
	  $bSuccess = false;
	  
	  if(strlen($_POST['pmmessage']) > 0 && strlen($_POST['pmto']) > 0 )
	  {
		 $bSuccess = $database->SendPM($_POST['pmto'], $session->userDBid, $_POST['pmmessage']);
		 if($bSuccess)
		 {
			$_SESSION['errormsg'] = "Message sent successfully.";
			$_SESSION['lastBuddyPMed'] = $_POST['pmto'];
		 }
		 else
		 {
			$_SESSION['errormsg'] = "Error sending message. User '".$database->getNameFromID($_POST['pmto'])."' appears to have gone offline.";
		 }
		 header("Location: ".$session->referrer);
		 return;
	  }
	  else
	  {
	     $_SESSION['errormsg'] = "Error sending message. You either didn't specify a recipient, or didn't enter a message.";
	     header("Location: ".$session->referrer);
		 return;
	  }
   }
   
   function procAddServer(){
	  global $database, $session;

	  $bError = false;
	  
	  if($_POST['server_name']) { $server_name = mysql_real_escape_string(trim($_POST['server_name'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server name."; }
	  if($_POST['server_url']) { $server_url = mysql_real_escape_string(trim($_POST['server_url'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server URL."; }
	  if($_POST['server_tcpport']) { $server_tcpport = mysql_real_escape_string(trim($_POST['server_tcpport'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server TCP port."; }
	  if($_POST['briefinfo_cachetime']) { $briefinfo_cachetime = mysql_real_escape_string(trim($_POST['briefinfo_cachetime'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a cache time."; }
	  if($_POST['allow_local_lookup']) { $allow_local_lookup = mysql_real_escape_string($_POST['allow_local_lookup']); } else { $allow_local_lookup = 0; }
	  if($_POST['allow_universal_lookup']) { $allow_universal_lookup = mysql_real_escape_string($_POST['allow_universal_lookup']); } else { $allow_universal_lookup = 0; }
	  
	  if(!$bError)
	  {
	    $database->addServer($server_name,$server_url,$server_tcpport,$briefinfo_cachetime,$allow_local_lookup,$allow_universal_lookup);
	    $_SESSION['errormsg'] = "Server added successfully!.";
	  }
	  header("Location: ".$session->referrer);
	  return;
   }
   
   function procEditServer(){
	  global $database, $session;

	  $bError = false;
	  $bDelete = false;
	  
	  if($_POST['server_name']) { $server_name = mysql_real_escape_string(trim($_POST['server_name'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server name."; }
	  if($_POST['server_url']) { $server_url = mysql_real_escape_string(trim($_POST['server_url'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server URL."; }
	  if($_POST['server_tcpport']) { $server_tcpport = mysql_real_escape_string(trim($_POST['server_tcpport'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a server TCP port."; }
	  if($_POST['briefinfo_cachetime']) { $briefinfo_cachetime = mysql_real_escape_string(trim($_POST['briefinfo_cachetime'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You must enter a cache time."; }
	  if($_POST['allow_local_lookup']) { $allow_local_lookup = mysql_real_escape_string($_POST['allow_local_lookup']); } else { $allow_local_lookup = 0; }
	  if($_POST['allow_universal_lookup']) { $allow_universal_lookup = mysql_real_escape_string($_POST['allow_universal_lookup']); } else { $allow_universal_lookup = 0; }
	  if($_POST['servernum']) { $servernum = mysql_real_escape_string($_POST['servernum']); } else { $bError = true; $_SESSION['errormsg'] = "Error! Server number not passed from the page form."; }
	  if($_POST['deleteserversubmit']) { $bDelete = true; }
	  
	  if(!$bError)
	  {
	    $database->editServer($servernum,$server_name,$server_url,$server_tcpport,$briefinfo_cachetime,$allow_local_lookup,$allow_universal_lookup,$bDelete);
	    $_SESSION['errormsg'] = "Server entry modified successfully!.";
	  }
	  header("Location: ".$session->referrer);
	  return;
   }
   
   function procSearchSubmit(){
	  global $database, $session;

	  $bError = false;
	  
	  if($_POST['name']) { $name = mysql_real_escape_string(trim($_POST['name'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You did not enter a search string."; }
	  if($_POST['pageno'] > 0) { $pageno = mysql_real_escape_string($_POST['pageno']); } else { $pageno = 0; }
	  
	  if(!$bError)
	  {
	    $_SESSION['adminSearchName'] = $name;
		$_SESSION['pageno'] = $pageno;
	  }
	  header("Location: ".$session->referrer);
	  return;
   }
   
   function procQuerySubmit(){
	  global $database, $session;

	  $bError = false;
	  
	  if($_POST['query']) { $query = mysql_real_escape_string(trim($_POST['query'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You did not enter a search string."; }
	  if($_POST['wide'] == "true") $_SESSION['adminQueryWide'] = True; else unset($_SESSION['adminQueryWide']);
	  if($_POST['pageno'] > 0) { $pageno = mysql_real_escape_string($_POST['pageno']); } else { $pageno = 0; }

	  $_SESSION['adminQueryField'] = $_POST['searchby'];
	
	  if(!$bError)
	  {
	    $_SESSION['adminQuery'] = $query;
		$_SESSION['pageno'] = $pageno;
	  }
	  header("Location: ".$session->referrer);
	  return;
   }
   
   function procActionsSubmit(){
	  global $database, $session;

	  $bError = false;
	  
	  if($_POST['query']) { $query = mysql_real_escape_string(trim($_POST['query'])); } else { $bError = true; $_SESSION['errormsg'] = "Error! You did not enter a search string."; }
	  if($_POST['wide'] == "true") $_SESSION['adminActionsWide'] = True; else unset($_SESSION['adminActionsWide']);
	  if($_POST['pageno'] > 0) { $pageno = mysql_real_escape_string($_POST['pageno']); } else { $pageno = 0; }

	  $_SESSION['adminActionsField'] = $_POST['searchby'];
	
	  if(!$bError)
	  {
	    $_SESSION['adminActions'] = $query;
		$_SESSION['pageno'] = $pageno;
	  }
	  header("Location: ".$session->referrer);
	  return;
   }
   
   /* procAcceptDenyBuddyRequest */
   function procAcceptDenyBuddyRequest(){
      global $database, $session;
 
 	  $buddyacceptdenylist = $_POST['buddyacceptdenylist'];
	  $buddyacceptdenyoperation = $_POST['buddyacceptdenyoperation'];
	  
	  $buddyacceptdenylist = mysql_real_escape_string($buddyacceptdenylist);
	  $buddyacceptdenyoperation = mysql_real_escape_string($buddyacceptdenyoperation);
 
	  if(strlen($buddyacceptdenylist) > 0)
	  {
		 $database->doBuddyAcceptDeny($session->userDBid,$buddyacceptdenylist,$buddyacceptdenyoperation);
		 header("Location: ".$session->referrer);
		 return;
	  }
	  else
	  {
	     $_SESSION['errormsg'] = "You must first click on a buddy to accept or deny their request.";
	     header("Location: ".$session->referrer);
		 return;
	  }
   }
   
   /**
    * procForgotPass - Validates the given username then if
    * everything is fine, a new password is generated and
    * emailed to the address the user gave on sign up.
    */
   function procForgotPass(){
      global $database, $session, $mailer, $form;
	  
	  $user = $_POST['user'];
	  $answerq = $_POST['answerq'];
	  
	  $user = mysql_real_escape_string(trim($user));
	  $answerq = mysql_real_escape_string(trim($answerq));
	  
      /* Username error checking */
      $subuser = $user;
      if(!$subuser || strlen($subuser = trim($subuser)) == 0){
         $form->setError("user", "* Username or E-mail Address not entered<br>");
      }
	  else if(!$answerq || strlen($answerq = trim($answerq)) == 0){
         $form->setError("answerq", "* Answer to secret question not entered<br>");
      }
      else{
	  
		 if(!$database->usernameTaken($subuser))
		 {
			// username doesn't exist... try e-mail instead
			if($database->emailTaken($subuser))
			{
				$subuser = $database->getNameFromEmail($subuser);
			}
			else
			{
				$form->setError("user", "* Username or E-mail Address does not exist<br>");
			}
		 }
/*	  
         if(strlen($subuser) < 2 || strlen($subuser) > 30 ||
            !eregi("^[_a-zA-Z0-9]+[-a-zA-Z0-9]+[~a-zA-Z0-9]*$", $subuser) ||
            (!$database->usernameTaken($subuser))){
            $form->setError("user", "* Username or E-mail Address does not exist<br>");
         }
*/
		 if(strlen($answerq) > 100 ||
            (!$database->secretQuestionIsCorrect($subuser,$answerq))){
            $form->setError("answerq", "* Answer to secret question incorrect<br>");
         }
      }
      
      /* Errors exist, have user correct them */
      if($form->num_errors > 0){
         $_SESSION['value_array'] = $_POST;
         $_SESSION['error_array'] = $form->getErrorArray();
      }
      /* Generate new password and email it to user */
      else{
         /* Generate new password */
         $newpass = $session->generateRandStr(8);
         
         /* Get email of user */
         $usrinf = $database->getUserInfo($subuser);
         $email  = $usrinf['email'];
         
         /* Attempt to send the email with new password */
         if($mailer->sendNewPass($subuser,$email,$newpass)){
            /* Email sent, update database */
            $database->updateUserField($subuser, "password", md5($newpass));
            $_SESSION['forgotpass'] = true;
         }
         /* Email failure, do not change password */
         else{
            $_SESSION['forgotpass'] = false;
         }
      }
      
      header("Location: ".$session->referrer);
	  return;
   }
   
   /**
    * procEditAccount - Attempts to edit the user's account
    * information, including the password, which must be verified
    * before a change is made.
    */
   function procEditAccount(){
      global $session, $form;
	  
	  $curpass = $_POST['curpass'];
	  $newpass = $_POST['newpass'];
	  $autoaccept = $_POST['autoaccept'];
	  $emailaboutbuddies = $_POST['emailaboutbuddies'];
	  $email = $_POST['email'];
	  
	  $curpass = mysql_real_escape_string(trim($curpass));
	  $newpass = mysql_real_escape_string(trim($newpass));
	  $autoaccept = mysql_real_escape_string($autoaccept);
	  $emailaboutbuddies = mysql_real_escape_string($emailaboutbuddies);
	  $email = mysql_real_escape_string(trim($email));
	  
      /* Account edit attempt */
      $retval = $session->editAccount($curpass, $newpass, $email, $autoaccept, $emailaboutbuddies);

      /* Account edit successful */
      if($retval){
         $_SESSION['useredit'] = true;
         header("Location: ".$session->referrer);
		 return;
      }
      /* Error found with form */
      else{
         $_SESSION['value_array'] = $_POST;
         $_SESSION['error_array'] = $form->getErrorArray();
         header("Location: ".$session->referrer);
		 return;
      }
   }
   
   function procDeleteAccount(){
      global $session, $database;
      $retval = $session->logout();
	  $database->removeAccount($session->userDBid);
      header("Location: index.php");
	  return;
   }

   function procAdminEditAccount(){
      global $session, $form;
	  
	  $newpass = $_POST['newpass'];
	  $autoaccept = $_POST['autoaccept'];
	  $emailaboutbuddies = $_POST['emailaboutbuddies'];
	  $email = $_POST['email'];
	  $userlevel = $_POST['userlevel'];
	  $user = $_POST['user'];
	  $id = $_POST['id'];
	  
	  $newpass = mysql_real_escape_string(trim($newpass));
	  $autoaccept = mysql_real_escape_string($autoaccept);
	  $emailaboutbuddies = mysql_real_escape_string($emailaboutbuddies);
	  $email = mysql_real_escape_string(trim($email));
	  $userlevel = mysql_real_escape_string($userlevel);
	  $user = mysql_real_escape_string($user);
	  $id = mysql_real_escape_string($id);
	  
      /* Account edit attempt */
      $retval = $session->editAdminAccount($id, $user, $newpass, $email, $autoaccept, $emailaboutbuddies, $userlevel);

      /* Account edit successful */
      if($retval){
         $_SESSION['useredit'] = true;
         header("Location: ".$session->referrer);
		 return;
      }
      /* Error found with form */
      else{
         $_SESSION['value_array'] = $_POST;
         $_SESSION['error_array'] = $form->getErrorArray();
         header("Location: ".$session->referrer);
		 return;
      }
   }
   
   function procAdminDeleteAccount(){
      global $database, $session;
	  
	  $id = $_POST['id'];
	  $id = mysql_real_escape_string($id);

	  $database->removeAccount($id);
      $_SESSION['useredit'] = true;
      header("Location: ".$session->referrer);
	  return;
   }
};

/* Initialize process */
$process = new Process;

?>
