<?php
/**
 * This file handles the bug report
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		BugHandler
 * @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 		2009-01-05
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/reportBugs.php';
$CFG['lang']['include_files'][] = 'languages/%s/lists_array/bug_category_list_array.php';
$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

$CFG['is']['ajax_page'] = false;
if(isset($_REQUEST['ajax_page']) and $_REQUEST['ajax_page'])
	{
		$CFG['is']['ajax_page'] = true;
	}

//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------- Class ContactUsHandler begins --------------->>>>>//
/**
 * BugHandler
 * Class to handle the contact us page
 *
 * @package
 * @author Senthil
 * @copyright Copyright (c) 2010
 * @version $Id$
 * @access public
 */
class BugHandler extends ListRecordsHandler
    {
		/**
		 * productNews::buildSortQuery()
		 *
		 * @return
		 **/
		public function buildSortQuery()
			{
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
			}

		/**
		 * BugHandler::buildConditionQuery()
		 *
		 * @return
		 */
		public function buildConditionQuery()
			{
				if($this->getFormField('order') == 'all')
					$this->sql_condition = 'parent_id = 0';
				elseif($this->getFormField('order') == 'close')
					$this->sql_condition = 'parent_id = 0 AND status = \'Closed\'';
				elseif($this->getFormField('order') == 'open')
					$this->sql_condition = 'parent_id = 0 AND status = \'Open\'';
				else
					$this->sql_condition = 'parent_id = 0 AND status = \'Open\'';
			}

		/**
		 * BugHandler::restoreFormFields()
		 *
		 * @return
		 */
		public function restoreFormFields()
			{
				$this->setFormField('subject', '');
				$this->setFormField('message', '');
			}

		/**
		 * BugHandler::storeBugs()
		 *
		 * @return
		 */
		public function storeBugs()
			{
				$secret_key = microtime();
				$secret_key = md5($secret_key);
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['bugs'].
						' SET bug_subject = '.$this->dbObj->Param('bug_subject').
						', bug_content = '.$this->dbObj->Param('bug_content').
						', secret_key = '.$this->dbObj->Param('secret_key').
						', reply_from = '.$this->dbObj->Param('sitename').
						', date_added = NOW()';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['lists_array']['bug_category'][$this->getFormField('subject')], $this->getFormField('message'), $secret_key, $this->CFG['site']['name']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$bug_id = $this->dbObj->Insert_ID();

				$post_value = 'bid='.$bug_id.'&bsubject='.urlencode($this->CFG['lists_array']['bug_category'][$this->getFormField('subject')]).
							'&bcontent='.urlencode($this->getFormField('message')).
							'&bsite='.urlencode($this->CFG['site']['url']).'&skey='.$secret_key.'&sitename='.urlencode($this->CFG['site']['name']);

				postForm($this->CFG['members']['receivebugs'], $post_value);
			}

		/**
		 * BugHandler::populateBugReplyList()
		 *
		 * @param mixed $bid
		 * @return
		 */
		public function populateBugReplyList($bid)
			{
				$sql = 'SELECT DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') AS date_added'.
						', bug_id, bug_content, status, parent_id, reply_from'.
						' FROM '.$this->CFG['db']['tbl']['bugs'].
						' WHERE parent_id = '.$this->dbObj->Param('parent_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($bid));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$populateBugReplyList_arr = array();
				if($rs->PO_RecordCount())
					{
						$inc = 0;
						while($row = $rs->FetchRow())
							{
								$row['bug_content'] = nl2br(wordWrapManual($row['bug_content'], 200));
								$row['bug_content'] = html_entity_decode($row['bug_content'], ENT_QUOTES);
								$populateBugReplyList_arr[$inc]['record'] = $row;
								$populateBugReplyList_arr[$inc]['replySpanIDId'] = 'replySpanID_'.$row['bug_id'];
								if($row['status'] == 'Open')
									{
									$populateBugReplyList_arr[$inc]['replybugs_open']['url'] = $this->CFG['site']['url'].'admin/reportBugs.php';
									}
								$inc++;
							}
					}
				return $populateBugReplyList_arr;
			}

		/**
		 * BugHandler::populateBugReplyListAjax()
		 *
		 * @param mixed $bid
		 * @return
		 */
		public function populateBugReplyListAjax($bid)
			{
				global $smartyObj, $LANG,$CFG ;
				$sql = 'SELECT bug_id, bug_content, status, parent_id, reply_from'.
						', DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') AS date_added'.
						' FROM '.$this->CFG['db']['tbl']['bugs'].
						' WHERE parent_id = '.$this->dbObj->Param('bug_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($bid));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$populateBugReplyList_arr = array();
				if($rs->PO_RecordCount())
					{
						$inc = 0;
						while($row = $rs->FetchRow())
							{
								$row['bug_content'] = nl2br(wordWrapManual($row['bug_content'], 200));
								$row['bug_content'] = html_entity_decode($row['bug_content'], ENT_QUOTES);
								$populateBugReplyList_arr[$inc]['record'] = $row;

								$populateBugReplyList_arr[$inc]['replySpanIDId'] = 'replySpanID_'.$row['bug_id'];
								if($row['status'] == 'Open')
									{
									$populateBugReplyList_arr[$inc]['replybugs_open']['url'] = $this->CFG['site']['url'].'admin/reportBugs.php';
									}
								$inc++;
							}
					}
				if($this->getFormField('success') == 'success')
					$smartyObj->assign('success','success');
				else
					$smartyObj->assign('success','');
				$smartyObj->assign('LANG',$LANG);
				$smartyObj->assign('sitename',$this->CFG['site']['name']);
				$smartyObj->assign('populateBugReplyList_arr',$populateBugReplyList_arr);
				setTemplateFolder('admin/');
				$smartyObj->display('replyBugsListAjax.tpl');
			}

		/**
		 * BugHandler::getBugDetails()
		 *
		 * @param mixed $bug_id
		 * @return
		 */
		public function getBugDetails($bug_id)
			{
				$sql = 'SELECT  bug_content, DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') AS date_added, status, parent_id'.
						' FROM '.$this->CFG['db']['tbl']['bugs'].
						' WHERE bug_id = '.$this->dbObj->Param('bid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->getFormField('bid')));
				    if (!$rs)
					    trigger_db_error($this->dbObj);
				if($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row;
					}
			}

		/**
		 * BugHandler::populateBugsList()
		 *
		 * @return
		 */
		public function populateBugsList()
			{
				$populateBugsList_arr = array();
				$inc = 0;
				while($row = $this->fetchResultRecord())
					{
						$row['bug_content'] = nl2br(wordWrapManual($row['bug_content'], 75));
						$populateBugsList_arr[$inc]['record'] = $row;
						$populateBugsList_arr[$inc]['bug_id'] = $row['bug_id'];
						$populateBugsList_arr[$inc]['populateBugReplyList'] = $this->populateBugReplyList($row['bug_id']);
						$populateBugsList_arr[$inc]['replySpanIDId'] = 'replySpanID_'.$row['bug_id'];
						if($row['status'] == 'Open')
							{
								$populateBugsList_arr[$inc]['replybugs_open']['url'] = $this->CFG['site']['url'].'admin/reportBugs.php';
							}
						$inc++;
					}
				return $populateBugsList_arr;
			}

		/**
		 * BugHandler::updateBugStatus()
		 *
		 * @param mixed $table_name
		 * @param mixed $status
		 * @return
		 */
		public function updateBugStatus($table_name, $status)
		    {
				if(!$this->fields_arr['bug_ids'])
					return ;

				$secret_key = microtime();
				$secret_key = md5($secret_key);
				$id = $this->fields_arr['bug_ids'];
				$date_closed = '';
				if ($status == 'Closed')
					$date_closed = ', date_closed = NOW()';
				$sql = 'UPDATE '.$table_name.' SET status='.$this->dbObj->Param($status).$date_closed.
						' WHERE bug_id IN ('.$id.') OR parent_id IN ('.$id.')'.
						' AND status =\'Open\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($status));
				if (!$rs)
				        trigger_db_error($this->dbObj);

				$post_value = 'bid='.$id.'&bsite='.urlencode($this->CFG['site']['url']).'&bstatus=Closed&skey='.$secret_key;
				postForm($this->CFG['members']['receivebugs'], $post_value);
		    }

		/**
		 * BugHandler::addReply()
		 *
		 * @param mixed $bid
		 * @param mixed $parent_id
		 * @param mixed $parent_bug_content
		 * @return
		 */
		public function addReply($bid, $parent_id,$parent_bug_content)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['bugs'].
						' SET bug_content = '.$this->dbObj->Param('user_reply').
						', parent_id = '.$parent_id.
						', reply_from = '.$this->dbObj->Param('sitename').
						', date_added = NOW()';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->getFormField('user_reply'), $this->CFG['site']['name']));
				if (!$rs)
						trigger_db_error($this->dbObj);

				$bug_id = $parent_id;
				$post_value = 'bid='.$bug_id.'&bcontent='.urlencode($this->getFormField('user_reply')).
							'&bsite='.urlencode($this->CFG['site']['url']).'&parent_id='.$parent_id.'&reply=reply&parent_bug_content='.urlencode($parent_bug_content).'&sitename='.urlencode($this->CFG['site']['name']).'';
				postForm($this->CFG['members']['receivebugs'], $post_value);

			}

		/**
		 * BugHandler::getParentBugDetails()
		 *
		 * @param mixed $bug_id
		 * @return
		 */
		public function getParentBugDetails($bug_id)
			{
				$sql = 'SELECT  bug_id, bug_content'.
						' FROM '.$this->CFG['db']['tbl']['bugs'].
						' WHERE bug_id = '.$this->dbObj->Param('bid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($bug_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row;
					}
			}
    }
//<<<<<---------------- Class BugHandler ends -------------//
//--------------------- Code begins -------------------->>>>>//
$BugHandler = new BugHandler();
$BugHandler->setPageBlockNames(array('block_reportbugs', 'block_bugs_list', 'cancel_option_to_reply', 'show_option_to_reply', 'post_your_reply', 'block_msg_form_success', 'block_msg_form_error'));
//set the form field
$BugHandler->restoreFormFields();
$BugHandler->setAllPageBlocksHide();
/*********** Page Navigation Start *********/
$BugHandler->setFormField('mode', '');
$BugHandler->setFormField('bug_ids', '');
$BugHandler->setFormField('action', '');
$BugHandler->setFormField('orderby_field', 'date_added');
$BugHandler->setFormField('orderby', 'DESC');
$BugHandler->setFormField('showOptionToReply', '');
$BugHandler->setFormField('reply', '');
$BugHandler->setFormField('bug_id', '');
$BugHandler->setFormField('parent_id', '');
$BugHandler->setFormField('bug_content', '');
$BugHandler->setFormField('user_reply', '');
$BugHandler->setFormField('not_id', '');
$BugHandler->setFormField('success', '');
$BugHandler->setFormField('cancelOptionToReply', '');
$BugHandler->setFormField('bid', '');
$BugHandler->setFormField('order', 'open');
$BugHandler->setTableNames(array($CFG['db']['tbl']['bugs']));
$BugHandler->setReturnColumns(array('bug_id', 'bug_subject', 'bug_content', 'DATE_FORMAT(date_added, \''.$CFG['mysql_format']['date_time'].'\') AS date_added', 'status', 'parent_id', 'reply_from'));
/************ page Navigation stop *************/

$BugHandler->sanitizeFormInputs($_REQUEST);
$BugHandler->LANG['reportbugs_page_title'] = $LANG['reportbugs_title'];
if ($BugHandler->isFormPOSTed($_REQUEST, 'showOptionToReply'))
	{
		ob_start();
		$BugHandler->sanitizeFormInputs($_REQUEST);
		$showOptionToReply_arr = array();
		$bug_id = $BugHandler->getFormField('bug_id');
		$replySpanIDId = 'replySpanID_'.$BugHandler->getFormField('bug_id');
		$showOptionToReply_arr['submit']['onclick'] = $CFG['site']['url'].'admin/reportBugs.php?ajax_page=true&postYourReply=1';
		$showOptionToReply_arr['cancel']['onclick'] = $CFG['site']['url'].'admin/reportBugs.php';
		$BugHandler->setPageBlockShow('show_option_to_reply');
		$BugHandler->includeAjaxHeader();
		$smartyObj->assign('showOptionToReply_arr', $showOptionToReply_arr);
		$smartyObj->assign('bug_id', $bug_id);
		$smartyObj->assign('replySpanIDId', $replySpanIDId);
		setTemplateFolder('admin/');
		$smartyObj->display('replyBugsAjax.tpl');
		$BugHandler->includeAjaxFooter();
		die();
	}
if ($BugHandler->isFormPOSTed($_REQUEST, 'cancelOptionToReply'))
	{
		ob_start();
		$BugHandler->sanitizeFormInputs($_REQUEST);
		$BugHandler->setPageBlockShow('cancel_option_to_reply');
		$BugHandler->includeAjaxHeader();
		setTemplateFolder('admin/');
		$smartyObj->display('replyBugsAjax.tpl');
		$BugHandler->includeAjaxFooter();
		die();
	}
if ($BugHandler->isFormPOSTed($_REQUEST, 'postYourReply'))
	{
		ob_start();
		$BugHandler->sanitizeFormInputs($_REQUEST);
		if ($BugHandler->getFormField('bid'))
			{
				$BugHandler->chkIsNotEmpty('user_reply', $BugHandler->LANG['err_tip_compulsory']);
				if ($BugHandler->isValidFormInputs())
					{
						$parent_details = $BugHandler->getParentBugDetails($BugHandler->getFormField('bid'));
						$BugHandler->addReply($BugHandler->getFormField('bid'),$parent_details['bug_id'], $parent_details['bug_content'] );
						$BugHandler->setFormField('success', 'success');
						$BugHandler->setCommonSuccessMsg($LANG['reportbugsreply_success']);
						$BugHandler->setPageBlockShow('block_msg_form_success');
						$BugHandler->populateBugReplyListAjax($BugHandler->getFormField('bid'));
						?>
						<script defer="defer" language="javascript" type="text/javascript">
							function hideMsgBox()
								{
									var a =  <?php echo $BugHandler->getFormField('bid');?>;
									document.getElementById("msgreplySpanID_"+ a).innerHTML = '';
								}
							hideMsgBox();
						</script>
						<?php
					}
				else
					{
						$BugHandler->populateBugReplyListAjax($BugHandler->getFormField('bid'));
						$BugHandler->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$BugHandler->setPageBlockShow('block_msg_form_error');
					}
				$BugHandler->includeAjaxHeader();
				setTemplateFolder('admin/');
				$smartyObj->display('replyBugsAjax.tpl');
				$BugHandler->includeAjaxFooter();
			}
		die();
	}

if($BugHandler->getFormField('mode')== 'add')
	{
		$BugHandler->setAllPageBlocksHide();
		$BugHandler->setPageBlockShow('block_reportbugs');
	}
else
    {
		$BugHandler->setAllPageBlocksHide();
		$BugHandler->setPageBlockShow('block_bugs_list');
    }

if ($BugHandler->isFormPOSTed($_POST, 'cancel'))
	{
		Redirect2URL($CFG['site']['relative_url'].'reportBugs.php');
	}
elseif ($BugHandler->isFormPOSTed($_POST, 'submit_reportbugs'))
	{
		$BugHandler->chkIsNotEmpty('subject', $BugHandler->LANG['err_tip_compulsory']);
		$BugHandler->chkIsNotEmpty('message', $BugHandler->LANG['err_tip_compulsory']);

		if ($BugHandler->isValidFormInputs())
			{
				$descriptions = stripString($BugHandler->getFormField('message'), $CFG['admin']['bug_max_size']);
				$BugHandler->setFormField('message', $descriptions);
				$BugHandler->storeBugs();
				$BugHandler->setCommonSuccessMsg($BugHandler->LANG['reportbugs_success']);
				$BugHandler->setAllPageBlocksHide();
				$BugHandler->setPageBlockShow('block_msg_form_success');
				$BugHandler->setPageBlockShow('block_bugs_list');
				$BugHandler->restoreFormFields();
			}
		else
			{
				$BugHandler->setCommonErrorMsg($BugHandler->LANG['common_msg_error_sorry']);
				$BugHandler->setPageBlockShow('block_msg_form_error');
			}
	}
elseif($BugHandler->isFormPOSTed($_POST, 'action') and $BugHandler->getFormField('bug_ids'))
	{
		$BugHandler->updateBugStatus($CFG['db']['tbl']['bugs'], 'Closed');
		$BugHandler->setAllPageBlocksHide();
		$BugHandler->setFormField('start', '0');
		$BugHandler->setPageBlockShow('block_bugs_list');
		$BugHandler->setPageBlockShow('block_msg_form_success');
		$BugHandler->setCommonSuccessMsg($LANG['bug_status_updated_succesfully']);

	}

if($BugHandler->isShowPageBlock('block_bugs_list'))
	{
		$BugHandler->LANG['reportbugs_page_title'] = $LANG['listbugs_title'];
		/****** navigtion continue*********/
		$BugHandler->buildSelectQuery();
		$BugHandler->buildConditionQuery();
		$BugHandler->buildSortQuery();
		$BugHandler->buildQuery();
		$BugHandler->executeQuery();

		if(!$BugHandler->isResultsFound())
			{
				$BugHandler->setPageBlockHide('block_bugs_list');
				$BugHandler->setPageBlockShow('block_msg_form_alert');
				$BugHandler->setCommonAlertMsg($LANG['common_no_records_found']);
			}
	}
$BugHandler->list_records_confirm_arr = array('start', 'numpg');
//<<<<--------------------Code Ends----------------------//

//--------------------Page block templates begins-------------------->>>>>//
if ($BugHandler->isShowPageBlock('block_bugs_list'))
	{
		$smartyObj->assign('smarty_paging_list', $BugHandler->populatePageLinksPOST($BugHandler->getFormField('start'), 'selListStaticForm'));
		$BugHandler->block_sel_page_list['hidden_arr'] = array('orderby','orderby_field','start','order');
		$BugHandler->block_sel_page_list['populateBugsList'] = $BugHandler->populateBugsList();
	}
$smartyObj->assign('all', $CFG['site']['url'].'admin/reportBugs.php?order=all');
$smartyObj->assign('open', $CFG['site']['url'].'admin/reportBugs.php?order=open');
$smartyObj->assign('close', $CFG['site']['url'].'admin/reportBugs.php?order=close');
setPageTitle($LANG['reportbugs_title']);
//include the header file
$BugHandler->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('reportBugs.tpl');
//includ the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
$BugHandler->includeFooter();
?>
<script type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm', 'selDelInfoconfirm');
	var replace_url = '<?php echo $CFG['site']['url'];?>login.php';
	var confirm_message = '';
	function getAction()
		{
			var act_value = document.selListStaticForm.action.value;
			if(act_value)
				{
					switch(act_value)
						{
							case '<?php echo $LANG['bug_close'];?>':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_close_the_bug'];?>';
								break;
						}
					$('msgConfirmText').innerHTML = confirm_message;
					document.msgConfirmform.action.value = act_value;
					document.msgConfirmform.act.value = '';
					Confirmation('selMsgConfirm', 'msgConfirmform', Array('bug_ids'), Array(multiCheckValue), Array('value'),'selListStaticForm');
				}
		}
</script>