<?php
	require(dirname(__FILE__).'/../init.php');

	define('AKB_WL_LANG_FILE',			dirname(__FILE__).'/../includes/language/'.$GLOBALS['currentLanguage'].'/whitelabel.ini');
	define('AKB_LANG_FILE',				dirname(__FILE__).'/../includes/language/'.$GLOBALS['currentLanguage'].'/back_language.ini');
	define('AKB_TPL_LOAD_PATH',			dirname(__FILE__).'/../templates/'.$GLOBALS['template'].'/');
	define('AKB_TPL_PHP_PATH',			dirname(__FILE__).'/includes/display/');
	define('AKB_TPL_HTTP_PATH',			$GLOBALS['pathToKB'].'/templates/'.$GLOBALS['template'].'/');
	define('AKB_TPL_IMAGE_PATH',		AKB_TPL_HTTP_PATH.'Images');
	define('AKB_PANEL_LOAD_PATH',		AKB_TPL_LOAD_PATH.'Panels/');
	define('AKB_SNIPPET_LOAD_PATH',	AKB_TPL_LOAD_PATH.'Snippets/');
	define('CLASS_DIR',					dirname(__FILE__).'/includes/classes');

	define("SEPTOKEN","!~_!#__akb");

	require(dirname(__FILE__).'/../lib/email.php');
	require(dirname(__FILE__).'/includes/helpers/helper.template.php');

	$GLOBALS['SNIPPETS'] = '';
	$GLOBALS['Message'] = '';
	$GLOBALS['HidePanels'] = array();
	
	require(CLASS_DIR.'/../../../includes/classes/class.helper.php');
	require(CLASS_DIR.'/../../../includes/classes/class.template.php');
	require(CLASS_DIR.'/../../../includes/classes/class.questions.php');
	require(CLASS_DIR.'/../../../includes/classes/class.auth.php');
	require(CLASS_DIR.'/class.category.php');
	require(CLASS_DIR.'/class.news.php');
	require(CLASS_DIR.'/class.admintable.php');
	require(CLASS_DIR.'/class.install.php');
	require(CLASS_DIR.'/class.engine.php');
	require(CLASS_DIR.'/class.group.php');
	
	$GLOBALS['AKB_CLASS_HELPER']	= new AKB_HELPER();

	$GLOBALS['AKB_CLASS_CATEGORY']	= new AKB_CATEGORY();
	$GLOBALS['AKB_CLASS_GROUP']		= new AKB_GROUP();
	$GLOBALS['AKB_CLASS_NEWS']		= new AKB_NEWS();
	$GLOBALS['AKB_CLASS_TEMPLATE']	= new AKB_TEMPLATE();
	$GLOBALS['AKB_CLASS_QUESTIONS']	= new AKB_QUESTIONS();
	$GLOBALS['AKB_CLASS_AUTH']		= new AKB_AUTH();
	$GLOBALS['AKB_CLASS_INSTALL']	= new AKB_INSTALL();
	
	$GLOBALS['AKB_CLASS_TEMPLATE']->disabledEmbeddedTemplateOverride = true;
	
	$GLOBALS['SNIPPETS'] = '';
	
	if (!pageLoad()) {
		AKB_AUTH::ShowLoginForm(GetLang('SessionLoggedOutMessage'));
		die();
	}
	
	// Is the site down for maintenance?
	if ($GLOBALS['downForMaintenance'] == 1) {
		// Show the down for maintenance panel
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle(GetLang('hpDownForMaintenance'));
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Maintenance');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		die();
	}
	
	if (FrontendAccess()) {
		$questionid = (int)@$_POST['id'];
		if ($questionid > 0) {
			if ($_SESSION['user']->verify('question', 'edit')) {
				
				$title = trim($_POST['title']);
				$answer = trim($_POST['answer']);
				
				if (($title != "") && ($answer != "")) {
					$approvalGroups = array();
					$question = new API_QUESTION();
					$question->load($questionid);
					$cat = $question->get_category_associations($questionid);
					$approvalCats = array();
					$emailUsers = array();

					$GLOBALS['AKB_CLASS_AUTH']		= new AKB_AUTH;

					// Get all the cat that always needs approval
					$query = sprintf("select distinct c.categoryid, c.approvaltype from %scategoryassociations ca, %scategories c  where ca.questionid='%d' and ca.categoryid = c.categoryid ", $GLOBALS["tablePrefix"],$GLOBALS["tablePrefix"], $questionid);
					$result = $GLOBALS['AKB_DB']->Query($query);
	
					$catAlwaysReqApp = array();
					while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
						if ($row['approvaltype'] == CATEGORIES_ALWAYS_APPROVAL) {
							$catAlwaysReqApp[] = $row['categoryid'];
						}
					}
					
					if (validUrl() && sizeof($catAlwaysReqApp)) {
						if ($question->workflowstatus == WF_STATUS_PENDING || $question->workflowstatus == WF_STATUS_REPENDING) {
							// Has permission
							if ($GLOBALS['AKB_CLASS_AUTH']->HasApprovalAccess($catAlwaysReqApp)) {
								// Allow edition and change the status to approved.
								$_POST['workflowstatus'] = WF_STATUS_APPROVED;
							} else {
								return;
							}
						} else {
	
							if ($GLOBALS['AKB_CLASS_AUTH']->HasApprovalAccess($catAlwaysReqApp, true)) {
								// Allow edition and change the status to auto approved.
								$_POST['workflowstatus'] = WF_STATUS_AUTO_APPROVED;
							} else {
								// Allow edition, but the change will appear after approval.
								$_POST['workflowstatus'] = WF_STATUS_REPENDING;
								// Need to check if email needs to be sent out...
								// Get all the valid categories that need appovals.
								$catIds = "'" . implode("','", $cat) . "'";
								$query = sprintf("SELECT categoryid, name from %scategories where categoryid IN (%s) AND approvaltype != '%d'", $GLOBALS['tablePrefix'], $catIds, CATEGORIES_NO_APPROVAL);
								$query .= sprintf(" AND approvaltype != '%d' ", CATEGORIES_ONCE_APPROVAL);
								
								$result = $GLOBALS['AKB_DB']->Query($query);
								while($row = $GLOBALS['AKB_DB']->Fetch($result)) {
									$approvalCats['ids'][] = $row['categoryid'];
									$approvalCats['names'][] = $row['name'];
								}
								
								if (isset($approvalCats['ids'])) {
									$approvalGroups = $GLOBALS['AKB_CLASS_CATEGORY']->GetApprovalGroups($approvalCats['ids']);
									if (!sizeof($approvalGroups)) {
										return;
									}
									
									// Get the name to be emailed.
									$totalCategoriesNames = implode("\n* ", $approvalCats['names']);
									if (sizeof($approvalCats['names']) == 1) {
										$totalCategoriesNames = "\n* " . array_pop($approvalCats['names']);
									}
									
									$GLOBALS['AKB_CLASS_GROUP']->getMembers($approvalGroups);
		
									if (!isset($GLOBALS['AKB_CLASS_GROUP']->members) || !is_array($GLOBALS['AKB_CLASS_GROUP']->members) || !sizeof($GLOBALS['AKB_CLASS_GROUP']->members)) {
										return;
									}
									$approvalMembers = $GLOBALS['AKB_CLASS_GROUP']->members;
									
									foreach ($approvalMembers as $eachGid) {
										foreach ($eachGid as $eachMember) {
											if (!in_array($eachMember['userid'], $emailUsers)) {
												$emailUsers[] = $eachMember['userid'];
											}
										}
									}
									
									$userIds = "'" .implode("','", $emailUsers). "'";
									$query = sprintf("SELECT * from %susers where userid IN (%s) AND status = '%d'", $GLOBALS['tablePrefix'], $userIds, 1);
									$result = $GLOBALS['AKB_DB']->Query($query);
									while($row = $GLOBALS['AKB_DB']->Fetch($result)) {
										
										$name = $row['username'];
										if (trim($row['firstname']) != '' || trim($row['lastname']) != '') {
											$name = trim($row['firstname']) . ' ' . trim($row['lastname']);
										}
										
										$message = sprintf(GetLang('ApprovalArticleMessageEdit'), $name,"\n\n", $totalCategoriesNames,"\n\n", $GLOBALS['pathToKB'], $questionid, 1);
										$subject = GetLang('ApprovalArticleSubjectEdit');
										
										$email = new Email_API();
										setEmailVars($email);
										$email->Set('CharSet', $GLOBALS['charset']);
										$email->From($GLOBALS['contactEmail']);
										$email->Set('Subject', $subject);
										$email->AddBody('text', $message);
										$email->AddRecipient($row['email'], '', 'h');
										$email_result = $email->Send();
									}

									
								} else {
									$_POST['workflowstatus'] = WF_STATUS_APPROVED;
								}
							}
						}
					} else {
						$_POST['workflowstatus'] = WF_STATUS_AUTO_APPROVED;
					}
					if ($question->save()) {
						$akbq = new AKB_QUESTIONS();
						$akbq->_questionid = $questionid;
						$akbq->SendSubscriberEmails($questionid);
						$akbq->_GetAnswer();
						$title = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders($akbq->_data['title']);
						echo $title.SEPTOKEN.$akbq->_GetAnswer().SEPTOKEN.$_POST['workflowstatus'];
						
						die();
					}
				} else {
					$_POST['workflowstatus'] = WF_STATUS_AUTO_APPROVED;
				}
			}
		}
	}
	
	die("false");

	// {{{ If debug is on, print the debug footer
	if (isset($GLOBALS['debug']) && $GLOBALS['debug'] == true) {
		$end_time = microtime_float();
		if (function_exists('memory_get_usage')) {
			$mem_used = memory_get_usage()/1024/1024;
		} else {
			$mem_used = 0;
		}
		printf('<div id="debug">Time taken to generate the page %.4f seconds and performed %d sql queries and used %.4f MB of memory</div>', ($end_time - $start_time), $GLOBALS['AKB_DB']->NumQueries, $mem_used);
	}
	// }}}
?>