Location: PHPKode > scripts > Utils > Utils.php
<?php
/*
  Implemented by Sandro Alves Peres
  hide@address.com
*/

define("RESIZE_WIDTH", 0);
define("RESIZE_HEIGHT", 1);
define("FRETE_PAC", "41106");
define("FRETE_SEDEX", "40010");
define("FRETE_SEDEX_10", "40215");
define("FRETE_SEDEX_HOJE", "40290");
define("FRETE_E_SEDEX", "81019");
define("FRETE_MALOTE", "44105");

final class Utils{
  

  static function makeEmail( $__name, $__email ){
    if(substr(strtoupper(PHP_OS), 0, 3) == "WIN"){
      return trim($__email);
    }
    else{
      return trim($__name)." <".trim($__email).">";
    }	  
  }
  
  
  static function isTime( $__time ){
    if(! @preg_match("/^\d{2}:\d{2}:\d{2}$/", $__time)){
	  return false;	
	}
	
    $__arrTime = explode(":", $__time);
    $__return  = false;
    
	list($__hours, $__minutes, $__seconds) = $__arrTime;
    settype($__hours, "integer");
    settype($__minutes, "integer");
    settype($__seconds, "integer");	
		
    if($__hours >= 0 && $__hours <= 23){
       if($__minutes >= 0 && $__minutes <= 59){
          if($__seconds >= 0 && $__seconds <= 59){
            $__return = true; 
          }
          else{
            $__return = false;	  
          }
        }
        else{
          $__return = false; 
        }
    }
    else{
      $__return = false; 
    }

    return $__return;
  }  
  
  
  static function tosecs( $__time ){
	if(Utils::isTime($__time)){
	  $arrTime = explode(":", $__time);
	  settype($arrTime[0], "integer");
	  settype($arrTime[1], "integer");
	  settype($arrTime[2], "integer");
		
	  $seconds = ($arrTime[0] * pow(60, 2));
	  $seconds += (($arrTime[1] * 60) + $arrTime[2]);
		
	  return $seconds;
	}
	else{
	  return 0;	
	}
  }
  
  
  static function isLeapYear( $__year ){
    if(($__year % 4) == 0 && (($__year % 100) != 0 || ($__year % 400) == 0)):
	  return true;
	else:
	  return false;	
	endif;
  }
    
  
  static function todays( $__date ){ # format dd/MM/yyyy or yyyy-MM-dd
	if(@preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $__date) || @preg_match("/^\d{4}-\d{2}-\d{2}$/", $__date)){
	 
	  if(@preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $__date)):
	    $__date = explode("/", $__date);
		list($__day, $__month, $__year) = $__date; 	
	  else:
		$__date = explode("-", $__date);
		list($__year, $__month, $__day) = $__date; 	 
	  endif;
	  
	  settype($__day, "integer");
	  settype($__month, "integer");
	  settype($__year, "integer");	  
	  
	  if(! checkdate($__month, $__day, $__year)){
		 return 0;  
	  }
	  
	  $days   = 0;
	  $days29 = 0; 	  
	  
	  $daysMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	
	  for($i=1; $i < $__year; $i++){
        if(Utils::isLeapYear($i)){
	      $days29++;
        }	  	
	  }
    
	  if(Utils::isLeapYear($__year)){
	    if($__month > 2 || ($__month == 2 && $__day == 29)){
	  	  $daysMonth[1] = 29;
	    }
	  }
	
	  for($i=0; $i <= ($__month - 2); $i++){
	    $days += $daysMonth[$i];
	  }
	
	  $days += (($__year * 365) + $__day + $days29);
	  return $days;
	}
	else{
	  return 0;
	}
  }
  
  
  static function datediff( $__date1, $__date2 ){ # format dd/MM/yyyy or yyyy-MM-dd
	return (Utils::todays($__date1) - Utils::todays($__date2));
  }  
  
  
  static function timediff( $__time1, $__time2 ){
	return (Utils::tosecs($__time1) - Utils::tosecs($__time2));
  }

  
  static function totime( $__secs ){
	$__hours   = 0;
	$__minutes = 0;
	$__seconds = 0;

    $__minutes += floor(abs($__secs) / 60);
	$__seconds =  abs($__secs) % 60;
	
	$__hours   += floor($__minutes / 60);
	$__minutes %= 60;	
	 
	$__hours   = str_pad($__hours, 2, "0", STR_PAD_LEFT);
	$__hours   = ($__secs < 0 ? "-" : "").$__hours;
	$__minutes = str_pad($__minutes, 2, "0", STR_PAD_LEFT);
	$__seconds = str_pad($__seconds, 2, "0", STR_PAD_LEFT);	 
	 
	return $__hours.":".$__minutes.":".$__seconds; 
  }  
  
  
  static function div( $n1, $n2 ){ # operator div
	return ($n2 > $n1 ? 0 : ($n1 == $n2 ? 1 : floor($n1 / $n2)));
  }
  
  
  static function multiplyTime( $__time, $__multBy=1 ){ # time between 00:00:00 and 23:59:59
	if(! Utils::isTime($__time) || $__multBy <= 1):
	  return $__time;	
	endif;
	
	list($__hours, $__minutes, $__seconds) = explode(":", $__time);
    settype($__hours, "int");
	settype($__minutes, "int");
	settype($__seconds, "int");	
	
	$__hours   *= $__multBy;
	$__minutes *= $__multBy;
	$__seconds *= $__multBy;	
	
	$__minutes += floor($__seconds / 60);
	$__seconds %= 60;
	
	$__hours   += floor($__minutes / 60);
	$__minutes %= 60;
	
	$__hours   = str_pad($__hours, 2, "0", STR_PAD_LEFT);
	$__minutes = str_pad($__minutes, 2, "0", STR_PAD_LEFT);
	$__seconds = str_pad($__seconds, 2, "0", STR_PAD_LEFT);	
	
	return $__hours.":".$__minutes.":".$__seconds;
  }
  
  
  static function adddate( $__date, $__days=1 ){
	if(!@preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $__date) && !@preg_match("/^\d{4}-\d{2}-\d{2}$/", $__date)){
	  return $__date;	
	}
	
	if(@preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $__date)):
	  $__arrdate = explode("/", $__date);
	  list($__day, $__month, $__year) = $__arrdate; 	
	else:
	  $__arrdate = explode("-", $__date);
	  list($__year, $__month, $__day) = $__arrdate; 	 
	endif;
	
	settype($__day, "integer");
	settype($__month, "integer");
	settype($__year, "integer");	  
	  
	if(! checkdate($__month, $__day, $__year)){
	  throw new Exception("Incorrect date!!!");
	  return;  
	}	
  
    if($__days >= 0){
	  
	  $__addday =  $__day;
	  $__addday += $__days;
	  
      while($__addday > cal_days_in_month(CAL_GREGORIAN, $__month, $__year)){
	    $__addday -= cal_days_in_month(CAL_GREGORIAN, $__month, $__year);
	    $__month++; 
	    if($__month > 12):
	      $__month = 1;
	      $__year++;
	    endif;
      }
    }
    else{
      $__addday = $__day;		
	  
      for($i=0; $i < abs($__days); $i++):
	    if($__addday > 1){
	      $__addday--;
	    }
	    else{
			
	      if($__month > 1):
		    $__month--;
		  else:
		    $__month = 12;
		    $__year--;
		  endif;
		  
		  $__addday = cal_days_in_month(CAL_GREGORIAN, $__month, $__year);
	    }
      endfor;							
    }
  
    $__addday = str_pad($__addday, 2, "0", STR_PAD_LEFT);
    $__month  = str_pad($__month, 2, "0", STR_PAD_LEFT);
    $__year   = str_pad($__year, 4, "0", STR_PAD_LEFT);
  
	if(@preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $__date)):
       return $__addday."/".$__month."/".$__year;
	else:
       return $__year."-".$__month."-".$__addday; 
	endif;    
  }
  
  
  static function addtime( $__time, $__addtime="00:00:01" ){
	$__secsTime    = Utils::tosecs($__time);
	$__secsAddTime = Utils::tosecs($__addtime);
	return Utils::totime($__secsTime + $__secsAddTime);
  }
  
  
  static function getVarsUrl(){
	global $_GET;
	
	if($_GET){
	  $vars = "";
	  foreach($_GET as $k => $v){
	    $vars .= $k."=".urldecode($v)."&";
	  }
	  return preg_replace("/\&+$/i", "", $vars);
	}
	else return NULL;
  }
  
  
  static function formatDate( $date, $op=1 ){
	$newdate = ($op == 1 ? explode("/", $date) : explode("-", $date));
	$newdate = array_reverse($newdate);
	return ($op == 1 ? implode("-", $newdate) : join("/", $newdate));
  }
 
  
  static function getExt( $path ){ # it gets the extension of the file
	$extension = explode(".", $path);
	end($extension);
	$ext = strtolower(pos($extension));
	return $ext;
  }
  
  
  static function imageCode( $path, $dimension=200, $resizeby=RESIZE_WIDTH ){
    $extension = Utils::getExt($path);
	
	if($extension == "jpg" xor $extension == "jpeg" xor $extension == "jpe"){
      $im = imagecreatefromjpeg($path);  
	}
	elseif($extension == "gif"){
	  $im = imagecreatefromgif($path); 
	}
	elseif($extension == "png"){
	  $im = imagecreatefrompng($path);
	}
	
    $widthEx  = imagesx($im); # it gets the width of the sample
    $heightEx = imagesy($im); # it gets the height of the sample
	
	if($resizeby == 0):
	  $newWidth  = $dimension;
      $newHeight = abs(($heightEx * $newWidth) / $widthEx);
	else:
      $newHeight = $dimension;
      $newWidth  = abs(($widthEx * $newHeight) / $heightEx);
	endif;

    $newImg=imagecreatetruecolor($newWidth, $newHeight); # it creates an empty image
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $newWidth, $newHeight, $widthEx, $heightEx);
 
	if($extension == "jpg" xor $extension == "jpeg" xor $extension == "jpe"){
	  imagejpeg($newImg, $path, 100); 
	}
	elseif($extension == "gif"){
	  imagegif($newImg, $path); 
	}
	elseif($extension == "png"){
	  imagepng($newImg, $path);
	}

    imagedestroy($newImg);
    imagedestroy($im);
	
    $file = fopen($path, "rb");  
    $code = addslashes(fread($file, filesize($path)));
    fclose($file);
    return $code;
  }
  
  
  static function fileCode( $path ){
    $file = fopen($path, "rb");  
    $code = addslashes(fread($file, filesize($path)));
    fclose($file);
    return $code;	  
  }
  

  static function encrypt( $var, $key="br" ){	  
	$r = "";
    settype($var, "string");	
	$i = strlen($var)-1;
	$j = strlen($key);
	
	if(strlen($var) <= 0):
	  return "";
	endif;
	
	do{
	  $r .= ($var{$i} ^ $key{$i % $j});
	}
	while($i--);
	
	$r = base64_encode(base64_encode(strrev($r)));		
	
	return $r;
  }
  
  
  static function decrypt( $var, $key="br" ) {
	$r = "";
	settype($var, "string");
	$i = strlen($var)-1;
	$j = strlen($key);
	
	if(strlen($var) <= 0):
	  return "";
	endif;	
	
	$var = base64_decode(base64_decode($var));
		
	do{
	  $r .= ($var{$i} ^ $key{$i % $j});
	}
	while($i--);
	
	$r = strrev($r);
		  
	return $r;
  }
  
  
  static function getInterval( $int1, $int2, $v1, $v2, $v3, $v4 ){ # get the time within the interval
    $__return = 0;  
	$v1   = Utils::tosecs($v1);
	$v2   = Utils::tosecs($v2);
	$v3   = Utils::tosecs($v3);
	$v4   = Utils::tosecs($v4);    
	$int1 = Utils::tosecs($int1);
	$int2 = Utils::tosecs($int2);
	
	if($int1 <= $v1){
	  
	  if($int2 <= $v2){
		 $__return = ($int2 - $v1);
	  }
	  elseif($int2 <= $v3){
		 $__return = ($v2 - $v1);	
	  }
	  elseif($int2 <= $v4){
		 $__return = ($v2 - $v1) + ($int2 - $v3);
	  }
	  elseif($int2 > $v4){
		 $__return = ($v2 - $v1) + ($v4 - $v3);	
	  }
	  else $__return = 0;
	  
	}
	elseif($int1 <= $v2){
	  
	  if($int2 <= $v2){
		$__return = ($int2 - $int1);
	  }
	  elseif($int2 <= $v3){
		$__return = ($v2 - $int1);	
	  }
	  elseif($int2 <= $v4){
		$__return = ($v2 - $int1) + ($int2 - $v3);	
	  }
	  elseif($int2 > $v4){
		$__return = ($v2 - $int1) + ($v4 - $v3);		
	  }
	  else $__return = 0;
		   
	}
	elseif($int1 <= $v3){
	  
	  if($int2 <= $v3){
		$__return = 0;	
	  }
	  elseif($int2 <= $v4){
		$__return = ($int2 - $v3);	
	  }
	  elseif($int2 > $v4){
		$__return = ($v4 - $v3);		
	  }
	  else $__return = 0;
		
	}
	elseif($int1 <= $v4){
	  
	  if($int1 > $v3){
		if($int2 <= $v4){
		   $__return = ($int2 - $int1);
		}
		else{
		  $__return = ($v4 - $int1);  
		}
	  }
	  elseif($int2 > $v4){
		if($int1 > $v3){
		  $__return = ($v4 - $int1);  
		}
		else{
		  $__return = ($v4 - $v3);
		}
	  }
	  else $__return = 0;
		
	}
	elseif($int1 > $v4){
	  $__return = 0;  
	}
	
	return Utils::totime($__return);
  }
  
  
  static function chmodR( $path, $filePerm=0777, $dirPerm=0777 ){
	if(! file_exists($path)):
      return false;
    endif;

    if(is_file($path)){
      chmod($path, $filePerm);
    }
	elseif(is_dir($path)){
      $foldersAndFiles = scandir($path);
      $entries = array_slice($foldersAndFiles, 2); # remove "." and ".." from the list
	  
      foreach($entries as $entry){
	    Utils::chmodR($path."/".$entry, $filePerm, $dirPerm);
	  }
	  
	  chmod($path, $dirPerm);
	}
    
	return true;
  } 
   
  
  static function dirSize( $path ){ 
    $totalSize = 0; 
    $files = scandir($path); 
 
    foreach($files as $dir): 
      if(is_dir(rtrim($path, '/').'/'.$dir)):
        if($dir != "." && $dir != ".."):
          $size = Utils::dirSize(rtrim($path, '/').'/'.$dir); 
          $totalSize += $size; 
        endif;
	  else:
        $size = filesize(rtrim($path, '/').'/'.$dir); 
        $totalSize += $size; 
      endif;    
    endforeach;
	
    return $totalSize; 
  } 
  
 
  static function formatCapacity( $size ) { 
    $mod = 1024; 
 
    $units = explode(" ", "B KB MB GB TB PB"); 
    for($i=0; $size > $mod; $i++){ 
      $size /= $mod; 
    } 
 
    return round($size, 2)." ".$units[$i]; 
  } 
  
  
  static function isIN( $value ){ # value, [arg1, arg2, arg3 ...]
	$args = func_get_args();
	array_shift($args);
	
	if(in_array($value, $args)):
	  return true;
	else:
	  return false;
	endif;
  }  
  
  
  static function getAbbrName( $name ){ # used for common names in Brazil
	$name = explode(" ", strtolower(preg_replace("/\s+/i", " ", trim($name))));
	 
	if(count($name) > 1):
	   if(count($name) == 2):
		  return ucfirst($name[0])." ".ucfirst($name[1]); 
	   else:
		 if(preg_match("/^de|da|do|dos|das|e$/i", $name[1])):
			return ucfirst($name[0])." ".strtolower($name[1])." ".ucfirst($name[2]);  
		 else:
			return ucfirst($name[0])." ".ucfirst($name[1]); 
		 endif;		  
	   endif;		
	else:
	   return ucfirst($name[0]);
	endif;	   	  
  }
    
  
  static function getFrete( $servico, $cepOrigem, $cepDestino, $peso ) { # used in Brazil
	$url  = "http://www.correios.com.br/encomendas/precos/calculo.cfm?resposta=&servico=".FRETE_SEDEX;
	$url .= "&cepOrigem=".$cepOrigem."&cepDestino=".$cepDestino."&peso=".$peso."&MaoPropria=N&valorDeclarado=&avisoRecebimento=N";
	$html = file_get_contents($url);
  
	preg_match_all("/[\?\&]([\w]+)=([a-zA-Z0-9\.]+)/i", $html, $parts);
	
	for($i=0; $i < sizeof($parts[1]); $i++):
	  $answer[$parts[1][$i]] = $parts[2][$i];
	endfor;
  
	return $answer;
  }     
      

} # end class
?>
Return current item: Utils