<?php
/*
+--------------------------------------------------------------------------
|   TanyaCMS - Question and Answer Sofware
|   -----------------------------------------------------------------------
|   by fbschool dev team
|   (c) 2011 - 2012 FBSCHOOL
|   http://www.fbschool.com/tanyacms
|   -----------------------------------------------------------------------
|   This is NOT a freeware, use is subject to license terms
|   Support: 13455n@gmail.com
+--------------------------------------------------------------------------
*/

define('IN_AJAX', TRUE);


if (!defined('IN_TANYACMS'))
{
	die;
}

class ajax extends ASK_CONTROLLER
{
	public function get_access_rule()
	{
		$rule_action['rule_type'] = 'white'; //Blacklist, blacklist check  'white' white list, outside the whitelist check
		
		$rule_action['actions'] = array(
			'check_username',
			'check_email',
			'register_process',
			'login_process',
			'register_agreement',
			'send_valid_mail',
			'valid_email_active',
			'request_find_password',
			'find_password_modify'
		);
		
		return $rule_action;
	}
	
	function setup()
	{
		HTTP::no_cache_header();
	}
	
	function check_username_action()
	{
		if ($this->model('account')->check_username_char($_GET['username']))
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, 'Incorrect Username'));
		}
		
		if ($this->model('account')->check_username_sensitive_words($_GET['username']) || $this->model('account')->check_username($_GET['username']))
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, 'This username has been registered'));
		}
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'Username can be used'));
	}
	
	function check_email_action()
	{
		if (!$_GET['email'])
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, 'Mail can not be empty'));
		}
		
		if ($this->model('account')->check_email($_GET['email']))
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, 'E-mail has been used'));
		}
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'E-mail can be used'));
	}
	
	function register_process_action()
	{
		if ($_POST['invite_question_id'])
		{
			$objetc_id = $_POST['invite_question_id'];
		}
		
		if (HTTP::get_cookie('fromuid'))
		{
			$fromuid = HTTP::get_cookie('fromuid');
		}
		
		$icode = trim($_POST['icode']);
		
		if (get_setting('invite_reg_only') == 'Y' && !$icode)
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, "Registration is by invitation only"));
		}
		
		if ($icode)
		{
			$invitation = $this->model('invitation')->check_code_available($icode);
			
			if ($invitation && ($_POST['email'] == $invitation['invitation_email']))
			{
				$email_valid = true;
			}
			else
			{
				H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'icode'
				), -1, "Invitation code error"));
			}	
		}
		else if ($fromuid > 0)
		{
			if (HTTP::get_cookie('fromemail'))
			{
				$fromemail_hash = H::decode_hash(base64_decode(HTTP::get_cookie('fromemail')));
				
				if ($fromemail_hash['email'] == $_POST['email'])
				{
					$email_valid = true;
				}
			}
		}
		
		//Check the Username
		if (trim($_POST['user_name']) == '')
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'user_name'
			), -1, "Please enter username"));
		}
		else if ($this->model('account')->check_username($_POST['user_name']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'user_name'
			), -1, "Username is exist"));
		}
		else if ($check_rs = $this->model('account')->check_username_char($_POST['user_name']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'user_name'
			), -1, 'UsernameEntry error'));
		}
		else if ($this->model('account')->check_username_sensitive_words($_POST['user_name']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'user_name'
			), -1, "The username has sensitive or forbidden words"));
		}
		
		if ($this->model('account')->check_email($_POST['email']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'email'
			), -1, "E-Mail has been used, or incorrect format"));
		}
		
		if (strlen($_POST['password']) < 6 OR strlen($_POST['password']) > 16)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'userPassword'
			), -1, "Please enter the correct length of password"));
		}
		
		if (! $_POST['agreement_chk'])
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, "Please select the user agreement to the terms agreed"));
		}
		
		// Check verification code
		if (!($_POST['fromuid'] || $_POST['icode']) && (!core_captcha::validate($_POST['seccode_verify'], false)) && (get_setting('register_seccode') == 'Y'))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'seccode_verify'
			), -1, 'Check verification code'));
		}
		
		core_captcha::clear();

		if ($fromuid > 0)
		{
			// The user does not have an invitation code source
			$follow_users = $this->model('account')->get_user_info_by_uid($fromuid);
		}
		else
		{
			$follow_users = $this->model('invitation')->get_invitation_by_code($icode);
		}
		
		if ($follow_users)
		{
			$follow_uid = $follow_users['uid'];
		}
		
		if (get_setting('sso_enabled') == 'Y')
		{
			$result = $this->model('sso')->register($_POST['user_name'], $_POST['password'], $_POST['email'], $email_valid);
			
			if (is_array($result))
			{				
				$uid = $result['user_info']['uid'];
			}
			else
			{
				H::ajax_json_output(ASK_APP::RSM(null, -1, $result));
			}
		}
		else
		{
			$uid = $this->model('account')->user_register($_POST['user_name'], $_POST['password'], $_POST['email'], $email_valid);
		}
		
		if ($uid)
		{
			$this->model("account")->setcookie_logout(); // Clear COOKIE
			$this->model("account")->setsession_logout(); // Clean up session;
			
			// Send invitation letter Q Station
			if ($objetc_id and $follow_users)
			{
				$url = get_js_url('/question/' . $_POST['invite_question_id']);
					
				$title = $follow_users['user_name'] . ' Invite you to reply to questions';
				$content = $follow_users['user_name'] . "  Invite you to reply to questions: " . $url . " \r\n\r\n Invite you to look forward to your reply back problems";
				
				$this->model('message')->send_message($follow_uid, $uid, $title, $content, 0, 0);
			}
			
			// Mutual concern
			if ($follow_uid)
			{
				$this->model('follow')->user_follow_add($uid, $follow_uid);
				$this->model('follow')->user_follow_add($follow_uid, $uid);
				
				$this->model('integral')->process($follow_uid, 'INVITE', get_setting('integral_system_config_invite'), 'Invite Register: ' . $_POST['user_name'], $follow_uid);
			}

			if ($email_valid || (get_setting('register_email_reqire') == 'N'))	//E-mail has been validated or do not need to verify the mailbox into the site
			{
				$user_info = $this->model('account')->get_user_info_by_uid($uid);
				
				$this->model('account')->setcookie_login($user_info['uid'], $user_info['user_name'], $_POST['password'], $user_info['salt']);
						
				if ($icode)
				{
					$this->model('invitation')->invitation_code_active($icode, time(), fetch_ip(), $uid);
				}

				H::ajax_json_output(ASK_APP::RSM(array(
					'url' => get_js_url('/home/first_login-TRUE')
				), 1, null)); // Return data
			}
			else
			{
				$_SESSION['valid_email'] = $_POST['email'];
				
				$this->model('active')->new_valid_email($uid);
								
				H::ajax_json_output(ASK_APP::RSM(array(
					'url' => get_js_url('/account/valid_email/')
				), 1, null));
			}
		}
		else
		{
			H::ajax_json_output(ASK_APP::RSM(null, -1, 'User registration failed, please contact your administrator')); //Return data			
		}
	}
	
	function login_process_action()
	{
		$user_name = trim($_POST['user_name']);
		$password = $_POST['password'];
		
		if ($_GET['tips_id'])
		{
			$tips_id = $_GET['tips_id'];
		}
		
		if (get_setting('sso_enabled') == 'Y')
		{
			if (!$user_info = $this->model('sso')->login($user_name, $password))
			{
				$user_info = $this->model('account')->check_login($user_name, $password);
			}
		}
		else
		{
			$user_info = $this->model('account')->check_login($user_name, $password);
		}
		
		if (! $user_info)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'tips_id' => $tips_id
			), -1, 'Check your account or password'));
		}
		else
		{			
			if ($user_info['forbidden'] == 1)
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'tips_id' => $tips_id
				), -1, 'sorry, your account has been suspended'));
			}
			
			if (get_setting('site_close') == 'Y' && $user_info['group_id'] != 1)
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'tips_id' => $tips_id,
				), -1, get_setting('close_notice')));
			}
			
			//  !NOTE: Antecedents can not recapture error prompt detection behind
			if (!valid_post_hash($_POST['post_hash']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'tips_id' => $tips_id,
				), -1, 'Incorrect form antecedents, Please try refreshing the page'));
			}

			if (!$user_info['valid_email'] && (get_setting('register_email_reqire') == 'Y'))
			{
				$_SESSION['valid_email'] = $user_info['email'];
				
				H::ajax_json_output(ASK_APP::RSM(array(
					'url' => get_js_url('/account/valid_email/')
				), 1, null));
			}
			
			if ($_POST['net_auto_login'])
			{
				$expire = 60 * 60 * 24 * 360;
			}

			$this->model('account')->update_user_last_login($user_info['uid']);
			$this->model('account')->setcookie_logout();
			
			// Default Remember Username
			HTTP::set_cookie('r_uname', $user_name, time() + 60 * 60 * 24 * 30);
			
			$this->model('account')->setcookie_login($user_info['uid'], $user_name, $password, $user_info['salt'], $expire);
			
			if ($user_info['is_first_login'] AND !$_GET['is_mobile'])
			{
				$url = get_js_url('/home/first_login-TRUE');
			}
			
			if ($_POST['return_url'] AND !strstr($_POST['return_url'], '/logout'))
			{
				$url = strip_tags($_POST['return_url']);
				
				if ($_GET['is_mobile'] AND !strstr($_POST['return_url'], '/mobile'))
				{
					unset($url);
				}
				else if (strstr($_POST['return_url'], '://') AND !strstr($_POST['return_url'], get_setting('base_url')))
				{
					unset($url);
				}
			}
			
			if (!$url AND $_GET['is_mobile'])
			{
				$url = get_js_url('/mobile/');
			}
			
			if (get_setting('sso_enabled') == 'Y')
			{
				$url = get_js_url('/account/sync_login/url-' . @base64_encode($url));
			}
			
			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => $url
			), 1, null));
		}
	}
	
	public function register_agreement_action()
	{
		H::ajax_json_output(ASK_APP::RSM(null, 1, '<div style="width: 790px; height: 320px; overflow:auto;">' . nl2br(get_setting('register_agreement')) . '</div>'));
	}
	

	function welcome_message_template_action()
	{
		TPL::assign('job_list', $this->model('work')->get_jobs_list());
		
		TPL::output('account/ajax/welcome_message_template');
	}
	
	function welcome_get_topics_action()
	{
		if ($topics_list = $this->model('topic')->get_topic_list(null, 8, false, 'rand()'))
		{
			foreach ($topics_list as $key => $topic)
			{
				$topics_list[$key]['has_focus'] = $this->model('topic')->has_focus_topic($this->user_id, $topic['topic_id']);
			}
		}
		TPL::assign('topics_list', $topics_list);
		
		TPL::output('account/ajax/welcome_get_topics');
	}

	function welcome_get_users_action()
	{
		if ($welcome_recommend_users = trim(rtrim(get_setting('welcome_recommend_users'), ',')))
		{
			$welcome_recommend_users = explode(',', $welcome_recommend_users);
			
			$users_list = $this->model('account')->fetch_all('users', "user_name IN('" . implode("','", $welcome_recommend_users) . "')", 'RAND()', 6);
		}
		
		if(!$users_list)
		{
			$users_list = $this->model('account')->get_activity_random_users(6);
		}
		
		if ($users_list)
		{
			foreach ($users_list as $key => $val)
			{
				$users_list[$key]['follow_check'] = $this->model('follow')->user_follow_check($this->user_id, $val['uid']);
			}
		}
		
		TPL::assign('users_list', $users_list);
		
		TPL::output('account/ajax/welcome_get_users');
	}

	function clean_first_login_action()
	{
		$this->model('account')->clean_first_login($this->user_id);
		
		die('success');
	}
	
	public function delete_draft_action()
	{
		if (!$_POST['item_id'] OR !$_POST['type'])
		{
			die;
		}
		
		$this->model('draft')->delete_draft($_POST['item_id'], $_POST['type'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'Draft deleted successfully'));
	}
	
	public function save_draft_action()
	{
		if (!$_GET['item_id'] OR !$_GET['type'] OR !$_POST)
		{
			die;
		}
		
		$this->model('draft')->save_draft($_GET['item_id'], $_GET['type'], $this->user_id, $_POST);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'Saved drafts,' . date('Y-m-d H:i:s', time())));
	}
	
	function send_valid_mail_action()
	{
		if (!$this->user_id)
		{
			if ( H::valid_email($_SESSION['valid_email']))
			{
				$this->user_info = $this->model('account')->get_user_info_by_email($_SESSION['valid_email']);
				$this->user_id = $this->user_info['uid'];
			}
		}
		
		if (! H::valid_email($this->user_info['email']))
		{
			H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Not set E-mail'));
		}
		
		if ($this->user_info['valid_email'] == 1)
		{
			H::ajax_json_output(ASK_APP::RSM(null, '-1', "E-mail has been certified"));
		}
		
		if ($this->model('active')->new_valid_email($this->user_id))
		{
			H::ajax_json_output(ASK_APP::RSM(null, 1, 'The Email has been sent'));
		}
	}
	
	function valid_email_active_action()
	{
		if (!$active_data = $this->model('active')->get_active_code_row($_POST['active_code'], 21))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => get_js_url('/'),
			), 1, 'Activation failed, Link Invalid'));
		}
		
		if ($active_data['active_time'] || $active_data['active_ip'] || $active_data['active_expire'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => get_js_url('/account/login/'),
			), 1, 'The account has been activated, please return to login'));
		}

		if (!$user_info = $this->model('account')->get_user_info_by_uid($active_data['uid']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
			), -1, 'Activation failed, Link is invalid'));
		}
		
		if ($user_info['valid_email'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => get_js_url('/account/login/'),
			), 1, 'The account as been verified, please return to login'));
		}
		
		if ($user_id = $this->model('active')->active_code_active($_POST['active_code'], 21))
		{
			if ($_SESSION['valid_email'])
			{
				unset($_SESSION['valid_email']);
			}
			
			$this->model('account')->update_users_fields(array(
				'valid_email' => 1,
			), $active_data['uid']);
			
			if ($user_info['group_id'] == 3)
			{
				$this->model('account')->update_users_fields(array(
					'group_id' => 4,
				), $active_data['uid']);
			}
			
			//Account Active successful, the state switched to login to jump to Home
			$this->model('account')->setsession_logout();
			$this->model('account')->setcookie_logout();
			
			$this->model('account')->update_user_last_login($user_info['uid']);
				
			HTTP::set_cookie('r_uname', $user_info['email'], time() + 60 * 60 * 24 * 30);
				
			$this->model('account')->setcookie_login($user_info['uid'], $user_info['user_name'], $user_info['password'], $user_info['salt'], null, false);
			
			$this->model('account')->welcome_message($user_info['uid'], $user_info['user_name'], $user_info['email']);
			
			$url = $user_info['is_first_login'] ? '/first_login-TRUE' : '/';
			
			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => get_js_url($url)
			), 1, null));
		}
	}
	
	function request_find_password_action()
	{
		if (!H::valid_email($_POST['email']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "email"
			), "-1", "Error email address"));
		}		

		if (!$user_info = $this->model('account')->get_user_info_by_email($_POST['email']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "email"
			), "-1", "Email/account does not exist."));
		}
		
		if (!core_captcha::validate($_POST['seccode_verify'], false))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "seccode_verify"
			), "-1", "Check verification code"));
		}
		
		core_captcha::clear();
		
		$this->model('active')->new_find_password($user_info['uid']);
		
		$_SESSION['find_password'] = $_POST['email'];
		
		H::ajax_json_output(ASK_APP::RSM(array(
			'url' => get_js_url('/account/find_password/process_success/')
		), 1, null));
	}
	
	function find_password_modify_action()
	{
		if (!core_captcha::validate($_POST['seccode_verify'], false))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "seccode_verify"
			), "-1", "Check verification code"));
		}
		
		core_captcha::clear();
		
		$active_data = $this->model('active')->get_active_code_row($_POST['active_code'], 11);
		
		if ($active_data)
		{
			if ($active_data['active_time'] || $active_data['active_ip'] || $active_data['active_expire'])
			{
				H::ajax_json_output(ASK_APP::RSM(null, 1, "Invalid URL, get back your password"));
			}
		}
		else
		{
			H::ajax_json_output(ASK_APP::RSM(null, 1, "Invalid URL, get back your password"));
		}
		
		if (empty($_POST['password']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "password"
			), "-1", "Password can not be blank"));
		}

		//Check verification code
		if ($_POST['password'] != $_POST['re_password'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => "password"
			), "-1", "Passwords do not match"));
		}
		
		if (! $uid = $this->model('active')->active_code_active($_POST['active_code'], 11))
		{
			H::ajax_json_output(ASK_APP::RSM(null, "-1", "Find your password Key has failed")); //Return data
		}
		
		$user_info = $this->model('account')->get_user_info_by_uid($uid);
		
		if ($this->model('account')->update_user_password_ingore_oldpassword($_POST['password'], $uid, $user_info['salt']))
		{
			//If the account is not activated, then activate your account
			$this->model('account')->update_users_fields(array(
				'valid_email' => 1
			), $uid);
			
			if ($user_info['group_id'] == 3)
			{
				$this->model('account')->update_users_fields(array(
					'group_id' => 4,
				), $active_data['uid']);
			}
			
			$this->model("account")->setcookie_logout(); //Clear COOKIE
			
			$this->model("account")->setsession_logout(); //Clean up session;
			
			$_SESSION['error'] = 0; //Reset the login error count
			
			unset($_SESSION['find_password']);

			H::ajax_json_output(ASK_APP::RSM(array(
				'url' => get_js_url('/account/login/'),
			), 1, "Password has been changed, please return to login"));
		}
		else
		{
			H::ajax_json_output(ASK_APP::RSM(null, "-1", "Modification fails, please contact your administrator"));
		}
	}
	
	function avatar_upload_action()
	{
		ASK_APP::upload()->initialize(array(
			'allowed_types' => 'jpg,jpeg,png,gif',
			'upload_path' => get_setting('upload_dir') . '/avatar/' . $this->model('account')->get_avatar($this->user_id, '', 1),
			'is_image' => TRUE,
			'max_size' => (get_setting('upload_avatar_size_limit') * 1024),
			'file_name' => $this->model('account')->get_avatar($this->user_id, '', 2),
			'encrypt_name' => FALSE
		))->do_upload('user_avatar');
		
		if (ASK_APP::upload()->get_error())
		{
			switch (ASK_APP::upload()->get_error())
			{
				default:
					H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Invalid code: ' . ASK_APP::upload()->get_error()));
				break;
				
				case 'upload_invalid_filetype':
					H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Invalid file format'));
				break;	
				
				case 'upload_invalid_filesize':
					H::ajax_json_output(ASK_APP::RSM(null, '-1', 'File too large, the maximum file size is ' . get_setting('upload_size_limit') .  ' KB'));
				break;
			}
		}
		
		if (! $upload_data = ASK_APP::upload()->data())
		{
			H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Failed to upload, please contact the administrator'));
		}
		
		if ($upload_data['is_image'] == 1)
		{
			foreach(ASK_APP::config()->get('image')->avatar_thumbnail AS $key => $val)
			{			
				$thumb_file[$key] = $upload_data['file_path'] . $this->model('account')->get_avatar($this->user_id, $key, 2);
				
				ASK_APP::image()->initialize(array(
					'quality' => 90,
					'source_image' => $upload_data['full_path'],
					'new_image' => $thumb_file[$key],
					'width' => $val['w'],
					'height' => $val['h']
				))->resize();	
			}
		}
		
		$update_data['avatar_file'] = $this->model('account')->get_avatar($this->user_id, null, 1) . basename($thumb_file['min']);
		
		//Update the main table
		$this->model('account')->update_users_fields($update_data, $this->user_id);
		
		if (!$this->model('integral')->fetch_log($this->user_id, 'UPLOAD_AVATAR'))
		{
			$this->model('integral')->process($this->user_id, 'UPLOAD_AVATAR', round((get_setting('integral_system_config_profile') * 0.2)), 'Upload');
		}
		
		H::ajax_json_output(ASK_APP::RSM( array(
			'preview' => get_setting('upload_url') . '/avatar/' . $this->model('account')->get_avatar($this->user_id, null, 1) . basename($thumb_file['max'])
		), 1, null));
	}
	
	function add_edu_action()
	{
		$school_name = htmlspecialchars(trim($_POST['school_name']));
		$education_years = intval($_POST['education_years']);
		$departments = htmlspecialchars($_POST['departments']);
		
		if (empty($_POST['school_name']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'school_name'
			), '-1', "Please enter school name"));
		}
		
		if (empty($_POST['departments']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'departments'
			), '-1', "Please enter department"));
		}
		
		if ($_POST['education_years'] == "Select" OR !$_POST['education_years'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'education_years'
			), '-1', "Please select admission year"));
		}
		
		$edu_id = $this->model('education')->add_education_experience($this->user_id, $school_name, $education_years, $departments);
		
		if (!$this->model('integral')->fetch_log($this->user_id, 'UPDATE_EDU'))
		{
			$this->model('integral')->process($this->user_id, 'UPDATE_EDU', round((get_setting('integral_system_config_profile') * 0.2)), 'Complete Education Background');
		}	
			
		H::ajax_json_output(ASK_APP::RSM(array(
			'id' => $edu_id
		), 1, null));
	
	}
	
	function remove_edu_action()
	{
		$this->model('education')->del_education_experience($_POST['id'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, null));
	
	}
	
	function add_work_action()
	{
		$job_id = intval($_POST['job_id']);
		$company_name = htmlspecialchars($_POST['company_name']);
		
		$start_year = intval($_POST['start_year']);
		$end_year = intval($_POST['end_year']);
		
		if (!$company_name)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'company_name'
			), '-1', "Please enter a company name"));
		}
		
		if (!$job_id)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'job_id'
			), '-1', "Please select a position"));
		}
		
		if (!$start_year OR !$end_year )
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'start_year'
			), '-1', "Please select a work period"));
		}
		
		$work_id = $this->model('work')->add_work_experience($this->user_id, $start_year, $end_year, $company_name, $job_id);
		
		if (!$this->model('integral')->fetch_log($this->user_id, 'UPDATE_WORK'))
		{
			$this->model('integral')->process($this->user_id, 'UPDATE_WORK', round((get_setting('integral_system_config_profile') * 0.2)), 'Please complete work experience');
		}	
			
		H::ajax_json_output(ASK_APP::RSM(array(
			'id' => $work_id
		), 1, null));
	}
	
	function remove_work_action()
	{
		$this->model('work')->del_work_experience($_POST['id'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, null));
	}
	
	//Modify Education 
	function edit_edu_action()
	{
		if (empty($_POST['school_name']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'school_name'
			), '-1', "Please enter school name"));
		}
		
		if (empty($_POST['departments']))
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'departments'
			), '-1', "Please enter department"));
		}
		
		if (!$_POST['education_years'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'education_years'
			), '-1', "Please select admission year"));
		}
		
		$update_data['school_name'] = htmlspecialchars($_POST['school_name']);
		$update_data['education_years'] = intval($_POST['education_years']);
		$update_data['departments'] = htmlspecialchars($_POST['departments']);		
		
		$this->model('education')->update_education_experience($update_data, $_GET['id'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, null));
	}
	
	//Modify Work Experience 
	function edit_work_action()
	{
		if (!$_POST['company_name'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'company_name'
			), '-1', "Please enter a company name"));
		}
		
		if (!$_POST['job_id'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'job_id'
			), '-1', "Please select a position"));
		}
		
		if (!$_POST['start_year'] OR !$_POST['end_year'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'start_year'
			), '-1', "Please select a work period"));
		}

		$update_data['job_id'] = intval($_POST['job_id']);
		$update_data['company_name'] = htmlspecialchars($_POST['company_name']);
		
		$update_data['start_year'] = intval($_POST['start_year']);
		$update_data['end_year'] =  intval($_POST['end_year']);
		
		$this->model('work')->update_work_experience($update_data, $_GET['id'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, null));
	}
	
	function privacy_setting_action()
	{
		$update_data['inbox_recv'] = intval($_POST['inbox_recv']);
		
		//Update the main table
		$this->model('account')->update_users_fields($update_data, $this->user_id);
		
		$update_dataay['sender_11'] = intval($_POST['sender_11']);
		$update_dataay['sender_12'] = intval($_POST['sender_12']);
		$update_dataay['sender_13'] = intval($_POST['sender_13']);
		$update_dataay['sender_14'] = intval($_POST['sender_14']);
		$update_dataay['sender_15'] = intval($_POST['sender_15']);
		
		if ($notify_actions = $this->model('notify')->notify_action_details)
		{
			foreach ($notify_actions as $key => $val)
			{
				if (! isset($_POST['notification_setting'][$key]) && $val['user_setting'])
				{
					$nt_data[] = $key;
				}
			}
		}
		$update_nt_array = array(
			'data' => serialize($nt_data)
		);
		
		$this->model('account')->update_notification_setting_fields($update_nt_array, $this->user_id);
		$this->model('account')->update_email_setting_fields($update_dataay, $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'Settings saved'));
	}
	
	function profile_setting_action()
	{
		if (!$this->user_info['user_name'] OR $this->user_info['user_name'] == $this->user_info['email'])
		{
			$update_data['user_name'] = htmlspecialchars(trim($_POST['user_name']));
			
			if ($check_result = $this->model('account')->check_username_char($_POST['user_name']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'user_name'
				), '-1', $check_result));
			}
		}
		
		if ($_POST['url_token'] AND $_POST['url_token'] != $this->user_info['url_token'])
		{
			if ($this->user_info['url_token_update'] AND $this->user_info['url_token_update'] > (time() - 3600 * 24 * 30))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'url_token'
				), '-1', 'It has been less than 30 days since the last change of the web address'));
			}
			
			if (!preg_match("/^(?!__)[a-zA-Z0-9_]+$/i", $_POST['url_token']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'url_token'
				), '-1', 'Please enter only alphabets or numbers'));
			}
			
			if ($this->model('account')->check_url_token($_POST['url_token'], $this->user_id))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'url_token'
				), '-1', 'The address already exist, please use another one'));
			}
			
			if (preg_match("/^[\d]+$/i", $_POST['url_token']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'url_token'
				), '-1', 'The address cannot be only numbers'));
			}
			
			$this->model('account')->update_url_token($_POST['url_token'], $this->user_id);
		}
		
		if ($update_data['user_name'] and $this->model('account')->check_username($update_data['user_name']) and $this->user_info['user_name'] != $update_data['user_name'])
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'user_name'
			), '-1', 'Same name already exist, please use another name'));
		}
		
		if (! H::valid_email($this->user_info['email']))
		{
			if (! H::valid_email($_POST['email']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'email'
				), '-1', 'Please enter the correct E-mail address'));
			}
			
			if ($this->model('account')->check_email($_POST['email']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'email'
				), '-1', 'The Email already exist, please use another Email'));
			}
			
			$update_data['email'] = $_POST['email'];
		
			$this->model('active')->new_valid_email($this->user_id, $_POST['email']);
		}
		
		if($_POST['common_email'])
		{
			if (! H::valid_email($_POST['common_email']))
			{
				H::ajax_json_output(ASK_APP::RSM(array(
					'input' => 'common_email'
				), '-1', 'Please enter a correct Email address'));
			}
			
			$update_data['common_email'] = $_POST['common_email'];
		}
		
		$update_data['sex'] = intval($_POST['sex']);
		
		$update_data['province'] = htmlspecialchars($_POST['province']);
		$update_data['city'] = htmlspecialchars($_POST['city']);
		$update_data['job_id'] = intval($_POST['job_id']);
		
		if ($_POST['birthday_y'])
		{
			$update_data['birthday'] = intval(strtotime(intval($_POST['birthday_y']) . '-' . intval($_POST['birthday_m']) . '-' . intval($_POST['birthday_d'])));
		}
		
		if (!$this->user_info['verified'])
		{
			$update_attrib_data['signature'] = htmlspecialchars($_POST['signature']);
		}
		
		if ($_POST['signature'] AND !$this->model('integral')->fetch_log($this->user_id, 'UPDATE_SIGNATURE'))
		{
			$this->model('integral')->process($this->user_id, 'UPDATE_SIGNATURE', round((get_setting('integral_system_config_profile') * 0.1)), 'Complete one sentence introduction');
		}
		
		$update_attrib_data['ym'] = htmlspecialchars($_POST['ym']);
		$update_attrib_data['homepage'] = htmlspecialchars($_POST['homepage']);		
		$update_data['mobile'] = htmlspecialchars($_POST['mobile']);
		
		if (($update_attrib_data['ym'] OR $update_attrib_data['homepage'] OR $update_data['mobile']) AND !$this->model('integral')->fetch_log($this->user_id, 'UPDATE_CONTACT'))
		{
			$this->model('integral')->process($this->user_id, 'UPDATE_CONTACT', round((get_setting('integral_system_config_profile') * 0.1)), 'Complete contact information');
		}

		//Update the main table
		$this->model('account')->update_users_fields($update_data, $this->user_id);
		
		//Updates from the table
		$this->model('account')->update_users_attrib_fields($update_attrib_data, $this->user_id);
		
		$this->model('account')->set_default_timezone($_POST['default_timezone'], $this->user_id);
		
		H::ajax_json_output(ASK_APP::RSM(null, 1, 'Personal information has been updated'));
	}
	
	function modify_password_action()
	{		
		$old_password = $_POST['old_password'];
		$password = $_POST['password'];
		$re_password = $_POST['re_password'];
		
		if (!$old_password)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'old_password'
			), '-1', 'Please enter current password'));
		}
		
		if ($password != $re_password)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'password'
			), '-1', 'Please enter the same password again'));
		}
		
		if (strlen($password) < 6 OR strlen($password) > 16)
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'password'
			), -1, "Please enter the correct length of password"));
		}
		
		if (get_setting('sso_enabled') == 'Y')
		{
			if ($this->model('sso')->is_uc_user($this->user_info['email']))
			{
				$result = $this->model('sso')->user_edit($this->user_id, $this->user_info['user_name'], $old_password, $password);
				
				if ($result !== 1)
				{
					H::ajax_json_output(ASK_APP::RSM(null, -1, $result));
				}
			}
		}
		
		if ($this->model('account')->update_user_password($old_password, $password, $this->user_id, $this->user_info['salt']))
		{
			H::ajax_json_output(ASK_APP::RSM(null, 1, 'Password has been changed, please remember the new one'));
		}
		else
		{
			H::ajax_json_output(ASK_APP::RSM(array(
				'input' => 'old_password'
			), '-1', 'Please enter a correct current password'));
		}
	}
	
	public function areas_json_data_action()
	{
		echo file_get_contents(ROOT_PATH . 'static/js/areas.js');
	}
	
	public function integral_log_action()
	{
		$log = $this->model('integral')->fetch_all('integral_log', 'uid = ' . intval($this->user_id), 'time DESC', (intval($_GET['page']) * 50) . ', 50');
		
		foreach ($log AS $key => $val)
		{
			$parse_items[$val['id']] = array(
				'item_id' => $val['item_id'],
				'action' => $val['action']
			);
		}
		
		TPL::assign('log', $log);
		TPL::assign('log_detail', $this->model('integral')->parse_log_item($parse_items));
		
		TPL::output('account/ajax/integral_log');
	}
}
