<?php
/**
 * Edit Users settings
 *
 * PHP version 5.0
 *
 * @category	###Agriya Answers###
 * @package		###edit settings###
 * @author 		senthil_52ag05
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:  $
 * @since 		2007-12-22
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/editMembers.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';
$CFG['mods']['include_files'][] = 'common/classes/class_Image.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_ftp.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_AnovaHandler.lib.php';
//partial optimization. Don't use DB unnecessarily ie, DB only needed when the form is submitted/posted.
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
//we shouldn't send any texts as we have to redirect/send headers.
if ($_POST)
	$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------- Class EditMembersHandler begins --------------->>>>>//
class EditMembersHandler extends AnovaHandler
	{
		/**
		  * To update the form values into users table
		  *
		  * @param 		string $table_name Table name
		  * @param 		integer $user_id User id
		  * @param 		array $fields_to_update_arr Array of fields to update
		  * @return 	void
		  * @access 	public
		  */
		public function updateFormFieldsInTable($table_name, $user_id, $fields_to_insert_arr=array())
			{
				$this->fields_arr['subscribe_keywords'] = $this->removeDuplicateKeywords($this->fields_arr['subscribe_keywords']);
				// field name, parameters and fields value are intialized
				$field_names_separated_by_comma = '';
				$parameters_separated_by_comma  = '';
				$field_values_arr = array();
				// field name, parameters and fields value are set
				foreach($fields_to_insert_arr as $field_name)
					if (isset($this->fields_arr[$field_name]))
						{
							$field_names_separated_by_comma .= $field_name.'='.$this->dbObj->Param($field_name).', ';
							$field_values_arr[] = $this->fields_arr[$field_name];
						}
				// eleminates last comma
				$field_names_separated_by_comma = substr($field_names_separated_by_comma, 0, strrpos($field_names_separated_by_comma, ','));

				$sql = 'UPDATE '.$table_name.' SET '.
						$field_names_separated_by_comma;
				$sql .= ' WHERE user_id ='.$this->dbObj->Param($user_id);
				$field_values_arr[] = $user_id;

				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, $field_values_arr);
				if (!$result)
					trigger_db_error($this->dbObj);
			}

		/**
		  * To update the form values into users table
		  *
		  * @param 		string $table_name Table name
		  * @param 		integer $user_id User id
		  * @param 		array $fields_to_update_arr Array of fields to update
		  * @return 	void
		  * @access 	public
		  */
		public function updateFormFieldsInUserTable($table_name, $user_id, $fields_to_insert_arr=array())
			{
				$this->fields_arr['subscribe_keywords'] = $this->removeDuplicateKeywords($this->fields_arr['subscribe_keywords']);
				// field name, parameters and fields value are intialized
				$field_names_separated_by_comma = '';
				$parameters_separated_by_comma  = '';
				$field_values_arr = array();
				// field name, parameters and fields value are set
				foreach($fields_to_insert_arr as $field_name)
					if (isset($this->fields_arr[$field_name]))
						{
							$field_names_separated_by_comma .= $this->getUserTableField($field_name).'='.$this->dbObj->Param($field_name).', ';
							$field_values_arr[] = $this->fields_arr[$field_name];
						}
				// eleminates last comma
				$field_names_separated_by_comma = substr($field_names_separated_by_comma, 0, strrpos($field_names_separated_by_comma, ','));
				$sql = 'UPDATE '.$table_name.' SET '.
						$field_names_separated_by_comma;
				$sql .= ' WHERE user_id ='.$this->dbObj->Param($user_id);
				$field_values_arr[] = $user_id;
				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, $field_values_arr);
				if (!$result)
					trigger_db_error($this->dbObj);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateUserImagePath()
			{
				$image_path = $this->fields_arr['image_path'];
				$user_id = $this->fields_arr['uid'];

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users'].
						' SET '.$this->getUserTableField('image_path').'='.$this->dbObj->Param($image_path).
						' WHERE '.$this->getUserTableField('user_id').'='.$this->dbObj->Param($user_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($image_path, $user_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * To get the user details from the DB
		 *
		 * @param 		string $table_name table name
		 * @param 		array $fields_arr Array of fields
		 * @param 		integer $user_id user id
		 * @return 		array has array with field values
		 * @access 		public
		 */
		public function getUserDetailsArrFromDB($table_name, $fields_arr=array(), $user_id)
			{
				$sql = 'SELECT ';
				foreach($fields_arr as $field_name)
						$sql .= $field_name . ', ';
				$sql = substr($sql, 0, strrpos($sql, ','));
				$sql .= ' FROM '.$table_name.
						' WHERE user_id='.$this->dbObj->Param($user_id);

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id));
				if (!$rs)
					trigger_db_error($this->dbObj);

				$row = array();
				if ($rs->PO_RecordCount())
						$row = $rs->FetchRow();
				$ret_fields_arr = array();
				foreach($fields_arr as $field_name)
					$ret_fields_arr[$field_name] = isset($row[$field_name]) ? $row[$field_name] : '';
				return $ret_fields_arr;
			}

		/**
		 * PhotoUpload::setIHObject()
		 *
		 * @param $imObj
		 * @return
		 **/
		public function setIHObject($imObj)
			{
				$this->imageObj = $imObj;
			}

		/**
		 * chkValidFileType()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkValidFileType($field_name, $err_tip = '')
			{
				$this->EXTERN = strtolower($_FILES[$field_name]['type']);
				if (!in_array($this->EXTERN, $this->CFG['admin']['ans_photos']['format_arr']))
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * chkValideFileSize()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkValideFileSize($field_name, $err_tip='')
			{
				$max_size = $this->CFG['admin']['ans_photos']['max_size'] * 1024;
				if ($_FILES[$field_name]['size'] > $max_size)
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * chkErrorInFile()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkErrorInFile($field_name, $err_tip='')
			{
				if($_FILES[$field_name]['error'])
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * PhotoUpload::getServerDetails()
		 *
		 * @return
		 **/
		public function getServerDetailsForPhotos()
			{
				$sql = 'SELECT server_url, ftp_server, ftp_usrename, ftp_password'.
						' FROM '.$this->CFG['db']['tbl']['server_settings'].
						' WHERE server_for=\'Ans_photo\' AND server_status=\'Yes\' LIMIT 0,1';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					trigger_db_error($this->dbObj);

				$row = array();
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$this->fields_arr['ftp_server'] = $row['ftp_server'];
						$this->fields_arr['ftp_usrename'] = $row['ftp_usrename'];
						$this->fields_arr['ftp_password'] = $row['ftp_password'];
						$this->fields_arr['server_url'] = $row['server_url'];
						return true;
					}
				return false;
			}

		/**
		 * PhotoUpload::storeImagesTempServer()
		 *
		 * @param $uploadUrl
		 * @param $extern
		 * @return
		 **/
		public function storeImagesTempServer($uploadUrl, $extern)
			{
				//GET LARGE IMAGE
				if($this->CFG['admin']['ans_photos']['large_name']=='L')
					{
						if($this->CFG['admin']['ans_photos']['large_height'] or $this->CFG['admin']['ans_photos']['large_width'])
							{
								$this->imageObj->resize($this->CFG['admin']['ans_photos']['large_width'], $this->CFG['admin']['ans_photos']['large_height'], '-');
								$this->imageObj->output_resized($uploadUrl.'L.'.$extern, strtoupper($extern));
								$image_info = getImageSize($uploadUrl.'L.'.$extern);
								$this->L_WIDTH = $image_info[0];
								$this->L_HEIGHT = $image_info[1];
							}
						else
							{
								$this->imageObj->output_original($uploadUrl.'L.'.$extern, strtoupper($extern));
								$image_info = getImageSize($uploadUrl.'L.'.$extern);
								$this->L_WIDTH = $image_info[0];
								$this->L_HEIGHT = $image_info[1];
							}
					}
				//GET THUMB IMAGE
				if($this->CFG['admin']['ans_photos']['thumb_name']=='T')
					{
						$this->imageObj->resize($this->CFG['admin']['ans_photos']['thumb_width'], $this->CFG['admin']['ans_photos']['thumb_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'T.'.$extern, strtoupper($extern));
						$image_info = getImageSize($uploadUrl.'T.'.$extern);
						$this->T_WIDTH = $image_info[0];
						$this->T_HEIGHT = $image_info[1];
					}
				//GET SMALL IMAGE
				if($this->CFG['admin']['ans_photos']['small_name']=='S')
					{
						$this->imageObj->resize($this->CFG['admin']['ans_photos']['small_width'], $this->CFG['admin']['ans_photos']['small_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'S.'.$extern, strtoupper($extern));
						$image_info = getImageSize($uploadUrl.'S.'.$extern);
						$this->S_WIDTH = $image_info[0];
						$this->S_HEIGHT = $image_info[1];
					}

				$wname = $this->CFG['admin']['ans_photos']['large_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_photos']['large_name'].'_HEIGHT';
				$this->L_WIDTH = $this->$wname;
				$this->L_HEIGHT = $this->$hname;

				$wname = $this->CFG['admin']['ans_photos']['thumb_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_photos']['thumb_name'].'_HEIGHT';
				$this->T_WIDTH = $this->$wname;
				$this->T_HEIGHT = $this->$hname;

				$wname = $this->CFG['admin']['ans_photos']['small_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_photos']['small_name'].'_HEIGHT';
				$this->S_WIDTH = $this->$wname;
				$this->S_HEIGHT = $this->$hname;
			}

		/**
		 * EditPersonalProfileFormHandler::photoUpload()
		 *
		 * @return
		 **/
		public function photoUpload()
			{
				$extern = strtolower(substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'], '.')+1));

				$this->setFormField('user_id',$this->fields_arr['uid']);
				$this->setFormField('photo_ext',$extern);
				$image_name = getImageName($this->fields_arr['uid']);
				$imageObj = new ImageHandler($_FILES['photo']['tmp_name']);
				$this->setIHObject($imageObj);
				$temp_dir = '../'.$this->CFG['admin']['ans_photos']['temp_folder'];
				$this->chkAndCreateFolder($temp_dir);
				$temp_file = $temp_dir.$image_name;
				$this->storeImagesTempServer($temp_file, $extern);
				$dir = $this->CFG['admin']['ans_photos']['folder'];
				$local_upload = true;
				if($this->getServerDetailsForPhotos())
					{
						if($FtpObj = new FtpHandler($this->getFormField('ftp_server'),$this->getFormField('ftp_usrename'),$this->getFormField('ftp_password')))
							{
								$FtpObj->makeDirectory($dir);
								$FtpObj->changeDirectory($dir);
								$FtpObj->moveTo($temp_file.'.'.$extern, $dir.$image_name.'.'.$extern);
								unlink($temp_file.'.'.$extern);
								if($this->CFG['admin']['ans_photos']['large_name']=='L')
									{
										$FtpObj->moveTo($temp_file.'L.'.$extern, $dir.$image_name.'L.'.$extern);
										unlink($temp_file.'L.'.$extern);
									}
								if($this->CFG['admin']['ans_photos']['thumb_name']=='T')
									{
										$FtpObj->moveTo($temp_file.'T.'.$extern, $dir.$image_name.'T.'.$extern);
										unlink($temp_file.'T.'.$extern);
									}
								if($this->CFG['admin']['ans_photos']['small_name']=='S')
									{
										$FtpObj->moveTo($temp_file.'S.'.$extern, $dir.$image_name.'S.'.$extern);
										unlink($temp_file.'S.'.$extern);
									}
								$this->setFormField('server_url',$this->getFormField('server_url'));
								$local_upload = false;
								return;
							}
					}
				if($local_upload)
					{
						$dir = '../'.$this->CFG['admin']['ans_photos']['folder'];
						$this->chkAndCreateFolder($dir);
						$uploadUrl = $dir.$image_name;
						if($this->CFG['admin']['ans_photos']['large_name']=='L')
							{
								copy($temp_file.'L.'.$extern, $uploadUrl.'L.'.$extern);
								unlink($temp_file.'L.'.$extern);
							}
						if($this->CFG['admin']['ans_photos']['thumb_name']=='T')
							{
								copy($temp_file.'T.'.$extern, $uploadUrl.'T.'.$extern);
								unlink($temp_file.'T.'.$extern);
							}
						if($this->CFG['admin']['ans_photos']['small_name']=='S')
							{
								copy($temp_file.'S.'.$extern, $uploadUrl.'S.'.$extern);
								unlink($temp_file.'S.'.$extern);
							}
						$this->setFormField('server_url',$this->CFG['site']['url']);
					}
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users'].' SET'.
						' '.$this->CFG['users']['t_width'] .'=\''. $this->T_WIDTH.'\','.
						' '.$this->CFG['users']['t_height'] .'='. '\''.$this->T_HEIGHT.'\','.
						' '.$this->CFG['users']['l_width'] .'=\''. $this->L_WIDTH.'\','.
						' '.$this->CFG['users']['l_height'] .'='. '\''.$this->L_HEIGHT.'\','.
						' '.$this->CFG['users']['s_width'] .'='. '\''.$this->S_HEIGHT.'\','.
						' '.$this->CFG['users']['s_height'] .'='. '\''.$this->S_HEIGHT.'\','.
						' '.$this->CFG['users']['photo_ext'] .'='. '\''.$extern.'\','.
						' '.$this->CFG['users']['image_path'] .'=\'\','.
						' '.$this->CFG['users']['photo_server_url'] .'=\''. $this->fields_arr['server_url'].'\''.
						' WHERE '.$this->CFG['users']['user_id'] .'=\''. $this->fields_arr['uid'].'\'';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
			    if (!$rs)
				    trigger_db_error($this->dbObj);
			}

		/**
		 * EditMembersHandler::setIndexBlockFormField()
		 *
		 * @param mixed $index_block_arr
		 * @return
		 */
		public function setIndexBlockFormField($index_block_arr)
			{
				foreach($index_block_arr as $value)
					{
						$this->setFormField($value, $this->CFG['admin']['index'][$value]);
					}
			}

		/**
		 * EditMembersHandler::populateIndexBlockValues()
		 *
		 * @param mixed $index_block_value
		 * @return
		 */
		public function populateIndexBlockValues($index_block_value)
			{
				$index_block_value_arr = unserialize($index_block_value);
				if(!is_array($index_block_value_arr))
					return;

				foreach($index_block_value_arr as $key=>$value)
					{
						if (!isset($this->fields_arr[$key])) continue;

						if(!($this->fields_arr[$key]=='compulsory' or $value=='compulsory'))
							$this->fields_arr[$key] = $value;
						else
							$this->fields_arr[$key] = $this->CFG['admin']['index'][$key];
					}
			}

		/**
		 * EditMembersHandler::populateIndexPageFields()
		 *
		 * @param mixed $index_block_arr
		 * @return
		 */
		public function populateIndexPageFields($index_block_arr)
			{
				global $smartyObj;
				$populateIndexPageFields_arr = array();
				$inc = 1;
				foreach($index_block_arr as $value)
					{
						$populateIndexPageFields_arr[$inc]['label'] = $this->LANG[$value];

						if(!$this->isShowIndexBlock($this->CFG['admin']['index'][$value]))
							continue;

						$populateIndexPageFields_arr[$inc]['value'] = $value;
						$inc++;

					}
				$smartyObj->assign('populateIndexPageFields_arr', $populateIndexPageFields_arr);
			}

		/**
		 * EditMembersHandler::serializeIndexBlockValues()
		 *
		 * @param mixed $index_block_arr
		 * @return
		 */
		public function serializeIndexBlockValues($index_block_arr)
			{
				$array = array();
				foreach($index_block_arr as $value)
					{
						$array[$value] = $this->fields_arr[$value];
					}
				$this->fields_arr['index_block'] = serialize($array);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsValidUser()
			{
				$uid = $this->fields_arr['uid'];
				if($this->isAnonymsUser($uid))
					{
						$this->setCommonErrorMsg($this->LANG['anonyms_account_msg']);
						$this->setPageBlockShow('block_msg_form_error');
						return false;
					}
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE '.$this->getUserTableField('user_id').'='.$this->dbObj->Param($uid);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if($rs->PO_RecordCount())
					return true;
				return false;
			}

		/**
		 * To check for the duplicate email
		 *
		 * @param 		string $table_name table name
		 * @param 		string $field_name field name
		 * @param 		string $err_tip error tip
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsNotDuplicateEmail($table_name, $field_name, $err_tip='')
			{
				$uid = $this->fields_arr['uid'];
				$sql = 'SELECT '.$this->getUserTableField('user_id').' FROM ' . $table_name .
				 	   ' WHERE '.$this->getUserTableField('email').' ='.$this->dbObj->Param($field_name).
						' AND '.$this->getUserTableField('user_id').'!='.$this->dbObj->Param($uid);
				// prepare query
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name], $uid));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				$is_ok = ($numrows == 0 ) ;
				// set error tips
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name] =  $err_tip;
				return $is_ok;
			}
		public function IsOpenidUser()
			{
				$uid = $this->fields_arr['uid'];
				$sql = ' SELECT * FROM '.$this->CFG['db']['tbl']['user_identity'].''.
					   ' WHERE user_id = '.$this->dbObj->Param($uid);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				$numrows = $rs->PO_RecordCount();
				if($numrows >0)
					return false;
				else
					return true;

			}

		public function IsTwitterUser()
			{
				$uid = $this->fields_arr['uid'];
				$sql = ' SELECT * FROM '.$this->CFG['db']['tbl']['twitter_identity'].''.
					   ' WHERE user_id = '.$this->dbObj->Param($uid);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				$numrows = $rs->PO_RecordCount();
				if($numrows >0)
					return false;
				else
					return true;

			}

		/**
		 * EditMembersHandler::chkIsNotDuplicateName()
		 *
		 * @param mixed $table_name
		 * @param mixed $field_name
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsNotDuplicateName($table_name, $field_name, $err_tip='')
			{
				$uid = $this->fields_arr['uid'];
				$sql = 'SELECT '.$this->getUserTableField('user_id').' FROM ' . $table_name .
				 	   ' WHERE '.$this->getUserTableField('name').' ='.$this->dbObj->Param($field_name).
						' AND '.$this->getUserTableField('user_id').'!='.$this->dbObj->Param($uid);
				// prepare query
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name], $uid));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				$is_ok = ($numrows == 0 ) ;
				// set error tips
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name] =  $err_tip;
				return $is_ok;
			}

		/**
		 * To check the confirmation of password and password are same
		 *
		 * @param 		string $field_name1 password Field name
		 * @param 		string $field_name2 confirmation password field name
		 * @param 		string $err_tip error tip message
		 * @return 		boolean $is_ok true/false
		 * @access 		public
		 */
		public function chkIsSamePasswords($field_name1, $field_name2, $err_tip='')
			{
				$is_ok = ($this->fields_arr[$field_name1]==$this->fields_arr[$field_name2]);
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name1] = $this->fields_err_tip_arr[$field_name2] = $err_tip;
				return $is_ok;
			}

		/**
		 * EditMembersHandler::chkIsPasswordAndUserNameAreSame()
		 *
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsPasswordAndUserNameAreSame($err_tip = '')
			{
				if($this->fields_arr['name'] and $this->fields_arr['password'])
					{
						if($this->fields_arr['name'] == $this->fields_arr['password'])
							{
								$this->fields_err_tip_arr['password'] = $err_tip;
								return false;
							}
					}
				return true;
			}

		/**
		 * EditMembersHandler::chkIsValidSize()
		 *
		 * @param mixed $field_name
		 * @param mixed $min
		 * @param mixed $max
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsValidSize($field_name, $min, $max, $err_tip = '')
			{
				if((strlen($this->fields_arr[$field_name])<$min) or (strlen($this->fields_arr[$field_name])>$max))
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * EditMembersHandler::chkIsAllowedUserName()
		 *
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsAllowedUserName($err_tip = '')
			{
				$user_name = strtolower($this->fields_arr['name']);
				if(in_array($user_name, $this->CFG['admin']['not_allowed_usernames']))
					{
						$this->fields_err_tip_arr['name'] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function sendChangeMailAlert()
		    {
				$activation_link = "<a target=\"_blank\" href=\"".URL($this->CFG['site']['url'])."\">".URL($this->CFG['site']['url'])."</a>";
				$subject = $this->getMailContent($this->LANG['admin_changemail_subject'], array('VAR_USERNAME'=>$this->fields_arr['display_name'], 'VAR_EMAIL'=>$this->fields_arr['email'], 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_LINK'=>$activation_link));
				$content = $this->getMailContent($this->LANG['admin_mailchange_message'], array('VAR_USERNAME'=>$this->fields_arr['display_name'], 'VAR_EMAIL'=>$this->fields_arr['email'], 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_LINK'=>$activation_link));
				$this->_sendMail($this->fields_arr['old_email'],
											$subject,
											$content,
											$this->CFG['site']['noreply_name'],
											$this->CFG['site']['noreply_email']);
			}

		/**
		 * EditMembersHandler::_sendMail()
		 *
		 * @param mixed $to_email
		 * @param mixed $subject
		 * @param mixed $body
		 * @param mixed $sender_name
		 * @param mixed $sender_email
		 * @return
		 */
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
			{
				$this->buildEmailTemplate($subject, $body, false, true);
				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}
		public function getAnonymousTwitterUserId()
			{
				$sql = ' SELECT  user_id  FROM '.$this->CFG['db']['tbl']['users'].''.
						' WHERE name =\''.$this->CFG['user']['not_allowed'].'\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				$row = $rs->FetchRow();
				if($row)
					return $row['user_id'];
			}
	}
//<<<<<-------------- Class EditMembersHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
#print_r($_POST);
$editmember = new EditMembersHandler();
$index_block_arr = array('recent_questions', 'popular_questions', 'recently_answered', 'best_answered_questions', 'recent_forums', 'recent_blogs', 'featured_analyst', 'popular_videos');
$editmember->setPageBlockNames(array('form_search', 'form_settings'));
// To set the DB object
$editmember->setFormField('subscribe_keywords', '');
$editmember->setFormField('keyword_mail', '');
$editmember->setFormField('reply_mail', '');
$editmember->setFormField('favorite_mail', '');
$editmember->setFormField('best_ans_mail', '');
$editmember->setFormField('abuse_mail', '');
$editmember->setFormField('internal_mail', '');
$editmember->setFormField('all_email_notification', '');
$editmember->setFormField('search_question', '');
$editmember->setFormField('image_path', '');
$editmember->setFormField('msg', '');
$editmember->setFormField('uid', '');
$editmember->setFormField('name', '');
$editmember->setFormField('display_name', '');
$editmember->setFormField('password', '');
$editmember->setFormField('confirm_password', '');
$editmember->setFormField('email', '');
$editmember->setFormField('old_email', '');
$editmember->setFormField('gender', 'Female');
$editmember->setFormField('bio', '');
$editmember->setFormField('user_access', '');
$editmember->setFormField('photo', '');
$editmember->setFormField('photo_ext', '');
$editmember->setFormField('photo_server_url', '');
$editmember->setFormField('index_block', '');
$editmember->setFormField('avatar', '');
$editmember->setIndexBlockFormField($index_block_arr);
$pagename = $LANG['manage_settings'];
$editmember->setDBObject($db);
$editmember->sanitizeFormInputs($_REQUEST);
$tweet_id = $editmember->getAnonymousTwitterUserId();
// Default page block
$editmember->setAllPageBlocksHide();
$title = $LANG['editmembers_title'];
$isChkFacebookUser = false;
if ($editmember->chkIsValidUser())
	{
		if ($CFG['admin']['module']['facebook'])
			$isChkFacebookUser = $editmember->isFacebookUser($editmember->getFormField('uid'));
		$editmember->setPageBlockShow('form_settings');
		$LANG['common_username'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['username_min_size'], $LANG['common_username']);
		$editmember->LANG['common_username'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['username_max_size'], $LANG['common_username']);
		$LANG['signup_password'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['password_min_size'], $LANG['signup_password']);
		$editmember->LANG['signup_password'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['password_max_size'], $LANG['signup_password']);
		$LANG['common_display_name'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['display_name_min_size'], $LANG['common_display_name']);
		$editmember->LANG['common_display_name'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['display_name_max_size'], $LANG['common_display_name']);
		if ($editmember->isFormPOSTed($_POST, 'editmembers_submit'))
			{
				$user_details_arr = $editmember->getUserDetailsFromUsersTable($CFG['db']['tbl']['users'], $editmember->getFormField('uid'));
				$editmember->sanitizeFormInputs($_POST);
				if(!$CFG['admin']['use_profile_external_image'])
					{
						if (isset($_FILES['photo']) and $_FILES['photo']['tmp_name'])
							{
								$editmember->chkValidFileType('photo',$LANG['err_tip_invalid_file_type']) and
									$editmember->chkValideFileSize('photo',$LANG['err_tip_invalid_file_size']) and
										$editmember->chkErrorInFile('photo',$LANG['err_tip_invalid_file']);
							}
					}
				$editmember->chkIsNotEmpty('display_name', $LANG['err_tip_compulsory']) and
						$editmember->chkIsValidSize('display_name', $CFG['admin']['display_name_min_size'], $CFG['admin']['display_name_max_size'], $LANG['err_tip_invalid_size']);
				if ((!$isChkFacebookUser) && ($editmember->getFormField('uid') != $tweet_id))
					{
						$editmember->chkIsNotEmpty('email', $LANG['err_tip_compulsory']) and
						$editmember->chkIsValidEmail('email', $LANG['err_tip_invalid_email']) and
							($editmember->chkIsNotDuplicateEmail($CFG['db']['tbl']['users'], 'email', $LANG['err_tip_email_already_exists']) or
								$editmember->setCommonErrorMsg($LANG['err_tip_email_already_exists']));

						if ($editmember->getFormField('password') AND isDemoSite())
							{
								$editmember->setPageBlockShow('block_msg_form_error');
								$LANG['common_msg_error_sorry'] = $LANG['no_permission_to_edit_password_mail'];
								$editmember->setCommonErrorMsg($editmember->LANG['common_msg_error_sorry']);
							}
						elseif ($editmember->getFormField('password') OR $editmember->getFormField('confirm_password'))
							{
								$editmember->chkIsNotEmpty('password', $LANG['err_tip_compulsory']) and
									$editmember->chkIsValidSize('password', $CFG['admin']['password_min_size'], $CFG['admin']['password_max_size'], $LANG['err_tip_invalid_size']);
										$editmember->chkIsNotEmpty('confirm_password', $LANG['err_tip_compulsory']) and
											$editmember->chkIsSamePasswords('password', 'confirm_password', $LANG['common_err_tip_same_password']);
												$editmember->chkIsPasswordAndUserNameAreSame($LANG['password_user_name']);
							}
					}
				if ($editmember->isValidFormInputs())
					{
						$editmember->serializeIndexBlockValues($index_block_arr);
						$editmember->updateFormFieldsInTable($CFG['db']['tbl']['users_ans_log'], $editmember->getFormField('uid'),
											array('subscribe_keywords', 'keyword_mail', 'reply_mail', 'favorite_mail', 'best_ans_mail', 'abuse_mail', 'internal_mail', 'index_block'));
						$bio = html_entity_decode($editmember->getFormField('bio'));
						$bio = strip_tags ($bio, $CFG['html']['allowed_tags']);
						$editmember->setFormField('bio', $bio);
						if (isDemoSite())
							$editmember->setFormField('user_access', 'User');
						$update_fields = array('name', 'display_name', 'gender', 'bio', 'user_access');
						if ($editmember->getFormField('password'))
							{
								$editmember->setFormField('password', md5($editmember->getFormField('password')));
								$update_fields[] = 'password';
							}
						if (!$isChkFacebookUser AND $editmember->getFormField('email') != $editmember->getFormField('old_email'))
							{
								$update_fields[] = 'email';
								$editmember->sendChangeMailAlert();
							}
						$editmember->updateFormFieldsInUserTable($CFG['db']['tbl']['users'], $editmember->getFormField('uid'),
												$update_fields);

						if($CFG['admin']['use_profile_external_image'])
							{
								$editmember->updateUserImagePath();
							}
						elseif (isset($_FILES['photo']) and $_FILES['photo']['tmp_name'])
							{
								$editmember->photoUpload();
							}
						elseif ($editmember->getFormField('avatar'))
							{
								$avatarImagePath = $CFG['site']['url'].$CFG['admin']['avatar_path'].$editmember->getFormField('avatar');
								$editmember->setFormField('image_path' , $avatarImagePath);
								$editmember->updateUserImagePath();
							}
						$editmember->setPageBlockShow('block_msg_form_success');
						$editmember->setCommonSuccessMsg($LANG['editmembers_updated_successfully']);
						Redirect2URL('editMembers.php?uid='.$editmember->getFormField('uid').'&msg=1');
					}
				else
					{
						$editmember->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$editmember->setPageBlockShow('block_msg_form_error');
						$editmember->setPageBlockShow('form_editprofile');
					}
						$editmember->setFormField('password', '');
						$editmember->setFormField('confirm_password', '');
			}
		elseif ($editmember->isFormPOSTed($_POST, 'editmembers_cancel'))
			{
				Redirect2URL($CFG['site']['relative_url'].'manageAnswersMembers.php');
			}
		else
			{
				$user_settings_arr = $editmember->getUserDetailsArrFromDB($CFG['db']['tbl']['users_ans_log'],
									array('subscribe_keywords', 'keyword_mail', 'reply_mail', 'favorite_mail', 'best_ans_mail', 'abuse_mail', 'internal_mail', 'index_block'),
									$editmember->getFormField('uid'));
				$editmember->populateIndexBlockValues($user_settings_arr['index_block']);
				$editmember->setFormField('subscribe_keywords', $user_settings_arr['subscribe_keywords']);
				$editmember->setFormField('keyword_mail', $user_settings_arr['keyword_mail']);
				$editmember->setFormField('reply_mail', $user_settings_arr['reply_mail']);
				$editmember->setFormField('favorite_mail', $user_settings_arr['favorite_mail']);
				$editmember->setFormField('best_ans_mail', $user_settings_arr['best_ans_mail']);
				$editmember->setFormField('abuse_mail', $user_settings_arr['abuse_mail']);
				$editmember->setFormField('internal_mail', $user_settings_arr['internal_mail']);
				$user_details_arr = $editmember->getUserDetailsFromUsersTable($CFG['db']['tbl']['users'], $editmember->getFormField('uid'));
				$editmember->setFormField('image_path', $user_details_arr['image_path']);
				$editmember->setFormField('name', $user_details_arr['name']);
				$editmember->setFormField('display_name', $user_details_arr['display_name']);
				$editmember->setFormField('email', $user_details_arr['email']);
				$editmember->setFormField('old_email', $user_details_arr['email']);
				$editmember->setFormField('bio', $user_details_arr['bio']);
				$editmember->setFormField('gender', $user_details_arr['gender']);
				$editmember->setFormField('user_access', $user_details_arr['user_access']);
				$smartyObj->assign('user_details_arr',$user_details_arr);
			}
		if ($editmember->isFormPOSTed($_GET, 'msg') AND $editmember->isValidFormInputs())
			{
				$editmember->setPageBlockShow('block_msg_form_success');
				$editmember->setCommonSuccessMsg($LANG['editmembers_updated_successfully']);
			}
	}
else
	{
		if(!$editmember->isAnonymsUser($editmember->getFormField('uid'))){
			$editmember->setCommonErrorMsg($LANG['common_msg_error_sorry']);
			$editmember->setPageBlockShow('block_msg_form_error');
			$editmember->setCommonErrorMsg($LANG['err_tip_invalid_user']);
		}
	}
if ($editmember->isShowPageBlock('form_settings'))
	{
		$LANG['tag_size'] = str_ireplace('VAR_MIN_SIZE', $CFG['admin']['tag_min_size'], $LANG['tag_size']);
		$editmember->LANG['tag_size'] = str_ireplace('VAR_MAX_SIZE', $CFG['admin']['tag_max_size'], $LANG['tag_size']);
		$smartyObj->assign('var_size_photo', str_ireplace('VAR_SIZE', $CFG['admin']['ans_photos']['max_size'], $LANG['photo_allowed_size']));
		$allowed_image_formats = implode(', ', $CFG['admin']['ans_photos']['format_arr']);
		$allowed_image_formats = str_replace('image/', '', $allowed_image_formats);
		$photo_allowed_image_type = $LANG['photo_allowed_image_type'] . ': ' . $allowed_image_formats;
		$smartyObj->assign('photo_allowed_image_type', $photo_allowed_image_type);

		$smartyObj->assign('htmlspecialchars',htmlspecialchars($CFG['html']['allowed_tags']));
		$smartyObj->assign('index_block_arr',$index_block_arr);
		$user_details_arr = $editmember->getUserDetailsFromUsersTable($CFG['db']['tbl']['users'], $editmember->getFormField('uid'));
		$smartyObj->assign('user_details_arr',$user_details_arr);
	}
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$editmember->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('editMembers.tpl');
?>
<script language="javascript" type="text/javascript">
function checkAllMail(frm)
	{
		var frmLength = frm.elements.length;
		var rdId = '';
		var rdVal = '_no';
		if (($('all_email_notification').checked))
			rdVal = '_yes';
		for ( var i=0; i<frmLength; i++)
			{
				if ((frm.elements[i].name.indexOf('_mail')!=-1) && (frm.elements[i].type == 'radio')){
					rdId = frm.elements[i].name + rdVal;
					$(rdId).checked = true;
				}
			}
	}
function checkAllSettings(frm)
	{
		var frmLength = frm.elements.length;
		var rdId = '';
		var rdVal = '_no';
		if (($('all_home_settings').checked))
			rdVal = '_yes';
		for ( var i=0; i<frmLength; i++)
			{
				if ((frm.elements[i].name.indexOf('_mail')==-1) && (frm.elements[i].type == 'radio')){
					rdId = frm.elements[i].name + rdVal;
					if (($(rdId)))
						$(rdId).checked = true;
				}
			}
	}
	needLiveValidation('display_name',Array('Presence','Length|3|30'));
</script>
<?php  if (!$isChkFacebookUser) { ?>
<script language="javascript" type="text/javascript">
	needLiveValidation('email',Array('Presence','Email'));
	needLiveValidation('password',Array('Length|4|30'));
	needLiveValidation('confirm_password',Array('Confirmation|password'));
</script>
<?php } ?>
<?php if ($editmember->isShowPageBlock('form_settings') AND isUserImageAllowed()) { ?>
<script language="javascript" type="text/javascript">
	ajaxUpdateDiv('<?php echo $CFG['site']['url'].$CFG['admin']['index']['anova_module']?>/avatars.php?uid=<?php echo $editmember->getFormField('uid')?>', '', 'selShowAvatarImages');
</script>
<?php } ?>
<?php
//<<<<<-------------------- Page block templates ends --------------------//
$editmember->includeFooter();
?>