<?php
/**
 * Class to handle the form fields
 *
 * This is having class FormHandler to handle the validation of form fields, to
 * set or get values for form fields, to handle page blocks, to handle CSS for
 * form fields and to populate the common static array file.
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		FormHandler
 * @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 		2008-11-05
 */
//Defining constants for form field validation at the time of setting the form field array
define('ISNOTEMPTY', 1<<0);
define('ISVALIDALPHA', 1<<1);
define('ISVALIDALPHANUMERIC', 1<<2);
define('ISNUMERIC', 1<<3);
define('ISREAL', 1<<4);
define('ISVALIDEMAIL', 1<<5);
define('ISVALIDPHONENO', 1<<6);
define('ISVALIDURL', 1<<7);
define('ISCUSTOMFUN', 1<<8);
//------------------- Class FormHandler begins ------------------->>>>>//
//To test this class in standalone mode with test cases
//found at the end of this class...
if (!isset($CFG['debug']['debug_standalone_modules']))
		$CFG['debug']['debug_standalone_modules'] = true;

/**
 * FormHandler class for handling form fields
 *
 * <b>Class overview</b>
 *
 * FormHandler class is used to inherit various types of methods in other classes
 * such as css related methods validation methods form fileds storage error messages
 * genearting methods etc are developed here.
 *
 * <b>Methods overview</b>
 *
 * setFormField, getFormField type methods are used to store the form fields.
 * In array methods such as setCSSFormLabelCellDefaultClass are used to adpot
 * css styles to the cells chkIsValidEmail, chkIsAlphaNumeric etc are related
 * to the validation techniques.
 *
 * <b>How to use this class</b>
 *
 * create object for one class. And inherit this class.call the methods
 * depending upon the situations like validation of the user inputs,
 * setting the values given to arrays.
 *
 * @category	Anova
 * @package		###Common/Classes###
 * @author 		senthil_52ag05
 * @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-05
 */
class FormHandler
	{
		/**
		 * @var		string common error messsage
		 */
		protected $common_error_message = '';
		/**
		 * @var		string common success messsage
		 */
		protected $common_success_message = '';
		/**
		 * @var		string common alert messsage
		 */
		protected $common_alert_message = '';
		/**
		 * @var		array array of form fields
		 */
		protected $fields_arr = array();
		/**
		 * @var		array array of error tips for fields
		 */
		protected $fields_err_tip_arr = array();
		/**
		 * @var		array array of form block show status
		 */
		protected $page_block_show_stat_arr = array();	//Array of Page Block show status
		/**
		 * @var		array array of css class
		 */
		protected $css_class_arr = array();
		/**
		 * @var		array array of countries list
		 */
		protected $countries_list_arr;
		/**
		 * @var		array array of months list
		 */
		protected $months_list_arr;
		/**
		 * @var		array array of years list
		 */
		protected $years_list_config;
		/**
		 * @var 	boolean option to allow dynamic form fields
		 */
		protected $is_allow_dynamic_fields = false;
		/**
		 * @var		array array of email template value
		 */
		protected $email_template_value_arr = array();
		/**
		 * @var		string email subject
		 */
		protected $email_subject;
		/**
		 * @var		string email content
		 */
		protected $email_content;

		//youtube_flv_url
		public $youtube_flv_url = '';
		public $google_video_details_arr = array();

		//audio url
		public $audio_url = '';
	   /**
		* Constructor
		*
		* When object is initiated, constructor method is called immediately.
		*
		* @return 		void
		* @access 		public
		*/
		public function __construct()
			{
				global $CFG, $LANG, $db;
				if (isset($CFG))
					{
						$this->CFG = $CFG;
					}
				if (isset($LANG))
					{
						$this->LANG = $LANG;
					}
				if (isset($db))
					{
						$this->setDBObject($db);
					}
				$this->setCSSFormFieldErrorTipClass('clsFormFieldErrTip');
				$this->setCSSFormLabelCellDefaultClass('clsFormLabelCellDefault');
				$this->setCSSFormFieldCellDefaultClass('clsFormFieldCellDefault');
				$this->setCSSFormLabelCellErrorClass('clsFormLabelCellError');
				$this->setCSSFormFieldCellErrorClass('clsFormFieldCellError');
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function assignSmartyVariables()
			{
				global $smartyObj;
				$smartyObj->assign('CFG', $this->CFG);
				$smartyObj->assign('LANG', $this->LANG);
				$smartyObj->assign_by_ref('myobj', $this);
			}

	   /**
		* To set the form fields
		*
		* Before using form fields, set the form field using this method.
		* we can set the default value to the form fields
		*
		* @param 		string $field_name Form field name
		* @param 		string $field_value Form field value
		* @param		int $validation_scheme number having bits set for the required validation
		* @return 		void
		* @access 		public
		*/
		public function setFormField($field_name, $field_value, $validation_scheme = null, $custom_validation_fun_name = null)
			{
				global $smartyObj;
				$this->fields_arr[$field_name] = $field_value;
				$smartyObj->assign('field_value_'.$field_name, $field_value);
				if (isset($validation_scheme))
					{
						$this->validation_scheme_arr[$field_name] = $validation_scheme;
						$this->custom_validation_fun_name[$field_name] = $custom_validation_fun_name;
					}
			}

	   /**
		* To set the indirect form fields
		*
		* alias of setFormField() method
		*
		* @param 		string $field_name Form field name
		* @param 		string $field_value Form field value
		* @return 		void
		* @access 		public
		*/
		public function setIndirectFormField($field_name, $field_value)
			{
				$this->setFormField($field_name, $field_value);
			}

	   /**
		* To set the form variables
		*
		* Alias of setFormField() method. But use this method only for
		* displaying the form fields.
		*
		* @param 		string $field_name Form field name
		* @param 		string $field_value Form field value
		* @return 		void
		* @access 		public
		*/
		public function setDisplayVar($field_name, $field_value)
			{
				$this->setFormField($field_name, $field_value);
			}

	   /**
		* To get the form field
		*
		* To get the form field value after setting the form field value
		*
		* @param 		string $field_name Form field name
		* @return 		string $this->fields_arr[$field_name] Form field value
		* @access 		public
		*/
		public function getFormField($field_name)
			{
				return $this->fields_arr[$field_name];
			}

	   /**
		* To get the form field
		*
		* To get the form field variaiables. Alias of setFormField() method.
		* use this method only to get the form field variables
		*
		* @param 		string $field_name Form field name
		* @return 		string
		* @access 		public
		*/
		public function getDisplayVar($field_name)
			{
				return $this->getFormField($field_name);
			}

	   /**
		* To set the common error message
		*
		* Use this method to set the common error message. After
		* submitting form, call this method to set the error message
		*
		* @param 		string $err_msg common error message
		* @return 		string
		* @access 		public
		*/
		public function setCommonErrorMsg($err_msg)
			{
				$this->common_error_message = $err_msg;
			}

	   /**
		* To get the common error message
		*
		* Use this method to get the common error message. Call this
		* method in error page block to show the common error message
		*
		* @return 		string $this->common_error_message
		* @access 		public
		*/
		public function getCommonErrorMsg()
			{
				return $this->common_error_message;
			}

		/**
		* To set the common success message
		*
		* Use this method to set the common success message. After
		* submitting form, call this method to set the success message
		*
		* @param 		string $success_msg common success message
		* @return 		string
		* @access 		public
		*/
		public function setCommonSuccessMsg($success_msg)
			{
				$this->common_success_message = $success_msg;
			}

	   /**
		* To get the common success message
		*
		* Use this method to get the common success message. Call this
		* method in success page block to show the common success message
		*
		* @return 		string $this->common_success_message
		* @access 		public
		*/
		public function getCommonSuccessMsg()
			{
				return $this->common_success_message;
			}

		/**
		* To set the common alert message
		*
		* Use this method to set the common alert message. After
		* submitting form, call this method to set the alert message
		*
		* @param 		string $alert_msg common alert message
		* @return 		string
		* @access 		public
		*/
		public function setCommonAlertMsg($alert_msg)
			{
				$this->common_alert_message = $alert_msg;
			}

	   /**
		* To get the common alert message
		*
		* Use this method to get the common alert message. Call this
		* method in alert page block to show the common alert message
		*
		* @return 		string $this->common_alert_message
		* @access 		public
		*/
		public function getCommonAlertMsg()
			{
				return $this->common_alert_message;
			}

	   /**
		* To set the email template value
		*
		* @param 		string template key
		* @param 		string template value
		* @return 		void
		* @access 		public
		*/
		public function setEmailTemplateValue($key, $value)
			{
				$this->email_template_value_arr[$key] = $value;
			}

	   /**
		* To get the email template value
		*
		* @param 		string template key
		* @return 		string
		* @access 		public
		*/
		public function getEmailTemplateValue($key)
			{
				return $this->email_template_value_arr[$key];
			}

	   /**
		* To build the email template
		*
		* @param 		string subject of the mail
		* @param 		string content of the mail
		* @param 		boolean htmal changes needed in subject
		* @param 		boolean htmal changes needed in content
		* @return 		string
		* @access 		public
		*/
		public function buildEmailTemplate($subject, $content, $html_subject = false, $html_content = true)
			{
				$subject = str_replace('VAR_SITE_NAME', $this->CFG['site']['name'], $subject);
				$content = str_replace('VAR_SITE_NAME', $this->CFG['site']['name'], $content);

				$subject = str_replace('VAR_SITE_URL', $this->CFG['site']['url'], $subject);
				$content = str_replace('VAR_SITE_URL', $this->CFG['site']['url'], $content);

				foreach($this->email_template_value_arr as $key=>$value)
					{
						$subject = str_replace($key, $value, $subject);
						$content = str_replace($key, $value, $content);
					}
				if($html_subject)
					{
						$subject = makeClickableLinks($subject);
						$subject = nl2br($subject);
					}
				if($html_content)
					{
						$content = makeClickableLinks($content);
						$content = nl2br($content);
					}
				$this->email_subject = $subject;
				$this->email_content = $content;
			}

	   /**
		* To get the email subject
		*
		* @param
		* @return 		string
		* @access 		public
		*/
		public function getEmailSubject()
			{
				return $this->email_subject;
			}

	   /**
		* To get the email content
		*
		* @param
		* @return 		string
		* @access 		public
		*/
		public function getEmailContent()
			{
				return $this->email_content;
			}

	   /**
        * To set the page block names
        *
        * Before using any page block names set the name in this method
        *
		* @param 		array $block_names_arr Array of page block names
        * @return 		void
		* @access 		public
        */
		public function setPageBlockNames($block_names_arr=array())
			{
				$default_blocks = array('block_msg_form_error', 'block_msg_form_success', 'block_msg_form_alert');
				$block_names_arr = array_merge($default_blocks, $block_names_arr);
				$block_names_arr = array_unique($block_names_arr);
				//also reset stat
				foreach($block_names_arr as $block_name)
					{
						$this->page_block_show_stat_arr[$block_name] = false;	//hide all. reset.
					}
			}

	   /**
        * To show the page block
        *
		* @param 		string $block_name page block name
        * @return 		void
		* @access 		public
        */
		public function setPageBlockShow($block_name)
			{
				$this->page_block_show_stat_arr[$block_name] = true; //show
			}

	   /**
        * To hide the page block
        *
        *
		* @param 		string $block_name page block name
        * @return 		void
		* @access 		public
        */
		public function setPageBlockHide($block_name)
			{
				$this->page_block_show_stat_arr[$block_name] = false; //hide
			}

	   /**
        * To show all the page blocks
        *
        * @return 		void
		* @access 		public
        */
		public function setAllPageBlocksShow()
			{
				foreach($this->page_block_show_stat_arr as $block_name=>$is_show)
					{
						$this->page_block_show_stat_arr[$block_name] = true; //show
					}
			}

	   /**
        * To hide all the page blocks
        *
        * @return 		void
		* @access 		public
        */
		public function setAllPageBlocksHide()
			{
				foreach($this->page_block_show_stat_arr as $block_name=>$is_show)
					{
						$this->page_block_show_stat_arr[$block_name] = false; //hide
					}
			}

	   /**
        * To check whether the page block is show or not
        *
        * Before use the page block, set the page block name in setPageBlockShow()
        * method. It is checked in this methid. If it is set, this method return
		* true otherwise it return false
		*
        * @param 		string $block_name page block name
        * @return 		boolean true/false
		* @access 		public
        */
		public function isShowPageBlock($block_name)
			{
				return $this->page_block_show_stat_arr[$block_name];
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getCSSFormFieldElementClass($field_name)
			{
				$class_name = isset($this->fields_err_tip_arr[$field_name]) ? 'LV_invalid_field' : '';
				return $class_name;
			}

	   /**
        * To set the css class for error tip
        *
        * We can set the css error tip class for the form fields
        *
        * @param 		string $class_name Error tip class name
        * @return 		void
		* @access 		public
        */
		public function setCSSFormFieldErrorTipClass($class_name)
			{
				$this->css_class_arr['form_field_err_tip'] = $class_name;
			}

	   /**
        * To set the default css class for label
        *
        * @param 		string $class_name default label class
        * @return 		void
		* @access 		public
        */
		public function setCSSFormLabelCellDefaultClass($class_name)
			{
				$this->css_class_arr['form_label_cell_default'] = $class_name;
			}

	   /**
        * To set the css class for error label
        *
        * @param 		string $class_name error label class
        * @return 		void
		* @access 		public
        */
		public function setCSSFormLabelCellErrorClass($class_name)
			{
				$this->css_class_arr['form_label_cell_error'] = $class_name;
			}

	   /**
        * To set the default css class for form field
        *
        * @param 		string $class_name default form field class
        * @return 		void
		* @access 		public
        */
		public function setCSSFormFieldCellDefaultClass($class_name)
			{
				$this->css_class_arr['form_field_cell_default'] = $class_name;
			}

	   /**
        * To set css class for error form fields
        *
        * @param 		string $class_name error form field class
        * @return 		void
		* @access 		public
        */
		public function setCSSFormFieldCellErrorClass($class_name)
			{
				$this->css_class_arr['form_field_cell_error'] = $class_name;
			}

	   /**
        * To get the css label class
        *
        * @param 		string $field_name form field
        * @return 		string
		* @access 		public
        */
		public function getCSSFormLabelCellClass($field_name)
			{
				$class_name = isset($this->fields_err_tip_arr[$field_name]) ? 'form_label_cell_error' : 'form_label_cell_default';
				return $this->css_class_arr[$class_name];
			}

	   /**
        * To get the css form field class
        *
        * @param 		string $field_name form field name
        * @return 		string
		* @access 		public
        */
		public function getCSSFormFieldCellClass($field_name)
			{
				$class_name = isset($this->fields_err_tip_arr[$field_name]) ? 'form_field_cell_error' : 'form_field_cell_default';
				return $this->css_class_arr[$class_name];
			}

	   /**
        * To check whether the form is posted
        *
        * @param 		array $post_arr
		* @param 		string $form_submit_name submit field name
        * @return 		array Array posted variables
		* @access 		public
        */
		public function isFormPOSTed($post_arr, $form_submit_name='')
			{
				return $form_submit_name ? isset($post_arr[$form_submit_name]) : $post_arr;
			}

	   /**
        * To check whether the form is geted
        *
        * @param 		array $get_arr
		* @param 		string $form_submit_name
        * @return 		array
		* @access 		public
        */
		public function isFormGETed($get_arr, $form_submit_name='')
			{
				return $form_submit_name ? isset($get_arr[$form_submit_name]) : $get_arr;
			}

		/**
		 * To check the page is geted or not
		 *
		 * @param 		array $get_arr
		 * @param 		string $var_name variable name
		 * @return 		boolean true/false
		 */
		public function isPageGETed($get_arr, $var_name='')
			{
				return $this->isFormGETed($get_arr, $var_name);
			}

	    /**
        * To santize the form fields
        *
        * @param 		array $request_arr GET/ POST
        * @return 		void
		* @access 		public
        */
		public function sanitizeFormInputs($request_arr) //GET or POST
			{
				global $smartyObj;
				foreach($this->fields_arr as $field_name=>$default_value)
					{
						if (isset($request_arr[$field_name]))
							{
								if (is_string($request_arr[$field_name]))
									{
										$this->fields_arr[$field_name] = htmlspecialchars(trim($request_arr[$field_name]));
										$smartyObj->assign('field_value_'.$field_name, $this->fields_arr[$field_name]);
									}
								  else if (is_array($request_arr[$field_name]))
									{
										foreach($request_arr[$field_name] as $sub_key=>$sub_value)
											{
												$this->fields_arr[$field_name][$sub_key] = htmlspecialchars(trim($sub_value));
												$smartyObj->assign('field_value_'.$field_name.'__'.$sub_key, $this->fields_arr[$field_name][$sub_key]);
											}
									}
								  else //unexpected as of now. if occurred, make a note so as to fix.
								  		trigger_error('Developer Notice: Unexpected field type ('.gettype($request_arr[$field_name]).'). FormHandler needs fix.', E_USER_ERROR);
							}
						  else
						  	{
								$this->fields_arr[$field_name] = $default_value;
								$smartyObj->assign('field_value_'.$field_name, $this->fields_arr[$field_name]);
							}
					}
			}

	   /**
        * Validating the form fields based on the validation_scheme_arr value
        *
        * @return 		void
		* @access 		public
		* @todo			Need to implement the coding for this method
        */
		public function validateFormFields()
			{
				if (isset($this->validation_scheme_arr))
					{
						//Coding the call the validation function based on
						//the value of validation_scheme_arr value
				    }
			}

	   /**
        * Function to get the sanitized form field seperately
        *
        * @return 		string sanitized form field value
		* @access 		public
		* @todo			Need to implement the coding for this method
        */
		public function getSanitizedFormField($field_name)
			{
				return htmlspecialchars(trim($this->fields_arr[$field_name]));
			}

	   /**
        * To check whether the form field value is empty or not
        *
        * By calling this method, we can check the form field value is empty.
        * if it is empty, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name Form field name
		* @param 		string $err_tip Error tip
        * @return 		boolean true/false
		* @access 		public
        */
		public function chkIsNotEmpty($field_name, $err_tip='')
			{
				$is_ok = (is_string($this->fields_arr[$field_name])) ?
								($this->fields_arr[$field_name]!='') : (!empty($this->fields_arr[$field_name]));
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

	   /**
        * To check whether the form field value is numeric
        *
        * If it is numeric, return true otherwise false (does not accept string or real numbers)
        * if it is false, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name
		* @param 		string $err_tip
        * @return 		boolean true/false
		* @access 		public
        */
		public function chkIsNumeric($field_name, $err_tip='')
			{
				$is_ok = ctype_digit($this->fields_arr[$field_name]);
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
		 * To check whether the form field value is real or not
		 *
		 * If it is real, return true otherwise false (does not accept string)
		 * if it is false, the error tip will diplay near the form field
         * with the error tip class
		 *
		 * @param 		string $field_name Form field name
		 * @param 		string $err_tip Error tip
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsReal($field_name, $err_tip='')
			{
				$is_ok = is_numeric($this->fields_arr[$field_name]);
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

	   /**
        * To check whether the form field value is string
        *
        * If it is string, return true otherwise false (does not accept numbers)
        * if it is false, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name form field name
		* @param 		string $err_tip error tip
        * @return 		boolean true/false
		* @access 		public
        */
		public function chkIsAlpha($field_name, $err_tip='')
			{
				$is_ok = ctype_alpha($this->fields_arr[$field_name]);
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

	   /**
        * To check whether the form field value is string or numbers
        *
        * If it is string or numbers, return true otherwise false (does not accept real numbers)
        * if it is false, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name form field name
		* @param 		string $err_tip error tip
        * @return 		boolean true/false
		* @access 		public
        */
		public function chkIsAlphaNumeric($field_name, $err_tip='')
			{
				$is_ok = ctype_alnum($this->fields_arr[$field_name]);
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
		 * To check whether the form field value is not negative
		 *
		 * @param mixed $field_name
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsNotNegative($field_name, $err_tip='')
			{
				$is_ok = $this->fields_arr[$field_name]>=0;
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

	   /**
        * To check the email is valid or not
        *
        * This method is checking the email format for the email field
        * returns true if it is a valid format otherwise returns false
        * if it is false, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name form field name
		* @param 		string $err_tip error tip
		* @param 		string $is_chk_mxrr
        * @return 		boolean true/false
		* @access 		public
		* @todo			check mxrr
        */
		public function chkIsValidEmail($field_name, $err_tip='', $is_chk_mxrr=false)
			{
				$is_ok = (preg_match("/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/i", $this->fields_arr[$field_name]));
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
        * To check the valid date
        *
        * @param 		string $field_name form field name
		* @param 		string $err_tip error tip
        * @return 		boolean true/false
		* @access 		public
        */
		public function chkIsValidDate($field_name, $err_tip='')
			{
				return true;
				$array = explode(' ', $this->fields_arr[$field_name]);
				$date_arr = explode('-', $array[0]);
				$time_arr = array();
				if(isset($array[1]))
					{
						$time_arr = explode(':', $array[1]);
					}
				$is_ok = false;
				if((sizeof($array)==2 or sizeof($array)==1) and sizeof($date_arr)==3 and (sizeof($time_arr)==3 or sizeof($time_arr)==0))
					{
						$is_ok = true;
					}
				if($is_ok)
					{
						if(is_numeric($date_arr[0]) and is_numeric($date_arr[1]) and is_numeric($date_arr[2]) and checkdate($date_arr[1], $date_arr[2], $date_arr[0]))
							$is_ok = true;
						else
							$is_ok = false;
					}
				if($is_ok and sizeof($time_arr)==3)
					{
						if(is_numeric($time_arr[0]) and is_numeric($time_arr[1]) and is_numeric($time_arr[2]) and $time_arr[0]<24 and $time_arr[1]<60 and $time_arr[2]<60)
							$is_ok = true;
						else
							$is_ok = false;
					}
				if(!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsDateGreaterThanNow($field_name, $err_tip = '')
			{
				$sql = 'SELECT IF(DATE_FORMAT(NOW() , \'%Y-%m-%d\')<\''.$this->getFormField($field_name).'\',\'false\',\'true\') AS d';

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

				$row = $rs->FetchRow();

				if($row['d']=='false')
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
						return false;
					}
				return true;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsDateLesserThanNow($field_name, $err_tip = '')
			{
				$sql = 'SELECT IF(DATE_FORMAT(NOW() , \'%Y-%m-%d\')>\''.$this->getFormField($field_name).'\',\'false\',\'true\') AS d';

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

				$row = $rs->FetchRow();

				if($row['d']=='false')
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
						return false;
					}
				return true;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsDateDiff($from_field_name, $to_field_name, $err_tip = '', $err_tip2 = '')
			{
				$sql = 'SELECT IF(\''.$this->getFormField($to_field_name).'\'<\''.$this->getFormField($from_field_name).'\',\'false\',\'true\') AS d';

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

				$row = $rs->FetchRow();
				$err_tip2 = $err_tip2!=''?$err_tip2:$err_tip;
				if($row['d']=='false')
					{
						$this->setFormFieldErrorTip($from_field_name, $err_tip);
						$this->setFormFieldErrorTip($to_field_name, $err_tip2);
						return false;
					}
				return true;
			}

	   /**
        * To check the URL is valid or not
        *
        * This method is checking the URL format for the URL field
        * returns true if it is a valid format otherwise returns false
        * if it is false, the error tip will diplay near the form field
        * with the error tip class
        *
        * @param 		string $field_name form field name
		* @param 		string $err_tip error tip
		* @param 		string $is_chk_real
        * @return 		boolean true/false
		* @access 		public
		* @todo 		improve regex. Add optional param as isvalidemail (real check)
        */
		public function chkIsValidURL($field_name, $err_tip='', $is_chk_real=false)
			{
				if (preg_match("/^[^@]*@[^@]*\.[^@]*$/", $this->fields_arr[$field_name])) {
		            $this->setFormFieldErrorTip($field_name, $err_tip);
		            return false;
		        }
				$is_ok = (preg_match("/^http.+\..+$/i", $this->fields_arr[$field_name]));
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
        * To check the valid size
        *
        * @param 		string $field_name form field name
		* @param 		string $min_size minimum size
		* @param 		string $max_size maximum size
		* @param 		string $err_tip error tip
        * @return 		boolean true/false
		* @access 		public
		* @todo 		improve regex
        */
		public function chkIsValidSize($field_name, $cfg_variable, $err_tip='')
			{
				$size = strlen($this->fields_arr[$field_name]);
				if($size<$this->CFG['fieldsize'][$cfg_variable]['min'] or $size>$this->CFG['fieldsize'][$cfg_variable]['max'])
					{
						$err_tip = str_replace('{min}', $this->CFG['fieldsize'][$cfg_variable]['min'], $err_tip);
						$err_tip = str_replace('{max}', $this->CFG['fieldsize'][$cfg_variable]['max'], $err_tip);
						$this->setFormFieldErrorTip($field_name, $err_tip);
						return false;
					}
				return true;
			}

	   /**
	    * To check the valid format
		*
	    * To check if the field has valid format. Check using regular expression.
	    *
	    * @param 		string $field_name form field name
	    * @param 		string $err_tip Error tip
	    * @param 		string $regex format
        * @return 		boolean true/false
		* @access 		public
	    */
	   public function chkIsValidFormat($field_name, $err_tip='', $regex="")
	   		{
				$is_ok = (preg_match($regex, $this->fields_arr[$field_name]));
				if (!$is_ok)
					{
						$this->setFormFieldErrorTip($field_name, $err_tip);
					}
				return $is_ok;
			}

		/**
        * To get the form field error tip
        *
        * @param 		string $field_name form field name
        * @return 		string
		* @access 		public
        */
		public function setFormFieldErrorTip($field_name, $err_tip = '')
			{
				$this->fields_err_tip_arr[$field_name] = $err_tip;
			}

	   /**
        * To get the form field error tip
        *
        * @param 		string $field_name form field name
        * @return 		string
		* @access 		public
        */
		public function getFormFieldErrorTip($field_name)
			{
				return (isset($this->fields_err_tip_arr[$field_name]) and $this->fields_err_tip_arr[$field_name]) ? '<span class="'.$this->css_class_arr['form_field_err_tip'].'">'.$this->fields_err_tip_arr[$field_name].'</span>' : '';
			}

		/**
		 * To get the form field error for live validation
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getFormFieldElementErrorTip($field_name, $select='')
			{
				$span_id = '';
				if(isset($select) && $select !='')
					$span_id = 'id="selectspan"';
				return (isset($this->fields_err_tip_arr[$field_name]) and $this->fields_err_tip_arr[$field_name]) ? '<span '.$span_id.'class="LV_validation_message LV_invalid">'.$this->fields_err_tip_arr[$field_name].'</span>' : '';
			}

	   /**
        * To check the form inputs are valid
        *
        * If the error tip and error message are not set, returns true
        * otherwise false
        *
        * @return 		boolean 0/1
		* @access 		public
        */
		public function isValidFormInputs()
			{
				return (!$this->fields_err_tip_arr && !$this->common_error_message); //or !count($this->fields_err_tip_arr) && !$this->common_error_message;
			}

		/**
		 * To set the array of months
		 *
		 * @param 		array $months_list_arr array of months
		 * @param 		array $first_option_arr default selected value
		 * @return 		void
		 * @access 		public
		 */
		public function setMonthsListArr($months_list_arr, $first_option_arr=array())
			{
				$this->months_list_arr = $first_option_arr + $months_list_arr;
			}

		/**
		 * To populate the array months list
		 *
		 * @param 		integer $highlight_m high lighted month
		 * @return 		void
		 * @access 		public
		 */
		public function populateMonthsList($highlight_m)
			{
				foreach($this->months_list_arr as $key=>$month_name)
					{
?>
	<option value="<?php echo $key;?>"<?php echo ($highlight_m==$key)? ' selected="selected"' : '';?>><?php echo $month_name;?></option>
<?php
					}
			}

		/**
		 * To set the minium and maximum year list
		 *
		 * @param 		integer $min_year minimum year
		 * @param 		integer $max_year maximum year
		 * @return		void
		 * @access 		public
		 */
		public function setYearsListMinMax($min_year, $max_year)
			{
				$this->years_list_config['min_year'] = $min_year;
				$this->years_list_config['max_year'] = $max_year;
			}

		/**
		 * To populate the year list
		 *
		 * @param 		integer $highlight_y high lighted year
		 * @return 		void
		 * @access 		public
		 */
		public function populateYearsList($highlight_y)
			{
				for($y=$this->years_list_config['min_year']; $y<=$this->years_list_config['max_year']; ++$y)
					{
?>
	<option value="<?php echo $y;?>"<?php echo($highlight_y==$y)? ' selected="selected"' : '';?>><?php echo $y;?></option>
<?php
					}
			}

		/**
		 * FormHandler::setDBObject()
		 * To connect database
		 *
		 * @param $dbObj
		 * @return
		 **/
		public function setDBObject($dbObj)
			{
				$this->dbObj = $dbObj;
			}

		/**
		 * To include header in all pages
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function includeHeader($assign_var = true)
			{
				global $CFG, $LANG, $WIDGET_LANG, $smartyObj;
				if($assign_var)
					{
						$this->assignSmartyVariables();
					}
				$CFG['mods']['is_include_only']['html_header'] = true;
				$CFG['html']['is_use_header'] = true;
				require($CFG['site']['project_path'].'common/application_top.inc.php');
			}

		/**
		 * To include header for ajax pages
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function includeAjaxHeader($assign_var = true)
			{
				global $CFG, $smartyObj;
				if($assign_var)
					{
						$this->assignSmartyVariables();
					}
				setHeaderStart();
			}

		/**
		 * To include footer for all pages
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function includeFooter()
			{
				global $CFG, $LANG, $WIDGET_LANG, $smartyObj, $DEBUG_TRACE, $SQL_QUERIES;
				require_once($this->CFG['site']['project_path'].'common/application_bottom.inc.php');
			}

		/**
		 * To include footer for ajax pages
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function includeAjaxFooter()
			{
				setHeaderEnd();
				exit;
			}

		/**
		 * FormHandler::setDBObject()
		 * contain all header and common functions
		 *
		 * @param $headerfrm
		 * @return
		 **/
		public function setHeaderObject($headerfrm)
			{
				$this->headerfrm = $headerfrm;
			}

		/**
		 * FormHandler::makeGlobalize()
		 * make globalize the $CFG and $LANG
		 *
		 * @param array $CFG
		 * @param array $LANG
		 * @return
		 **/
		public function makeGlobalize($CFG = array(), $LANG = array())
			{
				$this->CFG = $CFG;
				$this->LANG = $LANG;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function populateHidden($hidden_field)
			{
				foreach($hidden_field as $hidden_name)
					{
?>
						<input type="hidden" name="<?php echo $hidden_name;?>" id="<?php echo $hidden_name;?>" value="<?php echo isset($this->fields_arr[$hidden_name])?$this->fields_arr[$hidden_name]:'';?>" />
<?php
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function generalPopulateArray($list, $highlight_value='')
			{
				foreach($list as $key=>$value)
					{
						$selected = $highlight_value == $key?' selected':'';
?>
<option value="<?php echo $key;?>"<?php echo $selected;?>><?php echo $value;?></option>
<?php
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function populateBWNumbers($start_no, $end_no, $highlight_value='')
			{
				$populateBWNumbers_val = '';
				if ($start_no>$end_no)
					{
						for($start_no;$start_no>=$end_no;$start_no--)
							{
								$selected = $highlight_value == $start_no?' selected':'';
								$populateBWNumbers_val .= '<option value="'.$start_no.'"'.$selected.'>'.$start_no.'</option>';
							}
				    }
				else
					{
						for($start_no;$start_no<=$end_no;$start_no++)
							{
								$selected = $highlight_value == $start_no?' selected':'';
								$populateBWNumbers_val .= '<option value="'.$start_no.'"'.$selected.'>'.$start_no.'</option>';
							}
					}
				return $populateBWNumbers_val;
			}

		/**
		 * FormHandler::isCheckedCheckBox()
		 *
		 * @param $field_name
		 * @return
		 **/
		public function isCheckedCheckBox($field_name)
			{
				if($this->fields_arr[$field_name])
					return ' checked';
			}

		/**
		 * FormHandler::isCheckedCheckBox()
		 *
		 * @param $field_name
		 * @return
		 **/
		public function isCheckedCheckBoxArray($field_name, $value)
			{
				if(in_array($value,$this->fields_arr[$field_name]))
					return ' checked';
			}

		/**
		 * FormHandler::isCheckedRadio()
		 *
		 * @param $field_name
		 * @param $value
		 * @return
		 **/
		public function isCheckedRadio($field_name, $value)
			{
				if($this->fields_arr[$field_name] == $value)
					return ' checked';
			}

		/**
		 * FormHandler::ShowHelpTip()
		 *
		 * @param $tip_key
		 * @param $tip_for
		 * @return
		 **/
		public function ShowHelpTip($tip_key = '', $tip_for = '')
			{
				ShowHelpTip($tip_key, $tip_for);
			}
		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function isFavoriteContent($cid, $ctype)
		    {
				$sql = 'SELECT bookmark_id FROM '.$this->CFG['db']['tbl']['user_bookmarked'].
						' WHERE content_id = '.$this->dbObj->Param('content_id') .' AND'.
						' content_type = '.$this->dbObj->Param('content_type').' AND'.
						' user_id = '.$this->dbObj->Param('user_id');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cid, $ctype, $this->CFG['user']['user_id']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$ok = false;
				if ($rs->PO_RecordCount())
					$ok = true;
				return $ok;
		    }
		/**
		 * FormHandler::populateRichTextEdit()
		 *
		 * @param $field_name
		 * @param $value
		 * @param $useHtmlSpChars
		 * @return
		 **/
		public function populateHtmlEditor($field_name='')
			{
				switch($this->CFG['feature']['html_editor'])
					{
						case 'richtext':
							populateRichTextEdit($field_name, $this->getFormField($field_name), $this->isValidFormInputs());
							break;

						case 'fckeditor':
							fckEditor($field_name, $this->getFormField($field_name), $this->isValidFormInputs());
							break;
					}
			}

		/**
		 * FormHandler::getUrl()
		 *
		 * @param $file_name
		 * @param $normal
		 * @param $htaccess
		 * @param $change
		 * @return
		 **/
		public function getUrl($file_name, $normal = '', $htaccess = '', $change = 'current')
			{
				return getUrl($file_name, $normal, $htaccess, $change);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getCurrentUrl($with_query_string = false)
			{
				return getCurrentUrl($with_query_string);
			}

		public function getTpl($folder, $file, $module='')
			{
				global $smartyObj;
				global $CFG;
				global $LANG;
				if($module)
					{
						$filePath=$this->CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.$folder.'/'.$file;
						if(!file_exists($filePath))
							{
								$module='';
							}
					}
				setTemplateFolder($folder.'/',$module);
				$smartyObj->display($file);
			}
		/**
		 * FormHandler::populateCalendar()
		 *
		 * @param $textbox_id
		 * @param $button_id
		 * @param $show_time
		 * @return
		 **/
		public function populateCalendar($textbox_id, $button_id, $show_time = false)
			{
				$format = $show_time?$this->CFG['php_format']['date_time']:$this->CFG['php_format']['date'];
				$show_time = $show_time?'true':'false';
?>
<script type="text/javascript">
    Calendar.setup({
        inputField     :    "<?php echo $textbox_id;?>",    // id of the input field
        ifFormat       :    "<?php echo $format;?>",  		// format of the input field
        showsTime      :    <?php echo $show_time;?>, 		// will display a time selector
        button         :    "<?php echo $button_id;?>",   	// trigger for the calendar (button ID)
        singleClick    :    true,           				// double-click mode
        step           :    1                				// show all years in drop-down boxes (instead of every other year as default)
    });
</script>
<?php
			}

		/**
		 * FormHandler::fetchCached()
		 *
		 * @param $cache_id
		 * @param $life_time
		 * @return
		 **/
		public function fetchCached($cache_id, $life_time = 60)
			{
				if($this->CFG['feature']['data_cache']['mechanism'] == 'agcache')
					{
						$result = AgCache::fetch($cache_id, $life_time);
					}
				if($result)
					{
						if ($this->CFG['feature']['data_cache']['compress'] and isset($_SERVER['HTTP_ACCEPT_ENCODING']) and strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
							{
								$result = gzuncompress($result);
							}
						$result = unserialize($result);
					}
				return $result;
			}

		/**
		 * FormHandler::saveCached()
		 *
		 * @param $cache_id
		 * @param $content
		 * @return
		 **/
		public function saveCached($cache_id, $content)
			{
				$content = serialize($content);
				if ($this->CFG['feature']['data_cache']['compress'] and isset($_SERVER['HTTP_ACCEPT_ENCODING']) and strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
					{
						$content = gzcompress($content, $this->CFG['feature']['data_cache']['compress_level']);
					}
				if($this->CFG['feature']['data_cache']['mechanism'] == 'agcache')
					{
						AgCache::save($cache_id, $content);
					}
			}

		/**
		 * FormHandler::getSwiftConnection()
		 *
		 * @return
		 **/
		public function getSwiftConnection()
		 	{
				Swift_LogContainer::getLog()->setLogLevel(Swift_Log::LOG_EVERYTHING);
			    switch ($this->CFG['admin']['mailer']['mailer'])
				    {
				      case "smtp":
				        $enc = null;
				        $test_enc = $this->CFG['admin']['mailer']['smtp_encryption'];
				        if ($test_enc == "ssl") $enc = Swift_Connection_SMTP::ENC_SSL;
				        elseif ($test_enc == "tls") $enc = Swift_Connection_SMTP::ENC_TLS;
				        $conn = new Swift_Connection_SMTP($this->CFG['admin']['mailer']['host'], $this->CFG['admin']['mailer']['port'], $enc);
				        if ($user = $this->CFG['admin']['mailer']['username']) $conn->setUsername($user);
				        if ($pass = $this->CFG['admin']['mailer']['password']) $conn->setPassword($pass);
				        return $conn;
				      case "sendmail":
				        $conn = new Swift_Connection_Sendmail($this->CFG['admin']['mailer']['sendmail_path']);
				        return $conn;
				      case "nativemail":
				        $conn = new Swift_Connection_NativeMail();
				        return $conn;
				    }
		  	}

		/**
		 * FormHandler::getTabIndex()
		 *
		 * @return
		 **/
		public function getTabIndex()
			{
				return $this->tab_index += 5;
			}

		/**
		 * Verifies the date value
		 *
		 * @param string $date date
		 * @param string $month month
		 * @param string $year year
		 * @param string $field form field for the date
		 * @param $err_tip error tip
		 * @return
		 **/
		public function chkIsCorrectDate($date=0, $month=0, $year=0, $date_field='', $err_tip_empty='', $err_tip_invalid='')
			{
				if (empty($date) or empty($month) or empty($year))
				    {
						$this->fields_err_tip_arr[$date_field] = $err_tip_empty;
						return false;
				    }
				if (checkdate(intval($month), intval($date), intval($year)))
				    {
					  	$month = (strlen($month) < 2)? '0'.$month : $month;
					  	$date = (strlen($date) < 2)? '0'.$date : $date;
					  	$this->fields_arr[$date_field] = $year.'-'.$month.'-'.$date;
				       	$ok = true;
				    }
					else
						{
							$this->fields_err_tip_arr[$date_field] = $err_tip_invalid;
							$ok = false;
						}
				return $ok;
			}

		/**
		 * FormHandler::setUserDetails()
		 *
		 * @param $column_name
		 * @param $column_value
		 * @return
		 **/
		public function setUserDetails($column_name, $column_value)
			{
				global $CFG;
				if(!$column_value)
					{
						return false;
					}
				if(isset($CFG['user_details'][$column_value]))
					{
						return;
					}
				$condition = ' AND usr_status!=\'Deleted\'';

				$sql = 'SELECT * FROM '.$this->CFG['db']['tbl']['users'].' WHERE'.
						' '.$column_name.' = '.$this->dbObj->Param('column_name').$condition;

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

				if($row = $rs->FetchRow())
					{
						$row['display_name'] = getUserDisplayName($row);
						$CFG['user_details'][$row['name']] = $row;
						$CFG['user_details'][$row['user_id']] = $row;
						$CFG['user_details'][$row['email']] = $row;
						return true;
					}
				$CFG['user_details'][$column_value] = '';
				return false;
			}

		/**
		 * FormHandler::getUserDetail()
		 *
		 * @param $user_unique_identifier
		 * @param $column_name
		 * @param $column_value
		 * @param $return_column_name
		 * @return
		 **/
		public function getUserDetail($column_name, $column_value, $return_column_name = '')
			{
				global $CFG;
				$column_name = strtolower($column_name);
				//$column_value = strtolower($column_value);

				if(!isset($CFG['user_details'][$column_value]))
					{
						$this->setUserDetails($column_name, $column_value);
					}
				if(isset($CFG['user_details'][$column_value]))
					{
						if(!$return_column_name)
							{
								return $CFG['user_details'][$column_value];
							}
						else if(isset($CFG['user_details'][$column_value][$return_column_name]))
							{
								return $CFG['user_details'][$column_value][$return_column_name];
							}
					}
				return false;
			}
		public function getDefaultCssUrl($file='',$module='')
			{
				global $smartyObj;
				global $CFG;

				if($file)
					{
						$CFG['html']['stylesheet']['screen']['default_file']=$file;
					}
				else
					{
						$file=$CFG['html']['stylesheet']['screen']['default_file'];
					}
				if($module)
					{
						$cssPath=$CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/root/css/'.$CFG['html']['stylesheet']['screen']['default'].'/'.$file.'.css';
						//$memberCssPath=$CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/members/css/'.$file.'.css';

						if(!file_exists($cssPath)) //|| !file_exists($memberCssPath))
							{
								$module='';
							}
					}

				setTemplateFolder('root/',$module);
				echo $smartyObj->css_defalut_path;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getTableData($text)
			{
				return ($text!='')?nl2br($text):'&nbsp;';
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function includeJSLanguageFile()
			{
				$cache_file_name = 'jslanguage_'.$this->CFG['lang']['default'];
				$language = $this->fetchCached($cache_file_name, $this->CFG['javascript']['language_cache_time']);
				if(!$language)
					{
						require_once($this->CFG['site']['project_path'].'languages/'.$this->CFG['lang']['default'].'/general/js.php');
						$language .= 'var JS_LANG = new Array();';
						foreach($LANG['js'] as $key=>$value)
							{
								$language .= 'JS_LANG[\''.$key.'\'] = \''.addslashes($value).'\';';
							}
						$this->saveCached('$cache_file_name', $language);
					}
				echo '<script language="javascript" type="text/javascript">'.$language.'</script>';
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkAllowedModule($module = array())
			{
				if($this->CFG['feature']['phpgacl_module_control'])
					{
						foreach($module as $key=>$value)
							{
								if(!$this->aclCheck($value))
									{
										return false;
									}
							}
						return true;
					}
				return chkAllowedModule($module);
			}

		/**
		 * To get unread mail in inbox
		 *
		 * @access public
		 * @return void
		 **/
		public function countUnReadMail()
			{
				$sql = 'SELECT COUNT( mi.info_id ) AS mail_count'.
						' FROM '.$this->CFG['db']['tbl']['messages'].' AS ms,'.
						' '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
						' WHERE mi.to_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
						' AND mi.message_id = ms.message_id'.
						' AND mi.to_viewed = \'No\''.
						' AND mi.to_delete = \'No\''.
						' AND mi.to_stored = \'No\'';

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

				$row = $rs->FetchRow();

				return $row['mail_count'];
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayCompulsoryIcon()
			{
?>
<span class="clsCompulsory">*</span>
<?php
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayProfileImage($img_arr, $img_type, $showPopup = true, $contentDisplay = false)
			{
				displayProfileImage($img_arr, $img_type, $showPopup, $contentDisplay);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayBlogUserSmallImage($img_arr, $showPopup = true)
		    {
				$this->displayProfileImage($img_arr, 'tiny', $showPopup);
		    }

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function insertUsersAnswerLog()
			{
				if (isset($_SESSION['is_user_log_available']))
					return ;

				$uid = $this->CFG['user']['user_id'];
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['users_ans_log'].
						' WHERE 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())
					{
						$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['users_ans_log'].
								' SET 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);
					}

				//To know points for viewing updated
				$_SESSION['is_user_log_available'] = true;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function insertAdvanceSearch()
			{
				if (isset($_SESSION['is_advance_search_available']))
					return ;

				$uid = $this->CFG['user']['user_id'];
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['advanced_search'].
						' WHERE 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())
					{
						$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['advanced_search'].
								' SET 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);
					}

				//To know points for viewing updated
				$_SESSION['is_advance_search_available'] = true;
			}
		/**
		 * chkIsValidUrlNew()
		 *
		 * @param $field
		 * @param $err_tip
		 * @return
		 **/
		public function chkIsValidUrlNew($field, $err_tip = '')
			{
				if(!strstr($this->fields_arr[$field], '://'))
					$this->fields_arr[$field] = 'http://'.$this->fields_arr[$field];

				if (function_exists('curl_init'))
					{
						$ch = @curl_init();
						if ($ch)
						    {
								curl_setopt($ch, CURLOPT_URL, $this->getFormField($field));
								curl_setopt($ch, CURLOPT_HEADER, 0);
								curl_setopt($ch, CURLOPT_NOBODY, 1);
								curl_setopt($ch, CURLOPT_RANGE, "0-1");
								curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
								curl_setopt($ch, CURLOPT_TIMEOUT, 10);
								$result = curl_exec($ch);
								$errno = curl_errno($ch);
								curl_close($ch);
								if ($errno!=0)
									{
										$this->setFormFieldErrorTip($field, $err_tip);
										return false;
									}
						    }
					}
				return true;
			}

		public function formatPlayingTime($duration)
			{
				$min = floor($duration/60);
				$sec = round($duration-($min*60));
				$min = str_pad($min, 2, '0', STR_PAD_LEFT);
				$sec = str_pad($sec, 2, '0', STR_PAD_LEFT);
				return $min.':'.$sec;
			}

		/**
		 * changeArrayToCommaSeparator()
		 *
		 * @param array $arry_value
		 * @return
		 **/
		public function changeArrayToCommaSeparator($arry_value = array())
			{
				return implode(',',$arry_value);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */

		public function chkIsValidAudioUrl($field_name, $err_tip = '')
			{
				$this->audio_url = $this->fields_arr[$field_name];
				return true;
			}


		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function updateUsersAnswerLog()
		    {
				if (!isset($this->CFG['user']['user_id']) or empty($this->CFG['user']['user_id']) or (!$this->CFG['admin']['view_answers']['allowed']) or (isset($_SESSION['view_answers_points'])))
					return false;

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_points=total_points+'.$this->CFG['admin']['view_answers']['points'].','.
						' date_updated=NOW(), date_viewed=NOW()'.
						' WHERE user_id='.$this->dbObj->Param('uid').
						' AND DATEDIFF(DATE_FORMAT(date_viewed, \'%Y-%m-%d\'), DATE_FORMAT(NOW(), \'%Y-%m-%d\')) != 0';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				//To know points for viewing updated
				$_SESSION['view_answers_points'] = true;

				if ($this->dbObj->Affected_Rows())
					{
						return true;
					}
				return false;
		    }

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getUserOptions()
			{
				$user_options = array('recent_questions'=>'yes', 'best_answered_questions'=>'yes',
									  'popular_questions'=>'yes', 'recently_answered'=>'yes',
									  'recent_forums'=>'yes', 'recent_blogs'=>'yes', 'featured_analyst'=>'yes',
									  'popular_videos'=>'yes', 'recent_debates'=>'yes', 'popular_debates'=>'yes');
				if ($uid = $this->CFG['user']['user_id'])
					{
						$sql = 'SELECT index_block FROM '.$this->CFG['db']['tbl']['users_ans_log'].
								' WHERE 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())
							{
								$row = $rs->FetchRow();
								if ($row['index_block'])
									{
										$index_blocks = unserialize($row['index_block']);
										foreach($index_blocks as $block=>$value){
											$user_options[$block] = $value;
										}
									}
							}
					}
				return $user_options;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getUserTableFields($user_fields, $trim=true)
		    {
				$str = '';
				foreach($user_fields as $field){
					if (isset($this->CFG['users'][$field]) AND $this->CFG['users'][$field])
						$str .= $this->CFG['users'][$field].' AS '.$field.', ';
				}
				if ($trim)
					$str = substr($str, 0, strrpos($str, ', '));
				return $str;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getUserTableField($user_field)
		    {
				return $this->CFG['users'][$user_field];
		    }

		/**
		 * get username for user_id
		 *
		 * @param 		string $user_table
		 * @param 		integer $user_id
		 * @return 		string
		 * @access 		public
		 */
		public function getUserDetailsFromUsersTable($user_table, $user_id)
			{
				if (isset($this->_cache_user_details[$user_id]))
					{
						return $this->_cache_user_details[$user_id];
					}

				$sql = 'SELECT '.$this->getUserTableFields(array('user_id', 'name', 'display_name', 'email', 'image_path', 'bio', 'gender', 'usr_status', 'user_access', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext', 'usr_type', 'expiry_date', 'last_paid_date', 'signup_type', 'receipt_id', 'payment_gateway')).
						', '.$this->getUserTableField('user_id').' AS img_user_id'.
						' FROM '.$user_table.
						' WHERE '.$this->getUserTableField('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('name'=>'', 'display_name'=>'', 'email'=>'', 'image_path'=>'', 'gender'=>'', 'usr_status'=>'', 'user_access'=>'', 'img_user_id'=>'', 't_height'=>'', 't_width'=>'', 's_height'=>'', 's_width'=>'', 'photo_server_url'=>'', 'photo_ext'=>'', 'usr_type'=>'', 'expiry_date'=>'', 'last_paid_date'=>'', 'signup_type'=>'', 'receipt_id'=>'', 'payment_gateway'=>'');
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
					}

				//cache user detalis
				$this->_cache_user_details[$user_id] = $row;

				return	$row;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getUserLog($user_id)
			{
				if (isset($this->_cache_user_log_details[$user_id]))
					{
						return $this->_cache_user_log_details[$user_id];
					}
				$sql = 'SELECT total_ques, total_ans, total_points, total_best_ans, total_debates, total_debate_response'.
						', DATE_FORMAT(date_updated,\'%D %b %Y\') as date_updated'.
						' FROM '.$this->CFG['db']['tbl']['users_ans_log'].
						' 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);
				$user_ans_log = array('total_ques'=>'0', 'total_ans'=>'0', 'total_points'=>'0', 'date_updated'=>'');
				if ($rs->PO_RecordCount())
					$user_ans_log = $rs->FetchRow();

				//cache user log details
				$this->_cache_user_log_details[$user_id] = $user_ans_log;

				return $user_ans_log;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function ShowToolTip($tip)
			{
				return ShowToolTip($tip);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsAllowedModule($module_arr = array())
			{
				return chkIsAllowedModule($module_arr);
			}


		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayTopAnalystSmallImage($img_arr, $showPopup = true, $contentDisplay = false)
			{
				displayTopAnalystSmallImage($img_arr, 'small', $showPopup, $contentDisplay);
				return ;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayForumUserSmallImage($img_arr, $showPopup = true, $contentDisplay = false, $changePosition = false)
			{
				displayProfileImage($img_arr, 'tiny', $showPopup, $contentDisplay, $changePosition);
				return ;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function displayTopAnalystTinyImage($img_arr, $showPopup = true, $contentDisplay = false)
		    {
		    	displayProfileImage($img_arr, 'tiny', $showPopup, $contentDisplay);
				return ;
		    }

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getForumTitle($forum_id)
			{
				$sql = 'SELECT seo_title AS title FROM '.$this->CFG['db']['tbl']['forums'].
						' WHERE forum_id='.$this->dbObj->Param($forum_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($forum_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					return false;
				$row = $rs->FetchRow();
				return $row['title'];
			}

		/**
		 * Function to create week top analysts
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function createWeekExperts()
			{
				$sql = 'SELECT TIMEDIFF(NOW(), date_added) time_diff FROM '.$this->CFG['db']['tbl']['view_weekly_experts'].
						' LIMIT 0, 1';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$time_diff = explode(':', $row['time_diff']);
						$mins_after_created = ($time_diff[0]*60)+($time_diff[1]);
						$mins_after_created = ($time_diff[2])?($mins_after_created+1):$mins_after_created;
						if ($mins_after_created < $this->CFG['admin']['week_experts']['refresh'])
							{
								return ;
							}
					}

				$sql = 'CREATE OR REPLACE VIEW view_ques_expert AS'.
						' SELECT COUNT( ques_id ) AS \'total_count\', user_id,'.
						' (COUNT( ques_id ) * '.$this->CFG['admin']['ask_answers']['points'].') AS \'points\''.
						' FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE DATE_ADD(date_asked, INTERVAL 7 DAY) >= NOW()'.
						' GROUP BY user_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);

				$sql = 'CREATE OR REPLACE VIEW view_ans_expert AS'.
						' SELECT COUNT( ans_id ) AS \'total_count\', user_id,'.
						' (COUNT( ans_id ) * '.$this->CFG['admin']['reply_answers']['points'].') AS \'points\''.
						' FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE DATE_ADD(date_answered, INTERVAL 7 DAY) >= NOW()'.
						' GROUP BY user_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$sql = 'CREATE OR REPLACE ALGORITHM=MERGE VIEW view_experts AS'.
						' SELECT * FROM view_ques_expert UNION ALL SELECT * FROM view_ans_expert';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$sql = 'TRUNCATE TABLE '.$this->CFG['db']['tbl']['view_weekly_experts'];
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['view_weekly_experts'].
						' SELECT user_id, SUM(points) AS \'week_points\', NOW() FROM view_experts GROUP BY user_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function isShowIndexBlock($block, $userAllowed='yes')
			{
				$ok = true;
				switch($block){
					case 'no':
						$ok = false;
						break;
					case 'yes':
						if ($userAllowed != 'yes')
							$ok = false;
						break;
				} // switch
				return $ok;
			}
		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function checkAndRenameString($table_name, $primary_key_field, $to_field_name, $str)
			{
				$sql_sub_sub = 'SELECT COUNT('.$primary_key_field.') as cnt FROM '.$table_name.' WHERE
								'.$to_field_name.' = '.$this->dbObj->Param($str);

				$stmt_sub_sub = $this->dbObj->Prepare($sql_sub_sub);
				$rs_sub_sub = $this->dbObj->Execute($stmt_sub_sub, array($str));
				//raise user error... fatal
				if (!$rs_sub_sub)
						trigger_db_error($this->dbObj);
				$row_sub_sub = $rs_sub_sub->FetchRow();
				if ($row_sub_sub['cnt'] > 0)
					return true;
				return false;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoName($table_name, $primary_key_field, $to_field_name, $str_to_convert)
			{
				$temp_str = $to_str = $str_to_convert;
				if ($check = $this->checkAndRenameString($table_name, $primary_key_field, $to_field_name, $to_str))
				{
					$i = 0;
					while(true)
						{
							$to_str = $temp_str.'-'.++$i;
							if (!$this->checkAndRenameString($table_name, $primary_key_field, $to_field_name, $to_str))
								break;
						}
				}
				return $to_str;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitleForForum($forum_title = '', $forum_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['forums'], 'forum_title' ,$forum_title , 'forum_id', $forum_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitleForQuestion($question = '', $ques_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['questions'], 'question' ,$question , 'ques_id', $ques_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitleForQuestionCategory($cat_name = '', $cat_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['questions_category'], 'cat_name' ,$cat_name , 'cat_id', $cat_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitleForForumTopic($forum_topic = '', $topic_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['forum_topics'], 'forum_topic' ,$forum_topic , 'topic_id', $topic_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function populateForumDetails($topic_id)
			{
				$sql = 'SELECT forum_id, total_response, forum_topic, seo_title, user_id'.
						' FROM '.$this->CFG['db']['tbl']['forum_topics'].
						' WHERE topic_id = '.$this->dbObj->Param('topic_id');

				$stmt = $this->dbObj->Prepare($sql);

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

				if($row = $rs->FetchRow())
					{
						$sql = 'SELECT seo_title AS title FROM '.$this->CFG['db']['tbl']['forums'].
								' WHERE forum_id='.$this->dbObj->Param('forum_id');
						$stmt = $this->dbObj->Prepare($sql);

						$rs = $this->dbObj->Execute($stmt, array($row['forum_id']));
						if (!$rs)
							    trigger_db_error($this->dbObj);
						if (!$rs->PO_RecordCount())
							return false;
						$row_forum = $rs->FetchRow();
						$row['title'] = $row_forum['title'];
						return $row;
					}
				return false;
			}

       	/**
       	 * FormHandler::getSeoTitleForStaticPage()
       	 *
       	 * @param string $pagename
       	 * @param integer $page_id
       	 * @return
       	 */
       	public function getSeoTitleForStaticPage($pagename = '', $page_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['static_pages'], 'page_title' ,$pagename , 'page_id', $page_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function setFontSizeInsteadOfSearchCount($tag_array=array())
			{
				$formattedArray = $tag_array;
				$max_qty = max(array_values($formattedArray));
				$min_qty = min(array_values($formattedArray));
				$max_font_size = 28;
				$min_font_size = 12;
				$spread = $max_qty - $min_qty;
				if (0 == $spread) { // Divide by zero
					$spread = 1;
				}
				$step = ($max_font_size - $min_font_size)/($spread);
					foreach ($tag_array as $catname => $count)
					{
						$size = $min_font_size + ($count - $min_qty) * $step;
						$formattedArray[$catname] = ceil($size);
					}
				return $formattedArray;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function isAllowedToAsk()
		    {
				$uid = $this->CFG['user']['user_id'];
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['users_ans_log'].
						' WHERE user_id='.$this->dbObj->Param($uid).' AND is_blocked=\'No\'';
				$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;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function fckEditor($field_name='', $value='', $useHtmlSpChars = true)
			{
				fckEditor($field_name, $value, $useHtmlSpChars);
				return ;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function addThisOption()
			{
				addThisOption();
				return ;
			}


		/**
		 * To replace the email content
		 *
		 * @param 		string $content
		 * @param 		array $fieldsArr // should contain values in order
		 * @return		string $content
		 * @access 		public
		 */
		public function getMailContent($content, $fieldsArr)
			{
				$chkArray = array('VAR_FORUM', 'VAR_TOPIC', 'VAR_BLOG', 'VAR_COMMENT', 'VAR_EMAIL','VAR_PASSWORD','VAR_DISPLAYNAME','VAR_USERNAME','VAR_QUESTION','VAR_SITENAME', 'VAR_LINK', 'VAR_SENDER_NAME', 'VAR_SENDER_COMMENT', 'VAR_DESCRIPTION_OF_QUESTION', 'VAR_DESCRIPTION_OF_BLOG', 'VAR_DESCRIPTION_OF_FORUM', 'VAR_DESCRIPTION_OF_COMMENT', 'VAR_DEBATE', 'VAR_DESCRIPTION_OF_DEBATE');
				foreach($chkArray as $value)
					{
						$toReplace = $value;
						if(array_key_exists($value, $fieldsArr))
							$content = str_ireplace($toReplace, $fieldsArr[$value], $content);
						else
							$content = str_ireplace($toReplace, '', $content);
					}
				return $content;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getTimeDiffernceFormat($time)
			{
				return getTimeDiffernce($time);
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getTimeToGoFormat($time)
			{
				global $LANG;
				$date_added_pc = explode(':', $time);

				$date_added_pc[0] = intval($date_added_pc[0]);
				$date_added_pc[1] = intval($date_added_pc[1]);
				$date_added_pc[2] = intval($date_added_pc[2]);

				if($date_added_pc[0])
					{
						$day = floor($date_added_pc[0]/24);
						if($day>365)
							{
								$year = floor($day/365);
								if($year == 1)
									$time = $year.' '.$LANG['year_left_to_answer'];
								else
									$time = $year.' '.$LANG['years_left_to_answer'];
							}
						else if($day>30)
							{
								$month = floor($day/30);
								if($month == 1)
									$time = $month.' '.$LANG['month_left_to_answer'];
								else
									$time = $month.' '.$LANG['months_left_to_answer'];
							}
						else if($day)
							{
								if($day == 1)
									$time = $day.' '.$LANG['day_left_to_answer'];
								else
									$time = $day.' '.$LANG['days_left_to_answer'];
							}
						else
							{
								if($date_added_pc[0] == 1)
									$time = $date_added_pc[0].' '.$LANG['hour_left_to_answer'];
								else
									$time = $date_added_pc[0].' '.$LANG['hours_left_to_answer'];
							}
					}
				else if($date_added_pc[1])
					{
						if($date_added_pc[1] == 1)
							$time = $date_added_pc[1].' '.$LANG['minute_left_to_answer'];
						else
							$time = $date_added_pc[1].' '.$LANG['minutes_left_to_answer'];
					}
				else
					{
						if($date_added_pc[2] == 1)
							$time = $date_added_pc[2].' '.$LANG['second_left_to_answer'];
						else
							$time = $date_added_pc[2].' '.$LANG['seconds_left_to_answer'];
					}
				return $time;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function removeDuplicateKeywords($keywords)
			{
				$not_allowed_search_array = $this->CFG['admin']['not_allowed_chars'];
				$keywords = replaceCharacter($not_allowed_search_array, '', $keywords);
				$keywords_arr = explode(' ', $keywords);
				$keywords_arr = array_unique($keywords_arr);
				foreach($keywords_arr as $key=>$value)
					{
						$len = strlen($value);
						if(!($len>=$this->CFG['admin']['tag_min_size'] and $len<=$this->CFG['admin']['tag_max_size']))
							unset($keywords_arr[$key]);
					}
				$keywords = implode(' ', $keywords_arr);
				return trim($keywords);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getUsersDisplayName($name)
			{
				$sql = 'SELECT '.$this->getUserTableField('display_name').
						' FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE '.$this->getUserTableField('name').' = '.$this->dbObj->Param($name);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($name));
				if (!$rs)
						trigger_db_error($this->dbObj);
				$display_name = '';
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$display_name = $row['display_name'];
					}
				return	$display_name;
			}

		/**
		 * FormHandler::chkAndCreateFolder()
		 * if the parent directiory not there means surely not child directory for that only use the mode
		 * inorder to avoid to call the anothere function
		 *
		 * @param string $folderName
		 * @return void
		 * @access public
		 **/
		public function chkAndCreateFolder($folderName)
			{
				$folder_arr = explode('/', $folderName);
				$folderName = '';
				foreach($folder_arr as $key=>$value)
					{
						$folderName .= $value.'/';
						if($value == '..' or $value == '.')
							continue;
						if (!is_dir($folderName))
							{
								mkdir($folderName);
								@chmod($folderName, 0777);
							}
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function removeDirectory($dirname)
			{
				if (is_dir($dirname))
			   		{
				       	$result = array();
				   		if (substr($dirname,-1) != '/')
							{
								$dirname.='/';
							}
					  	$handle = opendir($dirname);
					    while (false !== ($file = readdir($handle)))
						   {
					   			if ($file != '.' && $file != '..')
							   		{    //Ignore . and ..
						               $path = $dirname.$file;
						               	if (is_dir($path))
									   		{    //Recurse if subdir, Delete if file
						                   		$result=array_merge($result, $this->removeDirectory($path));
						            		}
										else
											{
								            	unlink($path);
								                $result[].=$path;
					               			}
				           			}
			       			}
					     closedir($handle);
					     rmdir($dirname);
					     $result[].=$dirname;
					     return $result;
			   		}
				else
					{
				       return false;
				   	}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getBrowser($id='', $height='')
			{
				return getBrowser($id, $height);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitleForBlogs($subject = '', $blog_id = 0)
			{
				return $this->getSeoTitle($this->CFG['db']['tbl']['blogs'], 'subject' ,$subject , 'blog_id', $blog_id);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function isIgnoredUser($cid)
			{
				$uid = $this->CFG['user']['user_id'];
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['user_ignored'].
						' WHERE user_id='.$this->dbObj->Param($uid).
						' AND ignored_id='.$this->dbObj->Param($cid);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid, $cid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$ok = false;
				if ($rs->PO_RecordCount())
					$ok = true;
				return $ok;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsIntenalMailAllowed($user_id)
			{
				$sql = 'SELECT internal_mail FROM '.$this->CFG['db']['tbl']['users_ans_log'].
						' 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);
				$ok = true;
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						if ($row['internal_mail'] == 'No' or !$this->CFG['admin']['module']['mail'])
							$ok = false;
					}
				return $ok;
			}

		/**
		 * get user details user_id
		 *
		 * @param 		integer $user_id
		 * @return 		string
		 * @access 		public
		 */
		public function getUserDetails($user_id)
			{
				if (isset($this->_cache_user_details[$user_id]))
					{
						return $this->_cache_user_details[$user_id];
					}

				$sql = 'SELECT '.$this->getUserTableFields(array('user_id', 'display_name', 'name', 'email', 'image_path', 'gender', 'usr_status', 'user_access', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext')).
						', '.$this->getUserTableField('user_id').' AS img_user_id'.
						' FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE '.$this->getUserTableField('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('name'=>'', 'display_name'=>'', 'email'=>'', 'image_path'=>'', 'gender'=>'', 'usr_status'=>'', 'user_access'=>'', 'img_user_id'=>'', 't_height'=>'', 't_width'=>'', 's_height'=>'', 's_width'=>'', 'photo_server_url'=>'', 'photo_ext'=>'');
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
					}
				//cache user details
				$this->_cache_user_details[$user_id] = $row;

				return	$row;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function createErrorLogFile($type)
			{
				if((isset($this->_dir_path)) && ($this->_dir_path!=''))
					$temp_dir = $this->_dir_path.$this->CFG['admin']['logfile_path'];
				else
					$temp_dir = $this->CFG['admin']['logfile_path'];
				$this->chkAndCreateFolder($temp_dir);
				$temp_file_path = $temp_dir.$this->CFG['user']['user_id'].$type.'.txt';
				$this->fp = fopen($temp_file_path, 'w');
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function writetoTempFile($video_upload_str)
			{
				if($this->fp)
					{
						$video_upload_str .= "\r\n"."===================================================================================== "."\r\n\r\n";
						fwrite($this->fp, $video_upload_str);
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function closeErrorLogFile()
			{
				if ($this->fp)
					{
						fclose($this->fp);
					}
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function appendMetaDetails($text_to_add, $category)
			{
				global $LANG, $CFG;

				$split_string = explode(" ", $text_to_add);
				if($CFG['html']['meta']['min_characters_appendable'] && (count($split_string) > $CFG['html']['meta']['min_characters_appendable']))
					{
						$new_text = '';
						for($inc = 0; $inc < $CFG['html']['meta']['min_characters_appendable']; $inc++)
							{
								$new_text.=$split_string[$inc].' ';
							}
						$text_to_add = $new_text;
					}
				$text_to_add = htmlspecialchars($category.$text_to_add);
				if(isset($LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_keywords']))
					$LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_keywords'] = $text_to_add.', '.$LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_keywords'];
				else
					$CFG['html']['meta']['keywords'] = $text_to_add.', '.$CFG['html']['meta']['keywords'];

				if(isset($LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_description']))
					$LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_description'] = $text_to_add.', '.$LANG['meta_'.strtolower($CFG['html']['current_script_name']).'_description'];
				else
					$CFG['html']['meta']['description'] = $text_to_add.', '.$CFG['html']['meta']['description'];
			}

		public function fileGetContents($url)
			{
				return file_get_contents($url);
			}

		// ning related functions

		public function chkIsNingUser($uid = '')
			{
				if(!$this->CFG['admin']['module']['ning'])
					return false;

				if($uid == '')
					$uid = $this->CFG['user']['user_id'];
				$sql = ' SELECT * FROM '.$this->CFG['db']['tbl']['ning_identity'].''.
					   ' WHERE user_id = '.$uid;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows >0)
					return true;
				else
					return false;

			}

	   public function isNingImageAllowed($uid = '')
			{
				if($uid == '')
					$uid = $this->CFG['user']['user_id'];
				$sql = ' SELECT ning_image FROM '.$this->CFG['db']['tbl']['ning_identity'].''.
					   ' WHERE  user_id = '.$uid ;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					$row = $rs->FetchRow();
				return $row['ning_image'];

			}

	  public function chkIsTwitterImageUploaded($file_name,  $user_id)
			{
				$output = $this->CFG['site']['project_path'].'files/'.md5($filename).'.jpg';
				file_put_contents($output, getContents($file_name));
				$file_name = $output;
				$extern = 'jpg';
				//Initialize width and height of the image
				$this->setFormField('photo_ext', $extern);
				$image_name = getImageName($user_id);
				$temp_dir = $this->CFG['site']['project_path'] . $this->CFG['admin']['ans_photos']['temp_folder'];
				$this->chkAndCreateFolder($temp_dir);
				$temp_file = $temp_dir . $image_name;
				if(copy($file_name, $temp_file))
					{
						$imageObj = new ImageHandler($temp_file);
						$this->setIHObject($imageObj);
						$this->storeImagesTempServer($temp_file, $extern);
						$dir = $this->CFG['admin']['ans_photos']['folder'];
						$local_upload = true;

						if ($this->getServerDetails())
							{
								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['site']['project_path']  . $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'] . '=\'' .$user_id. '\'';

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

						@unlink($output);
						return true;

					}
				else
					{
						$this->updateImagePath();
					}
			}

	   public function getTwitterImageStatus($user_id)
			{
				$sql = 'SELECT twitter_image FROM ' . $this->CFG['db']['tbl']['twitter_identity'] .
				 	   ' WHERE  user_id ='. $user_id.' AND status = \'Ok\'' ;
				// prepare query
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row['twitter_image'];
			}

	  public function IsTwitterUser()
			{
				if(!$this->CFG['admin']['module']['twitter'])
					return false;

				$uid = $this->CFG['user']['user_id'];
				$sql = ' SELECT * FROM '.$this->CFG['db']['tbl']['twitter_identity'].''.
					   ' WHERE user_id = '.$uid;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows >0)
					return true;
				else
					return false;

			}
		/**
		 * FormHandler::isFacebookUser()
		 *
		 * @return
		 */
		public function isFacebookUser($uid = '')
			{
				if($uid == '')
					$uid = $this->CFG['user']['user_id'];

				if (isset($this->_cache_isFacebookUser[$uid]))
					{
						return $this->_cache_isFacebookUser[$uid];
					}

				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['facebook_identity'].
					   ' WHERE 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())
					$isFacebookUser = true;
				else
					$isFacebookUser = false;
				//cache facebook user
				$this->_cache_isFacebookUser[$uid] = $isFacebookUser;

				return	$isFacebookUser;
			}

	}
//<<<<<------------------ Class FormHandler ends --------------------//

/****************************************/
/*----Test cases in standalone mode-----*/
/****************************************/
if ($CFG['debug']['debug_standalone_modules'])
	{

	}
?>