<?php
/**
 * General functions
 *
 * Contains globally available tool functions. It is included in every
 * page and sets up some defaults like error reporting, environment
 * setups and config loading
 *
 *
 * @package Core
 * @author  Eric GALLENE <okrome@free.fr>
 * @version $Id: functions.php,v 1.00 2006/10/23 18:15:53
 */

// add pwd to include_path
ini_set('include_path', '.:'.ini_get('include_path'));

/* This is needed to make sure we have our very own namespace without
   interfering Environment variables */
foreach (array_keys($_ENV) as $key)
{
    unset($GLOBALS[$key]);
}

require_once './config.inc.php';          // global const CONFIG_FILE is not yet defined at this point
require_once './core/constants.php';
require_once './core/template.php';
require_once './core/compatibility.php';
require_once './smarty/Smarty.class.php';

/* --------------------------------------------------------------------*/
// Set up some defaults

//error_reporting($config['debug'] ? E_ALL ^ E_NOTICE : E_ERROR + E_PARSE);
error_reporting(0);

if (get_magic_quotes_gpc())
{
	if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
	ini_set('magic_quotes_gpc', 0);
}

set_magic_quotes_runtime(0);

// register_globals off? Well I like it...
extract($_REQUEST);

// security check
if (!empty($id))
{
    validate_input($id);
}



// create smarty object
$smarty = new Smarty;
$smarty->compile_dir	= './cache/smarty';	            // path to compiled templates
$smarty->cache_dir		= './cache/smarty';	            // path to cached html
$smarty->plugins_dir    = array('custom', 'plugins');   // add custom plugins folder
$smarty->use_sub_dirs	= 0;                            // restrict caching to one folder
$smarty->load_filter('output', 'trimwhitespace');       // remove whitespace from output


// load config
loadconfig();

//check if forced theme
if (isset($theme)) {
forcetheme($theme);
}


// check authentification data for multiuser
//if (basename($_SERVER['PHP_SELF']) != 'login.php') authcheck();



/* --------------------------------------------------------------------*/
// functions follow


/**
 * Force theme display
 */
function forcetheme($theme) {

    $tpl                    = split('::', $theme);
	$config['style']        = 'templates/'.$tpl[0].'/'.$tpl[1].'.css';
	$config['templatedir']  = 'templates/'.$tpl[0].'/';
	$config['template']     = 'templates/'.$tpl[0].'/';

	// store loaded configuration
    $_SESSION['pcs']['config']['style']       = $config['style'];
	$_SESSION['pcs']['config']['templatedir'] = $config['templatedir'];
	$_SESSION['pcs']['config']['template']    = $config['template'];

	$smarty->template_dir = array($config['templatedir'], 'templates/classic');
}



/**
 * Like html_entity_decode() but also supports numeric entities
 *
 * @author www.php.net
 * @param  string   $string  html entity loaded string
 * @return string            html entity free string 
 */
function html_entity_decode_all($string) 
{
    // replace numeric entities
    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
    $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
    
    // replace literal entities
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    
    return strtr($string, $trans_tbl);
}

/**
 * Collect cookies from httpclient response and add them to an existing array
 *
 * @param  mixed    $response   HTTP response
 * @param  array    $oldcookies old cookies
 * @return array                new and old cookies
 */
function get_cookies_from_response($response, $oldcookies = null) 
{
    if (preg_match_all('/Set-Cookie:\s*(.+?);/', $response['header'], $_cookies, PREG_PATTERN_ORDER))
    {
        foreach ($_cookies[1] as $cookie)
        {
            // limit split to 2 elements (key/value)
            list($key, $value) = split('=', $cookie, 2);
            $oldcookies[$key] = $value;
        }
    }
    return $oldcookies;
}

/**
 * Used to remove magic quotes from the $_GET, $_POST, $_COOKIE and
 * $_SESSION super global arrays. It's automatically called in
 * functions.php
 *
 * @param array &$array Reference to an array
 */
function remove_magic_quotes(&$array)
{
	foreach (array_keys($array) as $key)
	{
		if (is_array($array[$key])) {
			remove_magic_quotes($array[$key]);
		} else {
			$array[$key] = stripslashes($array[$key]);
		}
	}
}

/*
 * magicquote safe formoutputter
 *
 * Strips slashes when magic_quotes_gpc is set.
 *
 * @param  string $name     The input string
 * @return string           The cleaned string
 */
function formvar($name)
{
	if (get_magic_quotes_gpc()) {
		$name = stripslashes($name);
	}
	return htmlspecialchars($name);
	#  return $name;
}

/**
 * Get high resolution time
 *
 * @return integer  current time in microseconds
 */
function getmicrotime()
{
	list($usec, $sec) = explode(' ',microtime());
	return ((float)$usec + (float)$sec);
}


/**
 * Get US date format from FR date
 *
 * @return integer  current time in microseconds
 */
function getusdate($dateFR)
{
if ($dateFR)
{
$elementsdate=chunk_split($dateFR , 2 , "-");
$elementsdate=explode("-",$elementsdate);

$annee=$elementsdate[2].$elementsdate[3];
$mois=$elementsdate[1];
$jour=$elementsdate[0];
$dateUS=$annee."-".$mois."-".$jour;
return $dateUS;
}
else return "00000000";
}

/**
 * Get FR date format from US date
 *
 * @return integer  current time in microseconds
 */
function getfrdate($dateUS)
{
if ($dateUS)
{
$mydateUS=explode(" ",$dateUS);
$elementsdate=explode("-",$mydateUS[0]);

$annee=$elementsdate[0];
$mois=$elementsdate[1];
$jour=$elementsdate[2];
$dateFR=$jour.$mois.$annee;
return $dateFR;
}
else return "00000000";
}

/**
 * Get FR date format from US date with Hour
 *
 * @return integer  current time in microseconds
 */
function getfrdatehour($dateUS)
{
	if ($dateUS) {
	$elementsdate=explode(" ",$dateUS);
	$dateFR = getfrdate($elementsdate[0]);
	
	$elementshour=explode(":",$elementsdate[1]);
	$hourFR = $elementshour[0] . ':' . $elementshour[1];
	
	$mydata['myday']  = $dateFR;
	$mydata['myhour'] = $hourFR;
	return ($mydata);
	}
	else return "00000000";
	
}
/**
 * get Thumbnail
 *
 * @param  string   URL
 * @return string   the URL to the cached image if exists or a link to img.php
 */
function getThumbnail($imgurl)
{
    // really an image?
    if (preg_match('/\.(jpe?g|gif|png)$/i', $imgurl, $matches))
#    if (1==1)
	{
		// local file? - keep it!
		if (!preg_match('/^http/i', $imgurl)) return($imgurl);

        // file in cache?
		if (checkCacheFile($imgurl, $matches[1], $file))
        {
			return($file);
		}
        else
        {
            return('img.php?url='.urlencode($imgurl));
		}
	}
    else
    {
		// no image url given -> nopic
		return(img('nocover.gif'));
	}
}


/**
 * get subcat data
 *
 * @param  string   URL
 * @return string   the URL to the cached image if exists or a link to img.php
 */
function get_subcat_data($parent, $ident = '', $level = 0, $getcompet = 0)
{
    global $config, $cat_list;

    $SELECT = 'SELECT id, longname, shortname, pos, parent FROM '.TBL_CATEGORIES.' WHERE parent = '.$parent.' ORDER BY pos ASC';
	$result = runSQL($SELECT);

	if(count($result) > 0) {
        $pos = 0;
        foreach ($result as $subcat) {
		$mycompet='';
			if ($getcompet) {
			$SELECT = 'SELECT id, longname, shortname, country, category FROM '.TBL_COMPETITIONS.' WHERE category = '.$subcat['id'].' AND visible = 1 ORDER BY country ASC';
			$mycompet = runSQL($SELECT);
			}
				$cat_list[] = array('id' => $subcat['id'],
                    'parent' => $parent,
                    'pos' => $pos++,
                    'prev' => $prev_cid,
                    'level' => $level,
                    'longname' => $ident . $subcat['longname'],
					'shortname' => $ident . $subcat['shortname'],
					'competitions' => $mycompet);
            $prev_cid = $subcat['id'];
            $last_index = count($cat_list) -1;
//			echo $subcat['id'] . ' - ' . $subcat['shortname'] . 'tototo<br><br>';
            get_subcat_data($subcat['id'], $ident . '&nbsp;&nbsp;', $level++, $getcompet);
        }
	}
	return($cat_list); 
}


/**
 * get subcat data
 *
 * @param  string   URL
 * @return string   the URL to the cached image if exists or a link to img.php
 */
function get_subcompet_data($parent, $ident = '', $level = 0, $getsubcompet = 0)
{
    global $config, $subcat_list;

    $SELECT = 'SELECT id, longname, shortname, pos, category, subcompet, subpos FROM '.TBL_COMPETITIONS.' WHERE subcompet = '.$parent.' AND visible = 1 ORDER BY subpos ASC';
	$result = runSQL($SELECT);

	if(count($result) > 0) {
        $pos = 0;
        foreach ($result as $subcat) {
		$mycompet='';
			if ($getsubcompet) {
			$SELECT = 'SELECT id, longname, shortname, pos, category, subcompet, subpos FROM '.TBL_COMPETITIONS.' WHERE subcompet = '.$subcat['id'].' AND visible = 1 ORDER BY subpos ASC';
			$mycompet = runSQL($SELECT);
			}
				$subcat_list[] = array('id' => $subcat['id'],
                    'category' => $parent,
                    'pos' => $subcat['pos'],
                    'subcompet' => $subcat['subcompet'],
                    'subpos' => $pos++,
                    'prev' => $prev_cid,
                    'level' => $level,
                    'longname' => $ident . $subcat['longname'],
					'shortname' => $ident . $subcat['shortname'],
					'competitions' => $mycompet);
            $prev_cid = $subcat['id'];
            $last_index = count($cat_list) -1;
//			echo $subcat['id'] . ' - ' . $subcat['shortname'] . 'tototo<br><br>';
            get_subcompet_data($subcat['id'], $ident . '&nbsp;&nbsp;', $level++, $getsubcompet);
        }
	}
	return($subcat_list); 
}


/**
 * get carac data
 *
 * @param  string   URL
 * @return string   the URL to the cached image if exists or a link to img.php
 */
function get_carac($type, $id)
{
    global $config;

    $SELECT = 'SELECT * FROM '.TBL_CARACS.' WHERE type = '.$type;
	$result = runSQL($SELECT);

	for ($x=0;$x<count($result);$x++) {
	if ($VALUES) {$VALUES .= ",";}
	$VALUES .= $result[$x]['id'];
	}
	if ($VALUES) {
		$SELECT = 'SELECT '.TBL_CARACS.'.id, '.TBL_CARACS.'.shortname, '.TBL_CARACS.'.lib_key, '.TBL_CARACS.'.perm, '.TBL_CARACS.'.genre, '.TBL_VALUES.'.value 
		FROM '.TBL_CARACS.' 
		LEFT JOIN '.TBL_VALUES.' ON '.TBL_VALUES.'.id_carac = '.TBL_CARACS.'.id AND '.TBL_VALUES.'.id_item='.$id.'
		WHERE '.TBL_CARACS.'.id IN ('.$VALUES.')';

		$result = runSQL($SELECT);
		$perm_user = $_SESSION['pcs']['permissions']['USERLEVEL'];
		
		for ($x=0;$x<count($result);$x++) {
			if($perm_user >= $result[$x]['perm']) {
			$cat_list[$x+1] = Array( 'id' => $result[$x]['id'], 'name' => $result[$x]['shortname'], 'lib_key' => $result[$x]['lib_key'], 'value' => $result[$x]['value'], 'genre' => $result[$x]['genre']);
			}
		}
	}
	return($cat_list);
}

/**
 * get carac data
 *
 * @param  string   URL
 * @return string   the URL to the cached image if exists or a link to img.php
 */
function upload_carac($myfile,$mykey,$id)
{

if (isset($_FILES[$myfile]) && is_uploaded_file($_FILES[$myfile]['tmp_name'])) {

	$file = $_FILES[$myfile]['tmp_name'];
	$mime = $_FILES[$myfile]['type'];

	// determine file extension
	if (preg_match('=image/jpe?g=i', $mime)) {
	$ext = 'jpg';
	}
	elseif (preg_match('=image/(gif|png)=i', $mime, $m)) {
	$ext = $m[1];
	}
	elseif (preg_match('=application/octet-stream=i', $mime)) {
		if (preg_match("/\.(jpe?g|gif|png)$/i", $_FILES[$myfile]['name'], $matches)) {
		$ext = $matches[1];
		}
	}

	// move to cache and update db
	if (!empty($ext)) {
	$coverfile = 'cache/img/gallery/'.$mykey.'_'.$id.'_'.$myfile.'.'.$ext;
		if (move_uploaded_file($file, $coverfile)) {
		return($coverfile);
		}
	}
}

}

/**
 * SQL function
 *
 * Wrapper for all Database accesses
 *
 * @param  string $sql_string The SQL-Statement to execute
 * @return mixed  either the resultset as an array with hashes or the insertid
 */
function runSQL($sql_string, $verify = true)
{
	global $config;
	
	if ($config['debug'])
    {
		echo "\n\n<!-- $sql_string -->\n\n";
		$timestamp = getmicrotime();
	}

	$link =	mysql_pconnect($config['db_server'], $config['db_user'], $config['db_password']) or
			errorpage('DB Connection Error',
                      "<p>Edit the database settings in <code>".CONFIG_FILE."</code>.</p>
					   <p>Alternatively, consider running the <a href='install/install.php'>installation script</a>.</p>");

	$res  = mysql_db_query($config['db_database'], $sql_string, $link);

	// mysql_db_query returns either positive result ressource or true/false for an insert/update statement
	if ($res === false)
    {
		if ($verify)
        {
        	// report DB Problem
            errorpage('Database Problem', mysql_error($link)."\n<br />\n".$sql_string);
        }
        else
        {
        	// ignore problem but forward the information
        	$result = false;	
        }
	}
	elseif ($res === true)
	{
        // on insert, return id of created record
		$result = mysql_insert_id($link);
	}
	else
	{
        // return associative result array
        $result = array();

		for ($i=0; $i<mysql_num_rows($res); $i++)
		{
            $result[] = mysql_fetch_assoc($res);
		}
		mysql_free_result($res);
	}
	
	if ($config['debug'])
    {
		$timestamp = getmicrotime() - $timestamp;
		echo "\n\n<!-- time: $timestamp -->\n\n";
	}

	mysql_close($link);
	return $result;
}

/**
 * checks if the page is accessed from within the local net.
 * If not, displays a simple error page and exits
 */
function localnet_or_die()
{
	if (!localnet()) errorpage('Forbidden', 'You are not allowed to access this page');
}

/**
 * Checks if the page is accessed from within the local net.
 *
 * @return  bool  true if localnet
 */
function localnet()
{
	global $config;
	return (preg_match('/'.$config['localnet'].'/', $_SERVER['REMOTE_ADDR']));
}

/**
 * Checks individual cache folder for existance
 * Checks if folder is writable
 * Creates folder if it doesn't exist
 */
function verify_cache_folder($dir)
{
    if (!is_dir($dir))
    {
        if (!@mkdir($dir, 0700)) $error = 'Directory <code>'.$dir.'</code> does not exist.<br/>';
    }
    elseif (!is_writable($dir))
    {
        $error = 'Directory <code>'.$dir.'</code> is not writable.<br/>';
    }
    return $error;
}

/**
 * Checks if the cache directories exist and are writable by the webserver.
 * If they don't exist it tries to create them. If this fails, too a simple
 * error page is displayed.
 * The function checks if the MySQL PHP extensions is loaded, too.
 */
function verify_installation()
{
    global $config;

    // check MySQL extension
    if (!extension_loaded('mysql'))
    {
        errorpage('MySQL extension for PHP not loaded',
                  '<p>The MySQL extension for PHP is not loaded.</p>
                   <p>Please make sure the MySQL module for PHP is installed and enabled
                   in your <code>php.ini</code></p>');
    }

    // collect all directory-specific errors
    $error = '';

    // check cache
    foreach (array('cache' => 0,'cache/smarty' => 0, 'cache/imdb' => 1, 'cache/img' => 1) as $dir => $hierarchical)
	{
        // check top-level folders
        $error .= verify_cache_folder($dir);

        // check hierarchical folders
        if (empty($error) && $config['hierarchical'] && $hierarchical)
        {
            for ($i=0; $i<16; $i++)
            {
                $error .= verify_cache_folder($dir.'/'.dechex($i));
            }
        }
    }

	if (!empty($error))
	{
        errorpage('Cache directories not writable',
                  '<p>The cache directories have to be writable by the webserver!</p>
                   <p>Please fix the following errors:</p>
                   <p>'.$error.'</p>');
    }
}

/**
 * Verify existance of cached file for given url/ extension
  * @param  string	url of the image
 * @param  string	ext file extension of the image
 * @param  string	file result: URL to the cached image if exists
 * @return bool		result of check
 */
function checkCacheFile($url, $ext, &$file, $folder = 'img')
{
	global $config;

	// construct cache file name
	$md5    = md5($url);
	$subdir = ($config['hierarchical']) ? substr($md5, 0, 1).'/' : '';
	if ($ext) $ext = ".$ext";
	$file   = 'cache/'.$folder.'/'.$subdir.$md5.$ext;

	// return if existing
	$result = (file_exists($file) && filesize($file)) ? true : false;
	return($result);
}

/**
 * Find available countries
 */
function getCountries()
{
    if ($dh = opendir('images/flags')) 
    {
        while (($file = readdir($dh)) !== false) 
        {
            if (preg_match("/(.*)\.gif$/", $file, $matches))
            {
                $languages[$matches[1]] = $matches[1];
            }
        }
        closedir($dh);
    }
    return $languages;
}


/**
*  Find seasons for a competition
*/

function getseasonsbycompet($compet){

$SELECT = 'SELECT DISTINCT '.TBL_CANDIDATES.'.id_season, '.TBL_SEASONS.'.season
FROM '.TBL_CANDIDATES.', '.TBL_SEASONS.' WHERE '.TBL_CANDIDATES.'.id_season = '.TBL_SEASONS.'.id AND '.TBL_CANDIDATES.'.id_compet='.$compet.' ORDER BY '.TBL_SEASONS.'.season';
$result = runSQL($SELECT);

return($result);
}

/**
*  Find table for a competition
*/

function gettablebycompet($competition, $season, $param_order, $day = 0) {

	if (!$day) {
	$lastday = runSQL('SELECT '.TBL_DAYS.'.id, '.TBL_DAYS.'.day FROM '.TBL_DAYS.' WHERE '.TBL_DAYS.'.date_day <= NOW() AND id_compet='.$competition.' AND id_season='.$season.' ORDER BY '.TBL_DAYS.'.date_day DESC LIMIT 1');
	$day = $lastday[0]['day'];
		if (!$lastday) {
			$day=1;
		}
	}
	if ($day) {

		$ORDER="";
		if ($param_order) {
			$table_order = array( 1 => 'pts DESC',2 => 'win DESC',3 => 'nul DESC',4 => '(sb - sa) DESC',5 => 'sb DESC',6 => 'dompts DESC',7 => 'domwin DESC',8 => 'domnul DESC',9 => '(domsb - domsa) DESC',10 => 'domsb DESC',11 => 'extpts DESC',12 => 'extwin DESC',13 => 'extnul DESC',14 => '(extsb - extsa) DESC',15 => 'extsb DESC' );
			$taborder = explode(',',$param_order);
			for ($x=0;$x<count($taborder);$x++) {
				if($ORDER) {$ORDER.=',';}
				$ORDER.=$table_order[$taborder[$x]];
			}
		}
		else {
			$ORDER = "pts DESC, (sb - sa) DESC, sb DESC";
		}
		if($ORDER) {$ORDER = 'ORDER BY '.$ORDER;}


		do {
		$SELECT = 'SELECT '.TBL_CLUBS.'.id as id, '.TBL_CLUBS.'.shortname as name, '.TBL_CLUBS.'.longname as longname, '.TBL_CLMNT.'.pts as points, '.TBL_CLMNT.'.played as nummatch, ('.TBL_CLMNT.'.sb - '.TBL_CLMNT.'.sa) as diff
			FROM '.TBL_CLMNT.'
			JOIN '.TBL_CLUBS.' ON '.TBL_CLUBS.'.id = '.TBL_CLMNT.'.id_team
			WHERE '.TBL_CLMNT.'.id_season='.$season.' AND '.TBL_CLMNT.'.id_compet = '.$competition.' AND '.TBL_CLMNT.'.id_day='.$day.' '.$ORDER;
		$result = runSQL($SELECT);

		if ($day == 0) {break;}
		$day = $day-1;
		} while (!$result);
	}


return($result);
}

/**
*  Find seasons for a club
*/

function getseasonsbyclub($club){

$SELECT = 'SELECT DISTINCT '.TBL_CANDIDATES.'.id_season as id, '.TBL_SEASONS.'.season
FROM '.TBL_CANDIDATES.', '.TBL_SEASONS.' WHERE '.TBL_CANDIDATES.'.id_season = '.TBL_SEASONS.'.id AND '.TBL_CANDIDATES.'.id_club='.$club.' ORDER BY '.TBL_SEASONS.'.season';
$result = runSQL($SELECT);

return($result);
}


/**
*  Find team coach for a club and a season
*/

function getcoachbyclub($id, $season){

$SELECT = 'SELECT '.TBL_TEAMS.'.id_person as id, '.TBL_PERSONS.'.lastname, '.TBL_PERSONS.'.firstname, '.TBL_PERSONS.'.birthday, '.TBL_PERSONS.'.country, '.TBL_CLUBS.'.shortname as clubname, '.TBL_PERSONS.'.position 
                 FROM '.TBL_TEAMS.'
				 JOIN '.TBL_PERSONS.' ON '.TBL_TEAMS.'.id_person = '.TBL_PERSONS.'.id
                 JOIN '.TBL_CLUBS.' ON '.TBL_TEAMS.'.id_club = '.TBL_CLUBS.'.id
                 WHERE '.TBL_TEAMS.'.id_season = '.$season.' AND '.TBL_TEAMS.'.id_club = '.$id.' AND '.TBL_PERSONS.'.type = 2  AND '.TBL_TEAMS.'.end = \'0000-00-00\' ORDER BY lastname, firstname';				 
	$teamcoach = runSQL($SELECT);	
return($teamcoach);
}



/**
*  Find teamplayer for a club and a season
*/

function getteambyclub($id, $season){

$SELECT = 'SELECT '.TBL_TEAMS.'.id_person as id, '.TBL_PERSONS.'.lastname, '.TBL_PERSONS.'.firstname, '.TBL_PERSONS.'.birthday, '.TBL_PERSONS.'.country, '.TBL_CLUBS.'.shortname as clubname, '.TBL_PERSONS.'.position 
                 FROM '.TBL_TEAMS.'
				 JOIN '.TBL_PERSONS.' ON '.TBL_TEAMS.'.id_person = '.TBL_PERSONS.'.id
                 JOIN '.TBL_CLUBS.' ON '.TBL_TEAMS.'.id_club = '.TBL_CLUBS.'.id
                 WHERE '.TBL_TEAMS.'.id_season = '.$season.' AND '.TBL_TEAMS.'.id_club = '.$id.' AND '.TBL_TEAMS.'.end LIKE "0000-00-00" ORDER BY lastname, firstname';				 
	$teamplayers = runSQL($SELECT);	
return($teamplayers);
}

/**
*  Find seasons for a competition
*/

function getreferee(){
$SELECT = 'SELECT id, lastname, firstname
FROM '.TBL_PERSONS.' WHERE type = 3 ORDER BY lastname, firstname';
$result = runSQL($SELECT);
return($result);
}

/**
*  Find seasons for a competition
*/

function getpresident(){
$SELECT = 'SELECT id, lastname, firstname
FROM '.TBL_PERSONS.' WHERE type = 4 ORDER BY lastname, firstname';
$result = runSQL($SELECT);
return($result);
}

/**
*  Find categories
*/

function getcategories(){
$SELECT = 'SELECT id, longname, shortname, country, active, visible, pos, parent, imgurl
FROM '.TBL_CATEGORIES.' ORDER BY parent, pos, longname';
$result = runSQL($SELECT);
return($result);
}

/**
*  Find stadium for a competition
*/

function getstadium(){
$SELECT = 'SELECT id, longname
FROM '.TBL_STADIUMS.' ORDER BY longname';
$result = runSQL($SELECT);
return($result);
}

/**
*  Find seasons for a competition
*/

function getlngoptions($lngdata){
$lngoptions=""; $x=0;
foreach ($lngdata as $key => $val)
    {
      $lngoptions[$x]['id']  = $key;
	  $lngoptions[$x]['val'] = $val;	    
      $x++;
	}
return($lngoptions);
}

/**
*  Find countrys for clubs
*/

function getcountryfromclubs($nationalteamfilter){

if ($nationalteamfilter) {
$WHERES = 'WHERE '.TBL_CLUBS.'.nationalteam = 1';
}
else {
$WHERES = 'WHERE '.TBL_CLUBS.'.nationalteam != 1';
}

$SELECT = 'SELECT DISTINCT '.TBL_CLUBS.'.country FROM '.TBL_CLUBS.' '.$WHERES.' ORDER BY '.TBL_CLUBS.'.country';
$result = runSQL($SELECT);
return($result);
}

/**
*  Find countrys for competitions
*/

function getcountryfromcategories(){

$SELECT = 'SELECT DISTINCT '.TBL_CATEGORIES.'.country FROM '.TBL_CATEGORIES.' ORDER BY '.TBL_CATEGORIES.'.country';
$result = runSQL($SELECT);

return($result);
}

/**
*  Find countrys for competitions
*/

function getcountryfromcompetitions(){

$SELECT = 'SELECT DISTINCT '.TBL_COMPETITIONS.'.country FROM '.TBL_COMPETITIONS.' ORDER BY '.TBL_COMPETITIONS.'.country';
$result = runSQL($SELECT);

return($result);
}

/**
*  Find countrys for clubs
*/

function getcountryfrompersons($type){

$SELECT = 'SELECT DISTINCT '.TBL_PERSONS.'.country FROM '.TBL_PERSONS.' WHERE '.TBL_PERSONS.'.type = '.$type.' ORDER BY '.TBL_PERSONS.'.country';
$result = runSQL($SELECT);

return($result);
}

/**
*  Find countrys for stadiums
*/

function getcountryfromstadiums(){

$SELECT = 'SELECT DISTINCT '.TBL_STADIUMS.'.country FROM '.TBL_STADIUMS.' ORDER BY '.TBL_STADIUMS.'.country';
$result = runSQL($SELECT);

return($result);
}


/**
*  Find category news for a competition
*/

function getcategorynews(){

$SELECT = 'SELECT DISTINCT '.TBL_NEWS.'.category FROM '.TBL_NEWS.' ORDER BY '.TBL_NEWS.'.category';
$result = runSQL($SELECT);

return($result);
}

/**
 * Find available languages
 */
function getlanguages()
{
global $countrylng;
$x=0;
    if ($dh = opendir('language')) 
    {
        while (($file = readdir($dh)) !== false) 
        {
            if (preg_match("/(.*)\.php$/", $file, $matches))
            {
                $languages[$x]['id'] = $matches[1];
				$languages[$x]['val'] = $countrylng[$matches[1]];
				$x++;
            }
        }
        closedir($dh);
    }
    return $languages;
}

/**
 * Find available templates/styles
 */
function getTemplates()
{
	if ($dh = @opendir('templates'))
	{
		while (($file = readdir($dh)) !== false)
		{
			if (preg_match("/^\./", $file)) continue;
			if (is_dir('templates/'.$file) && $file != "pure" && $file != "widget")
			{
				if ($dh2 = opendir('templates/'.$file))
				{
					while (($style = readdir($dh2)) !== false)
					{
						if (preg_match("/(.*)\.css$/", $style, $matches)) {
							$templates[$file.'::'.$matches[1]] = $file.' ('.$matches[1].')';
						}
					}
	    			closedir($dh2);
				}
			}
		}
		closedir($dh);
	}
	return $templates;
}


/**
*  Make count operations points for user
*/

function count_points($user_id, $points = '0'){

$SELECT = 'UPDATE '.TBL_USERCONFIG.' SET '.TBL_USERCONFIG.'.value = '.TBL_USERCONFIG.'.value + '.$points.' WHERE '.TBL_USERCONFIG.'.opt = \'points\' AND '.TBL_USERCONFIG.'.user_id = '.$user_id;
$result = runSQL($SELECT);
return($result);
}


/**
 * Tries to find the given image in template directory then in the default
 * image directory.
 *
 * @param  string  filename of image
 * @return string  path to the image
 */
function img($img)
{
	global $config;

	$result = 'images/'.$img;
	if (file_exists($config['templatedir'].$result)) $result = $config['templatedir'].$result;
	return ($result);
}

/**
 * Load config options from config.inc.php and database and
 * setup sane defaults.
 * Return configuration in global $config array variable
 *
 * @todo    Add security check if install.php is still available
 * @param   boolean force reload of configuration data
 */
function loadconfig($force_reload = false, $id_user = 0)
{
	global $config;
	global $lang;
	global $lngtimezone;
	global $countrylng;
	global $caractype;
	global $caracgenre;
	global $personstype;
	global $postype;
	global $compettype;
	global $competrange;
	global $compettaborder;
	global $weatherlng;
	global $smarty;

	// configuration cached and not outdated?
    if (isset($_SESSION['pcs']['config']) && (!$force_reload) && (!$config['recompile']) && ($_SESSION['pcs']['config_timestamp'] == filemtime(CONFIG_FILE)))
	{
		// load from cache
        $config = $_SESSION['pcs']['config'];	
	}
	else {
        // check MySQL extension and cache directories
        verify_installation();

		// remember modification time
        $_SESSION['pcs']['config_timestamp'] = filemtime(CONFIG_FILE);

		// get config options from the database
		$SELECT = 'SELECT opt,value
                     FROM '.TBL_CONFIG;
		$result = runSQL($SELECT);

		// put db results into global config array
		foreach ($result as $option) {
			$config[$option['opt']] = $option['value'];
		}
		
		
        // check if database matches the current version
        if ($config['dbversion'] < DB_REQUIRED)
        {
            // run installer
            redirect('install/install.php?action=upgrade');
        }
		
		// get user config options from the database
		if ($id_user) {$user_id = $id_user;}
		else {$user_id = $_COOKIE['PCSuserid'];}
		
		if (!empty($user_id))
		{

			$SELECT = 'SELECT opt, value
                         FROM '.TBL_USERCONFIG.'
			            WHERE user_id = '.$user_id;
			
			$result = runSQL($SELECT);
			if (count($result))
            {
			    foreach ($result as $option) {
			        $config[$option['opt']] = $option['value'];
			    }
			}
		}

		// set some defaults
		if (empty($config['language'])) $config['language'] = 'fr';
		if (empty($config['template'])) $config['template'] = 'classic::compact';
		
		
		if ($config['clubslistcolumns'] < 1) $config['clubslistcolumns']  = 5;
		if ($config['stadiumslistcolumns'] < 1) $config['stadiumslistcolumns']  = 4;
		if ($config['personslistcolumns'] < 1) $config['personslistcolumns']  = 4;
		if ($config['competitionslistcolumns'] < 1) $config['competitionslistcolumns']  = 3;
		if ($config['newslistcolumns'] < 1) $config['newsslistcolumns']  = 2;
		if ($config['gallerylistcolumns'] < 1) $config['gallerylistcolumns']  = 4;
		if ($config['prizelistcolumns'] < 1) $config['prizelistcolumns']  = 5;


		// prepare template/style
		$tpl                    = split('::', $config['template']);
		$config['style']        = 'templates/'.$tpl[0].'/'.$tpl[1].'.css';
		$config['templatedir']  = 'templates/'.$tpl[0].'/';

        // smarty cacheid for multiuser mode
        $config['cacheid']      = $tpl[0];

		// check if selected template is valid
		if (!file_exists($config['style']))
		{
			$config['style']       = 'templates/classic/compact.css';
			$config['template']    = 'classic::compact';
			$config['templatedir'] = 'templates/classic/';
		}

		// store loaded configuration
		unset($_SESSION['pcs']['config']);
        $_SESSION['pcs']['config'] = $config;

	}
	
	// setup smarty
	$smarty->template_dir = array($config['templatedir'], 'templates/classic');
	
	if ($config['recompile'])
    {
		$smarty->force_compile = 1;
	}
	
    // initialize languages
    $lang = array();

	// load english language as default
	require './language/fr.php';

    // override it with local language if nessesary:
    if ($config['language'] != 'fr')
    {
        $languages = split('_', $config['language']);
        $file = '';
        foreach ($languages as $language)
        {
            if ($file) $file .= '_';
            $file .= $language;
            @include './language/'.$file.'.php';
        }
    }

}



/**
 * Downloads an URL to the given local file
 *
 * @param   string  $url    URL to download
 * @param   string  $local  Full path to save to
 * @return  bool            true on succes else false
 */
function download($url, $local)
{
	$resp = httpClient($url);
	
	
	if (!$resp['success']) return false;

	return(@file_put_contents($local, $resp['data']) !== false);
}


/**
 * Reads a saved HTTP response from a cachefile.
 * If caching is globally disabled ($config['IMDBage'] <= 0), file is not loaded.
 *
 * @param   string $url URL of the cached response
 * @return  mixed       HTTP Response, false on errors
 */
function getHTTPcache($url)
{
	global $config;

    $result = false;

    // only get file from cache if caching is enabled
    if ($config['IMDBage'] > 0)
    {
        if (checkCacheFile($url, null, $cfile, 'imdb') && (time()-filemtime($cfile) < $config['IMDBage']))
        {
            $resp = file_get_contents($cfile);
            if ($resp !== false) $resp = unserialize($resp);
            $result = $resp;
        }
	}
    return $result;
}

/**
 * Saves a HTTP resonse to a cachefile
 * If caching is globally disabled ($config['IMDBage'] <= 0), file is not saved.
 *
 * @param  string $url  URL of the response
 * @param  mixed  $resp HTTP Response
 */
function saveHTTPcache($url, $resp)
{
    global $config;

    // only put file to cache if caching is enabled
    if ($config['IMDBage'] > 0)
    {
        // get the cache file name
        checkCacheFile($url, null, $cfile, 'imdb');

        // commit to disk
        file_put_contents($cfile, serialize($resp));
    }
}


// decode content-encoding: gzip
function gzdecode(&$string)
{
	return gzinflate(substr($string, 10));
}

// convert cookies to http header
function cookies2header($cookies)
{
    global $request_cookies;

    // concatenate cookie string
	foreach ($cookies as $key => $val)
    {
        // remember cookies for next request
        $request_cookies[$key] = $val;

        if ($headers) $headers .= '; ';
        $headers .= $key.'='.$val;
    }

    // build header
    if ($headers) $headers = 'Cookie: '.$headers."\r\n";
    return $headers;
}

/**
 * HTTP Client
 *
 * Returns the raw data from the given URL, uses proxy when configured and follows redirects
 * @param  string  $url      URL to fetch
 * @param  bool    $cache    use caching? defaults to false
 * @param  string  $post     POST data, if nonempty POST is used instead of GET
 * @param  integer $timeout  Timeout in seconds defaults to 15
 * @return mixed             HTTP response
 */
function httpClient($url, $cache=0, $post='', $timeout=15, $cookies = null, $headers2 = '', $omitProxy = false, $omitRedirect = false)
{
    global $config;

    // since we shouldn't don't need session functionality here,
    // use this as workaround for php bug #22526 session_start/popen hang
    session_write_close();
	

    $method = 'GET';
    $headers = '';  // additional HTTP headers, used for post data
    if (!empty($post))
    {
        // POST request
        $method = 'POST';
        $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $headers .= "Content-Length: ".strlen($post)."\r\n";
    }

    // get data from cache?
    if ($cache)
    {
        $resp = getHTTPcache($url.$post);
        if ($resp !== false) {
            return $resp;
        }
    }

    $response['error']  = '';
    $response['header'] = '';
    $response['data']   = '';
    $response['url']    = $url;
    $response['success']= false;

    $uri = parse_url($url);
    $server = $uri['host'];
    $path = $uri['path'];
    if (empty($path)) $path = '/'; #get root on empty path
    if (!empty($uri['query'])) $path .= '?'.$uri['query'];
    $port = $uri['port'];

    // proxy setup
    if (!empty($config['proxy_host']) && !$omitProxy)
    {
        $request_url = $url;
        $server      = $config['proxy_host'];
        $port        = $config['proxy_port'];
        if (empty($port)) $port = 8080;
    }
    else
    {
        $request_url = $path;  // cpuidle@gmx.de: use $path instead of $url if HTTP/1.0
        $server      = $server;
        if (empty($port)) $port = 80;
    }

    // print "<pre>$request_url</pre>";

    // open socket
    $socket = fsockopen($server, $port);
    if (!$socket)
    {
        $response['error'] = "Could not connect to $server";
        return $response;
    }
    socket_set_timeout($socket, $timeout);

    // build request
    $request  = "$method $request_url HTTP/1.0\r\n";
    $request .= "Host: ".$uri['host']."\r\n";
    $request .= "User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)\r\n";
    if (extension_loaded('zlib')) $request .= "Accept-encoding: gzip\r\n";
    if ($cookies) $request .= cookies2header($cookies);
    $request .= "Connection: Close\r\n";
    $request .= $headers;
    $request .= $headers2;
    $request .= "\r\n";
    $request .= $post;

    // send request
    fputs($socket, $request);

    if ($config['debug']) echo "request:<br>".nl2br($request)."<p>";

    // log request
    if ($config['httpclientlog'])
    {
        $log = fopen('httpClient.log', 'a');
        fwrite($log, $request."\n");
        fclose($log);
    }

    // read headers from socket
    do
    {
        $response['header'] .= fread($socket,1);
    }
    while(!preg_match('/\r\n\r\n$/',$response['header']));

    // chunked encoding?
    if (preg_match('/transfer\-(en)?coding:\s+chunked\r\n/i',$response['header']))
    {
        do {
            unset($chunk_size);
            do
            {
                $byte = fread($socket,1);
                $chunk_size .= $byte;
            }
            while (preg_match('/[a-zA-Z0-9]/',$byte));  // read chunksize including \r

            $byte       = fread($socket, 1);            // readtrailing \n
            $chunk_size = hexdec($chunk_size);
            $this_chunk = fread($socket, $chunk_size);
            $response['data'] .= $this_chunk;
            if ($chunk_size) $byte = fread($socket, 2); // read trailing \r\n
        }
        while ($chunk_size);
    }
    else
    {
        // read entire socket
        while (!feof($socket))
        {
            $response['data'] .= fread($socket,4096);
        }
    }

    // close socket
    $status = socket_get_status($socket);
    fclose($socket);

    if ($config['debug']) echo "header:<br>".nl2br($response['header'])."<p>";
    // if ($config['debug']) echo "data:<br>".htmlspecialchars($response['data'])."<p>";

    // check for timeout
    if ($status['timed_out'])
    {
        $response['error'] = "Connection timed out";
        return $response;
    }

    // log response
    if ($config['httpclientlog'])
    {
        $log = fopen('httpClient.log', 'a');
        fwrite($log, $response['header']."\n");
        fclose($log);
    }

    // check server status code to follow redirect
    if (preg_match("/^HTTP\/1.\d 30[12].*?\n/s", $response['header']))
    {
        preg_match("/Location:\s+(.*?)\n/s",$response['header'],$matches);
        if (empty($matches[1]))
        {
            $response['error'] = 'Redirect but no Location header found';
            return $response;
        }
        else
        {
			// in case no redirect is needed stop here and respond success
        	if ($omitRedirect)
            {
                // save time if result is not needed
        		$response['error']   = '';
        		$response['success'] = true;
        		return $response;
        	}

            // get redirection target
            $location = trim($matches[1]);

            if (preg_match("/^\//", $location))
            {
                // local redirect
                $location = 'http://'.$uri['host'].':'.$uri['port'].$location;
            }
            elseif (!preg_match('/^http/', $location))
            {
                // local redirect without path
            	$path     = substr($uri['path'], 0, strrpos($uri['path'], '/') + 1);
            	$location = 'http://'.$uri['host'].':'.$uri['port'].$path.$location;
            }

            // don't use old headers again
            $headers	= '';

            // if this is a redirect, we must GET, not POST
            $post		= '';

            // add new cookies from response
            $cookies = get_cookies_from_response($response, $cookies);

            // perform redirected request
            $response = httpClient($location, $cache, $post, $timeout, $cookies, $headers2, $omitProxy);

            // remember we were redirected
            $response['redirect'] = $location;

            if ($response['success'] == true && $cache) saveHTTPcache($url.$post, $response);

            return $response;
        }
    }

    // verify status code
    if (!preg_match("/^.*? 200 .*?\n/s", $response['header']))
    {
        $response['error'] = 'Server returned wrong status.';
        return $response;
    }

    $response['success'] = true;

    // decode data if necessary- do not modify original headers
    if (preg_match("/Content-Encoding:\s+gzip\r?\n/i", $response['header']))
    {
        $response['data'] = gzdecode($response['data']);
    }

    // decode UTF8
    if (preg_match("/Content-Type:.*?charset=UTF-8/i", $response['header']))
    {
        $response['data'] = utf8_decode($response['data']);
    }

    // commit successful request to cache
    if ($cache) saveHTTPcache($url.$post, $response);


    return $response;
}

/**
 * Displays an errorpage and exits
 *
 * @param string $title   The pages headline
 * @param string $body    An additional message
 */
function errorpage($title = 'An error occured', $body = '')
{
    echo '<?xml version="1.0" encoding="en"?>';
?>
    <html xmlns="http:// www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    <head>
        <title>PHP Competition System - ERROR</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <meta name="description" content="PHP Competition System" />
    </head>
    <body>
        <h1><?=$title?></h1>
        <?=$body?>
    </body>
    </html>
<?
	exit;
}




/**
 * Used to check permissions on a user for a page
 *
 * @author Mike Clark <Mike.Clark@Cinven.com>
 * @author Chinamann <chinamann@users.sourceforge.net>
 * @param  integer $permission Permission to check
 * @param  String  $destUserId UserId to access
 * @return boolean             True if permission exists else false
 */
function check_permission($permission, $destUserId = false)
{
    global $config;
    if ($_SESSION['pcs']['permissions']) $_SESSION['pcs']['permissions'] = array();

    if (!$config['multiuser']) return true;
    if (empty($_COOKIE['PCSuserid']))
    {
        // not logged in
        $permissions = 0;
    }
    else
    {
        // User Level Permissions
        if (isset($_SESSION['pcs']['permissions']['USERLEVEL']))
        {
            $permissions |= $_SESSION['pcs']['permissions']['USERLEVEL'];
        }
        else
        {
			if (!$destUserId) {$userid = $_COOKIE['PCSuserid'];}
            else {$userid = $destUserId;}
			
            $SELECT = "SELECT permissions FROM ".TBL_USERS." WHERE id=".$userid;
            $result = runSQL($SELECT);
            $_SESSION['pcs']['permissions']['USERLEVEL'] = $result[0]['permissions'];
            $permissions |= $_SESSION['pcs']['permissions']['USERLEVEL'];
        }
    }
    // check permissionbits
    return ($permissions & $permission);
}



/**
 * Check permissions on a user for a page and display error message on failure
 *
 * @author  unknown
 * @author  Chinamann <chinamann@users.sourceforge.net>
 * @param   integer $permission  Permission to check (admin,write,writeall)
 * @param   String  $destUserId UserId to access
 */
function permission_or_die($permission, $destUserId = false)
{
    if (!check_permission($permission, $destUserId))
    {
        errorpage("Access denied",$lang[accessdenied]);
    }
}

/**
 * Checks if the user was authenticated and if the received auth cookie is valid.
 * Function is called for every page except login.php!
 *
 * @param  string $redirect  Redirect to login page if authentication check unsuccessful
 */
function authcheck($redirect = true)
{
    global $config;

    // auth result will always be success for single-user
    $result = true;

    // auth check only in multiuser mode
    if ($config['multiuser'])
    {
        $referer = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'],'/')+1) .'?'. $_SERVER['QUERY_STRING'];

        // already logged in?
        $user   = $_COOKIE['PCSusername'];
        $pass   = $_COOKIE['PCSpassword'];
        $userid = $_COOKIE['PCSuserid'];

        // auth cookies present?
        if (!empty($user) && !empty($pass) && !empty($userid))
        {
            // There are some auth cookies - we need to check if they are valid
            if (!(eregi('[a-z]', $user) && eregi('[0-9]', $pass) && eregi('[0-9]', $userid)))
            {
                $result = false;
            }
            else
            {
                // This is the crucial bit, lets just test the cookiecode with SQL again.
                $row = runSQL("SELECT cookiecode FROM ".TBL_USERS." WHERE name='".mysql_escape_string($user)."' AND id=$userid");

                if ($row[0]['cookiecode'] !== $pass && $userid !== $guestid)
                {
                    $result = false;
                }
            }
        }
        else
        {
        	$result = false;
        }

        // HTTP basic authentication (for RSS feed)?
        if (!$result && isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
        {
            $user   = $_SERVER['PHP_AUTH_USER'];
            $pass   = $_SERVER['PHP_AUTH_PW'];

            // check if basic auth headers are valid
            if (eregi('[a-z]', $user))
            {
                $row = runSQL("SELECT passwd FROM ".TBL_USERS." WHERE name='".mysql_escape_string($user)."'");

                // auth successful if password matches
                $result = (md5($pass) == $row[0]['passwd']);
            }
        }

        // autologin as guest?
        if (!$result && !$config['denyguest'])
        {
            // get script folder for cookie path
            $subdir = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'],'/')) . '/';
            $result = runSQL('SELECT name, passwd FROM '.TBL_USERS.' WHERE id = '.$config['guestid']);
            setcookie('PCSusername', $result[0]['name'], null, $subdir);
            setcookie('PCSpassword', $result[0]['passwd'], null, $subdir);
            setcookie('PCSuserid', $config['guestid'], null, $subdir);
            $_COOKIE['PCSusername'] = $result[0]['name'];
            $_COOKIE['PCSpassword'] = $result[0]['passwd'];
            $_COOKIE['PCSuserid']   = $config['guestid'];
            $result = true;
        }

        // goto login page if anything was fishy
        if ($redirect &! $result)
        {
            redirect('login.php?refer='.$referer);
        }
    }

    return $result;
}



/**
 * Verify variable is valid according to validation function
 * @param  string   $var                variable to validate (e.g. $id)
 * @param  string   $validation_func    validation function name (e.g. is_numeric)
 */
function validate_input(&$var, $validation_func = 'is_numeric')
{
    if (function_exists($validation_func))
    {
        if (!$validation_func($var))
        {
            errorpage('Forbidden', 'You are not allowed to access this page.');
        }
    }
}

/**
 * Display template with Smarty
 * If Smarty caching is enabled and cache id present, then cache will be used
 *
 * @param   string  $template   Template file name for display
 * @parem   string  $id         Cache id
 */
function smarty_display($template, $id = null)
{
    global $smarty, $config;

    $smarty->display($template, $id, $config['cacheid']);    
  
}


function tri_multi($tableau, $col, $direction = SORT_DESC, $col2, $direction2 = SORT_ASC){
  foreach($tableau as $k=>$v){
    $cle[$k] = $v[$col];
	$cle2[$k] = $v[$col2];
  }
  array_multisort($cle, $direction, $cle2, $direction2, $tableau);
  return $tableau;
} 



/**
 * Return UserId to a given UserName
 *
 * @author Chinamann <chinamann@users.sourceforge.net>
 * @param   string  $userName user name
 * @result  integer user id
 */
function getUserId($userName)
{
    $SELECT = "SELECT id
                 FROM ".TBL_USERS."
                WHERE name='".$userName."'";
    $result = runSQL($SELECT);
    return $result[0]['id'];
}

/**
 * Return UserName to a given UserId
 *
 * @author Chinamann <chinamann@users.sourceforge.net>
 * @param  integer   $userId user id
 * @param  string            user name
 */
function getUserName($userId)
{
    $SELECT = "SELECT name
                 FROM ".TBL_USERS."
                WHERE id=".$userId;
    $result = runSQL($SELECT);
    return $result[0]['name'];
}



/**
 * Redirect to new location
 *
 * @param   string  $dest   Redirect destination
 * @todo    Read somewhere that according to RFC redirects need to specify full URI
 */
function redirect($dest)
{
    header('Location: '.$dest);
    exit();
}

?>