<?php
/**
 * FILE_NAME_HERE - FILE_DESCRIPTION_HERE
 *
 * @author $Author: wichai $
 * @version $Id: Osa_uploader.php,v 1.12 2011/05/18 10:27:48 wichai Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Osa_uploader {
	private $CI = NULL;
	private $upload = NULL;
	private $unitid=NULL;
	private $type=NULL;
	private $courseid=NULL;
	//private $width = '450px';
	//private $height = '160px';

	function __construct($params) {
		if ( !array_key_exists('unitid', $params) || !array_key_exists('type', $params) || !array_key_exists('courseid', $params))
			return;
		$this->unitid = $params["unitid"];
		$this->type = $params["type"];
		$this->courseid = $params["courseid"];
		$this->CI =& get_instance();
		osa_load_lang('unit');
	}

	function upload($dir) {
		// HTTP headers for no cache etc
		header('Content-type: text/plain; charset=UTF-8');
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-store, no-cache, must-revalidate");
      header("Cache-Control: post-check=0, pre-check=0", false);
      header("Pragma: no-cache");

      // Settings
      $targetDir = $dir;

      // Get parameters
      $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
      $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
      $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

      // Create target dir
      if (!file_exists($targetDir)) {
          @mkdir($targetDir);
      }
      // Remove old temp files
      if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
          while (($file = readdir($dir)) !== false) {
              $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
              // Remove temp files if they are older than the max age
              if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge)){
                  @unlink($filePath);
              }
          }
		closedir($dir);
      }
      else {
          die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to open temp directory', $fileName) );
      }
      // Look for the content type header
      if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
          $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
      }
      if (isset($_SERVER["CONTENT_TYPE"])) {
          $contentType = $_SERVER["CONTENT_TYPE"];
      }
      // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
      if (strpos($contentType, "multipart") !== false) {
          if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
              // Open temp file
              $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
              if ($out) {
                  // Read binary input stream and append it to temp file
                  $in = fopen($_FILES['file']['tmp_name'], "rb");
                  if ($in) {
                      while ($buff = fread($in, 4096))
                          fwrite($out, $buff);
                  }
                  else {
                      die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to open input stream', $fileName) );
                  }
                  fclose($out);
                  // (issue: 192) Refer to php POST method uploads http://www.php.net/manual/en/features.file-upload.post-method.php
                  // The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
                  // No need to unlink(delete) file
                  //unlink($_FILES['file']['tmp_name']);
              }
              else {
                  die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to open output stream', $fileName) );
              }
          }
          else {
              die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to move uploaded file', $fileName) );
          }
      }
      else {
          // Open temp file
          $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
          if ($out) {
              // Read binary input stream and append it to temp file
              $in = fopen("php://input", "rb");
              if ($in) {
                  while ($buff = fread($in, 4096))
                      fwrite($out, $buff);
              }
              else {
                  die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to open input stream', $fileName) );
              }
              fclose($out);
          }
          else {
              die( osa_errorlog(__METHOD__ . ' - ' . 'Failed to open output stream', $fileName) );
          }
      }
      //die();
      return 'success';
	}
}

?>