<?php

class CDownload {

  /*
  // local
  private static $mysql_dsn = 'mysql:dbname=sessions;host=127.0.0.1';
  private static $mysql_user = 'sessionuser';
  private static $mysql_password = 'sessionpassword';
  */

  // product
  private static $mysql_dsn = 'mysql:dbname=sessions;host=210.245.80.72';
  private static $mysql_user = 'sessionuser';
  private static $mysql_password = 'sessionpassword';

  private static $pdo;

  public static function connect_session_db() {
    if (self::$pdo == null) {
      try {
        self::$pdo = new PDO(self::$mysql_dsn, self::$mysql_user, self::$mysql_password, array(PDO::ATTR_PERSISTENT=>true));
        return self::$pdo;
      } catch (Exception $e) {
        die;
      }
    } else {
      return self::$pdo;
    }
  }

  public static function dissconnect_session_db() {
  }

  public static function downloadFile($file_path, $downloadName) {
    $downloadName = str_replace('.', '', $downloadName);
    $allowed_ext = array (
      // archives
      'zip' => 'application/zip',
      'rar' => 'application/rar',
      '7z' => 'application/7z',

      // documents
      'pdf' => 'application/pdf',
      'rtf' => 'application/rtf',
      'doc' => 'application/msword',
      'xls' => 'application/vnd.ms-excel',
      'ppt' => 'application/vnd.ms-powerpoint',
      'pps' => 'application/vnd.ms-powerpoint',
      'docx'=> 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'xlsx'=> 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'pptx'=> 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'ppsx'=> 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',

      // images
      'gif' => 'image/gif',
      'png' => 'image/png',
      'jpg' => 'image/jpeg',
      'jpeg'=> 'image/jpeg',
      'bmp' => 'image/bmp',

      // audio
      'mp3' => 'audio/mpeg',
      'wav' => 'audio/x-wav',

      // video
      'flv' => 'video/x-flv',
      'swf' => 'application/x-shockwave-flash',
      
      // other
      'cg3' => 'application/cg3',
      'gsp' => 'application/gsp',
    );
    set_time_limit(0);

    // file size in bytes
    $fsize = filesize($file_path);

    // file extension
    $fext = strtolower(substr(strrchr($file_path,'.'),1));

    // check if allowed extension
    if (!array_key_exists($fext, $allowed_ext)) {
      die("Not allowed file type.");
    }

    //error_log(date("Y-m-d H:i:s ")."Download ".substr($file_path, 37).", size $fsize\n", 3, "/data/downloads.log");
    // get mime type
    if ($allowed_ext[$fext] == '') {
      $mtype = '';
      // mime type is not set, get from server settings
      if (function_exists('mime_content_type')) {
        $mtype = mime_content_type($file_path);
      }
      else if (function_exists('finfo_file')) {
        $finfo = finfo_open(FILEINFO_MIME); // return mime type
        $mtype = finfo_file($finfo, $file_path);
        finfo_close($finfo);
      }
      if ($mtype == '') {
        $mtype = "application/force-download";
      }
    }
    else {
      // get mime type defined by admin
      $mtype = $allowed_ext[$fext];
    }

    ini_set('zlib.output_compression', 'Off');

    // set headers
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Type: $mtype");
    header("Content-Disposition: attachment; filename=\"$downloadName.$fext\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $fsize);

    // download
    // @readfile($file_path);
    $file = @fopen($file_path,"rb");
    if ($file) {
    	session_write_close();
      while(!feof($file)) {
        print(fread($file, 2*1024*1024));
        flush();
        if (connection_status()!=0) {
          @fclose($file);
          return  false;
        }
      }
      @fclose($file);
    }

    return true;
  }

  public static function run() {
    $file_name = @$_REQUEST['file'];
    $file_path = @$_REQUEST['path'];
    $file_id = @$_REQUEST['id'];
    $user_id = @$_REQUEST['user'];
    if ($file_name==null || $user_id==null || $file_id==null) {
      echo 'Tai lieu khong ton tai';
      exit();
    }

    /*
    $code = 'dl'.abs(crc32($file_id.'@'.$file_path));

    if (!($pdo = self::connect_session_db())) exit();

    $stmt = $pdo->query("select count(*) from sessions where ss_userid='$user_id' and ss_data like '%;$code|%'");
    $is_match = false;
    if ($stmt) {
      if ($stmt->fetch(PDO::FETCH_COLUMN)==='1') {
        $is_match = true;
      }
    }

    if (!$is_match) exit();*/

    $root_dir = dirname(__FILE__);
    self::downloadFile($root_dir . '/' . $file_path, $file_name);
  }
}

CDownload::run();
