<?php
/**
* @version	$Id: thesaurus_tp.php 13086 2010-01-12 19:47:40Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class ThesaurusTagProcessor extends kDBTagProcessor {

		function SubSearchLink($params)
		{
			$object =& $this->getObject();
			/* @var $object kDBItem */

			$params['search_type'] = 'subsearch';
			$params['keywords'] = $object->GetDBField('ThesaurusTerm');
			$params['narrow_search'] = 1;

			return $this->Application->ProcessParsedTag('m', 'Link', $params);
		}

		function _getThesaurusRecords()
		{
			$keywords = unhtmlentities( trim($this->Application->GetVar('keywords')) );
			$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');

			$sql = 'SELECT *
					FROM ' . $table_name . '
					WHERE SearchTerm LIKE ' . $this->Conn->qstr($keywords).' OR SearchTerm LIKE ' . $this->Conn->qstr($keywords . '_');
			$records = $this->Conn->Query($sql);

			$new_records = Array ();
			foreach ($records as $record) {
				if ($record['ThesaurusType'] == THESAURUS_TYPE_USE) {
					// expand in global scope
					$sql = 'SELECT *
							FROM ' . $table_name . '
							WHERE SearchTerm = ' . $this->Conn->qstr($record['ThesaurusTerm']);
					$use_records = $this->Conn->Query($sql);
					if ($use_records) {
						$new_records = array_merge($new_records, $use_records);
					}
				}

				$new_records[] = $record;
			}

			usort($new_records, Array (&$this, '_sortThesaurus'));
			ksort($new_records);

			return $new_records;
		}

		function HasThesaurus($params)
		{
			$new_records = $this->_getThesaurusRecords();
			return count($new_records) > 0;
		}

		function PrintThesaurus($params)
		{
			$new_records = $this->_getThesaurusRecords();

			$ret = '';
			$block_params = $this->prepareTagParams($params);
			$block_params['name'] = $params['render_as'];
			foreach ($new_records as $record) {
				$block_params['term'] = $record['ThesaurusTerm'];

				$url_params = Array (
					'search_type' => 'subsearch',
					'keywords' => $record['ThesaurusTerm'],
					'narrow_search' => 1,
				);
				$block_params['url'] = $this->Application->ProcessParsedTag('m', 'Link', $url_params);

				$ret .= $this->Application->ParseBlock($block_params);
			}

			return $ret;
		}

		function _sortThesaurus($record_a, $record_b)
		{
			return strcmp(strtolower($record_a['ThesaurusTerm']), strtolower($record_b['ThesaurusTerm']));
		}
	}
