<?php

/* Search database for keywords */

//security check
if(!function_exists('checkOrigin') || !$bAdmin)
{
	require_once 'config.php';
	relocate(getError('Acc&egrave;s interdit'));
}

if(!isset($_REQUEST['keywords']))
{
	relocate(getError('Cherchez au moins un mot'));
}
else
{
	$asKeyWords = explode('+', $_REQUEST['keywords']);
	$sHtmlKeyWords = getHtml($asKeyWords, 'em', '', '', array(), false, ', ');
	foreach($asKeyWords as $sKeyWord)
	{
		foreach(getTables() as $sTableName)
		{
			$asColumnConstraint = "";
			foreach(getTableColumnNames($sTableName) as $sColumnName)
			{
				if(strpos($sColumnName, 'id_')===false && $sColumnName != 'pass')
				{
					if($asColumnConstraint != "")
					{
						$asColumnConstraint .= "OR";
					}
					$asColumnConstraint .= " $sColumnName LIKE '%$sKeyWord%' ";
				}
			}
			$sQuery = 	"SELECT /* ".basename(__FILE__)." ".__LINE__." */ * 
						FROM $sTableName 
						WHERE $asColumnConstraint";
			
			$asTableResult = getArrayQuery($sQuery);
			foreach($asTableResult as $asRow)
			{
				$sRowId = $sTableName.$asRow['id_'.$sTableName];
				$asResult[$sRowId] = $asRow;
				$asRank[$sRowId] = isset($asRank[$sRowId])?($asRank[$sRowId]+1):1;
			}
		}
	}
	
	if(isset($asRank))
	{
		arsort($asRank);
		foreach($asRank as $sRowId=>$iRank)
		{
			$asColumnDisplayed = array_filter(array_keys($asResult[$sRowId]), 'filterTable');
			$asResultRow = array_intersect_key($asResult[$sRowId], array_flip($asColumnDisplayed));
						
			$sColumnNames = getHtml(ucwords(str_replace('_', ' ', getHtml(array_keys($asResultRow), 'th'))), 'tr');
			$sHtmlRank = getHtml('Rang : '.$iRank, 'p', '', 'font-size:small;margin-top:10px;margin-bottom:0;');
			$asSearchResults[] = $sHtmlRank.getHtml($sColumnNames.getHtml(getHtml($asResultRow, 'td'), 'tr'), 'table', 'maxWidth');
		}
	}
	else
	{
		relocate(getWarning(array('Aucun r�sultat', 'Recherche effectu�e sur les mots : '.$sHtmlKeyWords)));
	}
}

function filterTable($sColumnName)
{
	return (!is_numeric($sColumnName) && $sColumnName!='pass');
}
?>
<p>Mots recherch�s : <?php echo $sHtmlKeyWords; ?></p>
<p>R�sultat<?php echo (count($asSearchResults)>1)?'s':''; ?> de la recherche :</p>
<?php echo implode($asSearchResults); ?>