<?php
require_once(WCF_DIR.'lib/acp/page/UserSuggestPage.class.php');

// Tagging util
require_once(WCF_DIR.'lib/util/TaggingReloadedUtil.class.php');

/**
 * receives input text, filters the words and returns tags as xml
 *
 * @author	Torben Brodt
 * @package	de.easy-coding.wcf.taggingreloaded
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 */
class TaggingReloadedQueryPage extends UserSuggestPage {
	public $query= '';
	
	/**
	 * @see Page::readParameters()
	 */
	public function readParameters() {
		parent::readParameters();
		
		if (isset($_POST['query'])) {
			$this->query = StringUtil::trim($_POST['query']);
			if (CHARSET != 'UTF-8') $this->query = StringUtil::convertEncoding('UTF-8', CHARSET, $this->query);
		}
	}
	
	/**
	 * @see Page::readData()
	 */
	public function readData() {
		// unify languages "en-us" to "en" and "de-informal" to "de"
		$lang = explode('-', WCF::getLanguage()->getLanguageCode()); 
		$lang = $lang[0];

		$query = TaggingUtil::text2tags($this->query);
		$stopwords = array();

		$sql = "SELECT		stopword
			FROM		wcf".WCF_N."_taggingreloaded_stopwords
			WHERE		languagecode = '{$lang}'; ";
		$result = WCF::getDB()->sendQuery($sql);
		while ($row = WCF::getDB()->fetchArray($result)) {
			$stopwords[] = $row['stopword'];
		}
		
		$this->results = array_diff($query, $stopwords);
	}
	
	/**
	 * @see Page::show()
	 */
	public function show() {
		//parent::show();
		header('Content-type: text/xml');
		echo "<?xml version=\"1.0\" encoding=\"".CHARSET."\"?>\n<suggestions>\n";

		foreach($this->results as $tag => $weight) {
			printf("<tag weight=\"%d\"><![CDATA[%s]]></tag>\n", $weight, StringUtil::escapeCDATA($tag));
		}

		echo '</suggestions>';
		exit;
	}
}
?>
