<?php 
/*
 * b1gMail7
 * (c) 2002-2008 B1G Software
 * 
 * Redistribution of this code without explicit permission
 * is forbidden!
 *
 * $Id: index.php,v 1.49 2009/02/02 11:12:42 patrick Exp $
 *
 */

include('./serverlib/init.inc.php');
include('./serverlib/safecode.class.php');

/**
 * file handler for modules
 */
ModuleFunction('FileHandler',
	array(substr(__FILE__, strlen(dirname(__FILE__))+1),
	isset($_REQUEST['action']) ? $_REQUEST['action'] : ''));

/**
 * default action = login 
 */
if(!isset($_REQUEST['action']))
	$_REQUEST['action'] = 'login';

/**
 * terms of service
 */
if($_REQUEST['action'] == 'tos')
{
	// terms of service
	$tpl->assign('pageTitle', $lang_user['tos']);
	$tpl->assign('tos', nl2br(HTMLFormat($lang_custom['tos'])));
	$tpl->assign('page', 'nli/tos.tpl');
}

/**
 * imprint
 */
else if($_REQUEST['action'] == 'imprint')
{
	// imprint
	$tpl->assign('pageTitle', $lang_user['imprint']);
	$tpl->assign('imprint', $lang_custom['imprint']);
	$tpl->assign('page', 'nli/imprint.tpl');
}

/**
 * faq
 */
else if($_REQUEST['action'] == 'faq')
{
	// faq
	$faq = array();
	$res = $db->Query('SELECT id,frage,antwort FROM {pre}faq WHERE (lang=? OR lang=?) AND (typ=? OR typ=?) ORDER BY frage ASC',
		':all:',
		$currentLanguage,
		'both',
		'nli');
	while($row = $res->FetchArray(MYSQL_ASSOC))
	{
		$answer = $row['antwort'];
		$answer = str_replace('%%hostname%%', $_SERVER['HTTP_HOST'], $answer);
		$answer = str_replace('%%selfurl%%', $bm_prefs['selfurl'], $answer);
		$answer = nl2br($answer);
	
		array_push($faq, array(
			'question'		=> $row['frage'],
			'answer'		=> $answer
		));
	}
	$res->Free();
	
	$tpl->assign('pageTitle', $lang_user['faq']);
	$tpl->assign('faq', $faq);
	$tpl->assign('page', 'nli/faq.tpl');
}

/**
 * sign up
 */
else if($_REQUEST['action'] == 'signup')
{
	$tpl->assign('pageTitle', $lang_user['signup']);
	
	// sign up ip lock?
	if($bm_prefs['regenabled'] == 'yes'
		&& ($bm_prefs['user_count_limit'] == 0 || BMUser::GetUserCount() < $bm_prefs['user_count_limit']))
	{
		$res = $db->Query('SELECT COUNT(*) FROM {pre}users WHERE reg_ip=? AND reg_date>?',
			$_SERVER['REMOTE_ADDR'],
			time()-$bm_prefs['reg_iplock']);
		$row = $res->FetchArray();
		$res->Free();

		if($row[0] != 0)
		{
			// block sign up
			$tpl->assign('msg', $lang_user['reglock']);
			$tpl->assign('page', 'nli/regdone.tpl');
		}
		else 
		{
			$showForm = true;
			
			if(isset($_POST['do']) && $_POST['do']=='createAccount')
			{
				$showForm = false;
				$invalidFields = array();
				$errorInfo = '';
				
				//
				// check fields
				//
				
				// email domain
				$suEMailDomain = trim($_POST['email_domain']);
				if(!in_array($suEMailDomain, explode(':', $bm_prefs['domains'])))
					$invalidFields[] = 'email_domain';
				
				// email 
				$suEMailLocal = trim($_POST['email_local']);
				$suEMail = $suEMailLocal . '@' . $suEMailDomain;
				if(!BMUser::AddressValid($suEMail) || !BMUser::AddressAvailable($suEMail) 
					|| BMUser::AddressLocked($suEMailLocal)
					|| strlen($suEMailLocal) < $bm_prefs['minuserlength'])
					$invalidFields[] = 'email_local';
				
				// first name
				$suFirstname = trim($_POST['firstname']);
				if(strlen($suFirstname) < 2)
					$invalidFields[] = 'firstname';
					
				// last name
				$suSurname = trim($_POST['surname']);
				if(strlen($suSurname) < 2)
					$invalidFields[] = 'surname';
					
				// 'strasse'-group
				if($bm_prefs['f_strasse'] != 'n')
				{
					// street
					$suStreet = trim($_POST['street']);
					if((strlen($suStreet) < 3) && (strlen($suStreet) > 0 || $bm_prefs['f_strasse'] == 'p'))
						$invalidFields[] = 'street';
					
					// no
					$suNo = trim($_POST['no']);
					if((strlen($suNo) < 1) && (strlen($suNo) > 0 || $bm_prefs['f_strasse'] == 'p'))
						$invalidFields[] = 'no';
					
					// zip
					$suZIP = trim($_POST['zip']);
					if((strlen($suZIP) < 3) && (strlen($suZIP) > 0 || $bm_prefs['f_strasse'] == 'p'))
						$invalidFields[] = 'zip';
					
					// city
					$suCity = trim($_POST['city']);
					if((strlen($suCity) < 3) && (strlen($suCity) > 0 || $bm_prefs['f_strasse'] == 'p'))
						$invalidFields[] = 'city';
					
					// country
					$suCountry = (int)$_POST['country'];
					if($bm_prefs['f_strasse'] == 'p' && !in_array($suCountry, array_keys(CountryList())))
						$invalidFields[] = 'country';
						
					// zip/city check?
					if(!in_array('zip', $invalidFields)
						&& !in_array('city', $invalidFields)
						&& !in_array('country', $invalidFields)
						&& $bm_prefs['plz_check'] == 'yes'
						&& !ZIPCheck($suZIP, $suCity, $suCountry))
					{
						$invalidFields[] = 'zip';
						$invalidFields[] = 'city';
						$errorInfo .= ' ' . $lang_user['plzerror'];
					}
				}
				else if($bm_prefs['f_strasse'] == 'n')
				{
					$suStreet = $suNo = $suZIP = $suCity = '';
					$suCountry = $bm_prefs['std_land'];
				}
				
				// 'telefon'-field
				if($bm_prefs['f_telefon'] != 'n')
				{
					$suPhone = trim($_POST['phone']);
					if((strlen($suPhone) < 5) && (strlen($suPhone) > 0 || $bm_prefs['f_telefon'] == 'p'))
						$invalidFields[] = 'phone';
				}
				else if($bm_prefs['f_telefon'] == 'n')
				{
					$suPhone = '';
				}
				
				// safecode
				if($bm_prefs['f_safecode'] == 'p')
				{
					$code = Safecode::GetCode((int)$_POST['codeID']);
					if(!isset($_POST['safecode']) 
						|| strlen($code) < 4
						|| strtolower($_POST['safecode']) != strtolower($code))
						$invalidFields[] = 'safecode';
					if(strlen($code) >= 4)
						Safecode::ReleaseCode((int)$_POST['codeID']);
				}
				
				// 'fax'-field
				if($bm_prefs['f_fax'] != 'n')
				{
					$suFax = trim($_POST['fax']);
					if((strlen($suFax) < 5) && (strlen($suFax) > 0 || $bm_prefs['f_fax'] == 'p'))
						$invalidFields[] = 'fax';
				}
				else if($bm_prefs['f_fax'] == 'n')
				{
					$suFax = '';
				}
				
				// 'altmail'-field
				if($bm_prefs['f_alternativ'] != 'n')
				{
					$suAltMail = trim($_POST['altmail']);
					if((strlen($suAltMail) > 0 || $bm_prefs['f_alternativ'] == 'p') && (!BMUser::AddressValid($suAltMail) || ($bm_prefs['alt_check'] == 'yes' && !ValidateMailAddress($suAltMail))))
						$invalidFields[] = 'altmail';
				}
				else if($bm_prefs['f_alternativ'] == 'n')
				{
					$suAltMail = '';
				}
				
				// 'mail2sms_nummer'-field
				if($bm_prefs['f_mail2sms_nummer'] != 'n'
					|| $bm_prefs['reg_smsvalidation'] == 'yes')
				{
					$suMobileNr = trim(ereg_replace('[^0-9]', '', str_replace('+', '00', $_POST['mail2sms_nummer'])));
					if((strlen($suMobileNr) < 6) && (strlen($suMobileNr) > 0 || $bm_prefs['f_mail2sms_nummer'] == 'p'
						|| $bm_prefs['reg_smsvalidation'] == 'yes'))
						$invalidFields[] = 'mail2sms_nummer';
				}
				else if($bm_prefs['f_mail2sms_nummer'] == 'n')
				{
					$suMobileNr = '';
				}
				
				// password
				$suPass1 = $_POST['pass1'];
				$suPass2 = $_POST['pass2'];
				if(strlen($suPass1) < 3 || $suPass1 != $suPass2 || $suPass1 == $suEMailLocal)
				{
					$invalidFields[] = 'pass1';
					$invalidFields[] = 'pass2';
					$errorInfo .= ' ' . $lang_user['pwerror'];
				}
				
				// coupon
				$suCoupon = isset($_POST['code']) ? trim($_POST['code']) : '';
				if($suCoupon != '' && !BMUser::CouponValid($suCoupon))
				{
					$invalidFields[] = 'code';
					$errorInfo .= ' ' . $lang_user['signupcouponerror'];
				}
				
				// tos
				if(!isset($_POST['tos']) || $_POST['tos'] != 'true')
					$errorInfo .= ' ' . $lang_user['toserror'];
				
				// profile fields
				$suProfile = array();
				$res = $db->Query("SELECT id,rule,pflicht,typ FROM {pre}profilfelder");
				while($row = $res->FetchArray())
				{
					$feld_ok = false;
					$feld_name = 'field_' . $row['id'];
					switch($row['typ'])
					{
					case FIELD_CHECKBOX:
						$feld_ok = true;
						$suProfile[$row['id']] = isset($_POST[$feld_name]);
						break;
					case FIELD_DROPDOWN:
						$feld_ok = true;
						if($feld_ok)
							$suProfile[$row['id']] = $_POST[$feld_name];
						break;
					case FIELD_RADIO:
						$feld_ok = isset($_POST[$feld_name]);
						if($feld_ok)
							$suProfile[$row['id']] = $_POST[$feld_name];
						break;
					case FIELD_TEXT:
						$feld_ok = (trim($row['rule']) == '') || (ereg($row['rule'], $_POST[$feld_name]));
						if(isset($_POST[$feld_name]))
							$suProfile[$row['id']] = $_POST[$feld_name];
						break;
					}
					if(($row['pflicht']=='yes' || (isset($_POST[$feld_name]) && strlen($_POST[$feld_name]) > 0)) && (!$feld_ok))
						$invalidFields[] = $feld_name;
				}
				$res->Free();
				
				// go on
				if(count($invalidFields) > 0)
				{
					// errors => mark fields red and show form again
					$showForm = true;
					$tpl->assign('errorStep', true);
					$tpl->assign('errorInfo', $lang_user['checkfields'] . $errorInfo);
					$tpl->assign('invalidFields', $invalidFields);
				}
				else 
				{
					// create account
					$userId = BMUser::CreateAccount($suEMail,
						$suFirstname,
						$suSurname,
						$suStreet,
						$suNo,
						$suZIP,
						$suCity,
						$suCountry,
						$suPhone,
						$suFax,
						$suAltMail,
						$suMobileNr,
						$suPass1,
						$suProfile);
					
					// successful?
					if($userId !== false && $userId > 0)
					{
						// redeem coupon?
						if($suCoupon != '')
						{
							$theNewUser = _new('BMUser', array($userId));
							$theNewUser->RedeemCoupon($suCoupon);
						}
						
						// account created
						Add2Stat('signup');
						$showForm = false;
						$tpl->assign('msg', 			sprintf($bm_prefs['usr_status'] == 'locked'
															? $lang_user['regdonelocked']
															: $lang_user['regdone'], $suEMail));
						$tpl->assign('page', 			'nli/regdone.tpl');
						
						
						// module handler
						ModuleFunction('AfterSuccessfulSignup', array($userId, $suEMail));
					}
					else 
					{
						// error occured				
						$showForm = true;
						$tpl->assign('errorStep', 		true);
						$tpl->assign('errorInfo', 		$lang_user['regerror']);
						$tpl->assign('invalidFields', 	array());
					}
				}
			}
			
			if($showForm)
			{
				// codes?
				$res = $db->Query('SELECT COUNT(*) FROM {pre}codes');
				$row = $res->FetchArray(MYSQL_NUM);
				$res->Free();
				$tpl->assign('code', $row[0] > 0);
				
				// safe code
				if($bm_prefs['f_safecode'] == 'p')
					$tpl->assign('codeID', Safecode::RequestCode());
					
				// profile fields?
				$profilfelder = array();
				$res = $db->Query('SELECT feld,pflicht,id,extra,typ FROM {pre}profilfelder');
				while($row = $res->FetchArray())
				{
					array_push($profilfelder, array(
						'feld'			=> $row['feld'],
						'pflicht'		=> $row['pflicht']=='yes',
						'id'			=> $row['id'],
						'extra'			=> explode(',', $row['extra']),
						'typ'			=> $row['typ']
					));
				}
				$res->Free();
				if(count($profilfelder) > 0)
					$tpl->assign('profilfelder', $profilfelder);
					
				// required fields
				$tpl->assign('f_strasse', 			$bm_prefs['f_strasse']);
				$tpl->assign('f_telefon', 			$bm_prefs['f_telefon']);
				$tpl->assign('f_fax', 				$bm_prefs['f_fax']);
				$tpl->assign('f_alternativ',	 	$bm_prefs['f_alternativ']);
				$tpl->assign('f_mail2sms_nummer', 	$bm_prefs['reg_smsvalidation'] == 'yes' ? 'p' : $bm_prefs['f_mail2sms_nummer']);
				$tpl->assign('f_safecode', 			function_exists('imagepng') ? $bm_prefs['f_safecode'] : 'n');
				
				// show page
				$tpl->assign('countryList',		CountryList());
				$tpl->assign('defaultCountry',	$bm_prefs['std_land']);
				$tpl->assign('tos',				HTMLFormat($lang_custom['tos']));
				$tpl->assign('domainList', 		explode(':', $bm_prefs['domains']));
				$tpl->assign('page', 			'nli/signup.tpl');
			}
		}	
	}
	else 
	{
		// sign up disabled
		$tpl->assign('msg', $lang_user['regdisabled']);
		$tpl->assign('page', 'nli/regdone.tpl');
	}
}

/**
 * safe code image dump
 */
else if($_REQUEST['action'] == 'codegen')
{
	// dump code as image
	if(isset($_GET['id']) && is_numeric($_GET['id']))
		Safecode::DumpCode($_GET['id']);
	exit();
}

/**
 * safe code validation RPC
 */
else if($_REQUEST['action'] == 'checkSafeCode')
{
	// check code
	if(isset($_GET['id']) && is_numeric($_GET['id'])
		&& isset($_GET['code']))
	{
		$id = $_GET['id'];
		$code = trim($_GET['code']);
		
		$rightCode = Safecode::GetCode($id);
		if(strlen($rightCode) < 4 || strtolower($code) != strtolower($rightCode))
			echo('0');
		else 
			echo('1');
	}
	else 
		echo('0');
	exit();
}

/**
 * address availability check (RPC)
 */
else if($_REQUEST['action'] == 'checkAddressAvailability')
{
	if(!isset($_GET['address']))
		exit();
		
	// check address availability
	$result = BMUser::AddressValid($_GET['address']) ? 1 : 2;
	
	if($result == 1)
	{
		list($localPart) = explode('@', $_GET['address']);
		if(strlen(trim($localPart)) < $bm_prefs['minuserlength']
			|| BMUser::AddressLocked($localPart))
			$result = 0;
	}
	
	if($result == 1)
		$result = BMUser::AddressAvailable($_GET['address']) ? 1 : 0;
	
	// respond
	$response = array(
		'available'		=> $result 
	);
	
	Array2XML($response);
	exit();
}

/**
 * custom page
 */
else if($_REQUEST['action'] == 'page' && isset($_GET['page']))
{
	$page = ereg_replace('([^a-zA-Z0-9]*)', '', $_GET['page']);
	$tpl->assign('page', 'custompages/' . $page . '.tpl');
}

/**
 * forget cookies
 */
else if($_REQUEST['action'] == 'forgetCookie')
{
	// delete cookies
	setcookie('bm_savedUser', 		'',		 		time() - TIME_ONE_HOUR);
	setcookie('bm_savedPassword', 	'',		 		time() - TIME_ONE_HOUR);
	setcookie('bm_savedLanguage', 	'',		 		time() - TIME_ONE_HOUR);
	
	// reload
	header('Location: index.php');
	exit();
}

/**
 * forgot password
 */
else if($_REQUEST['action'] == 'lostPassword'
		&& ((isset($_REQUEST['email_local'])
				&& isset($_REQUEST['email_domain'])
				&& trim($_REQUEST['email_local']) != '')
			|| (isset($_REQUEST['email_full'])
				&& trim($_REQUEST['email_full']) != '')))
{
	$tpl->assign('pageTitle', $lang_user['lostpw']);
	
	$userMail = isset($_REQUEST['email_full'])
					? trim($_REQUEST['email_full'])
					: trim($_REQUEST['email_local']) . '@' . $_REQUEST['email_domain'];
	
	if(BMUser::LostPassword($userMail))
	{
		// send PW link
		$tpl->assign('msg', $lang_user['pwresetsuccess']);
	}
	else 
	{
		// unknown address
		$tpl->assign('msg', $lang_user['pwresetfailed']);
	}
	
	$tpl->assign('title', $lang_user['lostpw']);
	$tpl->assign('page', 'nli/msg.tpl');
}

/**
 * reset password
 */
else if($_REQUEST['action'] == 'resetPassword'
		&& isset($_REQUEST['user'])
		&& isset($_REQUEST['key']))
{
	$tpl->assign('pageTitle', $lang_user['lostpw']);
	
	$userID = (int)$_REQUEST['user'];
	$resetKey = trim($_REQUEST['key']);
	
	if(BMUser::ResetPassword($userID, $resetKey))
	{
		// delete cookies
		setcookie('bm_savedUser', 		'',		 		time() - TIME_ONE_HOUR);
		setcookie('bm_savedPassword', 	'',		 		time() - TIME_ONE_HOUR);
		setcookie('bm_savedLanguage', 	'',		 		time() - TIME_ONE_HOUR);
		
		// ok
		$tpl->assign('msg', $lang_user['pwresetsuccess2']);
	}
	else 
	{
		// invalid id/key
		$tpl->assign('msg', $lang_user['pwresetfailed2']);
	}
	
	$tpl->assign('title', $lang_user['lostpw']);
	$tpl->assign('page', 'nli/msg.tpl');
}

/**
 * confirm alias
 */
else if($_REQUEST['action'] == 'confirmAlias'
		&& isset($_REQUEST['id'])
		&& isset($_REQUEST['code']))
{
	$tpl->assign('pageTitle', $lang_user['confirmaliastitle']);
	
	if(BMUser::ConfirmAlias((int)$_REQUEST['id'], $_REQUEST['code']))
		$tpl->assign('msg', $lang_user['confirmaliasok']);
	else
		$tpl->assign('msg', $lang_user['confirmaliaserr']);
	
	$tpl->assign('title', $lang_user['confirmaliastitle']);
	$tpl->assign('page', 'nli/msg.tpl');
}

/**
 * read cert mail
 */
else if($_REQUEST['action'] == 'readCertMail'
		&& isset($_REQUEST['id'])
		&& isset($_REQUEST['key']))
{
	$tpl->assign('pageTitle', $lang_user['certmail']);
	
	$id = (int)$_REQUEST['id'];
	$key = trim($_REQUEST['key']);
	
	if(!class_exists('BMMailbox'))
		include('./serverlib/mailbox.class.php');
		
	$mail = BMMailbox::GetCertMail($id, $key);
	
	if($mail)
	{
		// get text part
		$textParts = $mail->GetTextParts();
		if(isset($textParts['html']))
		{
			$textMode = 'html';
			$text = $textParts['html'];
		}
		else if(isset($textParts['text']))
		{
			$textMode = 'text';
			$text = formatEMailText($textParts['text']);
		}
		else 
		{
			$textMode = 'text';
			$text = '';
		}
		
		// get attachments
		$attachments = $mail->GetAttachments();
		
		// show text only?
		if(isset($_REQUEST['showText']))
		{
			if($textMode == 'html')
				$text = '<base target="_blank" /><font face="arial" size="2">' . formatEMailHTMLText(isset($textParts['html']) ? $textParts['html'] : '', true, $attachments, (int)$_REQUEST['id']) . '</font>';
			else 
				$text = '<base target="_blank" /><font face="arial" size="2">' . formatEMailText(isset($textParts['text']) ? $textParts['text'] : '') . '</font>';
			echo($text);
			exit();
		}
		
		// get attachment?
		if(isset($_REQUEST['downloadAttachment']))
		{
			$parts = $mail->GetPartList();
			if(isset($parts[$_REQUEST['attachment']]))
			{
				$part = $parts[$_REQUEST['attachment']];
				
				header('Pragma: public');
				header('Content-Type: ' . $part['content-type']);
				header(sprintf('Content-Disposition: %s; filename="%s"',
							'attachment',
							addslashes($part['filename'])));
							
				$attData = &$part['body'];
				$attData->Init();
				while($block = $attData->DecodeBlock(PART_CHUNK_SIZE))
				{
					echo $block;
				}
				$attData->Finish();
				
				exit();
			}
		}
		
		// assign
		$tpl->assign('mailID',				$id);
		$tpl->assign('key',					$key);
		$tpl->assign('subject',				$mail->GetHeaderValue('subject'));
		$tpl->assign('fromAddresses', 		ParseMailList($mail->GetHeaderValue('from')));
		$tpl->assign('toAddresses', 		ParseMailList($mail->GetHeaderValue('to')));
		$tpl->assign('ccAddresses', 		ParseMailList($mail->GetHeaderValue('cc')));
		$tpl->assign('replyToAddresses',	ParseMailList($mail->GetHeaderValue('reply-to')));
		$tpl->assign('flags', 				$mail->flags);
		$tpl->assign('date',				$mail->date);
		$tpl->assign('priority', 			(int)$mail->priority);
		$tpl->assign('text', 				$text);
		$tpl->assign('textMode', 			$textMode);
		$tpl->assign('attachments', 		$attachments);
		$tpl->assign('page', 				'nli/certmail.read.tpl');
	}
	else 
	{
		$tpl->assign('msg', 				$lang_user['certmailerror']);
		$tpl->assign('title', 				$lang_user['certmail']);
		$tpl->assign('page', 				'nli/msg.tpl');
	}
}

/**
 * address book completion
 */
else if($_REQUEST['action'] == 'completeAddressBookEntry'
		&& isset($_REQUEST['contact'])
		&& isset($_REQUEST['key']))
{
	$tpl->assign('pageTitle', $lang_user['addrselfcomplete']);
	
	$contactID = (int)$_REQUEST['contact'];
	$key = trim($_REQUEST['key']);
	
	if(!class_exists('BMAddressbook'))
		include('./serverlib/addressbook.class.php');
	
	$contactData = BMAddressbook::GetContactForSelfCompleteInvitation($contactID, $key);
	if($contactData)
	{
		if(isset($_REQUEST['do']) && $_REQUEST['do'] == 'save')
		{
			// save data
			$book = _new('BMAddressbook', array($contactData['user']));
			$book->Change($contactID,
				$_REQUEST['firma'],
				$contactData['vorname'],
				$contactData['nachname'],
				$_REQUEST['strassenr'],
				$_REQUEST['plz'],
				$_REQUEST['ort'],
				$_REQUEST['land'],
				$_REQUEST['tel'],
				$_REQUEST['fax'],
				$_REQUEST['handy'],
				$_REQUEST['email'],
				$_REQUEST['work_strassenr'],
				$_REQUEST['work_plz'],
				$_REQUEST['work_ort'],
				$_REQUEST['work_land'],
				$_REQUEST['work_tel'],
				$_REQUEST['work_fax'],
				$_REQUEST['work_handy'],
				$_REQUEST['work_email'],
				$_REQUEST['anrede'],
				$_REQUEST['position'],
				$_REQUEST['web'],
				$contactData['kommentar'],
				SmartyDateTime('geburtsdatum_'),
				$contactData['default_address'],
				false);
			$book->InvalidateSelfCompleteInvitation($contactID, $key);
			
			// send mail
			$userData = BMUser::Fetch($contactData['user']);
			$vars = array(
				'vorname'	=> $contactData['vorname'],
				'nachname'	=> $contactData['nachname']
			);
			SystemMail($bm_prefs['passmail_abs'],
				$userData['email'],
				$lang_custom['selfcomp_n_sub'],
				'selfcomp_n_text',
				$vars);
			
			// log
			PutLog(sprintf('Address book entry completed after accepting invitation (contact id: %d, key: %s, IP: %s)',
				$contactID,
				$key,
				$_SERVER['REMOTE_ADDR']),
				PRIO_NOTE,
				__FILE__,
				__LINE__);
			
			$tpl->assign('msg', $lang_user['completeok']);
			$tpl->assign('title', $lang_user['addrselfcomplete']);
			$tpl->assign('page', 'nli/msg.tpl');
		}
		else 
		{
			// show form
			$tpl->assign('contact', $contactData);
			$tpl->assign('page', 'nli/contact.complete.tpl');
		}
	}
	else 
	{
		$tpl->assign('msg', $lang_user['completeerr']);
		$tpl->assign('title', $lang_user['addrselfcomplete']);
		$tpl->assign('page', 'nli/msg.tpl');
	}
}

/**
 * login
 */
else 
{
	$availableLanguages = GetAvailableLanguages();
	
	if(isset($_REQUEST['do']) && $_REQUEST['do']=='login')
	{
		// get login
		$password 	= isset($_REQUEST['password']) && !empty($_REQUEST['password'])
						? $_REQUEST['password']
						: (isset($_REQUEST['passwordMD5']) ? $_REQUEST['passwordMD5'] : '');
		$email 		= (isset($_REQUEST['email_full'])
						? $_REQUEST['email_full']
						: $_REQUEST['email_local'] . '@' . $_REQUEST['email_domain']);
		$language 	= (isset($_REQUEST['language']) && isset($availableLanguages[$_REQUEST['language']])
						? $_REQUEST['language']
						: $bm_prefs['language']);
		
		// sms validation
		$requiresValidation	 = BMUser::RequiresSMSValidation($email);
		$smsValidationCode	 = $requiresValidation && isset($_REQUEST['sms_validation_code'])
								? $_REQUEST['sms_validation_code']
								: '';
		
		// login
		list($result, $param) = BMUser::Login($email, $password, true, true, $smsValidationCode);
		
		// login ok?
		if($result == USER_OK)
		{
			// stats
			Add2Stat('login');
			
			// save login?
			if(isset($_POST['savelogin']))
			{
				// set cookies
				setcookie('bm_savedUser', 		$email, 		time() + TIME_ONE_YEAR);
				setcookie('bm_savedPassword', 	$password, 		time() + TIME_ONE_YEAR);
				setcookie('bm_savedLanguage', 	$language, 		time() + TIME_ONE_YEAR);
				setcookie('bm_savedSSL',
					isset($_POST['ssl']) ? true : false,
					time() + TIME_ONE_YEAR);
			}
			else 
			{
				// delete cookies
				setcookie('bm_savedUser', 		'', 			time() - TIME_ONE_HOUR);
				setcookie('bm_savedPassword', 	'', 			time() - TIME_ONE_HOUR);
				setcookie('bm_savedLanguage', 	'', 			time() - TIME_ONE_HOUR);
				setcookie('bm_savedSSL', 		'', 			time() - TIME_ONE_HOUR);
			}
			
			// register language
			$_SESSION['bm_sessionLanguage'] = $language;
			
			// redirect to target page
			if(!isset($_REQUEST['target']))
			{
				header('Location: start.php?sid=' . $param);
			}
			else if($_REQUEST['target'] == 'inbox')
			{
				header('Location: email.php?folder=0&sid=' . $param);
			}
			else if($_REQUEST['target'] == 'compose')
			{
				header('Location: email.compose.php?sid=' . $param
					. (isset($_REQUEST['draft']) && $_REQUEST['draft']!='' ? '&redirect=' . (int)($_REQUEST['draft']) : '')
					. (isset($_REQUEST['to']) && $_REQUEST['to']!='' ? '&to=' . urlencode($_REQUEST['to']) : '')
					. (isset($_REQUEST['cc']) && $_REQUEST['cc']!='' ? '&subject=' . urlencode($_REQUEST['cc']) : '')
					. (isset($_REQUEST['subject']) && $_REQUEST['subject']!='' ? '&subject=' . urlencode($_REQUEST['subject']) : '')
					. (isset($_REQUEST['text']) && $_REQUEST['text']!='' ? '&text=' . urlencode($_REQUEST['text']) : ''));
			}
			else if($_REQUEST['target'] == 'membership')
			{
				header('Location: prefs.php?sid=' . $param . '&action=membership');
			}
			exit();
		}
		else 
		{
			// sms validation input?
			if($result == USER_LOCKED
				&& $requiresValidation)
			{
				$tpl->assign('email',		$email);
				$tpl->assign('password',	strlen($password) == 32 ? $password : md5($password));
				$tpl->assign('savelogin',	isset($_POST['savelogin']));
				$tpl->assign('language',	$language);
				$tpl->assign('page',		'nli/login.smsvalidation.tpl');
			}
			else
			{
				// tell user what happened
				switch($result)
				{
				case USER_BAD_PASSWORD:
					$tpl->assign('msg',	sprintf($lang_user['badlogin'], $param));
					break;
				case USER_DOES_NOT_EXIST:
					$tpl->assign('msg', $lang_user['baduser']);
					break;
				case USER_LOCKED:
					$tpl->assign('msg', $lang_user['userlocked']);
					break;
				case USER_LOGIN_BLOCK:
					$tpl->assign('msg', sprintf($lang_user['loginblocked'], FormatDate($param)));
					break;
				}
				$tpl->assign('page',	'nli/loginresult.tpl');
			}
		}
	}
	else 
	{
		// login page
		if(isset($_COOKIE['bm_savedUser']))
		{
			$tpl->assign('welcomeBack', sprintf($lang_user['welcomeback'], $_COOKIE['bm_savedUser']));
		}
		
		// lost password and no email entered?
		if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'lostPassword')
		{
			$tpl->assign('invalidFields', array('email_local_pw'));
		}
		
		$tpl->assign('ssl_url',				$bm_prefs['ssl_url']);
		$tpl->assign('ssl_login_enable',	$bm_prefs['ssl_login_enable'] == 'yes');
		$tpl->assign('ssl_login_option',	$bm_prefs['ssl_login_option'] == 'yes');
		$tpl->assign('domain_combobox',		$bm_prefs['domain_combobox'] == 'yes');
		$tpl->assign('languageList', 		$availableLanguages);
		$tpl->assign('domainList', 			explode(':', $bm_prefs['domains']));
		$tpl->assign('page', 				'nli/login.tpl');
	}
}

$tpl->display('nli/index.tpl');
?>