<?
/**
 * Edit Page
 *
 * The edit form for adding and editing person data
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_persons.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('persons.php?filter=new');
            }
            // exactly one person imported?
            else
            {
                redirect('show_persons.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
$person_set_fields    = array('lastname','firstname','aka','country','imgurl','birthday','birthcity','deathday','international','type','height','weight','position','contribution',
'stop_mail','email','license','website','address','tel1','tel2','plot');
// list of fields to be overwritten by refetchAllInfos-Script
$person_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 persons in DB
    $person = runSQL('SELECT * FROM '.TBL_PERSONS.' WHERE id = '.$id);

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

    // Build a list of all fields which are allowed to be overwritten
    $overwrites = array();
    foreach ($person_set_fields as $field)
    {
        $tempFieldName = 'update_'.$field;
        if (isset($$tempFieldName) && $$tempFieldName == 1) $overwrites[] = $field;
    }
    $person_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
        $person = array();
		    		
        // select all fields according to list, plus id
        foreach ($person_set_fields as $name)
        {
            $person[0][$name] = $$name;
        }
        $CLIENTERROR = $lang['warn_noOwner'];
        $noError = false;
    }
}

// save data
if ($save)
{
	$birthday = getusdate($birthday);
	$deathday = getusdate($deathday);
    // update all fields according to list
    foreach ($person_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_PERSONS.' SET '.$SETS.' WHERE id = '.$id;
            runSQL($INSERT);
        }
        else
        {
            // insert new record
            $INSERT = 'INSERT INTO '.TBL_PERSONS.' SET '.$SETS;
            $id = runSQL($INSERT);
        }

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

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

    $SELECT = 'SELECT id, '.$SELECT.'
                 FROM '.TBL_PERSONS.'
                 WHERE id = '.$id;
	$person = runSQL($SELECT);
	
	if ($config['activecomments']) {
	$person[0]['commentable'] = check_permission(PERM_MKCOMMENT, $_COOKIE['PCSuserid']);
	}
	if ($config['activegallery']) {
    $person[0]['seegallery'] = check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']);
	}
	//Get additionnal caracs
	$person[0]['carac_ads'] = get_carac('4',$id);
	
	if (!$LIMIT && ($config['prizelistsize'] > 0)) {
		// check Page Number
		if (!isset($pageno))
		{
			$pageno = 1;
		}
	// define Max Results Per Page
	$maxresults = $config['prizelistsize'];

	// define the Start Number
	$from = (($pageno * $maxresults) - $maxresults);
	
	// get total amount of results from DB
	$totalresults = runSQL('SELECT count(*) AS num FROM '.TBL_SEASONS);
	// 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
	
	$allseasons= runSQL('SELECT id, season FROM '.TBL_SEASONS.' ORDER BY season DESC'.$LIMIT);
	$smarty->assign('allseasons', $allseasons);
	
} 
else {
	$person[0]['carac_ads'] = get_carac('4','0');
}

if ($effectif) {

	$SELECT = 'SELECT id_club, id_season FROM '.TBL_TEAMS.' WHERE id_person='.$personid;
	$result = runSQL($SELECT);		
	foreach ($result as $re) {$stack[$re['id_season']] = $re['id_club'];}

	$SELECT = 'SELECT id, season FROM '.TBL_SEASONS.' ORDER BY season ASC;'; 
	$res   = runSQL($SELECT);
	foreach ($res as $name) {
		if(${'season'.$name['id']}) {$stuck[$name['id']] = ${'season'.$name['id']};}		
	}

if (!$toinsert) { $toinsert = $stuck;}
if ($toinsert) {
	$VALUES="";
	// update all fields according to list
	foreach ($toinsert as $key => $val) {
		if ($IN) {$IN .= ', ';}
		else {$IN = '(';}
		$IN .= $key;
		if ($VALUES) {$VALUES .= ",";}
		$VALUES .= "(".$personid.",".$val.",".$key.")";		
	}
	$IN .= ')';
	
	$DELETE = 'DELETE FROM '.TBL_TEAMS.' WHERE id_person='.$personid.' AND id_season IN '.$IN;;
	runSQL($DELETE);
	
	$INSERT = 'INSERT INTO '.TBL_TEAMS.' (id_person, id_club, id_season) VALUES '.$VALUES;
    // insert new record
    $id = runSQL($INSERT);
}

redirect('show_persons.php?id='.$personid);
}

// prepare templates
tpl_page();
tpl_edit_person($person);
$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_persons.tpl');	

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

?>
