<?php
/**
 * This file is to manage avatars
 *
 * PHP version 5.0
 *
 * @avatar	Agriya Answers
 * @package		Admin
 * @author 		karthiselvam_75ag08
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id: $
 * @since 		2008-11-19
 */
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/manageAvatars.php';
$CFG['mods']['include_files'][] = 'common/classes/class_Image.lib.php';

$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;

/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');

//-------------------------class ManageAvatarHandler-------------------->>>
/**
 * @avatar	Agriya Answers
 * @package		ManageAvatarHandler
 * @author 		karthiselvam_75ag08
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		Release: @package_version@
 * @since 		2008-11-18
 */
class ManageAvatarHandler extends FormHandler
	{
		/**
		 *
		 * @return 		void
		 * @access 		public
		 */

		public function displayAvatars()
			{
				$this->displayAvatars_arr	=	array();
				$avatar_img_arr = glob($this->CFG['site']['project_path'].$this->CFG['admin']['avatar_path']."default_*");
				function filemtime_compare($a, $b)
						{
							return  filemtime($b) -  filemtime($a);
						}
				usort($avatar_img_arr, 'filemtime_compare');
				$no_of_avatar_img = count($avatar_img_arr);
				$inc	=	0;
				$this->displayAvatars_arr['row']	=	array();
				foreach ($avatar_img_arr as $filename)
					{
						$this->displayAvatars_arr['row'][$inc]['img_file']	=	substr($filename, strrpos($filename, 'avatars/') + 8);
						$this->displayAvatars_arr['row'][$inc]['imp_url']	=	$this->CFG['site']['url'].$this->CFG['admin']['avatar_path'].$this->displayAvatars_arr['row'][$inc]['img_file'];
						$inc++;
					}
				$this->displayAvatars_arr['populateFilterList']	=	$this->populateFilterList($this->action_arr, $this->fields_arr['action']);
				$this->displayAvatars_arr['total_count']	=	$inc;
				return $this->displayAvatars_arr;
			}

		/**
		 * To populate filter list
		 *
		 * @param	    string $highlight Selected filter
		 * @return 		void
		 * @access		public
		*/
		public function populateFilterList($array_to_expand, $highlight)
			{
				$this->populateFilterList_arr	=	array();
				$inc=0;
				foreach ($array_to_expand as $key=>$value)
					{
						$this->populateFilterList_arr[$inc]['key']	=	$key;
						$this->populateFilterList_arr[$inc]['name']	=	$value;
						if($key == $highlight)
							{
								$this->populateFilterList_arr[$inc]['selected_chk']	=	'selected="selected"';
							}
						else
							{
								$this->populateFilterList_arr[$inc]['selected_chk']	=	'';
							}
						$inc++;
					}
				return $this->populateFilterList_arr;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function deleteAvatars()
			{
				$avatarImagePath = $this->CFG['site']['project_path'].$this->CFG['admin']['avatar_path'];
				$avatarImageUrl = $this->CFG['site']['url'].$this->CFG['admin']['avatar_path'];

				$avatar_img_arr = explode(',', $this->fields_arr['avatar_ids']);
				foreach($avatar_img_arr as $avatar_img)
					{
						@unlink($avatarImagePath.$avatar_img);

						$avatarImageFullUrl = $avatarImageUrl.$avatar_img;

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

		/**
		 * 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::storeImagesTempServer()
		 *
		 * @param $uploadUrl
		 * @param $extern
		 * @return
		 **/
		public function storeImagesTempServer($uploadUrl, $extern)
			{
				//GET THUMB IMAGE
				$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));
			}

		/**
		 * EditPersonalProfileFormHandler::photoUpload()
		 *
		 * @return
		 **/
		public function photoUpload()
			{
				$extern = strtolower(substr($_FILES['avatar']['name'], strrpos($_FILES['avatar']['name'], '.')+1));
				$this->setFormField('photo_ext',$extern);
				$image_name = 'default_avatar'.time();
				$imageObj = new ImageHandler($_FILES['avatar']['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']['avatar_path'];
				$local_upload = true;
				if($local_upload)
					{
						$dir = '../'.$this->CFG['admin']['avatar_path'];
						$this->chkAndCreateFolder($dir);
						$uploadUrl = $dir.$image_name;

						if($this->CFG['admin']['ans_photos']['thumb_name']=='T')
							{
								copy($temp_file.'T.'.$extern, $uploadUrl.'T.'.$extern);
								unlink($temp_file.'T.'.$extern);
							}
					}
			}


	}
//<<<<<---------------class ManageAvatarHandler------///
//--------------------Code begins-------------->>>>>//
$avatarfrm = new ManageAvatarHandler();
$avatarfrm->setPageBlockNames(array('form_add_avatar', 'form_view_avatar', 'form_view_sub_avatar', 'form_add_sub_avatar'));
// Set the form fields
$avatarfrm->setFormField('user_id', '');
$avatarfrm->setFormField('avatar', '');
$avatarfrm->setFormField('avatar_name', '');
$avatarfrm->setFormField('action', '');
$avatarfrm->setFormField('avatar_ids', array());
$avatarfrm->setFormField('mode', '');
$action_arr = array('' => $LANG['common_select_action'],
					'Delete' => $LANG['common_delete']
					);
$avatarfrm->action_arr = $action_arr;

// Default page block
$avatarfrm->setAllPageBlocksHide();

$avatarfrm->sanitizeFormInputs($_REQUEST);
$avatarfrm->setPageBlockShow('form_view_avatar');
if (isDemoSite() AND ($avatarfrm->isFormPOSTed($_POST, 'add_avatar') or $avatarfrm->isFormPOSTed($_POST, 'confirm_action')))
	{
		$avatarfrm->setCommonErrorMsg($LANG['no_permission_for_demo_user']);
		$avatarfrm->setPageBlockShow('block_msg_form_error');
	}
elseif ($avatarfrm->isFormPOSTed($_POST, 'add_avatar'))
	{
		// Validations
		if (isset($_FILES['avatar']) and $_FILES['avatar']['tmp_name'])
			{
				$avatarfrm->chkValidFileType('avatar',$LANG['err_tip_invalid_file_type']) and
					$avatarfrm->chkValideFileSize('avatar',$LANG['err_tip_invalid_file_size']) and
						$avatarfrm->chkErrorInFile('avatar',$LANG['err_tip_invalid_file']);
			}
		else
			{
				$avatarfrm->setPageBlockShow('block_msg_form_error');
				$avatarfrm->setFormFieldErrorTip('avatar', $LANG['err_tip_select_avatar']);
			}
		if ($avatarfrm->isValidFormInputs())
			{
				$avatarfrm->photoUpload();
				$avatarfrm->setAllPageBlocksHide();
				$success_message = $LANG['avatar_success_message'];
				Redirect2URL($CFG['site']['url'].'admin/manageAvatars.php?msg=success');
				$avatarfrm->setCommonSuccessMsg($success_message);
				$avatarfrm->setPageBlockShow('block_msg_form_success');
				$avatarfrm->setPageBlockShow('form_view_avatar');
			}
			else
				{
					$avatarfrm->setAllPageBlocksHide();
					$avatarfrm->setPageBlockShow('form_add_avatar');
					$avatarfrm->setPageBlockShow('block_msg_form_error');
					$avatarfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				}
	}
elseif ($avatarfrm->isFormPOSTed($_POST, 'confirm_action'))
	{
		// Validations
		$avatarfrm->chkIsNotEmpty('avatar_ids', $LANG['err_tip_compulsory'])or
			$avatarfrm->setCommonErrorMsg($LANG['avatar_err_tip_select_avatar']);
		$avatarfrm->chkIsNotEmpty('action', $LANG['err_tip_compulsory'])or
			$avatarfrm->setCommonErrorMsg($LANG['err_tip_select_action']);
		if ($avatarfrm->isValidFormInputs())
			{
				$avatarfrm->setAllPageBlocksHide();
				$avatarfrm->setPageBlockShow('block_msg_form_success');
				$avatarfrm->setPageBlockShow('form_view_avatar');
				switch($avatarfrm->getFormField('action')){
					case 'Delete':
						$avatarfrm->deleteAvatars();
						$success_message = $LANG['avatar_success_delete'];
						$avatarfrm->setCommonSuccessMsg($success_message);
						break;
				} // switch
			}
			else
				{
					$avatarfrm->setAllPageBlocksHide();
					$avatarfrm->setPageBlockShow('block_msg_form_error');
				}
	}
elseif ($avatarfrm->isFormPOSTed($_POST, 'cancel'))
	{
		Redirect2URL($CFG['site']['relative_url'].'manageAvatars.php');
	}
elseif ($avatarfrm->isPageGETed($_GET, 'mode') && $avatarfrm->isValidFormInputs())
    {
		$mode = $avatarfrm->getFormField('mode');
		if (strcmp($mode, 'add')==0)
         	{
				$avatarfrm->setAllPageBlocksHide();
				$avatarfrm->setPageBlockShow('form_add_avatar');
	        }
    }
elseif ($avatarfrm->isFormPOSTed($_GET, 'msg'))
	{
		$avatarfrm->setCommonSuccessMsg($LANG['avatar_success_message']);
		$avatarfrm->setPageBlockShow('block_msg_form_success');
		$avatarfrm->setPageBlockShow('form_view_avatar');
	}
if ($avatarfrm->isShowPageBlock('form_add_avatar'))
	{
		$avatarfrm->LANG['avatar_title'] = $LANG['avatar_subtitle_add_avatar'];
		$max_file_size = $CFG['admin']['ans_photos']['max_size'];
		$allowed_image_formats = implode(', ', $CFG['admin']['ans_photos']['format_arr']);
		$allowed_image_formats = str_replace('image/', '', $allowed_image_formats);
  		$allowed_type = str_ireplace('VAR_FORMAT', $allowed_image_formats ,$LANG['attachment_format_tip']);
  		$max_file_size = str_ireplace('VAR_SIZE', $max_file_size , $LANG['common_maxsize_tip']);

		$smartyObj->assign('maxsize', $max_file_size);
		$smartyObj->assign('allowed_type', $allowed_type);
	}

//<<<<--------------------Code Ends----------------------//

//--------------------Page block templates begins-------------------->>>>>//
if ($avatarfrm->isShowPageBlock('form_view_avatar'))
	{
			$avatarfrm->form_view_avatar['displayAvatars']	=	$avatarfrm->displayAvatars();
	}
//include the header file
$avatarfrm->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('manageAvatars.tpl');
//includ the footer of the page
?>
<script type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm');
	var replace_url = '<?php echo $CFG['site']['url'];?>login.php';
	var please_select_action = '<?php echo $LANG['err_tip_select_action'];?>';
	var confirm_message = '';
	function getAction()
		{
			var act_value = document.formViewAvatar.action.value;
			if(act_value)
				{
					switch (act_value)
						{
							case 'Delete':
								confirm_message = '<?php echo $LANG['avatar_delete_msg'];?>';
								break;
						}
					$('confirmMessage').innerHTML = confirm_message;
					document.formConfirm.action.value = act_value;
					Confirmation('selMsgConfirm', 'formConfirm', Array('avatar_ids'), Array(multiCheckValue), Array('value'), 'formViewAvatar');
				}
				else
					alert_manual(please_select_action);
		}
</script>
<?php
//<<<<<<--------------------Page block templates Ends--------------------//
$avatarfrm->includeFooter();
?>