<?php
/**
 * File to create forum title
 *
 * Ther user can create a category
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		ForumFormHandler
 * @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-24-10
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/'.$CFG['admin']['index']['forum_module'].'/forumsAddTitle.php';
$CFG['html']['header'] = 'general/html_header.php';
$CFG['html']['footer'] = 'general/html_footer.php';

$CFG['mods']['include_files'][] = 'common/classes/class_ForumHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_AnovaHandler.lib.php';
//compulsory
$CFG['site']['is_module_page'] = $CFG['admin']['index']['anova_module'];
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
$CFG['auth']['is_authenticate'] = 'members';
/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------- Class ForumFormHandler begins --------------->>>>>//
class ForumFormHandler extends AnovaHandler
	{
		//Variable to store group forum details
		public $forum_details_arr;

		/**
		 * To check the length of given url
		 *
		 * @param 		string $field_name form field name
		 * @param 		string $err_tip error tip
		 * @access public
		 * @return Boolean
		 **/
		public function chkLength($field_name, $err_tip='')
			{
				$url_len = strlen($this->fields_arr[$field_name]);
				if ($url_len < 3 || $url_len > 20)
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * 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($forum_table, $forum_id, $err_tip='')
			{
				$sql = 'SELECT forum_id, forum_title, forum_description, forum_status'.
						' FROM '.$forum_table.
						' 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 ($this->forum_details_arr = $rs->FetchRow())
					{
						$this->setFormField('forum_title', stripslashes($this->forum_details_arr['forum_title']));
						$this->setFormField('forum_status', $this->forum_details_arr['forum_status']);
						$this->setFormField('forum_description', stripslashes($this->forum_details_arr['forum_description']));
						return true;
				    }
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * To Check if the forum title exists
		 *
		 * @param 		string $forum_title forum title
		 * @param		integer $forum_id
		 * @param 		string $table_name forums
		 * @param 		string $err_tip error tip
		 * @access public
		 * @return boolean
		 **/
		public function chkIsNotExists($forum_title, $forum_id, $forum_table, $err_tip='')
			{
				$sql = 'SELECT COUNT(forum_id) AS count'.
						' FROM '.$forum_table.
						' WHERE forum_title = '.$this->dbObj->Param($forum_title);
				$fields_value_arr[] = $forum_title;
				if ($forum_id)
					{
						$sql .= ' AND forum_id != '.$this->dbObj->Param($forum_id);
						$fields_value_arr[] = $forum_id;
					}
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, $fields_value_arr);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				if ($row['count'])
					{
						$this->fields_err_tip_arr['forum_title'] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * To create a group
		 *
		 * @param 		string $table_name forums
		 * @param 		integer $forum_id
		 * @access public
		 * @return void
		 **/
		public function createForumTitle($forum_id)
			{
				$this->setFormField('seo_title', $this->getSeoTitleForForum($this->fields_arr['forum_title'], $this->fields_arr['forum_id']));
				if ($forum_id)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['forums'].' SET'.
								' forum_title = '.$this->dbObj->Param($this->fields_arr['forum_title']).
								', seo_title = '.$this->dbObj->Param($this->fields_arr['seo_title']).
								', forum_description = '.$this->dbObj->Param($this->fields_arr['forum_description']).
								' WHERE forum_id = '.$this->dbObj->Param($forum_id).'';
						$fields_value_arr = array($this->fields_arr['forum_title'],
												  $this->fields_arr['seo_title'],
												  $this->fields_arr['forum_description'], $forum_id);
				    }
					else
						{
							$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['forums'].' SET'.
									' forum_title = '.$this->dbObj->Param($this->fields_arr['forum_title']).
									', seo_title = '.$this->dbObj->Param($this->fields_arr['seo_title']).
									', forum_description = '.$this->dbObj->Param($this->fields_arr['forum_description']).
									', forum_userid = '.$this->dbObj->Param('forum_userid').
									', publish_status = '.$this->dbObj->Param('publish').
									', date_added = NOW()';

							if(!$this->CFG['admin']['forums']['auto_publish']['allowed'])
								{
									$sql .= ', forum_status=\'ToActivate\'';
								}

							$fields_value_arr = array($this->fields_arr['forum_title'],
												  $this->fields_arr['seo_title'],
													  $this->fields_arr['forum_description'],
													  $this->CFG['user']['user_id'],
													  $this->fields_arr['publish']);
						}
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, $fields_value_arr);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return true;
			}

			public function paymentUpgradeDisplay()
				{
					$notifyForum_arr = array();

					if(chkIsPaymentAllowed('payment_forum'))
						{
							if(chkIsPaymentAlertMessageAllowed())
								{
									$req_count = $this->getPlanLogForForum();
									$req_today_count = $this->getPlanLogForForumPerDay();
									$req_count = $req_count < 0?'0':$req_count;
									$req_today_count = $req_today_count < 0?'0':$req_today_count;

									if($req_count === $this->CFG['plan']['unlimited_text'])
										$notifyForum_arr['total_notify'] = $this->CFG['plan']['unlimited_text'];
									elseif(chkIsPaymentUpgradeAllowed())
										{
											$notifyForum_arr['total_notify'] = str_ireplace('VAR_LIMIT', $req_count, $this->LANG['total_notify_upgrade']);
											$notifyForum_arr['total_notify'] = str_ireplace('VAR_UPGRADE', '<a href="'.getAnovaUrl('paymentupgrade', '', '', 'members').'">'.$this->LANG['forum_upgrade'].'</a>', $notifyForum_arr['total_notify']);
										}
									else
										$notifyForum_arr['total_notify'] = str_ireplace('VAR_LIMIT', $req_count, $this->LANG['total_notify_admin']);

									if($req_today_count === $this->CFG['plan']['unlimited_text'])
										$notifyForum_arr['today_notify'] = $this->CFG['plan']['unlimited_text'];
									elseif(chkIsPaymentUpgradeAllowed())
										{
											$notifyForum_arr['today_notify'] = str_ireplace('VAR_LIMIT', $req_today_count, $this->LANG['today_notify_upgrade']);
											$notifyForum_arr['today_notify'] = str_ireplace('VAR_UPGRADE', '<a href="'.getAnovaUrl('paymentupgrade', '', '', 'members').'">'.$this->LANG['forum_upgrade'].'</a>', $notifyForum_arr['today_notify']);
										}
									else
										$notifyForum_arr['today_notify'] = str_ireplace('VAR_LIMIT', $req_today_count, $this->LANG['today_notify_admin']);
								}

						}
					return $notifyForum_arr;
				}

				public function getPlanLogForForum()
					{
						$sql = 'SELECT forum_id FROM '.$this->CFG['db']['tbl']['forums'].
								' WHERE forum_userid = '.$this->dbObj->Param('forum_userid').
								' AND date_added >= '.$this->dbObj->Param('date_added');

						$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($this->CFG['plan']['plan_total_forum'] != $this->CFG['plan']['unlimited'])
							return ($this->CFG['plan']['plan_total_forum'] - $numrows);
						else
							return $this->CFG['plan']['unlimited_text'];

					}

				public function getPlanLogForForumPerDay()
					{
						$sql = 'SELECT forum_id FROM '.$this->CFG['db']['tbl']['forums'].
						       ' WHERE forum_userid = '.$this->dbObj->Param('forum_userid').
							   ' AND DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') >= DATE_FORMAT((select DATE_SUB(now(), INTERVAL 1 DAY)),\''.$this->CFG['mysql_format']['date_time'].'\')';

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

						$numrows = $rs->PO_RecordCount();

						if($this->CFG['plan']['plan_forum_perday'] != $this->CFG['plan']['unlimited'])
							return ($this->CFG['plan']['plan_forum_perday'] - $numrows);
						else
							return $this->CFG['plan']['unlimited_text'];
					}
				public function totalPostedForumCount($user_id)
					{
						if(!chkIsPaymentAllowed('payment_forum'))
							return true;

						$sql = 'SELECT forum_id FROM '.$this->CFG['db']['tbl']['forums'].
						       ' WHERE forum_userid = '.$this->dbObj->Param('forum_userid').
							   ' AND date_added >= '.$this->dbObj->Param('date_added');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($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_total_forum'] || $this->CFG['plan']['plan_total_forum'] == $this->CFG['plan']['unlimited'])
							return true;
						else
							return false;
					}
				public function todayPostedForumCount($user_id)
					{
						if(!chkIsPaymentAllowed('payment_forum'))
							return true;

						$sql = 'SELECT forum_id FROM '.$this->CFG['db']['tbl']['forums'].''.
						       ' WHERE forum_userid = '.$this->dbObj->Param('forum_userid').''.
							   ' AND DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') >= DATE_FORMAT((select DATE_SUB(now(), INTERVAL 1 DAY)),\''.$this->CFG['mysql_format']['date_time'].'\')';

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($user_id));
						if (!$rs)
						    trigger_db_error($this->dbObj);
						$numrows = $rs->PO_RecordCount();
						if($numrows < $this->CFG['plan']['plan_forum_perday'] || $this->CFG['plan']['plan_forum_perday'] == $this->CFG['plan']['unlimited'] )
							return true;
						else
							return false;
					}

	}
//<<<<<-------------- Class ForumFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$forum = new ForumFormHandler();
if(!chkIsAllowedModule(array('forums')))
	Redirect2URL(getForumsUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$forum->setPageBlockNames(array('form_create_forum'));

//default form fields and values...
$forum->setFormField('forum_id', '');
$forum->setFormField('forum_title', '');
$forum->setFormField('seo_title', '');
$forum->setFormField('forum_status', '');
$forum->setFormField('forum_description', '');
$forum->setFormField('publish', 'Yes');

$forum->setAllPageBlocksHide();
$forum->sanitizeFormInputs($_REQUEST);
if (!isMember())
	{
		$_SESSION['url'] = getForumsUrl('forumsaddtitle', '', '', 'members');
		$_SESSION['login_error'] = 'login_err_authorization_required';
		Redirect2URL(getUrl('login'));
	}
elseif (!$CFG['admin']['forums']['add_title'])
	{
		Redirect2URL(getForumsUrl('forums'));
	}
if ($forum->isFormGETed($_GET, 'forum_id'))
	{
		$forum->chkIsNotEmpty('forum_id', $LANG['err_tip_compulsory'])and
			$forum->chkIsNumeric('forum_id', $LANG['err_tip_compulsory'])and
				$forum->isValidForumId($CFG['db']['tbl']['forums'], $forum->getFormField('forum_id'), $LANG['forums_err_tip_invalid_forum_id']);
		if ($forum->isValidFormInputs())
			{
				//
			}
		else
			{
				$forum->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$forum->setPageBlockShow('block_msg_form_error');
			}
	}
elseif ($forum->isFormPOSTed($_POST, 'forum_submit'))
	{
		//validations...
		$forum->chkIsNotEmpty('forum_title', $LANG['err_tip_compulsory'])and
			$forum->chkIsNotExists($forum->getFormField('forum_title'), $forum->getFormField('forum_id'), $CFG['db']['tbl']['forums'], $LANG['forum_err_tip_forum_title_exists']);
		$forum->chkIsNotEmpty('forum_description', $LANG['err_tip_compulsory']);

		$forum->getFormField('forum_id')and
			$forum->chkIsNotEmpty('forum_id', $LANG['err_tip_compulsory'])and
				$forum->chkIsNumeric('forum_id', $LANG['err_tip_compulsory']);
		$forum->isValidFormInputs()and
			$forum->createForumTitle($forum->getFormField('forum_id'));
		$forum->setAllPageBlocksHide();
		if ($forum->isValidFormInputs())
			{
				$forum->setPageBlockShow('block_msg_form_success');
				//now redirect to members page...
				Redirect2URL(getForumsUrl('forums','?msg=sucess', '?msg=sucess'));
			}
		else //error in form inputs
			{
				$forum->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$forum->setPageBlockShow('block_msg_form_error');
			}
	}
elseif ($forum->isFormPOSTed($_POST, 'forum_cancel'))
	{
		//now redirect to members page...
		Redirect2URL(getForumsUrl('forums'));//getForumsUrl('forums.php', 'forum/')
	}

//$forum->setPageBlockShow('form_create_forum'); //default page block. show it. All others hidden
$forum->forum_add['notifyForum_arr'] = $forum->paymentUpgradeDisplay();

if (!$forum->isAllowedToAsk())
	{
		$forum->setAllPageBlocksHide();
		$forum->setPageBlockShow('block_msg_form_error');
		$forum->setCommonErrorMsg($LANG['forums_info_not_allowed_to_post']);
	}
else
	{
		if($forum->totalPostedForumCount($CFG['user']['user_id']))
			  {
				if($forum->todayPostedForumCount($CFG['user']['user_id']))
					{
						if (chkIsPaymentAllowed('payment_forum'))
							{
								$forum->overRideConfigs();
								$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$forum->LANG['forum_upgrade'].'</a>';
								if(!chkIsPaymentUpgradeAllowed())
									$upgrade = $LANG['inform_site_admin'];
							}
						$forum->setPageBlockShow('form_create_forum');
					}
				else
					{
						$forum->setAllPageBlocksHide();
						$forum->setPageBlockShow('block_msg_form_error');
						$forum->setCommonErrorMsg($LANG['info_not_allowed_to_ask_today']);
					}
			   }
			else
			   {
			   		$forum->setAllPageBlocksHide();
			   		$forum->setPageBlockShow('block_msg_form_error');
					$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$forum->LANG['forum_upgrade'].'</a>';
					if(!chkIsPaymentUpgradeAllowed())
							$upgrade = $LANG['inform_site_admin'];
					$LANG['info_limit_exceeded_to_ask_forum'] = str_ireplace('VAR_UPGRADE', $upgrade, $LANG['info_limit_exceeded_to_ask_forum']);
					$forum->setCommonErrorMsg($LANG['info_limit_exceeded_to_ask_forum']);
			   }

	}
$forum->back_to_forums['url'] = getForumsUrl('forums');
$forum->button_value = $LANG['forum_create_title'];
if ($forum->getFormField('forum_id'))
	{
		$forum->button_value = $LANG['common_update'];
	}
$forum->displaytabs['allForumsLI'] = $forum->displaytabs['myForumsLI'] = $forum->displaytabs['postForumsLI'] = '';
$clsLeftActiveQuestionsLink = 'clsLeftActiveQuestionsLink';
$forum->myforums_link = getForumsUrl('forums', '?my=1', '?my=1', 'members');
$forum->allforums_link = getForumsUrl('forums');
$forum->forumsAddTitle_url = getForumsUrl('forumsaddtitle', '', '', 'members');
$forum->displaytabs['postForumsLI'] = $clsLeftActiveQuestionsLink;
//<<<<<-------------------- Code ends----------------------//
//-------------------- Page block templates begins -------------------->>>>>//

//<<<<<-------------------- Page block templates ends -------------------//
//include the header file
$forum->includeHeader();
//include the content of the page
setTemplateFolder('members/', $CFG['admin']['index']['forum_module']);
$smartyObj->display('forumsAddTitle.tpl');
//include the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
?>
<script type="text/javascript">
needLiveValidation('forum_title',Array('Presence'));
needLiveValidation('forum_description',Array('Presence'));
</script>
<?php
$forum->includeFooter();
?>