* @version 1.1.0 */ function disksize_readable($size, $unit = null, $retstring = null) { // Units $sizes = array('B', 'KB', 'MB', 'GB', 'TB'); $ii = count($sizes) - 1; // Max unit $unit = array_search((string) $unit, $sizes); if ($unit === null || $unit === false) $unit = $ii; // Defaukt return string if ($retstring === null) $retstring = '%01.2f %s'; // Loop $i = 0; while ($unit != $i && $size >= 1024 && $i < $ii) { $size /= 1024; $i++; } return sprintf($retstring, $size, $sizes[$i]); } /** * Return human readable sizes for bandwidth * * @param int $size Size * @param int $unit The maximum unit * @param int $retstring The return string format * @author Aidan Lister * @version 1.1.0 */ function bandwidth_readable($size, $unit = null, $retstring = null) { // Units $sizes = array('b/s', 'kb/s', 'Mb/s', 'Gb/s', 'Tb/s'); $ii = count($sizes) - 1; // Max unit $unit = array_search((string) $unit, $sizes); if ($unit === null || $unit === false) $unit = $ii; // Defaukt return string if ($retstring === null) $retstring = '%01.2f %s'; // Loop $i = 0; while ($unit != $i && $size >= 1000 && $i < $ii) { $size /= 1000; $i++; } return sprintf($retstring, $size, $sizes[$i]); } function LocalGMT() { $stamp1 = mktime(0,0,0,5,5,2004); $d1 = Date("d",$stamp1); $h1 = Date("H",$stamp1); $h1 = $h1+($d1*24); $stamp2 = gmmktime(0,0,0,5,5,2004); $d2 = Date("d",$stamp2); $h2 = Date("H",$stamp2); $h2 = $h2+($d2*24); return ($h2-$h1); } /* * generate_password * Generates a random string of specified length, great for use as a password * * Params $length int The length of the password string Returns float Returns a random set of chars of specified length */ function generate_password($length = 10) { // start with a blank password $password = ""; // define possible characters $possible[] = "0123456789"; $possible[] = "abcdfghjkmnpqrstvwxyz"; $possible[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$possible[] = "!@#$%^&*()_+=-[]<>"; /* Very good characters to use in a password - but I dont want to explain to a client how to type the ^ character*/ // add random characters to $password until $length is reached for ($i=0; $i<$length; $i++) { $char = ''; // pick a random character from the possible ones // keep looking untill we find one we havnt used yet. while( ($char == '') OR (strstr($password, $char)) ) { $charstring = $possible[ $i % count($possible) ]; $char = substr($charstring, mt_rand(0, strlen($charstring)-1), 1); } // while // Place the character at a random position in the string $cut = rand(0,$i); $password = substr( $password, 0, $cut ) . $char . substr( $password, $cut ); }; // done! return $password; } /* * Currency * Takes a value and makes it a float containing only 2 decimal numbers. * * Params $val float A floating point money value Returns float Returns the value in float with only 2 decimal numbers. */ function Currency($val) { $val = sprintf("%0.2f",$val); settype($val,'float'); return $val; } function CurrencyStr($val) { $val = sprintf("%0.2f",$val); return $val; } /* * ReadDef * Returns a default if a value is empty * * Params $val mixed A variable with a value attached to it. $def string A empty string Returns float Returns the value if there is one else it returns $def */ function ReadDef($val,$def = "") { if(empty($val)) return $def; else return $val; } /* * IP2Int * takes an ip address and turns it into an integer value * * Params $ip float the value of the ip address Returns int Returns the value of the ip address as an int */ function IP2Int($ip) { $intIP = sprintf("%u", ip2long($ip)); return $intIP; } /* * Int2IP * takes an integer value and turns it into an ip value * * Note: * Value is first casted to "double" floating point since PHP can only handle signed integers, * while an IP address is an unsigned integer. * * Params $intIP int The integer IP value; Returns string Returns an ip address */ function Int2IP($intIP) { settype($intIP, "double"); return long2ip($intIP); } /* * bestIP * Gets the current ip address available * Returns array Returns the current ip address. */ function bestIP() { if (getenv("HTTP_X_FORWARDED_FOR")) $hi = getenv("HTTP_X_FORWARDED_FOR"); else $hi = getenv("REMOTE_ADDR"); //This might contain multiple IP addresses! $hi = explode(",",$hi); return $hi[0]; } /* * intIP * converts the current ip address to int * Returns ip Returns the current ip address as an int. */ function intIP() { return IP2Int(bestIP()); } /* * DisableBrowserCache * Adds headers to the browser so that it does not cache anything */ function DisableBrowserCache() { header("Expires: ".gmdate("D, d M Y H:i:s", time()) . " GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, no-store, must-revalidate"); header("Pragma: no-cache"); } /* * EnableBrowserCache * Adds headers to the browser to enable it to cache again. */ function EnableBrowserCache() { $modified = mktime(0, 0, 0, 12, 32, 2003); $expire = mktime(0, 0, 0, 12, 32, 2008); header("Expires: ".gmdate("D, d M Y H:i:s", $expire) . " GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s",$modified) . " GMT"); } /* * StripArray * Takes an array and strips it from slashes * * Params $arr array the array needing to be stripped Returns array Returns the array that is stripped of its slashes */ function StripArray($arr) { if(!is_array($arr)) return stripslashes($arr); else foreach($arr as $key => $val) { if(is_array($val)) $arr["$key"] = StripArray($val); else $arr["$key"] = stripslashes($val); } return $arr; } //Add slahes to items in array function SlashArray($arr) { if(!is_array($arr)) return addslashes($arr); else foreach($arr as $key => $val) { if(is_array($val)) $arr["$key"] = SlashArray($val); else $arr["$key"] = addslashes($val); } return $arr; } /* * CleanArray * Takes an array and removes white space from infront or at the back of each element * It also removed array keys which contains no value * * Params $arr array the array needing to be cleaned Returns array Returns the cleaned array */ function CleanArray($arr) { $res = array(); if(!is_array($arr)) return trim($arr); else foreach($arr as $key => $val) { $val = trim($val); if(!empty($val)) $res["$key"] = $val; } return $res; } /* * Array2Params * Takes an array and encodes each element to URL form for use as a paramater * in a URL * * Params $data array the array needing to be encoded $pre and $post are generally only for internal use, but can be used to put arrays into a parameter string Returns string Returns the string to be used in the URL as a parameter */ function Array2Params($data, $pre = "", $post = "") { $res = ""; reset($data); while (list($key, $val) = each($data)) { if(is_array($val)) $res .= Array2Params($val,$key."[","]"); else { $val = urlencode($val); $res .= "&".$pre.$key.$post."=".$val; } } return $res; } /* * ValidField * Checks a field to see if it is valid (no bad chars and must be more than 3 chars long) * If the variable ($val) is NOT valid, $val is set to an empty string and an error message * is returned as the result. * * Params $val string referenced value to be checked $name string the name of the field to be checked Returns string a message stating if it is not valid */ function ValidField(&$val,$name, $max_size = 15, $min_size = 3) { $msg = ""; $valid = true; if(strlen($val)<$min_size) { $msg = "$name must be at least $min_size characters long."; $valid = false; } if(strlen($val)>$max_size) { $msg = "$name may not be longer than $max_size characters."; $valid = false; } if($valid) { $validchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!{}()[]=-$%._"; $badchars = " ?/\\:*'<>|\"#&@"; for($c=0;(($crow() * so it only contains an associative array containing fieldnames => values * * Params * $in mixed Array/record of data * Result mixed Returns an array where all the array keys that is a number are removed */ function StripNumericKeys($in) { reset($in); $res = Array(); while(list($key, $val) = each($in)){ if(!is_numeric($key)) $res[$key] = $val; } // while loop return $res; } /* * DateMove * Generates a unix timestamp from the variables given * Can be used to calculate a date in the past or future * * Params $d string day value $m string Month value $y string year value Returns datetime Returns a unix format timestamp */ function DateMove(&$d, &$m, &$y, $ad, $am, $ay) { $stamp = mktime(0,0,0,$am,$ad,$ay); $d = date("d",$stamp); $m = date("m",$stamp); $y = date("Y",$stamp); return $stamp; } /* * DaysInMonth * works out how many days there are in a certain month * * Params $m string the month value (Optional, uses current month as default) $y string the current year (Optional, uses current year as default) Returns int Returns the number of days in a given month */ function DaysInMonth($m = '', $y = '') { if(empty($m)) $m = date("m"); if(empty($y)) $y = date("Y"); $stamp = mktime(0,0,0,$m+1,0,$y); $d = date("d",$stamp); return $d; } /* * Def * Sets a default value for a variable if it is empty * * Params $val string a possible value $def string the default value if $val is empty Returns string Returns either the value in $val or arrigns $def to it */ function Def(&$val, $def = '') { if(empty($val)) $val = $def; return $val; } /* FillData Replaces tags containec in a text string with the values supplied in $data 'date' and 'time' is two default tags you may use as well Tags: {fieldname} - Replaces tag with normal text #fieldname# - Replace tag with HTML formatted text (i.e. newlines =
) [fieldname] - Replace tag with URL encoded text Params $data array associative array containing the fieldnames as keys and the values as the field values. $source string Source string containing template tags that will be replaced Result string Returned string with all tags replaced by the values in the $data array. */ function FillData($data,$source) { reset($data); while (list($key, $val) = each($data)) { if ($key[0]!='_') ReplaceField($key,$val,$source); } ReplaceField("time",date('Y-m-d'),$source); ReplaceField("date",date('H:i:s'),$source); return $source; } /* ReplaceField Replaces $field tag in $message with $value, properly formatted for tag type (i.e. {},## or []) */ function ReplaceField($field,$value,&$message) { $message = eregi_replace("\{".$field."\}", $value , $message); $message = eregi_replace("#".$field."#", Text2Html($value), $message); $message = eregi_replace("\[".$field."\]", urlencode($value), $message); } /* * File2Str * open a file and reads the content into a string * Note: File can be an HTTP page * * Params $fname string The file name to be opened Returns string The string containing the files information */ function File2Str($fname) { $temp = ""; $fd = fopen($fname, "r"); while ($buffer = fgets($fd, 4096)) { $temp .= $buffer; } fclose($fd); return $temp; } /* * Str2File * Takes the value of a string and writes it to a file * * Params $fname string The name of the file to be written to $data string The string to be written to the file */ function Str2File($fname, $data) { $res = true; $temp = ""; $fd = fopen($fname, "w"); if(!$fd){ echo "Error writing to $fname"; $res = false; } if(!fputs($fd, $data)){ echo "Error writing to $fname"; $res = false; } fclose($fd); return $res; } /* * Text2Html * Takes a string and adds html tags to it, * turns all newlines into
* * Params $txt string the string to be processed Returns string Returns a html formatted string */ function Text2Html($txt) { return str_replace("\n","\n
",$txt); } /* * getmicrotime * Gets the current unix microtime * Returns float Returnsthe current Unix timestamp with microseconds */ function getmicrotime() { list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } /*########################################################################## In here is various functions to handle the data received from HTML forms It allows for standards to accept data from any form and put it into a Database //==========================================================================*/ /* * DataConvert * Takes one piece of data and converts it to another data type * * Params $from mixed the data type to convert $to mixed the data type to convert to Returns mixed Returns the converted data */ function DataConvert(&$data,$from,$to) { $from = explode(',',$from); $to = explode(',',$to); for ($k=0; $k0) return 0; else return 1; } //========================================================================== /* * CreateSQLQuery * Creates an SQL query * * Params $form array The data to be entered into the database $fields mixed The specific names of the fields $values mixed The values of the forms to be entered $mode string The mode of the Query (update/delete) */ function CreateSQLQuery($form,&$fields,&$values,$mode) { //Set Database insert/update mode $fields = ""; $values = ""; reset($form); while (list($key, $val) = each($form)) { if ($key[0]!='_') AddKey($key,$val,$fields,$values,$mode,"auto"); } } //================== ## /*########################################################################## Various Form output functions //==========================================================================*/ /* * FormatDefData * if the data is an array, it assignes $name to it else it assignes a default value to $data * * Params $name string The name of the field in a form $data mixed A reference to the data $def mixed The default value */ function FormatDefData($name,&$data,$def) { if (gettype($data)=="array") $data = $data["$name"]; if (empty($data)) $data = $def; } //========================================================================== /* * InputHidden * inserts a hidden field into the form * * Params $name string The name of the field in a form $data mixed The data to be inserted $def mixed The default value */ function InputHidden($name,$data,$def = "") { FormatDefData($name,$data,$def); ?> > > > "; } //==========================================================================*/ /* * InputDay * inserts a dropdown field into the form containing the days of the month * * Params $d int The day of the month to be selected $name string The name of the field */ function InputDay($d,$name) { FormatDefData($name,$d,date('d')); $d = (int)$d; echo ""; } /* * InputMonth * inserts a dropdown field into the form containing the months data * * Params $d int The month of the year to be selected $name string The name of the field */ function InputMonth($m,$name) { FormatDefData($name,$m,date('m')); $m = (int)$m; echo ""; } /* * InputYear * inserts a dropdown field into the form containing the year * * Params $d int The year to be selected $name string The name of the field */ function InputYear($y,$name) { FormatDefData($name, $y, date('Y')); $y = (int)$y; echo ""; } /* * InputDate * inserts dropdown fields into the form containing the date * * Params $f ?????? ????????????????????? $fieldname string The name of the field */ function InputDate($f,$fieldname) { $months[1]="Jan"; $months[2]="Feb"; $months[3]="Mar"; $months[4]="Apr"; $months[5]="May"; $months[6]="Jun"; $months[7]="Jul"; $months[8]="Aug"; $months[9]="Sep"; $months[10]="Oct"; $months[11]="Nov"; $months[12]="Dec"; if (empty($f['d'])) { $f['d'] = date ("d"); $f['m'] = date ("m"); $f['y'] = date ("Y"); }; ?> ') { if(!is_array($a)) { echo "$pre value=$a
"; return; } reset($a); while(list($key, $value) = each($a)){ echo "$pre $key=$value
"; if(is_array($value)) Walk($value,$pre.'-->'); } // while loop } //========================= --[ END ]-- ==================================== ?>