<?php

include_once("common/constants.inc");
include_once("common/segf.php");

/**
 * Handle file uploads via XMLHttpRequest
 */
class qqUploadedFileXhr {
  /**
   * Save the file to the specified path
   * @return boolean TRUE on success
   */
  function save($path) {
    $input = fopen("php://input", "r");
    $temp = tmpfile();
    $realSize = stream_copy_to_stream($input, $temp);
    fclose($input);
    
    if ($realSize != $this->getSize()) {            
      return false;
    }
    
    $target = fopen($path, "w");
    fseek($temp, 0, SEEK_SET);
    stream_copy_to_stream($temp, $target);
    fclose($target);
    
    return true;
  }

  function getName() {
    return $_GET['qqfile'];
  }

  function getSize() {
    if (isset($_SERVER["CONTENT_LENGTH"])){
      return (int)$_SERVER["CONTENT_LENGTH"];            
    } else {
      throw new Exception('A tartalom mérete nem támogatott.');
    }      
  }
}

/**
 * Handle file uploads via regular form post (uses the $_FILES array)
 */
class qqUploadedFileForm {  
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
  function save($path) {
    if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
      return false;
    }
    return true;
  }

  function getName() {
    return $_FILES['qqfile']['name'];
  }

  function getSize() {
    return $_FILES['qqfile']['size'];
  }
}

class qqFileUploader {
  private $allowedExtensions = array();
  private $sizeLimit = 104857600; // 100Mb
  private $file;

  function __construct(array $allowedExtensions = array(), $sizeLimit = 2097152) {
    $allowedExtensions = array_map("strtolower", $allowedExtensions);
        
    $this->allowedExtensions = $allowedExtensions;
    $this->sizeLimit = $sizeLimit;
    
    $this->checkServerSettings();

    if (isset($_GET['qqfile'])) {
      $this->file = new qqUploadedFileXhr();
    } elseif (isset($_FILES['qqfile'])) {
      $this->file = new qqUploadedFileForm();
    } else {
      $this->file = false; 
    }
  }
  
  private function checkServerSettings() {
    $postSize = $this->toBytes(ini_get('post_max_size'));
    $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));

    if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
      $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
      die("{'error':'növeld meg a post_max_size és upload_max_filesize értékét $size-re'}");
    }
  }
  
  private function toBytes($str) {
    $val = trim($str);
    $last = strtolower($str[strlen($str)-1]);
    switch($last) {
      case 'g': $val *= 1024;
      case 'm': $val *= 1024;
      case 'k': $val *= 1024;
    }
    return $val;
  }
  
  /**
   * Returns array('success'=>true) or array('error'=>'error message')
   */
  function handleUpload($uploadDirectory, $replaceOldFile = FALSE) {
    if (!is_writable($uploadDirectory)) {
      return array('error' => "Szerver hiba. Upload könyvtár írásvédett.");
    }
    
    if (!$this->file) {
      return array('error' => 'Nincsenek feltöltött állományok.');
    }

    $size = $this->file->getSize();
    
    if ($size == 0) {
      return array('error' => 'A fájl üres');
    }

    if ($size > $this->sizeLimit) {
      return array('error' => 'A fájl túl nagy');
    }

    $pathinfo = pathinfo($this->file->getName());
    $origFilename = $pathinfo['filename'] . '.' . $pathinfo['extension'];
    $filename = str_replace(" ", "", $pathinfo['filename']);
    $filename = $this->removeAccent($filename);

    $ext = $pathinfo['extension'];

    if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
      $these = implode(', ', $this->allowedExtensions);
      return array('error' => 'A fájl típusa hibás, feltölthetõ típusok: '. $these . '.', 'basefile' => $filename . "." . $ext);
    }

    if (isset($_SESSION["user"]))
      $filename = "id" . $_SESSION["user"]["user_id"] . "_" . $filename;

    if (!$replaceOldFile) {
      /// don't overwrite previous files that were uploaded
      while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
        $filename .= uniqid("-");
      }
    }
    
    if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
      
      if ($ext == "xls" || $ext == "xlsx") { // xls, xlsx
      
        return array('success' => true, 'file' => $uploadDirectory . $filename . "." . $ext);
        
      } else {

        $fileSize = filesize($uploadDirectory . $filename . '.' . $ext);
  
        // get image width, height
        $image = new Imagick($uploadDirectory . $filename . '.' . $ext);
        $geo = $image->getImageGeometry();
        $resolution = $image->getImageResolution();
        $sizex = $geo['width'];
        $sizey = $geo['height'];
        $image->clear();
        $image->destroy();

        if ($sizex >= 10000 || $sizey >= 10000)
          return array('error'=> 'A feltöltött kép mérete túl nagy! Maximális képméret: 9999x9999px', 'basefile' => $filename . "." . $ext);
  
        // create tmp image for preview
        generateSmallImageFromFile2(UPLOAD_DIRECTORY . $filename . "." . $ext, $filename . "." . $ext);

        $fileType = "jpg";
        $src = base64_encode_image(TMP_DIRECTORY . $filename . "." . $ext, $fileType);

        return array('success' => true, 'file' => $uploadDirectory . $filename . "." . $ext, 'origfile' => $origFilename, 'tempfile' => TMP_DIRECTORY . $filename . "." . $ext, 'width' => $sizex, 'height' => $sizey, 'resolutionX' => $resolution['x'], 'resolutionY' => $resolution['y'], 'basefile' => $filename . "." . $ext, 'src' => $src);
      }
    } else {
      return array('error'=> 'A fájlt nem lehetett menteni! A feltöltés megszakadt!', 'basefile' => $filename . "." . $ext);
    }
  }
  
  function removeAccent($str) {
    return strtr($str, array("Á" => "A", "É" => "E", "Ú" => "U", "Ő" => "O", "Ű" => "U", "Ó" => "O", "Ü" => "U", "Ö" => "O", "Í" => "I", "á" => "a", "é" => "e", "ú" => "u", "ő" => "o", "ű" => "u", "ó" => "o", "ü" => "u", "ö" => "o", "í" => "i", "'" => ""));
  }
}

$a = session_id();
if ($a == '')
  session_start();

// list of valid extensions, ex. array("jpeg", "xml", "bmp")
if (!isset($_GET['extension']))
  $allowedExtensions = array("jpg","jpeg");
else {
  if (strpos($_GET['extension'], '_') !== false)
    $allowedExtensions = explode("_", $_GET['extension']);
  else
   $allowedExtensions = array($_GET['extension']);
}

// max file size in bytes (20Mb)
$sizeLimit = 20 * 1024 * 1024;

$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload(UPLOAD_DIRECTORY);
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

?>
