<?php
//--------------class ForumsTopicsFormHandler--------------->>>//
/**
 * @category	Anova
 * @package		forumsResponsesFormHandler
 * @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-04
 **/

class ForumsTopicsFormHandler extends ForumHandler
	{
		//Variable to store forum details
		public $paging_arr;

		/**
		 * ForumsTopicsFormHandler::storeSearchFields()
		 *
		 * @return
		 */
		public function storeSearchFields()
			{

				$allowed_fields_arr = array(
										'forum_title'=>$this->fields_arr['forum_title'],
										'forum_topic'=>$this->fields_arr['forum_topic'],
										'forum_response'=>$this->fields_arr['forum_response'],
										'dname'=>$this->fields_arr['dname'],
										'date_limits_to'=>$this->fields_arr['date_limits_to'],
										);
				$allowed_fields_arr = serialize($allowed_fields_arr);

				if($this->CFG['user']['user_id'] != 0)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['advanced_search'].' SET'.
								' forum = '.$this->dbObj->Param('forum').' WHERE'.
								' user_id = '.$this->dbObj->Param('user_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($allowed_fields_arr, $this->CFG['user']['user_id']));
							if (!$rs)
								trigger_db_error($this->dbObj);
					}
				else
					{
						$_SESSION['advanced_search_values_for_forums'] = 	$allowed_fields_arr;
					}
					//to fix search top box value populate..
					$_SESSION['forum_topic'] = $this->fields_arr['forum_topic'];
			}

		/**
		 * ForumsTopicsFormHandler::populateSearchFields()
		 *
		 * @return
		 */
		public function populateSearchFields()
			{

				if($this->fields_arr['so']=='adv')
					{
						if($this->CFG['user']['user_id'] != 0)
							{

								$sql = 'SELECT forum FROM '.$this->CFG['db']['tbl']['advanced_search'].
										' WHERE user_id='.$this->dbObj->Param('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);

								if($row = $rs->FetchRow())
									{
										if($row['forum'])
											{
												$search_fields_arr = unserialize($row['forum']);
												$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
											}
									}
							}
						else
							{
								if(isset($_SESSION['advanced_search_values_for_forums']) and !empty($_SESSION['advanced_search_values_for_forums']))
									{
											$search_fields_arr = unserialize($_SESSION['advanced_search_values_for_forums']);
											$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
									}

							}
							//to fix search top box value populate..
							$_SESSION['forum_topic'] = $this->fields_arr['forum_topic'];
					}
			}
		/**
		 * set the condition
		 *
		 * @access public
		 * @return void
		 **/
		public function buildConditionQuery($condition='')
			{

				$this->sql_condition = $condition;

				if($this->fields_arr['search_forum_topic'] && ($this->fields_arr['search_forum_topic'] != $this->LANG['search_for_forum_topics']))
					{
					$this->sql_condition .= ' AND ('.getSearchRegularExpressionQuery($this->fields_arr['search_forum_topic'], 'fr.forum_response').
									' OR '.getSearchRegularExpressionQuery($this->fields_arr['search_forum_topic'], 'ft.forum_topic').')';
					$this->paging_arr[] = 'search_forum_topic';
					}

				if($this->fields_arr['forum_title'])
					{
					$this->sql_condition .= ' AND ('.getSearchRegularExpressionQuery($this->fields_arr['forum_title'], 'f.forum_title').')';
					$this->paging_arr[] = 'forum_title';
					}
				if($this->fields_arr['forum_topic'])
					{
					$this->sql_condition .= ' AND ('.getSearchRegularExpressionQuery($this->fields_arr['forum_topic'], 'ft.forum_topic').')';
					$this->paging_arr[] = 'forum_topic';
					}
				if($this->fields_arr['forum_response'])
					{
					$this->sql_condition .= ' AND ('.getSearchRegularExpressionQuery($this->fields_arr['forum_response'], 'fr.forum_response').')';
					$this->paging_arr[] = 'forum_response';
					}
				if ($this->fields_arr['dname'])
					{
					$this->sql_condition .= ' AND u.'.$this->getUserTableField('display_name').' LIKE \''.addslashes($this->fields_arr['dname']).'%\'';
					$this->paging_arr[] = 'dname';
					}
				if ($this->fields_arr['uname'])
					{
					$this->sql_condition .= ' AND u.'.$this->getUserTableField('name').' LIKE \''.addslashes($this->fields_arr['uname']).'%\'';
					$this->paging_arr[] = 'uname';
					}
				if ($this->fields_arr['uid'])
					{
					$this->sql_condition .= ' AND ft.user_id=\''.$this->fields_arr['uid'].'\'';
					$this->paging_arr[] = 'uid';
					}

				switch($this->fields_arr['date_limits_to'])
					{
						case $this->LANG['search_option_today']:
							$date_condtion = 'date( ft.date_added ) = date( now( ) )';
							break;
						case $this->LANG['search_option_oneday']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 1 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_oneweek']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 7 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_onemonth']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 1 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_threemonths']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 3 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_sixmonths']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 6 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_oneyear']:
							$date_condtion = 'DATE_ADD(ft.date_added, INTERVAL 1 YEAR) >= NOW()';
							break;
						default:
							$date_condtion = 'ft.date_added <= NOW()';
							break;

					}

					$this->paging_arr[] = 'date_limits_to';
					$this->sql_condition .= ' AND '.$date_condtion.' GROUP BY ft.forum_topic ';
			}
		/**
		 * To sort the query
		 *
		 * @access public
		 * @return void
		 **/
		public function checkSortQuery($field, $sort='asc')
			{
				if(!($this->sql_sort))
				{
					$this->sql_sort = $field . ' ' . $sort;
				}
			}

		/**
		 * ForumsTopicsFormHandler::executeForumQuery()
		 *
		 * @return
		 */
		public function executeForumQuery()
			{
				//count...
				// prepare query
				$stmt = $this->dbObj->Prepare($this->sql_count);
				// execute query
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				// fetch array of row
				$row = $rs->fetchRow();
				// counts number of rows
				$this->results_tot_num = $rs->PO_RecordCount();

				$this->results_end_num = $this->results_tot_pages_num = 0;
				//main query.. don't query the whole unnecessarily...
				if ($this->results_tot_num)
					{
						$this->results_tot_pages_num = ceil($this->results_tot_num/$this->results_num_per_page);
						// prepare query
						$stmt = $this->dbObj->Prepare($this->sql);
						// execute query
						$this->rs = $this->dbObj->Execute($stmt);
						//raise user error... fatal
						if (!$this->rs)
							trigger_db_error($this->dbObj);
						// sets total number of records
						$this->results_end_num = $this->results_start_num + $this->rs->PO_RecordCount();
					}
			}

		/**
		 * To display the forums titles
		 *
		 * @access public
		 * @return void
		 **/
		public function showForumSearchResult()
			{

				$showForumSearchResult_arr = array();
				$inc=1;

				while($row = $this->fetchResultRecord())
					{
						$responseUserDetails['user_id'] = $row['topic_user_id'];
						$responseUserDetails['display_name'] = $row['topic_display_name'];
						$responseUserDetails['name'] = $row['topic_user_name'];
						if(isset($row['topic_user_image_path']) && $row['topic_user_image_path'])
							$responseUserDetails['image_path'] = $row['topic_user_image_path'];
						else
							$responseUserDetails['image_path'] = '';
						$responseUserDetails['gender'] = $row['topic_user_gender'];
						$responseUserDetails['img_user_id'] = $row['topic_img_user_id'];
						$responseUserDetails['t_width'] = $row['topic_t_width'];
						$responseUserDetails['t_height'] = $row['topic_t_height'];
						$responseUserDetails['s_width'] = $row['topic_s_width'];
						$responseUserDetails['s_height'] = $row['topic_s_height'];
						$responseUserDetails['photo_server_url'] = $row['topic_photo_server_url'];
						$responseUserDetails['photo_ext'] = $row['topic_photo_ext'];

						$responseDetails['forum_seo'] = $row['forum_seo'];
						$responseDetails['topic_seo'] = $row['topic_seo'];
						$responseDetails['forum_title'] = $row['forum_title'];
						$responseDetails['forum_topic']	= $row['forum_topic'];
						$responseDetails['forum_response'] = $row['forum_response'];
						$responseDetails['total_views'] = $row['total_views'];
						$responseDetails['total_response'] = $row['total_response'];

						$string1 = $row['forum_topic'];
						$string2 = $row['forum_response'];

						$showForumSearchResult_arr[$inc]['record'] = $row;
						$showForumSearchResult_arr[$inc]['responseUserDetails'] = $responseUserDetails;
						$showForumSearchResult_arr[$inc]['responseDetails'] = $responseDetails;

						$showForumSearchResult_arr[$inc]['forums_responses']['url'] = getForumsUrl('forumsresponses', '?title='.$responseDetails['forum_seo'].'&amp;topic_title='.$responseDetails['topic_seo'], $responseDetails['forum_seo'].'/'.$responseDetails['topic_seo'].'/');
						$showForumSearchResult_arr[$inc]['forums_responses']['title'] = wordWrapManual($string1, 25, $this->CFG['admin']['forum']['line_length']);
						$showForumSearchResult_arr[$inc]['forums_responses2']['title'] = wordWrapManual($string2, 25, $this->CFG['admin']['forum']['line_length']);

						$showForumSearchResult_arr[$inc]['user_my_answers']['url'] = getMemberUrl($responseUserDetails['user_id'], $responseUserDetails['name']);
						$showForumSearchResult_arr[$inc]['user_my_answers']['title'] = stripString($responseUserDetails['display_name'], $this->CFG['username']['short_length']);

						$showForumSearchResult_arr[$inc]['posted_by']['title'] = stripString($row['topic_display_name'], $this->CFG['username']['short_length']);
	    				$showForumSearchResult_arr[$inc]['forums_topics']['url'] = getForumsUrl('forumstopics', '?title='.$responseDetails['forum_seo'], $responseDetails['forum_seo'].'/');
						$showForumSearchResult_arr[$inc]['forums']['title'] = wordWrapManual($responseDetails['forum_title'], 15, $this->CFG['admin']['forum']['line_length']);

	    				$showForumSearchResult_arr[$inc]['forums_topics']['title'] = wordWrapManual($responseDetails['forum_topic'], 15, $this->CFG['admin']['forum']['line_length']);

						$inc++;
					}

				return $showForumSearchResult_arr;
			}

		public function printQuery()
			{
				print $this->sql;
			}

	}
//<<<<<<<--------------class ForumsTopicsFormHandler---------------//

//--------------------Code begins-------------->>>>>//
$forumstopics = new ForumsTopicsFormHandler();
if(!chkIsAllowedModule(array('forums')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$forumstopics->setPageBlockNames(array('form_advanced_search', 'form_forum_title', 'form_show_topics', 'form_confirm'));
$forumstopics->setAllPageBlocksHide();
//default form fields and values...
$forumstopics->setFormField('uid', '');
$forumstopics->setFormField('forum_id', '');
$forumstopics->setFormField('title', '');
$forumstopics->setFormField('search_forum_topic', '');
$forumstopics->setFormField('uname', '');
$forumstopics->setFormField('dname', '');
$forumstopics->setFormField('forum_title', '');
$forumstopics->setFormField('forum_topic', '');
$forumstopics->setFormField('forum_response', '');
$forumstopics->setFormField('date_limits_to', '');
$forumstopics->setFormField('adv_search', '');
$forumstopics->setFormField('so', 'min');

$forumstopics->setFormField('numpg',0);
$forumstopics->setFormField('start',0);
/***********set form field for navigation****/
$forumstopics->setFormField('asc', 'ft.forum_topic');
$forumstopics->setFormField('dsc', '');
/*************Start navigation******/
//fetch number of records show in the result--numpg
$condition = '';
$forumstopics->numpg = $CFG['data_tbl']['numpg'];
$forumstopics->setFormField('start', 0);
$forumstopics->setFormField('numpg', $CFG['data_tbl']['numpg']);

$forumstopics->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$forumstopics->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$forumstopics->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$forumstopics->setTableNames(array());
$forumstopics->setReturnColumns(array());

$forumstopics->sanitizeFormInputs($_REQUEST);
$forumstopics->search_title = $LANG['search_results'];
$title = $LANG['forumlistall_title_index'];
$forumstopics->searchOption_arr = array($LANG['search_option_allresult'] => $LANG['search_option_allresult'],
			  $LANG['search_option_today'] => $LANG['search_option_today'],
			  $LANG['search_option_oneday'] => $LANG['search_option_oneday'],
			  $LANG['search_option_oneweek'] => $LANG['search_option_oneweek'],
			  $LANG['search_option_onemonth'] => $LANG['search_option_onemonth'],
			  $LANG['search_option_threemonths'] => $LANG['search_option_threemonths'],
			  $LANG['search_option_sixmonths'] => $LANG['search_option_sixmonths'],
			  $LANG['search_option_oneyear'] => $LANG['search_option_oneyear']);
/*************End navigation******/

$forumstopics->setPageBlockShow('form_show_topics');

if($forumstopics->getFormField('so')=='adv' and !$forumstopics->isFormPOSTed($_REQUEST, 'adv_search'))
	{
		$forumstopics->populateSearchFields();
		$forumstopics->setPageBlockHide('form_show_topics');
		$forumstopics->setPageBlockShow('form_advanced_search');
		$forumstopics->search_title = $LANG['advanced_search'];
	}
if($forumstopics->isFormGETed($_GET, 'adv_search'))
	{
		$forumstopics->populateSearchFields();
		$forumstopics->setAllPageBlocksHide();
		$forumstopics->setPageBlockShow('form_show_topics');
	}
if($forumstopics->getFormField('uname'))
	{
		$uname = $forumstopics->getUsersDisplayName($forumstopics->getFormField('uname'));
		$forumstopics->search_title = $uname.' - '.$LANG['forums'];
		$title = $uname.'\'s '.$LANG['forums'];
		if($CFG['user']['user_id'])
			{
				if($CFG['user']['display_name'] == $uname)
					{
						$forumstopics->search_title =  $LANG['forum_search_myforum'];
						$title = $LANG['forum_search_myforum'];
					}
			}
	}
if($forumstopics->isFormPOSTed($_POST, 'adv_search'))
	{
		if ($forumstopics->isValidFormInputs())
			{
				$forumstopics->storeSearchFields();
			}
		else
			{
				$forumstopics->setPageBlockHide('form_show_topics');
				$forumstopics->setPageBlockShow('form_advanced_search');
				$forumstopics->setPageBlockShow('block_msg_form_error');
				$forumstopics->setCommonErrorMsg($LANG['err_msg_invalid_search_option']);
			}
	}

if(!$forumstopics->isFormGETed($_GET, 'search_forum_topic'))
	 {
			   $_SESSION['search_forum_topic'] = $LANG['header_search_for_forum_topics'];
	 }
if($forumstopics->isFormPOSTed($_POST, 'search'))
	 {
			   $_SESSION['search_forum_topic'] = $forumstopics->getFormField('search_forum_topic');
	 }
if($forumstopics->isFormGETed($_GET, 'search_forum_topic'))
	 {
			    if(isset($_SESSION['search_forum_topic']) and $_SESSION['search_forum_topic'])
				    $forumstopics->setFormField('search_forum_topic', $_SESSION['search_forum_topic']);
	 }
if ($forumstopics->isValidFormInputs())
	{
		if ($forumstopics->isShowPageBlock('form_show_topics'))
			{
				$forumstopics->setTableNames(array($CFG['db']['tbl']['forum_topics'].' as ft LEFT JOIN '.$CFG['db']['tbl']['forum_response'].
								' as fr ON  fr.topic_id =ft.topic_id LEFT JOIN '.$CFG['db']['tbl']['forums'].
								' as f ON f.forum_id=ft.forum_id LEFT JOIN '.$CFG['db']['tbl']['users'].
								' as u ON u.user_id=ft.user_id'));
				$return_fields = array('fr.response_id', 'fr.forum_response', 'fr.response_user_id',
								'ft.topic_id', 'ft.forum_topic', 'ft.seo_title as topic_seo',
								'ft.user_id', 'ft.total_response', 'ft.total_views',
								'f.forum_id', 'f.forum_title', 'f.seo_title as forum_seo',
							      	'DATE_FORMAT(ft.date_added, \''.$CFG['format']['date'].'\') AS date_add');
				if($forumstopics->getUserTableField('user_id'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('user_id').' AS topic_user_id';
					}
				if($forumstopics->getUserTableField('display_name'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('display_name').' AS topic_display_name';
					}
				if($forumstopics->getUserTableField('name'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('name').' AS topic_user_name';
					}
				if($forumstopics->getUserTableField('image_path'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('image_path').' AS topic_user_image_path';
					}
				if($forumstopics->getUserTableField('gender'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('gender').' AS topic_user_gender';
					}
				if($forumstopics->getUserTableField('user_id'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('user_id').' AS topic_img_user_id';
					}
				if($forumstopics->getUserTableField('t_height'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('t_height').' AS topic_t_height';
					}
				if($forumstopics->getUserTableField('t_width'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('t_width').' AS topic_t_width';
					}
				if($forumstopics->getUserTableField('s_height'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('s_height').' AS topic_s_height';
					}
				if($forumstopics->getUserTableField('s_width'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('s_width').' AS topic_s_width';
					}
				if($forumstopics->getUserTableField('s_width'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('s_width').' AS topic_s_width';
					}
				if($forumstopics->getUserTableField('photo_server_url'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('photo_server_url').' AS topic_photo_server_url';
					}
				if($forumstopics->getUserTableField('photo_ext'))
					{
						$return_fields[] = 'u.'.$forumstopics->getUserTableField('photo_ext').' AS topic_photo_ext';
					}


				$forumstopics->setReturnColumns($return_fields);
				//Condition of the query
				$condition = ' ft.topic_status = \'Yes\' AND u.'.$forumstopics->getUserTableField('usr_status').' = \'Ok\' ';
				$forumstopics->buildSelectQuery();
				$forumstopics->buildConditionQuery($condition);
				$forumstopics->buildSortQuery();
				$forumstopics->checkSortQuery('ft.topic_id', 'ASC');
				$forumstopics->buildQuery();
				//$forumstopics->printQuery();
				$forumstopics->executeForumQuery();
				/*************End navigation******/
				$forumstopics->setPageBlockShow('form_forum_title');
				if($forumstopics->getFormField('adv_search'))
					$forumstopics->paging_arr[] = 'adv_search';
				if($forumstopics->getFormField('so'))
					$forumstopics->paging_arr[] = 'so';
				if ($forumstopics->isResultsFound())
					{
						$forumstopics->form_show_topics_arr = $forumstopics->showForumSearchResult();
						$smartyObj->assign('smarty_paging_list', $forumstopics->populatePageLinksGET($forumstopics->getFormField('start'), $forumstopics->paging_arr));
					}
				else
					{
						$forumstopics->site_name_manual =  str_ireplace('VAR_SITENAME', $CFG['site']['name'], $LANG['forums_no_search_results']);
					}
			}
	}
else
	{
		$forumstopics->setPageBlockShow('block_msg_form_error');
		//now redirect to forums main page...
		Redirect2URL(getForumsUrl('forums'));
	}

if ($forumstopics->isFormPOSTed($_GET, 'msg'))
	{
		$forumstopics->setCommonSuccessMsg($LANG['forums_topic_created_successfully']);
		$forumstopics->setPageBlockShow('block_msg_form_success');
	}
$forumstopics->forums_url = getForumsUrl('forums');
$forumstopics->advanced_search_action = getForumsUrl('forumsearch', '?so=adv', '?so=adv');
//<<<<--------------------Code Ends----------------------//
$CFG['site']['title'] = $title.' - '.$CFG['site']['title'];
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$forumstopics->includeHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['forum_module']);
$smartyObj->display('forumSearch.tpl');
//include the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
$forumstopics->includeFooter();
?>
