<?
/**
 * Edit Page
 *
 * The edit form for adding and editing club data
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_clubs.php,v 1.00 2006/10/26 19:47:13
 */

require_once './core/functions.php';
require_once './core/security.php';

// check for localnet
localnet_or_die();

// multiuser permission check
permission_or_die(PERM_WRITE);
$noError = true;

// list of fields to be read/written from/to html form
$club_set_fields    = array('shortname','longname','aka','country','nationalteam','city','imgurl','creation','complete','website','email','adresse','tel','fax','newspaper','plot','id_stadium','id_president');
// list of fields to be overwritten by refetchAllInfos-Script
$club_overwrite_fields    = array('plot');


// get default lookup mode (0=ignore, 1=lookup, 2=overwrite) if not set
if (!isset($lookup)) $lookup = (empty($id)) ? $lookup = 2 : $config['lookupdefault'];

// preload old data for refresh all mechanism
if ($lookup == 3)
{
    // get a list of clubs in DB
    $club = runSQL('SELECT * FROM '.TBL_CLUBS.' WHERE id = '.$id);

    // get fields (according to list) from db to be saved later
    foreach ($club[0] as $name => $val)
    {
       if (in_array($name, $club_set_fields)) $$name = $val;
    }

    // Build a list of all fields which are allowed to be overwritten
    $overwrites = array();
    foreach ($club_set_fields as $field)
    {
        $tempFieldName = 'update_'.$field;
        if (isset($$tempFieldName) && $$tempFieldName == 1) $overwrites[] = $field;
    }
    $club_set_fields = $overwrites;

    $lookup = 2;
}


// save owner id
if ($ownersave) {
//echo print_r($candidate);
//exit;
	foreach ($candidate as $idmember) {
		if (!$VALUES) {$VALUES .= ",";}
		$VALUES .= $idmember.',';		
	}
	$INSERT = "UPDATE ".TBL_CLUBS." SET owner_id='".$VALUES."' WHERE id=".$id;
	runSQL($INSERT);
	redirect('edit_clubs.php?id='.$id);
}
// save data
else if ($save)
{
    // update all fields according to list
    foreach ($club_set_fields as $name)
    {
	
		$$name = removeEvilTags($$name);
        // make sure no formatting contained in basic data
        if ($SETS) $SETS .= ', ';
        $SETS .= "$name = '".addslashes($$name)."'";

    }

    //$SETS = "owner_id = '".addslashes($owner_id)."', ".$SETS;

    if ($noError)
    {
        if ($id)
        {
            $INSERT = 'UPDATE '.TBL_CLUBS.' SET '.$SETS.' WHERE id = '.$id;
            runSQL($INSERT);
        }
        else
        {
            // insert new record
            $INSERT = 'INSERT INTO '.TBL_CLUBS.' SET '.$SETS;
            $id = runSQL($INSERT);
        }
	
		//Additionnal caracs
		$SELECT = 'SELECT id, lib_key, genre FROM '.TBL_CARACS.' WHERE type = 1';
		$allcaracs = runSQL($SELECT);
		if ($allcaracs) {
			for ($x=0;$x<count($allcaracs);$x++) {
				if ($IN) {$IN .= ', ';}
				else {$IN = '(';}
				$IN .= $allcaracs[$x]['id'];
				if ($VALUES) {$VALUES .= ",";}
				if (${$allcaracs[$x]['lib_key']}) {
					if ($allcaracs[$x]['genre'] == 2) {$caracvalue = getusdate(${$allcaracs[$x]['lib_key']});}
					elseif ($allcaracs[$x]['genre'] == 7) {$caracvalue = upload_carac($allcaracs[$x]['lib_key'],'1',$id);}
					else {$caracvalue = ${$allcaracs[$x]['lib_key']};}
				}
				$VALUES .= "(".$allcaracs[$x]['id'].",".$id.",'".$caracvalue."')";
			}
			$IN .= ')';
			$DELETE = 'DELETE FROM '.TBL_VALUES.' WHERE id_item='.$id.' AND id_carac IN '.$IN;
			runSQL($DELETE);
			$INSERT = 'REPLACE INTO '.TBL_VALUES.' (id_carac, id_item, value) VALUES '.$VALUES;
			runSQL($INSERT);
		}

        // uploaded cover?
        if (isset($_FILES['coverupload']) && is_uploaded_file($_FILES['coverupload']['tmp_name']))
        {
            $file = $_FILES['coverupload']['tmp_name'];
            $mime = $_FILES['coverupload']['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['coverupload']['name'], $matches))
                {
                    $ext = $matches[1];
                }
            }

            // move to cache and update db
            if (!empty($ext))
            {
                $coverfile = 'cache/img/clubs/logo_'.$id.'.'.$ext;
                if (move_uploaded_file($file, $coverfile))
                {
                    $sql = "UPDATE ".TBL_CLUBS." SET imgurl='".$coverfile."' WHERE id=".$id;
                    runSQL($sql);
                }
            }
			
	    }

		if (preg_match('/http/i', $imgurl))
    	{
			if (preg_match('/\.(jpe?g|gif|png)$/i', $imgurl, $matches)) {
					// determine mime type
					switch (strtolower($matches[1]))
					{
						case 'gif':	$mime = 'image/gif';
									break;
						case 'png':	$mime = 'image/png';
									break;
						default:	$mime = 'image/jpeg';
					}
			$coverfile = 'cache/img/clubs/logo_'.$id.'.'.$matches[1];
			download($imgurl, $coverfile);
			$imgurl = $coverfile;
			$sql = "UPDATE ".TBL_CLUBS." SET imgurl='$coverfile' WHERE id=".$id;
            runSQL($sql);			
			}        
    	}
		

        // clear smarty cache for this item
        $smarty->clear_cache($id);

	    // add another?
	    if ($add_flag)
	    {
	        // remove id to prevent edit mode instead of new
	        $id = '';
	        $smarty->assign('add_flag', $add_flag);
	    }
	    else
	    {
	        // show the saved club
	        redirect('show_clubs.php?id='.$id);
	    }
	}
}


// load existing data
if ($id)
{
	// select all fields according to list, plus id
	foreach ($club_set_fields as $name)
    {
		if ($SELECT) $SELECT .= ', ';
		$SELECT .= $name;
	}

    $SELECT = 'SELECT id, owner_id, '.$SELECT.'
                 FROM '.TBL_CLUBS.'
                 WHERE id = '.$id;
	$club = runSQL($SELECT);
	//Get additionnal caracs
	$club[0]['carac_ads'] = get_carac('1',$id);

	if (check_permission(PERM_ADMIN, $_COOKIE['PCSuserid'])) {
		$administrable = 1;
		if ($club[0]['owner_id']) {
			$owners = split(',', $club[0]['owner_id']);
			$NOT_IN = '';
			foreach($owners as $owner) {
				if ($owner) {
					if ($NOT_IN) {$NOT_IN.=',';}
					$NOT_IN .= $owner;
				}
			}
			$NOTIN = '(1,10000,'.$NOT_IN.')';
		}
		else {$NOTIN = '(1,10000)';}
		
		$SELECT = 'SELECT id, name FROM '.TBL_USERS.' WHERE permissions > '.PERM_WRITE.' AND id NOT IN '.$NOTIN.' ORDER BY name';
		$members = runSQL($SELECT);
		$smarty->assign('members', $members);
		$smarty->assign('administrable', $administrable);
		
		if ($club[0]['owner_id']) {
			$SELECT = 'SELECT id, name FROM '.TBL_USERS.' WHERE id IN ('.$NOT_IN.') ORDER BY name';
			$owners_id = runSQL($SELECT);
			$smarty->assign('owners', $owners_id);
		}
	}


	$administrable = check_permission(PERM_ADMIN, $_COOKIE['PCSuserid']);

	$owners = split(',', $club[0]['owner_id']);
	foreach($owners as $owner) {
		if($owner == $_COOKIE['PCSuserid']) {
			$editable = 1;
			$smarty->assign('editable', $editable);
		}
	}
	if (!$administrable && !$editable) {
		errorpage("Access denied",$lang[accessdenied]);
	}
	
	if ($config['activecomments']) {
	$club[0]['commentable'] = check_permission(PERM_MKCOMMENT, $_COOKIE['PCSuserid']);
	}
	if ($config['activegallery']) {
    $club[0]['seegallery'] = check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']);
    }

} 
else {
	$club[0]['carac_ads'] = get_carac('1','0');
}

$smarty->assign('clubstats', $config['clubstats']);
// prepare templates
tpl_page();
tpl_edit_club($club);
$smarty->assign('lookup_id', $lookup);
$smarty->assign('http_error', $CLIENTERROR);
// allow XML import
if ($config['xml'] && empty($id)) $smarty->assign('xmlimport', true);
// display templates
tpl_display('edit_clubs.tpl');

// caching enabled?
if ($config['http_caching'])
{
    httpCacheOutput('edit_clubs'.$id, httpCacheCaptureEnd());
}	

?>
