<?php

class AKB_NEWS extends AdminView {

	/**
	* @var string $query The sql used to display the list of news
	*/
	var $query = "";

	/**
	* @var string $countQuery The sql used to work out the number of
	* news that running $this->query is going to display
	*/
	var $countQuery = "";
	var $defaultTableSort = "lastupdated";

	/**
	* AKB_NEWS
	* A blank class constructor
	*
	* @return void
	*/
	function AKB_NEWS() {
	}

	/**
	* ShowNewNews
	* Show the form for creating new News Items
	*
	* @return void
	*/
	function ShowNewNews() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')) {
			$this->NoPermission();
			return;
		}

		//Setup Breadcrumbs
		$GLOBALS['BreadcrumEntries'][GetLang("UserManageNews")] = "index.php?ToDo=viewNews";
		$GLOBALS['BreadcrumEntries'][GetLang("CreateNews")] = "";


		$GLOBALS['NewsHeadingTitle'] = GetLang("CreateNewsItemHeading");
		$GLOBALS['NewsIntro'] = GetLang("CreateNewsItemIntro");
		$GLOBALS['CheckVisible'] = ' CHECKED ';
		$newsContent = GetLang('DefaultNewsEditorContent');
		$GLOBALS["FormAction"] = "saveNewNews";
		$GLOBALS["NewsTitle"] = '';
		$GLOBALS['WYSIWYG'] = $this->GetWYSIWYGEditor($newsContent);
		$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("news.form");
		$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
	}

	/**
	* EditNews
	* Show the form for editing News Items
	*
	* @return void
	*/
	function EditNews() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')) {
			$this->NoPermission();
			return;
		}

		//Setup Breadcrumbs
		$GLOBALS['BreadcrumEntries'][GetLang("UserManageNews")] = "index.php?ToDo=viewNews";
		$GLOBALS['BreadcrumEntries'][GetLang("EditNews")] = "";


		$GLOBALS['NewsHeadingTitle'] = GetLang("EditNewsItemHeading");
		$GLOBALS['NewsIntro'] = GetLang("EditNewsItemIntro");
		$newsContent = '';
		$GLOBALS["FormAction"] = "saveUpdatedNews";
		$GLOBALS["NewsTitle"] = '';
		$GLOBALS["CheckVisible"] = '';



		if (isset($_GET['newsid'])) {
			$newsId = $_GET['newsid'];
			$GLOBALS['hiddenFields']	= sprintf("<input type='hidden' name='newsid' value='%d'>", $newsId);
			$query = sprintf("select * from %snewss where newsid='%d'", $GLOBALS["tablePrefix"], $newsId);
			$nResult = $GLOBALS['AKB_DB']->Query($query);

			if ($nRow = $GLOBALS['AKB_DB']->Fetch($nResult)) {
				$GLOBALS["NewsTitle"] =	htmlspecialchars($nRow['title'], ENT_QUOTES, $GLOBALS['charset']);
				$newsContent =	$nRow['content'];
				$GLOBALS['WYSIWYG'] = $this->GetWYSIWYGEditor($newsContent);

				$visible =	$nRow['visible'];
				if ($visible == 1) {
					$GLOBALS["CheckVisible"] = ' CHECKED ';

				}
			}
			$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("news.form");
			$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();

		} else {
			$this->ShowNewsList();
		}
	}

	/**
	* UpdateVisible
	* Update the visiblitiy of a news item
	*
	* @return void
	*/
	function UpdateVisible()
	{
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')) {
			$this->NoPermission();
			return;
		}

		if (isset($_GET['newsId']) && isset($_GET['visible'])) {
			$news = new API_NEWS();
			$news->load($_GET['newsId']);
			$_POST['visible'] = $_GET['visible'];

			if ($news->save()) {
				if ($_GET['visible'] == 1) {
					$this->ShowNewsList(GetLang('NewsVisibleSuccessfully'), MSG_SUCCESS);
				} else {
					$this->ShowNewsList(GetLang('NewsHiddenSuccessfully'), MSG_SUCCESS);
				}
			} else {
				$this->ShowNewsList();
			}
		} else {
			$this->ShowNewsList();
		}
	}

	/**
	* GetWYSIWYGEditor
	* Get the WYSIWYG field
	*
	* @param string $Content the content to display
	* @return string The html for the editor
	*/
	function GetWYSIWYGEditor($Content = "",$width="100%",$height="300")
	{
		// Output the WYSIWYG HTML editing component
		// $SpanId is the id of the tooltip to show for help
		ob_start();

		if ($GLOBALS["useWYSIWYGEditor"] == true && is_file(dirname(__FILE__).'/../../de/class.devedit.php')) {
			// Workout the image/flash directory path
			$parts = parse_url($GLOBALS['pathToKB'].'/images');
			$path = $parts['path'];

			//Include the DevEdit class file
			include_once(dirname(__FILE__).'/../../de/class.devedit.php');

			// Create a new DevEdit class object
			$myDE = new DevEdit();

			// Set the name of this DevEdit class
			$myDE->SetName("wysiwyg");

			// Set the path to the de folder
			SetDevEditPath("de");

			// Set the path to the folder that contains the flash files for the flash manager
			$myDE->SetFlashPath($path);
			$myDE->SetMediaPath($path);
			$myDE->SetLinkPath($path);

			if ($GLOBALS['charset'] == 'utf-8') {
				$myDE->DisableHTMLEntities();
			}

			//If you want to use the spell checker, then you can set
			//the spelling language to DE_AMERICAN, DE_BRITISH or DE_CANADIAN,
			//DE_FRENCH, DE_SPANISH, DE_GERMAN, DE_ITALIAN, DE_PORTUGESE,
			//DE_DUTCH, DE_NORWEGIAN, DE_SWEDISH or DE_DANISH
			$myDE->SetLanguage(DE_AMERICAN);

			//How do we want images to be inserted into our HTML content?
			//DE_PATH_TYPE_FULL will insert a image in this format: http://www.mysite.com/test.html
			//DE_PATH_TYPE_ABSOLUTE will insert a image in this format: /myimage.gif
			$myDE->SetPathType(DE_PATH_TYPE_FULL);

			//Are we editing a full HTML page, or just a snippet of HTML?
			//DE_DOC_TYPE_HTML_PAGE means we're editing a complete HTML page
			//DE_DOC_TYPE_SNIPPET means we're editing a snippet of HTML
			$myDE->SetDocumentType(DE_DOC_TYPE_SNIPPET);

			//Do we want images to appear in the image manager as thumbnails or just in rows?
			//DE_IMAGE_TYPE_ROW means just list in a tabular format, without a thumbnail
			//DE_IMAGE_TYPE_THUMBNAIL means list in 4-per-line thumbnail mode
			$myDE->SetImageDisplayType(DE_IMAGE_TYPE_ROW);

			//Do we want flash files to appear in the flash manager as thumbnails or just in rows?
			//DE_FLASH_TYPE_ROW means just list in a tabular format, without a thumbnail
			//DE_FLASH_TYPE_THUMBNAIL means list in 4-per-line thumbnail mode
			$myDE->SetFlashDisplayType(DE_FLASH_TYPE_ROW);

			// Always clear ms word tags from the code
			$myDE->ForcePasteWord();

			//Show table guidelines as dashed
			$myDE->EnableGuidelines();

			// Set the content
			$myDE->SetValue($Content);

			// Set the default wysiwyg mode - after the intial load the mode
			// is determined from a cookie
			$myDE->SetDevEditMode("Simple");

			// Disable the preview tab
			$myDE->DisablePreviewMode();

			// Setup the toolbars
			$myDE->AddToolbarButton("Insert Image", 57, 20, $GLOBALS["pathToKB"]."/admin/images/image_toolbaricon.gif", "wysiwyg.commands.getCommand('Image').execute();", "Simple");
			$myDE->AddToolbarButton("Insert Image", 57, 20, $GLOBALS["pathToKB"]."/admin/images/image_toolbaricon.gif", "wysiwyg.commands.getCommand('Image').execute();", "Complete");

			$rows = array (
			"Fullscreen,Paste,Findreplace,Spellcheck,-,Bold,Underline,Italic,-,OrderedList,UnorderedList,-,JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,-,CreateLink",
			"Fontname,Fontsize,-,Fontcolor,Highlight,-,Insert Image,Flash,Media,-,Table,-,Help",
			);
			$myDE->AddToolbar("Simple", implode(",|,", $rows));

			$rows = array (
			"Fullscreen,Paste,Findreplace,Spellcheck,Bold,Underline,Italic,Strikthrough,-,OrderedList,UnorderedList,-,JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,Help",
			"Spellcheck,-,RemoveFormat,-,Indent,Outdent,-,SubScript,SuperScript,CreateLink,CreateEmailLink,Anchor,-,Insert Image,Flash,Media,-,Table,Form",
			"Fontname,Fontsize,Formatblock,Fontcolor,Highlight,HR,Insertchars,Showborders",
			);
			$myDE->AddToolbar("Complete", implode(",|,", $rows));

			//Display the DevEdit control. This *MUST* be called between <form> and </form> tags
			$myDE->ShowControl($width,$height,$path);

		} else {
			?>
				<textarea class="Field500" style="height:200" name="wysiwyg_html"><?php echo str_replace("<br>", "\r\n", $Content); ?></textarea>
			<?php
		}

		$editor = ob_get_contents();
		ob_end_clean();

		return $editor;
	}

	/**
	* saveUpdatedNews
	* Save updated news items
	*
	* @return void
	*/
	function saveUpdatedNews() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')) {
			$this->NoPermission();
			return;
		}

		$_POST['content']		= $_POST['wysiwyg_html'];
		$_POST['userid']		= $_SESSION['user']->userid;
		$_POST['title']			= $_POST['title'];
		$_POST['lastupdated'] = date("Y-m-d H:i:s");

		if (isset($_POST['visible'])) {
			$_POST['visible'] = 1;
		} else {
			$_POST['visible'] = 0;
		}

		$n = new API_NEWS();
		$n->load($_POST['newsid']);

		$saveresult = $n->save();

		$this->ShowNewsList(GetLang('NewsSaved'), MSG_SUCCESS);

	}

	/**
	* SaveNewNews
	* Save new news items
	*
	* @return void
	*/
	function SaveNewNews() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')) {
			$this->NoPermission();
			return;
		}
		
		$_POST['content']		= $_POST['wysiwyg_html'];
		$_POST['userid']		= $_SESSION['user']->userid;
		$_POST['title']			= $_POST['title'];

		if (isset($_POST['visible'])) {
			$_POST['visible'] = 1;
		} else {
			$_POST['visible'] = 0;
		}
		$_POST['lastupdated'] = date("Y-m-d H:i:s");


		$news = new API_NEWS();
		$GLOBALS['newid'] = $news->create();

		if ($GLOBALS['newid']) {
			$msg = sprintf(GetLang("NewsCreatedSuccessfully"), htmlspecialchars($_POST['title'], ENT_QUOTES, $GLOBALS['charset']));
			$status = MSG_SUCCESS;
		} else {
			$msg = sprintf(GetLang("NewsCreatedFailed"), htmlspecialchars($_POST['name'], ENT_QUOTES, $GLOBALS['charset']));
			$msg .= ' '.$news->error;
			$status = MSG_ERROR;
			break;
		}
		$this->ShowNewsList($msg,$status);
	}

	/**
	* HandlePage
	* Handle the action in the news editing page
	*
	* @return void
	*/
	function HandlePage() {
		if ($_SESSION['user']->verify('news', 'edit')
		|| $_SESSION['user']->verify('news', 'delete')) {

			if (isset($_GET['ToDo'])) {
				switch (strtolower($_GET['ToDo'])) {
					case 'viewnews':
					default:
					if (isset($_POST['bulkaction'])) {
						$this->BulkAction();
					}
					$this->ShowNewsList();
				}
			}
		} else {
			$this->NoPermission();
		}
	}

	/**
	* ShowNewsList
	* Display the list for managing news
	*
	* @param string $MsgDesc The message text
	* @param int $MsgStatus The type of message
	*
	* @return void
	*/
	function ShowNewsList($MsgDesc = "", $MsgStatus = "")
	{
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')
		&& !$_SESSION['user']->verify('news', 'delete')) {
			$this->NoPermission();
			return;
		}

		$GLOBALS['BreadcrumEntries'] = array(GetLang("Home") => "index.php", GetLang("ManageNews") => "");
		$GLOBALS['FormAction'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewNews';

		$start = 0;
		$numPages = 0;
		//		$GLOBALS['HideHeading'] = '';
		$GLOBALS['NewsBulkOptions'] = '';
		if ($MsgDesc != '') {
			$GLOBALS["Message"] = MessageBox($MsgDesc, $MsgStatus);
		}

		if ($_SESSION['user']->verify('news', 'delete')) {
			$GLOBALS['NewsBulkOptions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('NewsBulkDeleteOptions');
		}

		$GLOBALS['ManageNewsMessage'] = GetLang('ManageNewsMessage');

		// {{{ Build the alpha list (A-Z box list)
		$GLOBALS["AlphaList"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListHeader');
		$GLOBALS["Item"] = 'news items';
		$letters = GetAlphaList();
		foreach ($letters as $letter) {
			$GLOBALS['Letter'] = $letter;
			$GLOBALS['TermClickLetter'] = sprintf(GetLang("TermClickLetter"), strtolower(GetLang('News')), $letter);
			if (isset($_SESSION['news_search']['letter']) && $letter == $_SESSION['news_search']['letter']) {
				$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRow');
			} else {
				$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRow');
			}
		}
		$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListFooter');
		// }}

		$this->BuildListQueries();


		$result = $GLOBALS['AKB_DB']->Query($this->countQuery);
		$this->numRecords = $GLOBALS['AKB_DB']->FetchOne($result);

		if ($this->numRecords > 0) {
			$GLOBALS['ManageNewsMessage'] = GetLang('ManageNewsMessage');

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('news.manage');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		} else {
			$valid_letters = GetAlphaList();
			if (isset($_SESSION['news_search']['letter']) && in_array($_SESSION['news_search']['letter'], $valid_letters)) {
				// No questions found when searching by letter
				$GLOBALS['Title'] = GetLang('ManageNews');
				$GLOBALS['ManageQuestMessage'] = GetLang('ManageNewsMessage');
				$GLOBALS['ButtonText'] = GetLang('CreateNews');
				$GLOBALS['ButtonClass'] = 'Field150';
				$GLOBALS['Message'] = MessageBox(sprintf(GetLang('NoNewsLetter'), $_SESSION['news_search']['letter']), MSG_WARNING);
				$GLOBALS['URL'] = 'index.php?ToDo=createNews';
				$GLOBALS['HideHeading'] = 'style="display:none"';
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('news.manage');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {
				// No questions exist at all
				$GLOBALS['Style'] = '';
				$GLOBALS['Title'] = GetLang('ManageNews');
				$GLOBALS['ButtonText'] = GetLang('CreateNews');
				$GLOBALS['ButtonClass'] = 'Field150';
				$GLOBALS['Message'] = MessageBox(GetLang('NoNews'), MSG_SUCCESS);
				$GLOBALS['URL'] = 'index.php?ToDo=createNews';

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('messagewithbutton');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			}
		}
	}

	/**
	* ShowNewsListRemote
	* Display the list for managing news
	*
	* @return void
	*/
	function ShowNewsListRemote() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('news', 'edit')
		&& !$_SESSION['user']->verify('news', 'delete')) {
			$this->NoPermission();
			return;
		}

		$page = 0;
		$start = 0;
		$numpages = 0;

		$todo = $_GET['todo'];
		$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
		$GLOBALS['TableIconImagePath'] = "images/newspaper.png";
		$sortVars = array("lastupdated","title","firstname", "visible");

		$sortTableArray = $this->SetupSortingParams($sortVars,$todo,$page);

		$this->BuildListQueries();

		$newsResult = $GLOBALS['AKB_DB']->Query($this->query);

		//Setup pagination
		$field = "lastupdated";
		if (isset($_GET['field'])) {
			$_GET['field'];
		}

		$direction = "d";
		if (isset($_GET['direction'])) {
			$direction = $_GET['direction'];
		}

		//Set pagination information.
		$this->SetupPaginationLink("ShowNewsListRemote",$direction,$field);
		$this->SetupPagination($this->countQuery,$page,AKB_NEWS_PER_PAGE);

		if ($GLOBALS['AKB_DB']->CountResult($this->query)) {
			$adminTable = new AKB_AdminTable();

			$adminTable->headingArray['title'] 			= GetLang("Title");
			$adminTable->headingArray['firstname'] 		= GetLang("NewsAuthor");
			$adminTable->headingArray['lastupdated'] 	= GetLang("NewsLastUpdated");
			$adminTable->headingArray['visible'] 		= '<span style="align=center;">'.GetLang("Visible").'</span>';
			$adminTable->headingArray['action'] 		= '<span style="align=center;">'.GetLang("Action").'</span>';

			$adminTable->sizeArray						= array("10%","10%,10%,10%");
			$adminTable->sortArray 						= $sortTableArray;

			$adminTable->prependDataID 					= "newsid";
			$adminTable->addCallback("unixdate",	"strtotime",array("__lastupdated__"));
			$adminTable->addCallback("lastupdated",		"date",array("jS F Y","__unixdate__"));
			$adminTable->addCallback("firstname",array($GLOBALS['AKB_CLASS_NEWS'],"FormatAuthor"), array("__firstname__","__lastname__","__username__"));
			$adminTable->addCallback("visible",array($GLOBALS['AKB_CLASS_NEWS'],"ReturnVisibleCell"),array("__newsid__","__visible__"));
			$adminTable->addCallback("action","","");
			if ($_SESSION['user']->verify('news', 'edit')) {
				$adminTable->addTemplateOverride("action","news.cell.edit",array("__newsid__"));
			} else {
				$adminTable->addTemplateOverride("action","news.cell.noedit");
			}

			$adminTable->tableIdent = "ShowNewsListRemote";

			$adminTable->rsData = $newsResult;

			echo $adminTable->ReturnTable();
			return;
		}
	}

	/**
	* ReturnVisibleCell
	* Display of the visible status cell of the news items
	*
	* @param int $newsid The news id
	* @param int $visible The visible status 0 or 1
	*
	* @return String
	*/
	function ReturnVisibleCell($newsid,$visible) {
		if ($visible == 0) {
			if ($_SESSION['user']->verify('news', 'edit')) {
				$visibleHTML = sprintf('<a title="%s" href="index.php?ToDo=updateNewsVisible&amp;newsId=%d&amp;visible=1"><img border="0" src="images/cross.gif" alt="cross"></a>', GetLang('NewsVisibleTip'), $newsid);
			} else {
				$visibleHTML = '<img border="0" src="images/cross.gif" alt="cross">';
			}
		} else {
			if ($_SESSION['user']->verify('news', 'edit')) {
				$visibleHTML = sprintf('<a title="%s" href="index.php?ToDo=updateNewsVisible&amp;newsId=%d&amp;visible=0"><img border="0" src="images/tick.gif" alt="tick"></a>', GetLang('NewsInvisibleTip'), $newsid);
			} else {
				$visibleHTML = '<img border="0" src="images/tick.gif" alt="tick">';
			}
		}
//		return $visibleHTML
		return "<span style=\"margin-left:10px;\">".$visibleHTML."</span>";
	}

	/**
	* FormatAuthor
	* Format the correct Author name
	*
	* @param String $firstname firstname
	* @param String $lastname lastname
	* @param String $username username
	*
	* @return String
	*/
	function FormatAuthor($firstname,$lastname,$username) {
		if (trim($firstname) || trim($lastname)) {
			$authorStr = $firstname.' '.$lastname;
		} else {
			$authorStr = $username;
		}
		return htmlspecialchars($authorStr,ENT_QUOTES,$GLOBALS['charset']);
	}

	/**
	* BulkAction
	* Perform the action from bulk action of list news items page
	*
	* @return Boolean
	*/
	function BulkAction() {
		if (!isset($_POST['bulkaction'])) {
			return false;
		}

		if (!isset($_POST['item']) || !is_array($_POST['item'])) {
			return false;
		}

		$nAPI = new API_NEWS();
		switch (strtolower($_POST['bulkaction'])) {
			case "delete":
			if ($_SESSION['user']->verify('news', 'delete')) {
				//Delete them all.
				if ($nAPI->multiDelete($_POST['item'])) {
					$GLOBALS['Message'] = MessageBox(GetLang('NewsDeleteOk'), MSG_SUCCESS);
				} else {
					$GLOBALS['Message'] = MessageBox(GetLang('NewsDeleteNotOk'), MSG_ERROR);
				}
			} else {
				$this->NoPermission();
			}
			break;
		}
	}

	/**
	* InitAdvancedSearch
	*
	* Sets up the session vars to control searching and sorting for the page
	* that displays the list of news.
	*
	* @return void
	*/
	function InitAdvancedSearch()
	{
		// Define the vars we want to keep track of related to searching
		// and sorting
		$search_settings = array (
		'letter'		=> '',
		);
		$sort_settings = array (
		'sortfield'		=> 'title',
		'sortorder'		=> 'asc',
		);

		if (isset($_GET['resetsearch'])) {
			unset($_SESSION['news_search']);
		}

		if (!isset($_SESSION['sort']['sortfield'])
		|| !isset($_SESSION['sort']['sortorder'])
		|| isset($_GET['sortfield'])
		|| isset($_GET['sortorder'])) {
			foreach ($sort_settings as $k => $v) {
				if (!empty($_GET) && isset($_GET[$k])) {
					$validate_function = 'validate_'.$k;
					if (method_exists($this, $validate_function)
					&& $this->$validate_function($_GET[$k])) {
						$_SESSION['sort'][$k] = $_GET[$k];
					} elseif (method_exists($this, $validate_function)) {
						$_SESSION['sort'][$k] = $v;
					} else {
						$_SESSION['sort'][$k] = $_GET[$k];
					}
				} else {
					$_SESSION['sort'][$k] = $v;
				}
			}
		}
		// If our search settings have never been saved or settings have
		// just been submitted then set them up, otherwise we assume they
		// are already set
		if (!isset($_SESSION['news_search'])
		|| isset($_POST['q'])
		|| !empty($_GET['letter'])) {
			foreach ($search_settings as $k => $v) {
				if (!empty($_REQUEST) && isset($_REQUEST[$k])) {
					// Only set the session var to the post var IF
					// the var doesnt have a validate function or if
					// the value passeds the validate function
					$validate_function = 'validate_'.$k;

					if (method_exists($this, $validate_function)
					&& $this->$validate_function($_REQUEST[$k])) {
						$_SESSION['news_search'][$k] = $_REQUEST[$k];
					} elseif (method_exists($this, $validate_function)) {
						$_SESSION['news_search'][$k] = $v;
					} else {
						$_SESSION['news_search'][$k] = $_REQUEST[$k];
					}
				} else {
					$_SESSION['news_search'][$k] = $v;
				}
			}
		}

		if (!empty($_POST)) {
			$_SESSION['news_search']['searching'] = true;
		}
	}

	/**
	* BuildListQueries
	*
	* Create the queries for displaying the list based on values saved in
	* the session. This function assumes that InitAdvancedSearch has been
	* called at some time in the sesison before it (not necessarily on this
	* page view).
	*
	* @return void
	*/
	function BuildListQueries()
	{
		$this->InitAdvancedSearch();
		$page = isset($_GET['page'])? (int) $_GET['page'] : 1;
		$start = ($page == 1) ? 0 : ($page * AKB_NEWS_PER_PAGE) - (AKB_NEWS_PER_PAGE-1) -1;

		$this->countQuery = "SELECT COUNT(*) ";
		$this->countQuery .= "FROM ".$GLOBALS['tablePrefix']."newss n, ".$GLOBALS['tablePrefix']."users u ";
		$this->countQuery .= "WHERE 1=1 ";
		$this->countQuery .= "AND n.userid = u.userid ";

		$this->query  = "SELECT n.newsid, n.title, n.lastupdated, n.visible, n.userid, u.username, u.firstname, u.lastname, u.email ";
		$this->query .= "FROM ".$GLOBALS['tablePrefix']."newss n, ".$GLOBALS['tablePrefix']."users u ";
		$this->query .= "WHERE 1=1 ";
		$this->query .= "AND n.userid = u.userid ";

		if (!empty($_SESSION['news_search']['letter'])) {

			$fromStartWith = $_SESSION['news_search']['letter'];
			$toStartWith = $_SESSION['news_search']['letter'];
			$startWithHelper = explode('-', $_SESSION['news_search']['letter']);
			if (sizeof($startWithHelper) > 1) {
				$fromStartWith = $startWithHelper[0];
				$toStartWith = $startWithHelper[1];
			}

			$this->countQuery .= " AND ".$GLOBALS['AKB_DB']->SubString('title', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'\n";
			$this->query .= " AND ".$GLOBALS['AKB_DB']->SubString('title', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'\n";
		}

		if (!isset($this->sortField)) {
			$this->sortField = $this->defaultTableSort;
		}

		if (!isset($this->sortDirection)) {
			$this->sortDirection = "DESC";
		}

		$this->query .= "ORDER BY ".$GLOBALS['AKB_DB']->Quote($this->sortField)." ".$GLOBALS['AKB_DB']->Quote($this->sortDirection)."\n";
		$this->query .= $GLOBALS['AKB_DB']->AddLimit($start, AKB_NEWS_PER_PAGE);
	}
	
		/**
		* DeleteNews
		* Delete a news item from the database
		*
		* @return void
		*/
		function DeleteNews()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('news', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET["newsid"])) {
				$newsId = $_GET["newsid"];
				$query = sprintf("delete from %snewss where newsid='%d'", $GLOBALS["tablePrefix"], $newsId);
				if ($GLOBALS['AKB_DB']->Query($query)) {
					$this->ShowNewsList(GetLang("NewsDeleteOk"), MSG_SUCCESS);
				} else {
					$this->ShowNewsList(GetLang("NewsDeleteNotOk"), MSG_WARNING);
				}
			} else {
				$this->ShowNewsList(GetLang("NewsDeleteNotOk"), MSG_WARNING);
			}
		}
	
}



?>