<?php

function send_error_die($msg){
	die(json_encode(array('R'=>'ERR','MSG'=>$msg)));
}


$upload_dir = wp_upload_dir();
$base_dir = $upload_dir['basedir'].'/profil_avatar';
$front_dir = $upload_dir['baseurl'].'/profil_avatar';

if (!file_exists($base_dir)) {
    mkdir($base_dir, 0777);
}

$base_dir .= '/';
$front_dir .= '/';
$new_filename = '';
$ip_address = rhcp_get_client_ip();

if(isset($_FILES["myfile"]))
{
	$ret = array();

	$error =$_FILES["myfile"]["error"];
	if(!is_array($_FILES["myfile"]["name"]))
	{
 	 	$fileName = $_FILES["myfile"]["name"];
 	 	$ext = '.'.pathinfo($fileName, PATHINFO_EXTENSION);
 	 	$new_filename = 'tmp_g_'.$ip_address.$ext;
 	 	
		if (file_exists($base_dir.$new_filename)) {
		   unlink($base_dir.$new_filename);
		}
		
 		move_uploaded_file($_FILES["myfile"]["tmp_name"],$base_dir.$new_filename);
    	$ret[]= $fileName;
	}
	
    die($front_dir.$new_filename.'|'.$base_dir.$new_filename);
} else {
	send_error_die(__('No files found','act'));
}


function rhcp_get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP')){
        $ipaddress = getenv('HTTP_CLIENT_IP');
    } else if(getenv('HTTP_X_FORWARDED_FOR')){
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    } else if(getenv('HTTP_X_FORWARDED')){
        $ipaddress = getenv('HTTP_X_FORWARDED');
    } else if(getenv('HTTP_FORWARDED_FOR')){
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    } else if(getenv('HTTP_FORWARDED')){
       $ipaddress = getenv('HTTP_FORWARDED');
    } else if(getenv('REMOTE_ADDR')){
        $ipaddress = getenv('REMOTE_ADDR');
    } else {
        $ipaddress = 'UNKNOWN';
    }   
    $ipaddress = str_replace('.', '_', $ipaddress);
        
        
    return $ipaddress;
}

?>