<?php
/**
*	玩家上传头像
*/
$retData = array('code' => -1);
$allowSize = 200 * 1024;
$allowFileType = array('jpg', 'png', 'jpeg');
$signKey = "%^(sa)-#$9988@&";


//请求参数
$uid = max( 0, (int)$_REQUEST['uid']);
$sid = max( 0, (int)$_REQUEST['sid']);

if( !$uid ){
	die(json_encode($retData));
}

require_once( '../config/config.sids.php' );
if ( !array_key_exists($sid, $config['sidlist']) ) {
	$retData['code'] = -2;
	die(json_encode($retData));
}

$time	=	$_REQUEST['time'];
$sign   =	$_REQUEST['sign'];
$md5 	=	md5( $uid . '|' . $sid . '|' . $time . $signKey);

if ( $sign != $md5 ) {
	$retData['code'] = -3;
	$retData['uid'] = $uid;
	$retData['sid'] = $sid;
	$retData['time'] = $time;
	$retData['md5'] = $md5;
	die(json_encode($retData));
}

//判断图片类型
$fileType = strtolower( trim( substr( strrchr( $_FILES['upload']['name'], '.'), 1)));
if( ! in_array( $fileType, $allowFileType)){
	$retData['code'] = -4;
	die(json_encode($retData));
}

//判断图片大小
$size = max( 0, (int)$_FILES['upload']['size']);
if( $size > $allowSize){
	$retData['code'] = -5;
	die(json_encode($retData));
}

//按用戶uid分子目錄
$subname = $uid % 100;
$demo = $_REQUEST['demo'] ?? 0;
$userIconDir = $demo ? '/data/wwwroot/texas/usericon/' : '/data/texas/usericon/';
if( !is_dir($userIconDir) ){
    mkdir( $userIconDir, 0777);
}
$dirName = $userIconDir.$subname.'/';
if(!is_dir( $dirName))
{
	mkdir( $dirName, 0777);
}

$time = time();
$newName = $dirName . $uid . '-' . $time . '.png';
$tmp_name = $_FILES["upload"]["tmp_name"];

if ( file_exists( $newName)) {
	unlink( $newName);
}

if(( function_exists( 'move_uploaded_file') && move_uploaded_file( $tmp_name, $newName)))
{
	$retData['code'] = 1;
	$retData['iconname'] = $uid.'-'.$time . '.png';
	die(json_encode($retData));
}

$retData['code'] = -6;
die(json_encode($retData));