Location: PHPKode > scripts > Util > util.class.php
<?php
interface Util_interface{
	public function dateDiff($sStartDate, $sFinalDate);
	public function calculateAge($dtBorn);
	public function days_actual_month();
	public function formatDateTime($dataBD,$act=1);
	public function currentDay($lng = "pt");
	public function dayWeek($day,$month,$year,$lng = "pt");
	public function alert($msg);
	public function alertBack($msg);
	public function goBack();
	public function closeWindow();
	public function redirect($page);
	public function update();
	public function no_injection_login($str);
	public function validateCpf($cpf);
	public function validateEmail($address);
	public function rewriteString($str);
	public function removeTags($str);
	public function leaveTags();
	public function debugArray($array);
	public function limitPoint($str,$limit=3);
	public function array_diff_values($array);
	public function execPage($url,$packet);
}

// This class is a set of useful functions
// It streamlines a lot of the Programming process
class Util implements Util_interface {
	/**
	 * @author Raul Souza Silva
	 * @copyright Freeware
	 * @copyright Free to distribute and use
	 */
	
	// Functions related to date

	/**
	 * Calculate difference in dates
	 *
	 * @param String(date) $sStartDate
	 * @param String(date) $sFinalDate
	 * @return Integer
	 */
	public function dateDiff($sStartDate, $sFinalDate){
		$sDateI = explode("-", $sStartDate);
		$sDateF = explode("-", $sFinalDate);

		$nStartDate = mktime(0, 0, 0, $sDateI[1], $sDateI[0], $sDateI[2]);
		$nFinalDate = mktime(0, 0, 0, $sDateF[1], $sDateF[0], $sDateF[2]);

		return ($nStartDate > $nFinalDate) ?
		floor(($nStartDate - $nFinalDate)/86400) : floor(($nFinalDate - $nStartDate)/86400);
	}

	/**
	 * Calculate age
	 * The entry is the date of birth
	 * Format: dd-mm-aaaa
	 * 
	 * @param String(date) $dtBorn
	 * @return Integer
	 */
	public function calculateAge($dtBorn){
		$date1 		= str_replace("/" ,"-",$dtBorn);
		$date2 		= date("d-m-Y"); // Today

		$result  	= $this->datediff("$date1", "$date2");
		$years		= $result/365;
		$age		= explode("." , $years);
		return  $age[0];
	}

	/**
	 * Days that have in month
	 *
	 * @return Integer
	 */
	public function days_actual_month(){
		$actual_month = date("m", time());
		$actual_year  = date("Y", time());
		return cal_days_in_month(CAL_GREGORIAN, $actual_month, $actual_year);
	}

	/**
	 * Formats data coming from the database in the format YYYY-mm-dd hh:mm:ss
	 *
	 * @param String(date) $dataBD
	 * @param Integer $act
	 * @return unknown
	 */
	public function formatDateTime($dataBD,$act=1){
		list($date,$time)  	  		   = explode(" ",$dataBD);
		list($ano, $mes,$dia) 		   = explode("-",$date);
		list($hora, $minuto,$segundo)  = explode(":",$time);

		$retorno = "";
		switch ($act) {
			default:
				case 1: //Date on the Brazilian format: dd/mm/yyyy
				$return = $dia."/".$mes."/".$ano;
				break;
			case 2: // Time on the Brazilian format: hh:mm:ss
				$return = $hora.":".$minuto.":".$segundo;
				break;
			case 3: // Data on the North American format: mm/dd/yyyy
				$return = $mes."/".$dia."/".$ano;
				break;
		}
		return $return;
	}


	/**
	 * Return the current day
	 *
	 * @param String $lng
	 * @return String
	 */
	public function currentDay($lng = "pt"){ // Paramter can be pt or en
		$day = getdate();
		$arrayDays = array();
		$arrayDays["Monday"] 	= "Segunda-Feira";
		$arrayDays["Tuesday"] 	= "Terça-Feira";
		$arrayDays["Wednesday"] = "Quarta-Feira";
		$arrayDays["Thursday"] 	= "Quinta-Feira";
		$arrayDays["Friday"] 	= "Sexta-Feira";
		$arrayDays["Saturday"] 	= "Sabado";
		$arrayDays["Sunday"] 	= "Domingo";

		if(strtolower($lng)=="pt"){
			return $arrayDays[$day["weekday"]];
		} elseif(strtolower($lng)=="en") {
			return $day["weekday"];
		}
	}

	/**
	 * Get the day of the week the date reported
	 *
	 * @param Integer $day
	 * @param Integer $month
	 * @param Integer $year
	 * @param String $lng
	 * @return String
	 */
	public function dayWeek($day,$month,$year,$lng = "pt"){ // Parameter can be en or en
		$newDay 	= getdate(mktime(0,0,0,$month,$day,$year));

		$arrayDays 	= array();
		$arrayDays["Monday"]	= "Segunda-Feira";
		$arrayDays["Tuesday"] 	= "Terça-Feira";
		$arrayDays["Wednesday"] = "Quarta-Feira";
		$arrayDays["Thursday"] 	= "Quinta-Feira";
		$arrayDays["Friday"] 	= "Sexta-Feira";
		$arrayDays["Saturday"] 	= "Sabado";
		$arrayDays["Sunday"] 	= "Domingo";

		if(strtolower($lng)=="pt"){
			return $arrayDays[$newDay["weekday"]];
		} elseif(strtolower($lng)=="en") {
			return $newDay["weekday"];
		}
	}

	//* End of functions related to date *//

	// Bellow are the functions related with JavaScript

	/**
	 * Alert
	 *
	 * @param String $msg
	 */
	public function alert($msg){
		echo "<script language='javascript'>
				<!--	
					alert('".$msg."');
				-->
			  </script>";
	}

	/**
	 * Alert and back to previous page
	 *
	 * @param String $msg
	 */
	public function alertBack($msg){
		echo "<script language='javascript'>
				<!--	
					alert('".$msg."');
					history.back();
				-->
			  </script>";
	}

	/**
	 * Back to the previous page
	 *
	 */
	public function goBack(){
		echo "<script language='javascript'>
				<!--	
					history.back();
				-->
			  </script>";
	}

	/**
	 * Close actual window
	 *
	 */
	public function closeWindow(){
		echo "<script language='javascript'>
				<!-- 
					window.close();
				-->
			  </script>";
	}

	/**
	 * Redirect page
	 *
	 * @param String $page
	 */
	public function redirect($page){
		echo "<script language='javascript'>
				<!--	
					location.href='".$page."';
				-->
			  </script>";
	}


	/**
	 * Update current window
	 *
	 */
	public function update(){
		echo "<script language='javascript'>
				<!--	
					window.location.reload();
				-->
			  </script>";
	}

	//* End of javascript's functions *//

	// Bellow are the functions related with strings or arrays

	/**
	 * Anti SQL Injection: Only lets through numbers and letters
	 *
	 * @param String $str
	 * @return Boolean
	 */
	public function no_injection_login($str){
		if(!preg_match("/[^\sa-zA-Z0-9]/i", $str)){
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Validate CPF
	 *
	 * @param String $cpf
	 * @return Boolean
	 */
	public function validateCpf($cpf){
		for( $i = 0; $i < 10; $i++ ){
			if ( $cpf ==  str_repeat( $i , 11) or !preg_match("@^[0-9]{11}$@", $cpf ) or $cpf == "12345678909" )
			return false;
			if ( $i < 9 ) $soma[]  = $cpf{$i} * ( 10 - $i );
			$soma2[] = $cpf{$i} * ( 11 - $i );
		}
		if(((array_sum($soma)% 11) < 2 ? 0 : 11 - ( array_sum($soma)  % 11 )) != $cpf{9})
		return false;
		return ((( array_sum($soma2)% 11 ) < 2 ? 0 : 11 - ( array_sum($soma2) % 11 )) != $cpf{10}) ? false : true;
	}

	/**
	 * Validate Email
	 *
	 * @param String $address
	 * @return unknown
	 */
	public function validateEmail($address) {
		if (function_exists('filter_var')) { //Introduced in PHP 5.2
			if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
				return false;
			} else {
				return true;
			}
		} else {
			return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
		}
	}

	/**
	 * Rewirte String with accents
	 *
	 * @param String $str
	 * @return String
	 */
	public function rewriteString($str){
		$listArr = array(
		"á"=>"&aacute;",
		"à"=>"&agrave;",
		"Á"=>"&Aacute;",
		"À"=>"&Agrave;",
		"ã"=>"&atilde;",
		"Ã"=>"&Atilde;",
		"â"=>"&acirc;",
		"Â"=>"&Acirc",

		"é"=>"&eacute;",
		"É"=>"&Eacute;",
		"ê"=>"&ecirc;",
		"Ê"=>"&Ecirc;",

		"í"=>"&iacute;",
		"Í"=>"&Iacute;",

		"ú"=>"&uacute;",
		"Ú"=>"&Uacute;",

		"ó"=>"&oacute;",
		"Ó"=>"&Oacute;",
		"õ"=>"&otilde;",

		"ç"=>"&ccedil;",
		"Ç"=>"&Ccedil;",

		"^"=>"&circ;",
		"~"=>"&tilde;",
		"´"=>"&acute;",
		"`"=>"&grave;",

		"ª"=>"&ordf;",
		"º"=>"&ordm;",
		"÷"=>"&divide;",
		"ü"=>"u",
		"©"=>"&reg;"
		);
		return strtr($str,$listArr);
	}

	// Remove all the tags of string
	public function removeTags($str){
		return preg_replace("/\<[^\>]*\>?/"," ",$str);
	}

	/**
	 * Remove all the tags
	 * Only de tag's name
	 * Ex: leaveTags($str,'img','a')
	 *
	 * @return unknown
	 */
	public function leaveTags(){
		$args = func_get_args();
		$str = $args[0];
		if(is_array($args)){
			foreach($args as $arg){
				if($args[0]!=$arg){
					$pattern = "/\<".$arg."[^\>]*\>?/";
					$str = preg_replace($pattern," ",$str);
				}
			}
		}
		return $str;
	}

	/**
	 * debugArray function use the print_r() function
	 * and show html tag <pre></pre> to show correctly in your screen
	 *
	 * @param Array $array
	 */
	public function debugArray($array){
		echo "<pre>";
		echo "<code>";
		print_r($array);
		echo "</code>";
		echo "</pre>";
	}

	/**
	 * Limit point from string given
	 *
	 * @param String $str
	 * @param Integer $limit
	 * @return unknown
	 */
	public function limitPoint($str,$limit=3){
		if(strpos($str,",")!==false){
			list($numero,$decimal) = explode(",",$str);
			if(strlen($decimal)>$limit){
				$decimal = substr($decimal,0,$limit);
			}
			return $numero.",".$decimal;
		} elseif(strpos($str,".")!==false) {
			list($numero,$decimal) = explode(".",$str);
			if(strlen($decimal)>$limit){
				$decimal = substr($decimal,0,$limit);
			}
			return $numero.".".$decimal;
		} else {
			return $str;
		}
	}

	/**
	 * This function delete repeated data in the array
	 *
	 * @param Array $array
	 * @return Array
	 */
	public function array_diff_values($array){ // Under review
		if(is_array($array)){
			$numArray = count($array);
			$newArray = array();

			if($numArray>0){
				$newArray[0] = $array[0];
				$i=0;
				do {
					foreach ($array AS $key=>$value){
						if(!in_array($value,$newArray)){
							$newArray[] = $value;
						}
						$i++;
					}
				} while ($i<3);
				return $newArray;
			} else {
				// Empty array
				return false;
			}
		} else {
			// Not array
			return false;
		}
	}

	/**
	 * This function bellow send data via post
	 * The $packet parameter should be a array
	 * I don't use this funcion many times, I only use in restricted situations
	 *
	 * @param String $url
	 * @param Array $packet
	 * @return Array
	 */
	public function execPage($url,$packet){
		$o="";
		foreach ($packet as $key=>$value){
			$o.= "$key=".utf8_encode($value)."&";
		}

		$args = substr($o,0,-1);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, 1 );
		curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
		$result	   = curl_exec($ch);
		$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		$result[0] = $result;
		$result[1] = $responseCode;
		return $result;
	}
}
?>
Return current item: Util