<?php
/**
 * Search page
 *
 * Database searches
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: search.php,v 1.00 2006/10/26 19:47:13
 */

require_once './core/session.php';
require_once './core/functions.php';
require_once './core/queryparser.php';


// multiuser permission check
permission_or_die(PERM_READ);

//Assign searchtype
$searchtypes = Array($lang['clubs'],$lang['stadiums'],$lang['players'],$lang['referees'],$lang['coachs'],$lang['news']);

$smarty->assign('searchtype', $searchtype);
$smarty->assign('searchtypes', $searchtypes);

$optshowimg = Array($lang['noimage'],$lang['withimage']);
$smarty->assign('optshowimg', $optshowimg);
$smarty->assign('showimg', $showimg);

$RESTRICT = "";

if ($searchtype == 2 || $searchtype == 3 || $searchtype == 4) {
$search_fields = array( 'lastname'       => $lang['lastname'],
                        'firstname'      => $lang['firstname'],
                        'birthcity'      => $lang['birthcity'],
                        'country'        => $lang['country'],
                        'plot'           => $lang['comment']);
			if ($searchtype == 2) {			
			$RESTRICT .= "type = '1'";
			}
			else if ($searchtype == 3) {
			$RESTRICT .= "type = '3'";			
			}
			else if ($searchtype == 4) {
			$RESTRICT .= "type = '2'";
			}
			else {
			$RESTRICT .= "";
			}						
}
else if ($searchtype == 1) {
$search_fields = array( 'longname'   => $lang['longname'],
                        'country'    => $lang['country'],
                        'plot'       => $lang['comment']);
$RESTRICT .= '';						
}
else if ($searchtype == 5) {
$search_fields = array( 'title'         => $lang['title'],
                        'language'      => $lang['language'],
						'summary'       => $lang['summary'],
                        'plot'          => $lang['comment']);
$RESTRICT .= '';						
}
else {
// prepare fieldselect
$search_fields = array( 'shortname'     => $lang['shortname'],
                        'longname'      => $lang['longname'],
                        'city'          => $lang['city'],
                        'country'       => $lang['country'],
                        'plot'          => $lang['comment']);
}

// no fields given? Select all
if (empty($fields)) 
{
    // name search?
    if ($isname) {
        $fields = array('lastname', 'persons');
    } 
	else {
        $fields = array_keys($search_fields);
    }
} 
// only one field? convert to array
elseif (!is_array($fields)) 
{
     $fields = array($fields);
}



// translate search fields into SQL column names, store original for template first
$smarty->assign('selected_fields', $fields);
foreach ($fields as $search_field)
{
    /*
     * field name conversion is required since the mysql AS columns can't be used in where clauses
     * add all fields here where the logical name in the template differs from the physical column name (e.g. mediatype)
     * or where the column name is ambiguous (e.g. diskid)
     */
    if (array_key_exists($search_field, $replace_fields))
    {
        if (($key = array_search($search_field, $fields)) !== false)
        {
            unset($fields[$key]);
            $fields[] = $replace_fields[$search_field];
        }        
    }        
}

// prepare search query
if (isset($q) && !$cs)
{
	$QUERY = '';

	if (!empty($q))
	{
		$error  = '';
		$tokens = queryparser($q, $error);

		$wild_char = (empty($nowild)) ? '%' : '';

		foreach ($tokens as $token)
		{
            // escape search token
			$token['token'] = addslashes($token['token']);

            // concatenate tokens with token operator
			$QUERY .= $token['ops'].' (';

            // concatenate all searchable fields with OR
			foreach ($fields as $field) 
            {
				$QUERY .= " ($field LIKE '$wild_char".$token['token']."$wild_char') OR ";
			}

			$QUERY .= ' 1=2)';
		}
	}
	
    // XML / PDF export
    if ($export && $config[$export])
    {
        $func = $export.'export';
        require_once './core/'.$export.'.php';

        if (function_exists($func)) $func("1=1 $QUERY ORDER BY title, subtitle");
        exit();
    }

	if ($searchtype == 2 || $searchtype == 3 || $searchtype == 4) {
	
		if ($RESTRICT) { $QUERY .= ' AND '.$RESTRICT; } 
		$totalresults = runSQL('SELECT count(*) AS num
					 FROM '.TBL_PERSONS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY lastname, firstname'); 
	}
	else if ($searchtype == 1) {    
		$totalresults = runSQL('SELECT count(*) AS num
					 FROM '.TBL_STADIUMS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY longname'); 
	}
	else if ($searchtype == 5) {    
		$totalresults = runSQL('SELECT count(*) AS num
					 FROM '.TBL_NEWS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY title'); 
	}
	else  {    
		$totalresults = runSQL('SELECT count(*) AS num
					 FROM '.TBL_CLUBS.'
					WHERE 1=1 '.$QUERY.'
				 ORDER BY shortname'); 
	}

	
	if (!$LIMIT && ($config['pageno'] > 0))
	{
		// check Page Number
		if (!isset($pageno))
		{
			$pageno = 1;
		}
	
		// define Max Results Per Page
		$maxresults = $config['pageno'];
	
		// define the Start Number
		$from = (($pageno * $maxresults) - $maxresults);
		
			// calculate Total amount of pages
		$totalpages = ceil($totalresults[0]['num'] / $maxresults);
		
		$LIMIT = ' LIMIT '.$from.', '.$maxresults;
	
		$smarty->assign('pageno', $pageno);                         // assign current Page Number
		$smarty->assign('maxpageno', $totalpages);		            // set Maximum Pages
		$smarty->assign('totalresults', $totalresults[0]['num']);   // set Total Records Returned
	}


	if ($searchtype == 2 || $searchtype == 3 || $searchtype == 4) {    
		$select = 'SELECT DISTINCT id, lastname, firstname, country, plot, imgurl
					 FROM '.TBL_PERSONS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY lastname, firstname ' . $LIMIT; 
	}
	else if ($searchtype == 1) {    
		$select = 'SELECT DISTINCT id, longname, plot, imgurl
					 FROM '.TBL_STADIUMS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY longname ' . $LIMIT;
	}
	else if ($searchtype == 5) {    
		$select = 'SELECT DISTINCT id, title, summary, plot, imgurl
					 FROM '.TBL_NEWS.' 
					WHERE 1=1 '.$QUERY.'
				 ORDER BY title ' . $LIMIT;
	}
	else  {    
		$select = 'SELECT DISTINCT id, shortname, longname, imgurl, city, country
					 FROM '.TBL_CLUBS.'
					WHERE 1=1 '.$QUERY.'
				 ORDER BY shortname ' . $LIMIT; 
	}

    $result = runSQL($select);

    // store query result in session for prev/next navigation
    $_SESSION['pcs']['query_result'] = array_map(create_function('&$row', 'return $row["id"];'), $result);
}

// prepare templates
tpl_page('search', $q);
tpl_list($result);

$smarty->assign('q', $q);
$smarty->assign('q_q', formvar($q));
$smarty->assign('list', $result);
$smarty->assign('searchlistcolumns', 1);
$smarty->assign('search_fields', $search_fields);

// allow XML export
// $cs changesearch
if (isset($q) && !$cs)
{
    $link = $_SERVER['QUERY_STRING'];
    if ($link) $link .= '&';
    $link = 'search.php?'.$link;
    
    if ($config['xls']) $smarty->assign('xls', $link);
    if ($config['xml']) $smarty->assign('xml', $link);
    if ($config['pdf']) $smarty->assign('pdf', $link);
}

// display templates
smarty_display('header.tpl');
if (!$config['http_caching']) flush();
smarty_display('search.tpl');
if (isset($q)) smarty_display('list_search.tpl');
smarty_display('footer.tpl');

?>