<?php
  class myUtility {
    static $log_dir = null;

    /**
     * Return extension of a file name
     *
     */
    public static function getFileExt($fileName) {
      $names = explode('.', $fileName);
      $i = count($names);
      if ($i>0) return  strtolower($names[$i-1]); else return '';
    }

    /**
     * return file name (no extension)
     *
     *
     * @param String $fileName
     */
    public static function getFileName($fileName) {
      $names = explode('.', $fileName);
      $i = count($names);
      if (count($names)>0) array_pop($names);
      return join('.', $names);
    }

    /**
     * return safe file name (lower byte character)
     *
     * @param unknown_type $fileName
     */
    public static function getSafeFileName($fileName) {
      $names = explode('.', $fileName);
      $ext = array_pop($names);
      $safe = preg_replace('@[^A-Za-z0-9_]+@', '', join($names));
      if ($safe=='') $safe = '0';
      return $safe.'.'.$ext;
    }

    /**
     * Convert from UTF-8 to non mark Vietnamese text
     *
     * @param String $value: input text
     * @return Non marke Vietnamese text
     */
    public static function vietDecode($value)
    {
      $vietChar 	= 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
      $viet1258 = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
			$engChar	= 'a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|e|e|e|e|e|e|e|e|e|e|e|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|u|u|u|u|u|u|u|u|u|u|u|i|i|i|i|i|y|y|y|y|y|d|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|E|E|E|E|E|E|E|E|E|E|E|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|U|U|U|U|U|U|U|U|U|U|U|I|I|I|I|I|Y|Y|Y|Y|Y|D';
			$arrVietChar 	= explode('|', $vietChar);
			$arrViet1258 	= explode('|', $viet1258);
			$arrEngChar		= explode('|', $engChar);
			$value = str_replace($arrVietChar, $arrEngChar, $value);
			return str_replace($arrViet1258, $arrEngChar, $value);
    }

    public static function getUrlName($name) {
      $name = strtolower(myUtility::vietDecode($name));
      $name = preg_replace('@[^\w\d_]+@', '', $name);
      return $name;
    }

    /**
     * Check hard disk for not exist fileName, if file exists, change it name
     *
     * @param unknown_type $pathName
     * @param unknown_type $fileName
     * @param unknown_type $extName
     */
    public static function GetNoDuplicateFileName($pathName, &$fileName, $extName) {
      $i = 0;
      $newFileName = $fileName;
      while (file_exists("$pathName/$newFileName.$extName")) {
        $newFileName = $fileName . (++$i);
      }
      $fileName = $newFileName;
    }

    public static function moveDirectory($src, $dst) {
      if (!is_dir($dst)) {umask(0); mkdir($dst, 0777, true);}
      foreach (scandir($src) as $file) {
        if ($file=='.' || $file=='..') continue;
        $srcm = $src.'/'.$file;
        $dstm = $dst.'/'.$file;
        if (is_dir($srcm)) myUtility::moveDirectory($srcm, $dstm);
        else {
          rename($srcm, $dstm);
          chmod($dstm, 0777);
        }
      }
      rmdir($src);
    }

    public static function cleanDirectory($path) {
      foreach (scandir($path) as $dir) {
        if ($dir=='.' || $dir=='..') continue;
        $dname = $path.'/'.$dir; 
        if (is_dir($dname)) self::cleanDirectory($dname);
        else if (is_file($dname)) unlink($dname);
      }
      rmdir($path);
    }

    public static function global_image_tag($fileName, $width, $height, $vars = null) {
      $ext = myUtility::getFileExt($fileName);
      switch ($ext) {
        case 'swf':
          return flash_tag($fileName, $width, $height, $vars, true);
        default:
          return image_tag($fileName, array('width'=>$width, 'height'=>$height));
      }
    }

    /**
     * execute native sql
     *
     * @param unknown_type $sql
     * @return array of rows, each row is an array of fields (no key)
     */
    public static function execSql($sql, $noResult = false) {
      $criteria = new Criteria();
      $dbMap = Propel::getDatabaseMap($criteria->getDbName());
      $db = Propel::getDB($criteria->getDbName());

      $con = Propel::getConnection($criteria->getDbName(), Propel::CONNECTION_READ);

      $stmt = $con->prepare($sql);
      $stmt->execute();
      if ($noResult==true) return;
      $rows = array();
      try {
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
          $rows[] = $row;
        }
      } catch (Exception $e) {}
      $stmt->closeCursor();
      return $rows;
    }

    public static function log($message, $fileName = 'blog.log', $prefix = '') {
      if (null == self::$log_dir) self::$log_dir = sfConfig::get('sf_log_dir');
      error_log($prefix.date('Y-m-d H:i:s ').substr(session_id(), 0, 5).' '.$message."\n", 3, self::$log_dir.'/'.$fileName);
    }

    public static function track_upload($message, $logFile) {
      error_log(date('H:i:s ').$message."\n", 3, sfConfig::get('sf_web_dir').'/uploads/previews/upinfo/'.$logFile.'_'.date('Ymd').'.log');
    }

    /**
     * Truncates +text+ to the length of +length+ and replaces the last three characters with the +truncate_string+
     * if the +text+ is longer than +length+.
     */
    public static function mb_truncate_text($text, $length = 33, $truncate_string = '...', $truncate_lastspace = false)
    {
      if ($text == '') {
        return '';
      }

      if (mb_strlen($text, 'utf8') > $length) {
        $truncate_text = mb_substr($text, 0, $length - strlen($truncate_string), 'utf8');
        if ($truncate_lastspace) {
          $truncate_text = preg_replace('/\s+?(\S+)?$/', '', $truncate_text);
        }

        return $truncate_text.$truncate_string;
      }
      else {
        return $text;
      }
    }

    public static function htmlToText($str) {
      $text = new html2text($str);
      return $text->get_text();
    }

    /**
     * Return first day of week that include $date
     *
     * @param string $date (not include time)
     * @return string first day of week
     */
    public static function dateToWeek($date) {
      $time = strtotime($date);
      $dayOfWeek = date('w', $time);
      return date('Y-m-d', strtotime("$date -$dayOfWeek day"));
    }

    /**
     * Create random password
     *
     * @param int $lenght: length of random password
     * @return password
     */
    public function create_password($length = 6)
    {
      $chars = '0123456789';
      srand(time());
      $pass = '';
      for ($i = 0; $i < $length; $i++) {
        $num = rand(0, strlen($chars)-1);
        $pass .= $chars[$num];
      }
      return $pass;
    }

    public function getRealIpAddr() {
      if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
      } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
      } else {
        $ip = $_SERVER['REMOTE_ADDR'];
      }
      return $ip;
    }

    public function validate($filterclass, &$data, &$error) {
      $filter = new $filterclass();
      $filter->initialize(null);
      return $filter->execute($data, $error);
    }

    public function formatCurrency($c) {
      $r = '';
      if ($c == 0) $r = '0';
      while ($c > 0) {
        $s = $c % 1000;
        $c = (int)($c / 1000);
        while ($c > 0 && strlen($s) < 3) $s = '0' . $s;
        $r = $s . $r;
        if ($c > 0) $r = '.' . $r;
      }
      return $r . ' đồng';
    }

    /**
     * format_filesize choses the best human readable unit for $bytes returns a formatted string
     *  Updates, documentation and examples: http://daniel.lorch.cc/projects/format_filesize/
     *
     */
    function formatFilesize($bytes, $decimals = 1)
    {
      $units = array(
        '1152921504606846976' => 'EB', /* Exa Byte  10^18 */
        '1125899906842624'    => 'PB', /* Peta Byte 10^15 */
        '1099511627776'       => 'TB',
        '1073741824'          => 'GB',
        '1048576'             => 'MB',
        '1024'                => 'KB'
      );
      if ($bytes <= 1024) return $bytes . ' Bytes';
      foreach ($units as $base => $title)
        if (floor($bytes / $base) != 0)
          return number_format($bytes / $base, $decimals, ".", "'") . ' ' . $title;
    }

    public function splitData($pattern, $content) {
      $data = array();
      $arr = preg_split($pattern, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
      array_shift($arr);
      while (count($arr) > 0) $data[] = array_shift($arr).array_shift($arr);
      return $data;
    }

    public static function vietUpcase($value, $onlyFirstChar = false)
    {
      $vietLow = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ';
      $vietHi  = 'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
      $arrVietLow = explode('|', $vietLow);
      $arrVietHi  = explode('|', $vietHi);
      if ($onlyFirstChar) {
        if (preg_match("/^($vietLow)(.*)$/", $value, $m)) $value = $arrVietHi[array_search($m[1], $arrVietLow)] . $m[2];
        return ucfirst($value);
      }
      else return strtoupper(str_replace($arrVietLow, $arrVietHi, $value));
    }

  }
?>
