<?php

	include_once(dirname(__FILE__).'/class.captcha.php');
	include_once(dirname(__FILE__).'/../../lib/email.php');

	class AKB_CONTACT
	{
		/**
		* HandlePage
		* The function which works out what to do with this page
		*
		* @return void
		*/
		function HandlePage()
		{
			// Determine which function to load
			$todo = isset($_REQUEST['ToDo']) ? $_REQUEST['ToDo'] : '';
			$offset = isset($_GET['offset']) ? $_GET['offset'] : null;

			if (substr($todo, 0, 7) == 'captcha' && $offset === null) {
				$offset = (int) substr($todo, 8);
				$todo = 'captcha';
			}

			switch ($todo) {
				case 'SendQuestion':
					if (isset($_POST) && !empty($_POST)) {
						$_SESSION['contact']['name'] = $_POST['name'];
						$_SESSION['contact']['email'] = $_POST['email'];
						$_SESSION['contact']['subject'] = $_POST['subject'];
						$_SESSION['contact']['message'] = $_POST['message'];
						if (isset($_POST['groupid'])) {
							$_SESSION['contact']['groupid'] = $_POST['groupid'];
						}
					}

					if ($this->CheckContactForm()) {
						$this->SendQuestion();
					} else {
						$this->ShowContactForm(true);
					}
				break;
				case 'captcha':
					if ($GLOBALS['useCaptchaCheck']) {
						$this->showCaptchaImg($offset);
					}
				break;
				default:
					$this->ShowContactForm();
			}
		}

		/**
		* ShowContactForm
		* Show the contact form page
		*
		* @return void
		*/
		function ShowContactForm($load_from_session=false)
		{
			if ($load_from_session) {
				$GLOBALS['name'] = $_SESSION['contact']['name'];
				$GLOBALS['email'] = $_SESSION['contact']['email'];
				$GLOBALS['subject'] = $_SESSION['contact']['subject'];
				$GLOBALS['message'] = $_SESSION['contact']['message'];
			} else {
				$GLOBALS['name'] = '';
				$GLOBALS['email'] = '';
				$GLOBALS['subject'] = '';
				$GLOBALS['message'] = '';
			}

			// Generate our captcha (the html)
			$captcha = new AKB_CAPTCHA();
			$captcha->generateSecret(CAPTCHA_LENGTH);

			$captcha->urlPrefix = GetUrl('contact', 0, 'ToDo=captcha');
			$GLOBALS['AKB_CAPTCHA'] = $captcha->generateHtml();

			$GLOBALS['ShowCaptcha'] = 'table-row';

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Contact');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SendQuestion
		* Send the contact email and/or save the submitted question to the
		* database for later
		*
		* @return void
		*/
		function SendQuestion()
		{
			// Do we need to save the question/comment to the database ?
			if ($GLOBALS['saveSubmittedContact']) {				
				// Check to make sure that if we are using the captcha checks
				// that the captcha check actually passes
				if ($GLOBALS['useCaptchaCheck'] == false || ( isset($_POST['captcha']) && isset($_SESSION['captchaSecret']) && $_POST['captcha'] == $_SESSION['captchaSecret']) ) {
					$sq = new API_SUBMITTEDQUESTION();
					$sq->create();
					$GLOBALS['Message'] = GetLang('conMessageThankyou');
					$GLOBALS['Title'] = GetLang('conMessageSent');
				} else {
					$GLOBALS['Title'] = GetLang('questCommentRejected');

					$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['Message'] .= GetLang('questCommentRejectedCaptcha');

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('ContactResults');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
					return;
				}
			}
			
			// Do we need to email the administrator ?
			if ($GLOBALS['sendContactEmail'] && ($GLOBALS['useCaptchaCheck'] == false || ( isset($_POST['captcha']) && isset($_SESSION['captchaSecret']) && $_POST['captcha'] == $_SESSION['captchaSecret']))) {
				
				// Send an email and/or store the question in the pending questions table
				if (empty($_POST['name'])) {
					$fromName = GetLang('conKBVisitor');
				} else {
					$fromName = $_POST['name'];
				}
				if (empty($_POST['email'])) {
					$fromEmail = $GLOBALS['contactEmail'];
				} else {
					$fromEmail = $_POST['email'];
				}
				$subject	= $_POST['subject'];
				$message	= $_POST['message'];

				// Only mail if the mail headers are clean
				if (!preg_match("%\n|\r%", $fromName) && !preg_match("%\n|\r%", $fromEmail)) {
					$message = sprintf("%s\n-----------------------------------------------------\n\n%s\n%s", GetLang('conSubmittedFromKB'), 'From: '.$fromName.' <'.$fromEmail.'>', $message);

					// If the chose a group, email the group otherwise email
					// the address set as the contactAdmin on the settings page
					$email = new Email_API();
					setEmailVars($email);
					
					$email->Set('CharSet', $GLOBALS['charset']);
					$email->From($fromEmail, $fromName);
					$email->Set('Subject', $subject);
					$email->AddBody('text', $message);
					
					if (isset($_POST['groupid'])
					&& (int) $_POST['groupid'] == $_POST['groupid']
					&& $_POST['groupid'] > 0) {
						$query = 'SELECT DISTINCT email
						FROM '.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'members m
						WHERE u.userid = m.userid
						AND email != ""
						AND m.groupid = '.((int) $_POST['groupid']);
						
						$result = $GLOBALS['AKB_DB']->Query($query);
						if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
							while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
								$email->AddRecipient($row['email'], '', 't');
								$email_result = $email->Send();
								$email->ClearRecipients();
							}
						} else {
							$email->AddRecipient($GLOBALS['contactEmail'], '', 't');
							$email_result = $email->Send();
						}
					} else {
						$email->AddRecipient($GLOBALS['contactEmail'], '', 't');
						$email_result = $email->Send();
					}
				}
			}

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('ContactResults');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* GetContactGroupSelect
		*
		* Returns a full html select (or an empty string) containing a list of
		* groups which are marked in the database as being contactable
		*
		* @param int $selectedid The selected group id
		*
		* @return string The html for the select box
		*/
		function GetContactGroupSelect($selectedid=0)
		{
			$output = '';
			$query = 'SELECT groupid, name
			FROM '.$GLOBALS['tablePrefix'].'groups
			WHERE contactable=1
			ORDER BY name';
			$result = $GLOBALS['AKB_DB']->Query($query);
			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ContactGroupSelectHeader');
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					$GLOBALS['value'] = $row['groupid'];
					$GLOBALS['text'] = htmlspecialchars($row['name'], ENT_QUOTES, $GLOBALS['charset']);
					if ($selectedid > 0 && $selectedid == $row['groupid']) {
						$GLOBALS['selected'] = 'selected';
					} else {
						$GLOBALS['selected'] = '';
					}
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('Option');
				}
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ContactGroupSelectFooter');
			}
			return $output;
		}

		/**
		* showCaptchaImg
		* Show the CAPTCHA image
		*
		* @return void
		*/
		function showCaptchaImg($offset)
		{
			$col1s = array (
				'#ff0000',
				'#00ff00',
				'#0000ff',
			);

			$captcha = new AKB_CAPTCHA();
			if ($captcha->type == 'static') {
				$captcha->maxLoads = strlen($_SESSION['captchaSecret'])+1;
			}

			$captcha->loadSecret();
			$captcha->imgDir = dirname(__FILE__).'/../../templates/'.$GLOBALS['template'].'/Images/captcha';
			$captcha->fontFile = $captcha->PickRandomFile(dirname(__FILE__).'/../../lib/fonts', 'ttf');
			$captcha->RandFillType();

			$captcha->bgCol1		= $col1s[array_rand($col1s)];
			$captcha->bgCol2		= '#bcbcbc';

			ob_start();
			// send several headers to make sure the image is not cached
			// Date in the past
			header('Expires: Mon, 23 Jul 1993 05:00:00 GMT');

			// always modified
			header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

			// HTTP/1.1
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);

			header('Content-type: image/png');

			$captcha->showImg($offset);
			$captcha_img = ob_get_contents();
			ob_end_clean();
			echo $captcha_img;
		}

		/**
		* CheckContactForm
		*
		* Check that the contact form has been filled out correctly
		*
		* @return bool Has the form been filled out correctly
		*/
		function CheckContactForm()
		{
			// Verify the CAPTCHA is correct
			if ($GLOBALS['useCaptchaCheck'] == true) {
				if (!isset($_POST['captcha'])) {
					$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['Message'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}

				$captcha = new AKB_CAPTCHA();
				$captcha->loadSecret();

				if (!isset($captcha->secret) || empty($captcha->secret)) {
					$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['Message'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}

				if ($_POST['captcha'] != $captcha->secret) {
					$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['Message'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}

				if ($_SESSION['captchaLoads'] > $captcha->maxLoads) {
					$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['Message'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}
			}

			// Verify required form fields are filled out
			if (empty($_POST['name'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conInvalidName');
				return false;
			}

			if (empty($_POST['email'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conInvalidEmail');
				return false;
			}

			if (!is_email_address($_POST['email'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conInvalidEmail');
				return false;
			}

			if (empty($_POST['message'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conQuestionRequired');
				return false;
			}

			return true;
		}

	}

?>