<?php
  $wizard_template_page = 3;

  $cpanel_user_id_confirm_json = (isset($_SERVER['HTTP_X_CPANELID']) ? $_SERVER['HTTP_X_CPANELID'] : false);

  include ("wizard_initialize.php");

  $fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
  $pn = (isset($_SERVER['HTTP_X_FOLDERNAME']) ? $_SERVER['HTTP_X_FOLDERNAME'] : 'temp_uploads/');
  $pn = HOME_PATH . $pn;

  if ($fn) {

  	// AJAX call
    $url = if_exists_backup($pn . $fn);
  	file_put_contents($url, file_get_contents('php://input'));
    $path_parts = pathinfo($url);
    $fn = $path_parts['filename'].'.'.$path_parts['extension'];
  	echo "$fn";
  	exit();

  }
  else {

  	// form submit
  	$files = $_FILES['fileselect'];
  	foreach ($files['error'] as $id => $err) {
  		if ($err == UPLOAD_ERR_OK) {
  			$fn = $files['name'][$id];
            $url = if_exists_backup($pn . $fn);
   			move_uploaded_file($files['tmp_name'][$id],	$url);
  			header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit();
  		}
  	}

  }

  function if_exists_backup($url) {
//    echo $url;
    if (file_exists($url)) {
      $path_parts = pathinfo($url);
      $url = $path_parts['dirname'].'/'.$path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
    }
    return $url;
  }
?>