<?php
//standard $langA values are not available to this file
//

defined('WikyBlog') or die("Not an entry point...");


class registerUser{
	
	var $requireEmail = false;
	var $requireCaptcha = false;
	
	
	function attempt(){
		
		if( !cookies() ){
			message('COOKIES_REQUIRED');
			return false;
		}
		
		includeFile('tool/Variables.php');
		$config = wbVariables::getArray('register:');
		if( isset($config['register:reqemail']) && ($config['register:reqemail'] === 'On') ){
			$this->requireEmail = true;
		}
		
		if( isset($config['register:captcha']) && ($config['register:captcha'] === 'On') ){
			$this->requireCaptcha = true;
		}
		
		
		
		$_POST += array('session'=>'', 'email'=>'');
		if($_POST['session'] == 'Register'){
			$this->register();
			
		}elseif( !empty($_GET['username']) ){
			$_POST['username'] = $_GET['username'];
		}
	}
	
	function register($install = false){
		global $reservedWords,$eventKeywords,$dbInfo,$wbTables;
		$complete = true;
		
		//----------------
		// CHECK VALUES
		//----------------	
		
		
		$characters = '.\+*?^[]$(){}=!<>|:"\',&;/@%`~';
		$expression = '#[\#'.preg_quote($characters).']#';
		if( preg_match($expression,$_POST['username']) ){
			$characters .= '#'; //for showing the #
			message('ILLEGAL_USERNAME',$characters);
			return false;
		}
		
		if( $this->requireEmail ){
			$email = $_POST['email'];
			
			//empty
			if( empty($email) ){
				message('EMAIL_REQUIRED');
				return false;
			}
			
			//check format
			if( !eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
				message('EMAIL_REQUIRED');
				return false;
			}
			
			//check MX
			//	
			// if( function_exists('checkdnsrr') ){
			// 	list($username,$domain)=split('@',$email);
			// 	if(!checkdnsrr($domain,'MX')) {
			// 		message('EMAIL_REQUIRED');
			// 		return false;
			// 	}
			// }
			
			
		}
		
		if( $this->requireCaptcha ){
			global $wbUniq;
			
			if( empty($_POST['captcha']) ){
				message('INCORRECT_CAPTCHA');
				return false;
			}
			
			//prep the text
			session_start();
			$r = $_SESSION['captcha']['/Special/Main/Register'];
			session_write_close();
			$text = md5($wbUniq.$r);
			$text = str_replace(array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),array(''),$text);
			$text = substr($text,1,6);

			
			if( $text !== $_POST['captcha'] ){
				$i = 0;
				while($i < strlen($text) ){
					$a = $text{$i};
					$b = $_POST['captcha']{$i};
					$i++;
				}
				message('INCORRECT_CAPTCHA');
				return false;
			}
		}
		
			
		
		
		////////////////////////////////////////////////
		//
		//		password
		//
		if( empty($_POST['password']) ){
			message('ENTER_PASSWORD');
			return false;		
		}
		$length = wbStrlen($_POST['password']);
		if( $length < 5 ){
			message('SHORT_PASSWORD');
			return false;
		}
		if($_POST['password'] != $_POST['password2']){
			message('PASSWORDS_DIFFERENT');
			return false;
		}
	
		////////////////////////////////////////////////
		//
		//		username
		//
		$_POST['username'] = toStorage($_POST['username']);
		$temp = toStorage( $_POST['username'],true );
		
		//$reserved words is a string of comma seperated words in the database configuration
		//as apposed to an array of words in wiki.php change made 2006-Mar-21
		if( is_string($reservedWords) ){
			$notAllowed = wbStr_replace(', ',',',$reservedWords);
			$notAllowed = wbStr_replace(' ,',',',$notAllowed);
			$notAllowed = wbExplode(',',$notAllowed);
		}else{
			$notAllowed = $reservedWords;
		}
		
		$more1 = array();
		if( is_array($dbInfo) ){
			$more1 = array_keys($dbInfo);
		}
		$more2 = array('search','default','edit','include','imgs','userfiles','warnings','jscript','false','true');
		$notAllowed = array_merge( (array)$notAllowed, $more1, $more2);
		
		if( is_array($eventKeywords) ){
			$notAllowed = array_merge(	$notAllowed,
									array_values($eventKeywords),
									array_keys($eventKeywords)
									);
		}
		foreach($notAllowed as $key => $value){
			$notAllowed[$key] = toStorage($value);
		}
		$notAllowed = array_flip($notAllowed);
		$notAllowed = array_change_key_case($notAllowed, CASE_LOWER);
	
		if( isset($notAllowed[$temp]) ){
			message('USER_TAKEN',$_POST['username']);
			return;
		}
		if( ctype_digit($_POST['username']) ){
			message('USERNAME_ALL_DIGITS');
			return false;
		}
		$query = 'SELECT * FROM '.$wbTables['users'].' WHERE username="'.$_POST['username'].'"';
		$result = wbDB::runQuery($query);
		$num = mysql_num_rows($result);
		if( $num !== 0){
			message('USER_TAKEN',$_POST['username']);
			return false;
		}
		$length = wbStrlen($_POST['username']);
		if( $length < 3 ){
			message('SHORT_USERNAME');
			return false;
		}
		if($length > 20){
			message('LONG_USERNAME');
			return false;
		}
	
		return $this->createAccount($install);
	}

	function createAccount($install){
		global $page,$rootDir,$wbTables,$userLanguage,$wbNow;
		
		includeFile('tool/DefaultUser.php');
		$newUserValues = defaultUser();
		
		//get user language
		session_start();
		if( !empty($_SESSION['lang']) && strlen($_SESSION['lang']) =='2' ){
			$langFile = $rootDir.'/include/lang/'.$userLanguage;
			if( is_dir($langFile) ){
				$newUserValues['lang'] = $_SESSION['lang'];
			}
		}
		//open edits
		if( !empty($_SESSION['editPage']) ){
			$newUserValues['editPage'] = $_SESSION['editPage'];
		}
		session_write_close();
		$_SESSION = array();
		
		
		if( !empty($_POST['email']) ){
			$newUserValues['email'] = $_POST['email'];
		}
		
		$newUserValues['data2']['tabs']['/'.$_POST['username'].'/'.$GLOBALS['wbDefaultTitle']]= toDisplay($GLOBALS['wbDefaultTitle']);
		$newUserValues['data2']['tabs']['/Special/'.$_POST['username'].'/ControlPanel']= 'control_panel';
		$newUserValues['data2']['tabs']['/Special/'.$_POST['username'].'/ChangeLog']= 'change_log';
		
		$insert['username'] = $_POST['username'];
		$insert['password'] = md5($_POST['password']);
		$insert['created'] = $wbNow;
		$insert['total_usage'] = 0;
		$insert['restricted'] = '';
		$insert['keyword_count'] = '';
		
		//fields in `users`
		$insert['max_usage'] = $newUserValues['max_usage'];
		$insert['max_history'] = $newUserValues['abs_max_history'];
		$insert['flags'] = $newUserValues['flags'];
		
		unset($newUserValues['max_usage']);
		unset($newUserValues['abs_max_history']);
		unset($newUserValues['flags']);
		
		if( $this->requireEmail ){
			$flags = explode(',',$insert['flags']);
			$flags[] = 'pending';
			$flags = array_diff($flags,array('')); //to avoid "data truncated" mysql warning
			$insert['flags'] = implode(',', $flags);
		}
		
		$insert['data2'] = serialize($newUserValues['data2']);
		unset($newUserValues['data2']);
		
		$insert['data'] = serialize($newUserValues);
		
		
		$query = 'INSERT INTO '.$wbTables['users'].' SET '.wbDB::toSet($insert,true);
		$num = wbDB::runQuery($query,true);
		if($num != 1){
			trigger_error('<b>Error:</b> Could not save the user data.'.mysql_error() );
			return false;
		}
		
		includeFile('tool/sessionActions.php');
		
		if( $this->requireEmail ){
			$this->sendCode();
		}else{
			sessLog::in(true);
		}
		return true;
	}
	
	
	function sendCode(){
		global $wbUniq, $wbNow, $langA, $serverName1, $serverName2, $registered, $serverName4;
		
		
		includeFile('tool/sessionConfirm.php',false);
		$code = sessionConfirm::getCode($_POST['username']);
		//$link = $serverName4.'/'.$_POST['username'].'?session=confirm&u='.$_POST['username'].'&c='.$code;
		$link = $serverName4.'/Special/'.$_POST['username'].'/Register?session=confirm&u='.$_POST['username'].'&c='.$code;
		//message('<input type="text" value="'.$link.'" />');
		
		$subject = $langA['ACTIVATE_ACCOUNT'];
		
		$message = '<p><a href="'.$link.'">'.$langA['ACTIVATE_ACCOUNT'].'</a>';
		$message .= '<br/> ( '.$link.' )';
		$message .= '</p>';
		$message .= '<br/>';
		$message .= '<p>';
		$message .= $serverName2;
		$message .= '</p>';
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= 'From: '.$serverName1;
		$headers .= '<AutomatedSender@'.$serverName2.'>'."\r\n";
		
		if( @mail($_POST['email'], $subject, $message, $headers) ){
			message('REGISTERED_&_SENT',$_POST['email']);
			$registered = true;
			
		}else{
			//$registered = true;
			trigger_error('confirmation email not sent');
		}
	}
}





