<?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		ForumHandler
 * @author		shankar_76ag08
 * @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-29
 */
if(class_exists('VideoUploadLib'))
	{
		$parent_class = 3;
	}
else if(class_exists('AnovaHandler'))
	{
		$parent_class = 2;
	}
else
	{
		$parent_class = 1;
	}

switch($parent_class)
	{
		case 3:
			class Handler extends VideoUploadLib{}
			break;
		case 2:
			class Handler extends AnovaHandler{}
			break;
		case 1:
		default:
			class Handler extends FormHandler{}
			break;
	}

class ForumHandler extends Handler
	{
		public $response_array = array();
		/**
		 * To check if the forum id is valid
		 *
		 * @param 		string $table_name forums
		 * @param 		integer $forum_id
		 * @param 		string $err_tip error tip
		 * @access public
		 * @return Boolean
		 **/
		public function isValidForumId($title, $err_tip='')
			{
				$sql = 'SELECT forum_id, forum_title, seo_title, forum_userid, forum_description, forum_status, publish_status '.
						'FROM '.$this->CFG['db']['tbl']['forums'].' '.
						'WHERE seo_title = '.$this->dbObj->Param($title).' '.
						'AND forum_status = \'Yes\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($title));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($this->forum_details_arr = $rs->FetchRow())
					{
						$this->setFormField('forum_id', $this->forum_details_arr['forum_id']);
						$this->setFormField('seo_title', $this->forum_details_arr['seo_title']);
						$this->setFormField('publish_status', $this->forum_details_arr['publish_status']);
						$this->setFormField('forum_userid', $this->forum_details_arr['forum_userid']);
						return true;
				    }
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * To check if the forum topic id is valid
		 *
		 * @param 		string $forums_topics_table groups_forums_topics table
		 * @param 		integer $forum_id
		 * @param 		interger $topic_id
		 * @param 		string $err_tip error tip
		 * @access public
		 * @return Boolean
		 **/
		public function isValidForumTopicId($forum_id, $topic_title, $err_tip='')
			{
				$sql = 'SELECT g.topic_id, g.forum_id, g.forum_topic, g.topic_status, g.publish_status, g.seo_title, g.user_id, DATE_FORMAT(g.date_added, \''.$this->CFG['format']['date'].'\') AS date_added, g.total_response'.
						', '.$this->getUserTableFields(array('name', 'display_name', 'image_path', 'gender')).
						' FROM '.$this->CFG['db']['tbl']['forum_topics'].' AS g, '.$this->CFG['db']['tbl']['users'].' AS u'.
						' WHERE g.user_id = u.'.$this->getUserTableField('user_id').
						' AND seo_title = '.$this->dbObj->Param($topic_title).
						' AND forum_id = '.$this->dbObj->Param($forum_id);

				if($this->forum_details_arr['forum_userid'] == $this->CFG['user']['user_id'])
						$sql .= ' AND g.topic_status != \'No\'';
					else
						$sql .= ' AND g.topic_status = \'Yes\'';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($topic_title, $forum_id));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($this->forum_topic_details_arr = $rs->FetchRow())
					{
						$forum_user_id = $this->forum_topic_details_arr['user_id'];
						$this->forum_topic_details_arr['user_details'] = $this->getUserDetailsFromUsersTable('users', $forum_user_id);
						$this->setFormField('topic_id', $this->forum_topic_details_arr['topic_id']);
						$this->setFormField('seo_title', $this->forum_topic_details_arr['seo_title']);
						return true;
				    }
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		* To check if the group response id is valid
		 *
		 * @param 		string $forums_response_table forums_response table
		 * @param 		integer $topic_id
		 * @param 		interger $response_id
		 * @param 		string $err_tip error tip
		 * @access public
		 * @return Boolean
		 **/
		public function isValidForumResponseId($topic_id, $response_id, $err_tip='')
			{
				if($this->fields_arr['act'] == 'publish')
					return true;

				$sql = 'SELECT response_id, topic_id, forum_response, video_id, external_video_id, audio_id, external_audio_id, response_user_id '.
						'FROM '.$this->CFG['db']['tbl']['forum_response'].' '.
						'WHERE topic_id = '.$this->dbObj->Param($topic_id).' '.
						'AND response_id = '.$this->dbObj->Param($response_id).' '.
						'AND response_status = \'Yes\' '.
						'AND response_user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($topic_id, $response_id, $this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($row = $rs->FetchRow())
					{
						$this->setFormField('forum_response', $row['forum_response']);
						$this->setFormField('video_id', $row['video_id']);
						$this->setFormField('external_video_id', $row['external_video_id']);
						$this->setFormField('audio_id', $row['audio_id']);
						$this->setFormField('external_audio_id', $row['external_audio_id']);
						$this->response_array['video_id'] = $row['video_id'];
						$this->response_array['external_video_id'] = $row['external_video_id'];
						$this->response_array['audio_id'] = $row['audio_id'];
						$this->response_array['external_audio_id'] = $row['external_audio_id'];
						return true;
				    }
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * To update the User table
		 *
		 * @access public
		 * @return void
		 **/
		public function updateUsersAnsLog()
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_posts = total_posts + 1'.
						' WHERE '.$this->getUserTableField('user_id').' = '.$this->dbObj->Param($this->CFG['user']['user_id']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return true;
			}

		/**
		 * To update the last post user_id
		 *
		 * @param integer $forum_id
		 * @access public
		 * @return void
		 **/
		public function updateForums($forum_id)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['forums'].
						' SET last_post_user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
						', last_post_date = now()'.
						', total_topics = total_topics + 1'.
						', total_response = total_response + 1'.
						' WHERE forum_id = '.$this->dbObj->Param($forum_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id'], $forum_id));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return true;
			}

		/**
		 * To update the forum_response
		 *
		 * @param string $forum_id
		 * @access public
		 * @return void
		 **/
		public function insertForumResponse($topic_id)
			{
				$this->fields_arr['forum_response'] = replaceListClass($this->fields_arr['forum_response']);

				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['forum_response'].
						' SET topic_id = '.$this->dbObj->Param($topic_id).
						', forum_response = '.$this->dbObj->Param($this->fields_arr['forum_response']).
						', response_user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
						', date_added = NOW()';
				$response_status = 'Yes';
				if (isset($this->forum_topic_details_arr['publish_status']) AND $this->forum_topic_details_arr['publish_status']=='No')
					$response_status = $this->forum_topic_details_arr['publish_status'];
				if (isset($this->fields_arr['publish_status']) AND $this->fields_arr['publish_status']=='No')
					$response_status = $this->fields_arr['publish_status'];
				if($response_status=='No' AND $this->forum_topic_details_arr['user_id'] != $this->CFG['user']['user_id'])
						$sql .= ', response_status=\'ToActivate\'';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($topic_id, html_entity_decode($this->fields_arr['forum_response'], ENT_QUOTES, $this->CFG['site']['charset']),
														 $this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				$this->fields_arr['content_id'] = $this->dbObj->Insert_ID();
				return true;
			}

		/**
		 * To show the forum tilte
		 *
		 * @access public
		 * @return void
		 **/
		public function showForumDetails($pageName='')
			{
				global $smartyObj;

				$showForumDetails_arr = array();

			  	$showForumDetails_arr['forums']['url'] = getForumsUrl('forums');
				$showForumDetails_arr['forumlinks_back_index'] = $this->LANG['forumlinks_back_index'];
				$showForumDetails_arr['pageName'] = $pageName;

				if ($pageName != 'responselist')
					{
						$forum_topic_create_url = getForumsUrl('forumstopiccreate', '?title='.$this->forum_details_arr['seo_title'], $this->forum_details_arr['seo_title'].'/', 'members');
						if (isMember())
							{
								$showForumDetails_arr['forumsTopicCreate']['url'] = $forum_topic_create_url;
								$showForumDetails_arr['forumsTopicCreate']['title'] = $this->LANG['forumslinks_post_topic'];
							}
						else
							{
								$showForumDetails_arr['forumsTopicCreate']['url'] = getUrl('login', '?light_url='.$forum_topic_create_url, '?light_url='.$forum_topic_create_url);
								$showForumDetails_arr['forumsTopicCreate']['title'] = $this->LANG['forumslinks_post_topic'];

							}
					}
				else
					{
						$forum_topic_response_url = getForumsUrl('forumsresponsecreate', '?title='.$this->forum_details_arr['seo_title'].'&amp;topic_title='.$this->forum_topic_details_arr['seo_title'], $this->forum_details_arr['seo_title'].'/'.$this->forum_topic_details_arr['seo_title'].'/', 'members');//getUrl('forumstopics', '?title='.$this->forum_details_arr['seo_title'], $this->forum_details_arr['seo_title'].'/', 'members');
						if($this->forum_topic_details_arr['topic_status']=='Yes')
							{
								if (isMember())
									{
										$showForumDetails_arr['forumsResponseCreate']['url'] = $forum_topic_response_url;
										$showForumDetails_arr['forumsResponseCreate']['title'] = $this->LANG['forumslinks_post_response'];
									}
								else
									{
										$showForumDetails_arr['forumsResponseCreate']['url'] = getUrl('login', '?light_url='.$forum_topic_response_url, '?light_url='.$forum_topic_response_url);
										$showForumDetails_arr['forumsResponseCreate']['title'] = $this->LANG['forumslinks_post_response'];

									}
							 }
					}

                $smartyObj->assign('showForumDetails_arr', $showForumDetails_arr);
                setTemplateFolder('general/', $this->CFG['admin']['index']['forum_module']);
                $smartyObj->display('showForumDetails.tpl');
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function forumRelatedDetails($forum_id='', $topic_id='', $response_id='')
			{
				if($forum_id)
					{
						$where_id = $forum_id;
						$sql = 'SELECT f.forum_title as forum, f.seo_title as forum_seo, f.forum_userid as forum_ownerid,'.
							' u.'.$this->getUserTableField('display_name').' as forum_ownername, u.'.$this->getUserTableField('email').' as forum_owneremail FROM '.$this->CFG['db']['tbl']['forums'].
							' as f LEFT JOIN '.$this->CFG['db']['tbl']['users'].' as u ON'.
							' f.forum_userid=u.user_id WHERE f.forum_id = '.$this->dbObj->Param($forum_id);
					}
				elseif($topic_id)
					{
						$where_id = $topic_id;
						$sql = 'SELECT t.forum_topic as topic,t.user_id as topic_ownerid, t.seo_title as topic_seo, t.forum_id as topic_forumid,'.
							' u.'.$this->getUserTableField('display_name').' as topic_ownername, u.'.$this->getUserTableField('email').' as topic_owneremail FROM '.$this->CFG['db']['tbl']['forum_topics'].
							' as t LEFT JOIN '.$this->CFG['db']['tbl']['users'].' as u ON t.user_id=u.user_id WHERE t.topic_id = '.$this->dbObj->Param($topic_id);

					}
				elseif($response_id)
					{
						$where_id = $response_id;
						$sql = 'SELECT r.forum_response as response, r.topic_id as response_topicid,'.
							' r.response_user_id as response_ownerid,u.'.$this->getUserTableField('display_name').' as response_ownername,'.
							' u.'.$this->getUserTableField('email').' as response_owneremail FROM '.$this->CFG['db']['tbl']['forum_response'].
							' as r LEFT JOIN '.$this->CFG['db']['tbl']['users'].
							' as u ON r.response_user_id=u.user_id WHERE r.response_id = '.$this->dbObj->Param($response_id);
					}

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($where_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					return false;
				$row = $rs->FetchRow();
				return $row;
			}

			/********* payment gateway related functions end *************/
		public function overRideConfigs($isPost=true)
			{
				global $CFG, $smartyObj;

				if(!chkIsPaymentAllowed('payment'))
					return;

				if(!$CFG['user']['user_id'])
					return;

				if($CFG['plan']['plan_video_post_count'] != $CFG['plan']['unlimited'] and $isPost)
					{
						if(!$this->isAllwedToPostVideo())
							{
								if(chkIsPaymentAlertMessageAllowed())
									$this->CFG['admin']['paymentmodule']['video'] = $CFG['admin']['paymentmodule']['video'] = false;
								else
									$CFG['admin']['module']['video'] = false;
							}

					}
    			if($CFG['plan']['plan_audio_post_count'] != $CFG['plan']['unlimited'] and $isPost)
    				{
						if(!$this->isAllwedToPostAudio())
							{
								if(chkIsPaymentAlertMessageAllowed())
									$this->CFG['admin']['paymentmodule']['audio'] = $CFG['admin']['paymentmodule']['audio'] = false;
								else
									$CFG['admin']['module']['audio'] = false;
							}
					}

    			unset($_SESSION['video_record_time']);
				if($CFG['plan']['plan_video_recording_time'] != $CFG['plan']['unlimited'])
    				{
						$_SESSION['video_record_time'] = $CFG['plan']['plan_video_recording_time'];
					}

    			unset($_SESSION['audio_record_time']);
				if($CFG['plan']['plan_audio_recording_time'] != $CFG['plan']['unlimited'])
    				{
						$_SESSION['audio_record_time'] = $CFG['plan']['plan_audio_recording_time'];
					}

				if($CFG['plan']['plan_ans_characters'] != $CFG['plan']['unlimited'])
    				{
						$CFG['admin']['answers']['limit'] = $CFG['plan']['plan_ans_characters'];
					}

				if($CFG['plan']['plan_rate_ques'] == 'No')
    				{
						if(chkIsPaymentAlertMessageAllowed())
							$this->CFG['admin']['paymentmodule']['rate_ques'] = $CFG['admin']['paymentmodule']['rate_ques'] = false;
						else
							$CFG['admin']['question']['ratings'] = false;
					}

				if($CFG['plan']['plan_rate_ans'] == 'No')
    				{
						if(chkIsPaymentAlertMessageAllowed())
							$this->CFG['admin']['paymentmodule']['rate_ans'] = $CFG['admin']['paymentmodule']['rate_ans'] = false;
						else
							$CFG['admin']['answer']['ratings'] = false;
					}


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

		public function isAllwedToPostVideo()
			{
				$sql = 'SELECT video_id FROM '.$this->CFG['db']['tbl']['ans_video'].''.
				       ' WHERE user_id = '.$this->dbObj->Param('user_id').
				       ' AND date_added >= '.$this->dbObj->Param('date_added').
					   ' AND video_status = \'Ok\'';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id'], $this->CFG['user']['last_paid_date']));
				if (!$rs)
				    trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows < $this->CFG['plan']['plan_video_post_count']and $this->CFG['plan']['plan_video_post_count'] != 0)
					return true;
				else
					return false;


			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getSeoTitle($table_name='', $title_field='', $current_title_value='', $primary_field='', $primary_field_value='')
			{
				if ($primary_field_value)
					{
						$sql = 'SELECT seo_title FROM '.$table_name.
								' WHERE '.$primary_field.'='.$this->dbObj->Param($primary_field_value).
								' AND '.$title_field.'='.$this->dbObj->Param($current_title_value);

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

						// execute sql
						$rs = $this->dbObj->Execute($stmt, array($primary_field_value, $current_title_value));

						//raise user error... fatal
						if (!$rs)
							trigger_db_error($this->dbObj);
						if ($rs->PO_RecordCount())
							{
								$row = $rs->FetchRow();
								$seoTitle = trim($row['seo_title']);
								if ($seoTitle)
									{
										return $seoTitle;
									}
							}
					}

				$primaryCheck = '';
				$sql =  'SELECT COUNT('.$title_field.') AS title_count'.
						' FROM '.$table_name.
						' WHERE '.$title_field.' = '.$this->dbObj->Param($current_title_value);
				$paramFields = array($current_title_value);

				$sql = $sql.$primaryCheck;
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, array($paramFields));
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				$previousEntryCount = $row['title_count'];
				$seoTitle = $current_title_value;
				//Convert charset
				$seoTitle = seoFriendlyText($seoTitle, $this->CFG['site']['charset']);
				//$seoTitle = ereg_replace ('[^a-zA-Z0-9]', '-', trim($seoTitle));
				$seoTitle = preg_replace('/(-)+$/','',$seoTitle);
				//Removed repeated - symbol
				$seoTitle = ereg_replace('([-]+)', '-', trim($seoTitle));
				$seoTitle = ($seoTitle)?$seoTitle:'1';
				$seoTitle .= $previousEntryCount?'-'.$previousEntryCount:'';

				$seoTitle = $this->getSeoName($table_name, $primary_field, 'seo_title', $seoTitle);

				return $seoTitle;
			}
		/**
		 *
		 * @param $file_name
		 * @param $normal
		 * @param $htaccess
		 * @param $change
		 * @return
		 **/
		public function getForumsUrl($file_name, $normal = '', $htaccess = '', $change = 'current')
			{
				return getForumsUrl($file_name, $normal, $htaccess, $change);
			}
		/**
		 *
		 * @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'];
			}
	}