<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
//
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

$menu_section = "me";


if (!isset($_SESSION['md5'])) {
	header("Location: index.php?http_referer=" . urlencode($_SERVER['REQUEST_URI']) . "&" . strip_tags(SID));
	exit;
}

if (isset($_POST['set_dormant'])) {
	// set the status to dormant
	$query = "
		SELECT user_id, status_id 
		FROM " . $db->prefix . "_user
		WHERE 
		user_id=" . $_SESSION['user_id']
	;

	$result = $db->Execute($query);

	if (isset($result)) {
		if ($result->fields['status_id'] == $core_config['user']['status']['active']) {
			// we change the status
			$rec = array();
			$rec['status_id'] = $core_config['user']['status']['dormant'];
		
			$table = $db->prefix . "_user";
		
			$query = $db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
			$result = $db->Execute($query);
			
			$user->logoffUser();
			header("Location: index.php?amn=core_login&dormant=1");
			exit;
		}
	}

}
elseif (isset($_POST['update_account'])) {
	if  (count($core_config['language']['pack']) == 1) {
		$_POST['language_ids'] = array($core_config['language']['default_id']);
		$_POST['language_id'] = $core_config['language']['default_id'];
	}
	
	// we update the user account details
	if (empty($_POST['language_ids'])) {
		$GLOBALS['am_error_log'][] = array('lang_error');
	}

	if(empty($_POST['user_homepage'])) {
		$GLOBALS['am_error_log'][] = array('start_page');
	}

	if (empty($GLOBALS['am_error_log'])) {
		require_once('class/UserAdmin.class.php');
		$user = new UserAdmin($db, $core_config['user']);
		$user->user_id = $_SESSION['user_id'];
		$user->updateUserAccount($_POST);
		
		header("Location: index.php?amn=core_me_view");
		exit;
	}
}
elseif (isset($_POST['update_user_preferences'])) {
	$user->deletetUserPreference(null, $_SESSION['user_id']);
	
	if (isset($_POST['user_preferences'])) {
		foreach ($_POST['user_preferences'] as $key => $i):
			$user->insertUserPreference($key, $_SESSION['user_id'], $i);
		endforeach;
	}
}
elseif (isset($_POST['update_password'])) {
	// Check the password
	if(!empty($_POST['user_password1']) || !empty($_POST['user_password2'])) {

		if(empty($_POST['user_password1']) != empty($_POST['user_password2'])) {
			$GLOBALS['am_error_log'][] = array('password_mismatch');
		}

		if(strlen($_POST['user_password1']) < 5) {
			$GLOBALS['am_error_log'][] = array('password_size');
		}
	}
	
	if (empty($GLOBALS['am_error_log'])) {
		require_once('class/UserAdmin.class.php');
		$user = new UserAdmin($db, $core_config['user']);
		$user->user_id = $_SESSION['user_id'];
		$user->updateUserPassword($_POST);
		
		header("Location: index.php?logoff=1");
		exit;
	}
}
elseif (isset($_POST['update_email'])) {
	if(empty($_POST['user_email1']) || empty($_POST['user_email2'])) {
		$GLOBALS['am_error_log'][] = array('no_email');
	}
	
	if($_POST['user_email1'] != $_POST['user_email2']) {
		$GLOBALS['am_error_log'][] = array('email_mismatch');
	}
	
	if(!preg_match('/^[-A-Za-z0-9_.]+[@][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)*[.][A-Za-z]{2,8}$/', $_POST['user_email1'])) {
		$GLOBALS['am_error_log'][] = array('email_invalid');
	}

	if (empty($GLOBALS['am_error_log'])) {
		$query = "
			SELECT * 
			FROM " . $db->prefix . "_user
			WHERE user_id=" . $_SESSION['user_id']
		;

		$usr_result = $db->Execute($query);
		
		if(isset($usr_result->fields['user_email']) && isset($_POST['user_email1']) && ($_POST['user_email1'] != $usr_result->fields['user_email'])) {
			//check that the email is not already used
			$query = "
				SELECT user_id, user_email_new 
				FROM " . $db->prefix . "_user
				WHERE user_email=" . $db->qstr($_POST['user_email1'], get_magic_quotes_gpc())
			;

			$result = $db->Execute($query);

			if (isset($result) && empty($result->fields)) {
				// reset the password and set the status
				$rec = array();
				$rec['user_email_new'] = $_POST['user_email1'];
		
				$table = $db->prefix . "_user";
		
				$query = $db->GetUpdateSQL($usr_result, $rec, false, get_magic_quotes_gpc());

				$result = $db->Execute($query);
				
				// send an email with the new login details and a temporary access code
				require_once('class/Mail/class.phpmailer.php');
				$mail = new PHPMailer($core_config['mail']);
				$mail->AddReplyTo($core_config['mail']['no_reply_address'], $lang['subject_noreply']);
				$mail->Subject = $lang['subject_email_reset'];
				
				$body_email_reset_txt = readTxtFile($language_path . "texts/email_reset.txt.php");				
				
				$body_email_reset_txt = str_replace("SYS_KEYWORD_NAME", $usr_result->fields['user_firstname'], $body_email_reset_txt);
				$body_email_reset_txt = str_replace("SYS_KEYWORD_EMAIL", $usr_result->fields['user_email'], $body_email_reset_txt);
				$body_email_reset_txt = str_replace("SYS_KEYWORD_NEW_EMAIL", $_POST['user_email1'], $body_email_reset_txt);
				
				$temp_access_code = md5($usr_result->fields['user_password']);
				$temp_access_code = substr($temp_access_code, 0, 6);
				
				//create URL
				$url = "http://" . $_SERVER['HTTP_HOST'];
				$url .= dirname ($_SERVER['PHP_SELF']);
				//sometimes the server adds / as the last characture - we need to check.
				if (substr($url, -1, 1) != "/") {
				    $url .= "/";
				}
		
				$url .= "login.php?ac=" . $temp_access_code . "&language_id=" . $usr_result->fields['language_id'] . "&nem=" . $_POST['user_email1'];

				$body_email_reset_txt = str_replace("SYS_KEYWORD_URL", $url, $body_email_reset_txt);
				
				// HTML-version of the mail
				$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
				$html .= "<BODY>";
				$html .= utf8_decode($body_email_reset_txt);
				$html .= "</BODY></HTML>";
				
				$alt_body = strip_tags($body_email_reset_txt);
				
				// Clear all addresses for next loop
				$mail->ClearAddresses();
				
				//send email
				$mail->Body = nl2br($html);
				$mail->AltBody   = utf8_decode($alt_body);
				$mail->AddAddress($_POST['user_email1'], $usr_result->fields['user_firstname']);
		
				if(!$mail->Send()) {
					$error_info = "me_view.php - Mailer Error: " . $mail->ErrorInfo;
					$GLOBALS['am_error_log'][] = array('db_error', $error_info);
				}
				else {
					$user->logoffUser();
					header("Location: login.php?change_email=1");
					exit;
				}
			}
			// email in use
			$GLOBALS['am_error_log'][] = array('email_change_in_use', $error_info);
		}
	}
}


// SELECT TEMPLATES ------------------------------------------------------
$query = "
	SELECT t.template_id, t.template_title
	FROM " . $db->prefix . "_template t
	order by t.template_title"
;

$result = $db->Execute($query);

if (isset($result->fields)) {

	$output_templates = array();

	while (!$result->EOF) {
		array_push($output_templates, $result->fields);
		$result->MoveNext();
	}

	$result->Close();
	$body->set('templates', $output_templates);
}



// SELECT USER ----------------------------------------------------------
$user->user_id = $_SESSION['user_id'];
$output_user = $user->selUser();
$output_user['template'] = $user->selTemplate($output_user['template_id']);
$output_user['language_ids'] = $user->selLanguages();
$output_user['preferences'] = $user->selUserPreferences();

$body->set('user', $output_user);


// get locations
$output_locations = $user->selLocations($output_user['language_id']);
$body->set('locations', $output_locations);

$body->set('datedropdown', $date->dateDropdown($output_user['user_dob']));


?>