<?
/**
 * Edit Page
 *
 * The edit form for adding and editing stadium data
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_stadiums.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;

// XML import
if ($config['xml'] && ($import == 'xml'))
{
    require_once './core/xml.php';

    // xml file upload
    if (isset($_FILES['xmlfile']) && is_uploaded_file($_FILES['xmlfile']['tmp_name']))
    {
        $file    = $_FILES['xmlfile']['tmp_name'];
        $xmldata = file_get_contents($file);
        unlink($file);
    }

    // uploading XML data directly or loaded from file
    if (!empty($xmldata))
    {
        $error      = '';
        $item_id    = 0;

        if (($xmlitems = xmlimport($xmldata, $error)) !== false)
        {
            // multiple items imported
            if ($xmlitems === true)
            {
                redirect('stadiums.php?filter=new');
            }
            // exactly one stadium imported?
            else
            {
                redirect('show_stadiums.php?id='.$xmlitems);
            }
        }
        $smarty->assign('xmlerror', $error);
    }

    // prepare templates
    tpl_page();

    // display templates
    tpl_display('xmlimport.tpl');
    exit;
}

// list of fields to be read/written from/to html form
$stadium_set_fields    = array('longname','aka','country','imgurl','creation','renovation','adresse','places','plot');
// list of fields to be overwritten by refetchAllInfos-Script
$stadium_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 stadiums in DB
    $stadium = runSQL('SELECT * FROM '.TBL_STADIUMS.' WHERE id = '.$id);

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

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

    $lookup = 2;
}

// explicit setting of owner
if ($config['multiuser'] && empty($owner_id) && empty($id))
{
    if (check_permission(PERM_WRITE, $_COOKIE['PCSuserid']))
    {
        $owner_id = $_COOKIE['PCSuserid'];
    }
    else
    {
        // error no owner specified
        $stadium = array();
		    		
        // select all fields according to list, plus id
        foreach ($stadium_set_fields as $name)
        {
            $stadium[0][$name] = $$name;
        }
        $CLIENTERROR = $lang['warn_noOwner'];
        $noError = false;
    }
}

// save data
if ($save)
{
    // update all fields according to list
    foreach ($stadium_set_fields as $name)
    {
	
		$$name = removeEvilTags($$name);
        // make sure no formatting contained in basic data
        if ($SETS) $SETS .= ', ';
        $SETS .= "$name = '".addslashes($$name)."'";

    }

    

    if ($noError)
    {
        if ($id)
        {
            $INSERT = 'UPDATE '.TBL_STADIUMS.' SET '.$SETS.' WHERE id = '.$id;
            runSQL($INSERT);
        }
        else
        {
            // insert new record
            $INSERT = 'INSERT INTO '.TBL_STADIUMS.' SET '.$SETS;
            $id = runSQL($INSERT);
        }


		//Additionnal caracs
		$SELECT = 'SELECT id, lib_key, genre FROM '.TBL_CARACS.' WHERE type = 3';
		$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'],'3',$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/stadiums/'.$id.'.'.$ext;
                if (move_uploaded_file($file, $coverfile))
                {
                    $sql = "UPDATE ".TBL_STADIUMS." 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/stadiums/'.$id.'.'.$matches[1];
			download($imgurl, $coverfile);
			$imgurl = $coverfile;
			$sql = "UPDATE ".TBL_STADIUMS." 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 stadium
	        redirect('show_stadiums.php?id='.$id);
	    }
	}
}


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

    $SELECT = 'SELECT id, '.$SELECT.'
                 FROM '.TBL_STADIUMS.'
                 WHERE id = '.$id;
	$stadium = runSQL($SELECT);
	
	if ($config['activecomments']) {
	$stadium[0]['commentable'] = check_permission(PERM_MKCOMMENT, $_COOKIE['PCSuserid']);
	}
	if ($config['activegallery']) {
    $stadium[0]['seegallery'] = check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']);
	}
	$stadium[0]['carac_ads'] = get_carac('3',$id);
}
else {
	$stadium[0]['carac_ads'] = get_carac('3','0');
} 


// prepare templates
tpl_page();
tpl_edit_stadium($stadium);
$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_stadiums.tpl');

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

?>
