<?php /*~ common.inc.php
.---------------------------------------------------------------------------.
|  Software: Common Utilities Library                                       |
|   Version: 0.1.1                                                          |
|   Contact: via http://www.uniwits.com/contact                             |
|      Info: http://www.uniwits.com/                                        |
|   Support: http://www.uniwits.com/support                                 |
|      Note: This library is designed for Linux and compatible systems.     |
| ------------------------------------------------------------------------- |
|     Admin: Yuxiang Mao (project admininistrator)                          |
|   Authors: Yuxiang Mao (Uniwits) contact@uniwits.com                      |
|   Founder: Yuxiang Mao                                                    |
| Copyright (c) 2010-2012, Yuxiang Mao. All Rights Reserved.                |
| ------------------------------------------------------------------------- |
|   License: Distributed under Uniwits Shareware License (USL)              |
|            http://www.uniwits.com/licenses/shareware/                     |
| This program is distributed as a part of software provided by Uniwits     |
| System WITHOUT ANY WARRANTY; without even the implied warranty of         |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                      |
| ------------------------------------------------------------------------- |
*/ function _stripslashes_r($var) { if (is_array($var)) { $result=array(); foreach($var as $k=>$v) $result[$k]=&_stripslashes_r($v); return $result; } else return stripslashes($var); } function POST($idx) { if (get_magic_quotes_gpc()) return _stripslashes_r(@$_POST[$idx]); return @$_POST[$idx]; } function GET($idx) { if (get_magic_quotes_gpc()) return _stripslashes_r(@$_GET[$idx]); return @$_GET[$idx]; } function REQUEST($idx) { if (get_magic_quotes_gpc()) return _stripslashes_r(@$_REQUEST[$idx]); return @$_REQUEST[$idx]; } function _trim_for_array_walk($item,$key) { return trim($item); } function TPOST($idx) { $val=POST($idx); if (is_array($val)) array_walk_recursive($val,'_trim_for_array_walk'); return $val; } function TGET($idx) { $val=GET($idx); if (is_array($val)) array_walk_recursive($val,'_trim_for_array_walk'); return $val; } function TREQUEST($idx) { $val=REQUEST($idx); if (is_array($val)) array_walk_recursive($val,'_trim_for_array_walk'); return $val; } function REMOTE_ADDR() { if ($_SERVER['HTTP_X_FORWARDED_FOR']) return $_SERVER['HTTP_X_FORWARDED_FOR']; return $_SERVER['REMOTE_ADDR']; } function trim_parameter_variable($var) { if (is_array($var)) { if (get_magic_quotes_gpc()) { $trimmed=array(); foreach ($var as $key=>$value) $trimmed[$key]=_stripslashes_r($value); array_walk_recursive($trimmed,'_trim_for_array_walk'); return $trimmed; } else { array_walk_recursive($var,'_trim_for_array_walk'); return $var; } } else { if (get_magic_quotes_gpc()) return trim(_stripslashes_r($var)); else return trim($var); } } function purge_array_by_key_prefix(&$array,$keyprefix) { if (!$array) { $array=array(); return; } $keys=array(); $kplen=strlen($keyprefix); foreach ($array as $key=>$val) if (strncmp($key,$keyprefix,$kplen)==0) array_push($keys,$key); foreach ($keys as $k) unset($array[$k]); } function array_projection($array,$key) { $proj=array(); if ($array) foreach ($array as $a) if (isset($a[$key])) array_push($proj,$a[$key]); return $proj; } function rowset2map($rows,$key,$valuekey=null) { if (!$rows) return array(); $map=array(); if ($valuekey===null) { foreach ($rows as $r) @$map[$r[$key]]=$r; } else { foreach ($rows as $r) @$map[$r[$key]]=$r[$valuekey]; } return $map; } function rowset2multimap($rows,$key,$valuekey=null) { if (!$rows) return array(); $map=array(); if ($valuekey===null) { foreach ($rows as $r) { @$kv=$r[$key]; if (!isset($map[$kv])) $map[$kv]=array(); array_push($map[$kv],$r); } } else { foreach ($rows as $r) { @$kv=$r[$key]; if (!isset($map[$kv])) $map[$kv]=array(); array_push($map[$kv],$r[$valuekey]); } } return $map; } function sortrows_by_keys($rows,$keys=array()) { if (!$rows) return $rows; $keyedrows=array(); foreach ($rows as $r) { $kvrow=array(); foreach ($keys as $k) array_push($kvrow,$r[$k]); array_push($kvrow,$r); array_push($keyedrows,$kvrow); } array_multisort($keyedrows,SORT_ASC,SORT_REGULAR); $lastindex=sizeof($kvrow)-1; $sortedrows=array(); foreach ($keyedrows as $row) array_push($sortedrows,$row[$lastindex]); return $sortedrows; } function array_keyed_max($rows,$key) { $max=false; $maxvalid=false; foreach($rows as $r) if ($maxvalid) $max=max($max,$r[$key]); else { $max=$r[$key]; $maxvalid=true; } return $max; } function array_keyed_min($rows,$key) { $min=false; $minvalid=false; foreach($rows as $r) if ($minvalid) $min=min($min,$r[$key]); else { $min=$r[$key]; $minvalid=true; } return $min; } function array_select_keyprefix($array,$key_prefix) { $result=array(); $kplen=strlen($key_prefix); foreach ($array as $key=>$value) { if (strncmp($key,$key_prefix,$kplen)==0) $result[$key]=$value; } return $result; } function array_select_by_key($array,$keys) { $result=array(); foreach ($keys as $k) $result[$k]=$array[$k]; return $result; } function array_true_entries_only($array) { if (!$array) return array(); $result=array(); foreach ($array as $k=>$v) { if ($v) $result[$k]=$v; } return $result; } function iif_array4($quadruples) { $results=array(); foreach ($quadruples as $q) { if ($q[0]) $results[$q[1]]=$q[2]; else if (sizeof($q)==4) $results[$q[1]]=$q[3]; } return $results; } function count_true_entries($array) { $count=0; foreach ((array)$array as $a) if ($a) $count++; return $count; } function count_true_assignments($array,$key) { $count=0; foreach ($array as $a) if ($a[$key]) $count++; return $count; } function array_assoc_set_if(&$array,$condkey,$condval,$setkey,$setval) { foreach ($array as &$a) if ($a[$condkey]==$condval) $a[$setkey]=$setval; } function array_assoc_unset_if(&$array,$condkey,$condval,$unsetkey) { foreach ($array as &$a) if ($a[$condkey]==$condval) unset($a[$unsetkey]); } function array_assoc_set_iif(&$array,$condkey,$condval,$truekey,$trueval,$falsekey,$falseval,$skipfalsekey=true) { foreach ($array as &$a) if ($a[$condkey]==$condval) { if ($truekey || !$skipfalsekey) $a[$truekey]=$trueval; } else { if ($falsekey || !$skipfalsekey) $a[$falsekey]=$falseval; } } function array_deassociate($assoc,$keykey,$valuekey) { $rows=array(); foreach ($assoc as $k=>$v) array_push($rows,array($keykey=>$k,$valuekey=>$v)); return $rows; } function array_key_prepend($assoc,$prepend) { $result=array(); foreach ($assoc as $key=>$val) $result[$prepend.$key]=$val; return $result; } function array_key_cuthead($assoc,$prefix,$cutlength) { $plen=strlen($prefix); $result=array(); foreach ($assoc as $key=>$val) if (strncmp($key,$prefix,$plen)==0) $result[substr($key,$cutlength)]=$val; return $result; } function array_unset_keys(&$array,$keys) { foreach ($keys as $k) unset($array[$k]); } function is_decimal_in_range($text,$low,$high) { if (!ereg('^[0-9]+(\.[0-9]+)?$',$text)) return false; return 0+$low<=0+$text && 0+$text<=0+$high; } function is_integer_in_range($text,$low,$high) { if (!ereg('^[0-9]+$',$text)) return false; return 0+$low<=0+$text && 0+$text<=0+$high; } function bound_value($current,$min=false,$max=false,$default=false) { if (!$current) if ($default!==false) return $default; else if ($min!==false) return $min; else return $max; return max($min,min($max,$current)); } function bound_value_0($current,$min=false,$max=false,$default=false) { if (!$current && $current!==0) if ($default!==false) return $default; else if ($min!==false) return $min; else return $max; return max($min,min($max,$current)); } function coalesce() { $n=func_num_args(); for ($i=0;$i<$n;$i++) { $value=func_get_arg($i); if ($value) return $value; } } function build_full_url($urlparts=array(),$defaultparts=array()) { foreach ($defaultparts as $k=>$dp) if (!$urlparts[$k]) $urlparts[$k]=$defaultparts[$k]; $url=($urlparts['scheme']?$urlparts['scheme']:'http'.(is_https()?'s':'')).'://' .($urlparts['user'] || $urlparts['pass']?urlencode($urlparts['user']).':'.urlencode($urlparts['pass']).'@':'') .($urlparts['host']?$urlparts['host']:$_SERVER['SERVER_NAME']) .($urlparts['port']?":".$urlparts['port']:'') .($urlparts['path'][0]!='/'?'/':'') .($urlparts['path']?$urlparts['path']:'') .($urlparts['query']?'?'.$urlparts['query']:'') .($urlparts['fragment']?'#'.$urlparts['fragment']:''); return $url; } function dirname_ending_with_slash($path) { $dn=dirname($path); $len=strlen($dn); if ($len==0) return './'; if ($dn[$len-1]=='/' || $dn[$len-1]=='\\') return $dn; return $dn.'/'; } function is_valid_email($email) { return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email); } function copy_dir($srcdir,$destdir,$mode=0755,$istest=false,&$donetable=array(),&$failedfiles=array()) { $dh=opendir($srcdir); if (!$dh) return; if (!is_dir($destdir)) if (!@mkdir($destdir,$mode,true)) { $failedfiles[]=$destdir; return; } if (substr($srcdir,-1,1)!='/') $srcdir.='/'; if (substr($destdir,-1,1)!='/') $destdir.='/'; while (($entry=readdir($dh))!==false) { if ($entry=='.' || $entry=='..') continue; $fullpath=$srcdir.$entry; $es=stat($fullpath); $id=$es[0].'.'.$es[1]; if (isset($donetable[$id])) continue; $donetable[$id]=1; if (is_dir($fullpath)) copy_dir($fullpath,$destdir.$entry,$mode,$istest,$donetable,$failedfiles); else if (is_link($fullpath)); else if (is_file($fullpath)) if ($istest) { if (!is_writable(dirname($destdir.$entry))) $failedfiles[]=$destdir.$entry; } else { if (!copy($fullpath,$destdir.$entry)) $failedfiles[]=$destdir.$entry; } } closedir($dh); } function remove_dir($dir,$contentsonly=false) { if (!is_dir($dir)) return; $dh=opendir($dir); if (!$dh) return; if (substr($dir,-1,1)!='/') $dir.='/'; while (($entry=readdir($dh))!==false) { if ($entry=='.' || $entry=='..') continue; $fullpath=$dir.$entry; $fs=stat($fullpath); if (is_dir($fullpath)) remove_dir($fullpath,false); else if (is_link($fullpath) || is_file($fullpath)) unlink($fullpath); } closedir($dh); if (!$contentsonly) rmdir($dir); } function sum_dir_size($dir,$countdir=false,$selfsize=false) { if (!is_dir($dir)) return false; $sumsize=0; if ($selfsize) { $fs=stat($dir); $sumsize+=$fs[7]; } $dh=opendir($dir); if (!$dh) return false; if (substr($dir,-1,1)!='/') $dir.='/'; while (($entry=readdir($dh))!==false) { if ($entry=='.' || $entry=='..') continue; $fullpath=$dir.$entry; $fs=stat($fullpath); if (is_dir($fullpath)) { if ($countdir) $sumsize+=$fs[7]; $sumsize+=sum_dir_size($fullpath,$countdir); } else if (is_link($fullpath)); else if (is_file($fullpath)) $sumsize+=$fs[7]; } closedir($dh); return $sumsize; } function send_file($file,$mimetype=false,$as_attachment=true,$peakrate=false) { if (!$mimetype) $mimetype='application/octet-stream'; header("Content-Type: ".$mimetype); if ($as_attachment) header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Content-Length: '.filesize($file)); if (!$peakrate) readfile($file); else { $basetime=microtime(true); $lenbuf=0; $fp=fopen($file,'r'); while (!feof($fp)) { $data=fread($fp,$peakrate); echo $data; $lenbuf+=strlen($data); while ($lenbuf>=$peakrate) { $steptime=microtime(true); $waits=1-($steptime-$basetime); if ($waits>0) usleep($waits*1000000); $basetime=$steptime+$waits; $lenbuf-=$peakrate; } } fclose($fp); } } function get_user_agent_id_for_tracking($defaultid=false) { if (isset($_SERVER['HTTP_X_NETWORK_INFO'])) { $str1 =$_SERVER['HTTP_X_NETWORK_INFO']; $getstr1 =preg_replace('/(.*,)( 11 [d ])(,.*)/i','',$str1); return md5($getstr1); } elseif (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) { $getstr2 =$_SERVER['HTTP_X_UP_CALLING_LINE_ID']; return md5($getstr2); } elseif (isset($_SERVER['HTTP_X_NX_CLID'])) { $get4 =$_SERVER['HTTP_X_NX_CLID']; return md5($get4); } elseif (isset($_SERVER['HTTP_X_UP_SUBNO'])) { $str3 =$_SERVER['HTTP_X_UP_SUBNO']; $getstr3 =preg_replace ('/(.*)( 11 [d ])(.*)/i','',$str3); return md5($getstr3); } elseif (isset($_SERVER['DEVICEID'])) { return md5($_SERVER['DEVICEID']); } elseif ($defaultid) { return md5($defaultid); } else { return md5(REMOTE_ADDR()); } } function XML2Array($xml) { $arr=array(); $text=trim((string)$xml); if ($text) $arr['@text']=$text; foreach ($xml->attributes() as $key=>$value) $arr[$key]=(string)$value; $ci=0; foreach ($xml->children() as $name=>$sub) { if (!isset($arr['@children'][$name])) $arr['@children'][$name]=array(); array_push($arr['@children'][$name], XML2Array($sub) ); $ci++; } return $arr; } function array2XMLString($xmlarr,$roottag,$return=false,$isTop=true,$encoding='utf-8') { if ($isTop) { if ($return) $str='<?xml version="1.0" encoding="'.$encoding.'"?>'; else echo '<?xml version="1.0" encoding="'.$encoding.'"?>'; } if ($return) $str.="<$roottag"; else echo "<$roottag"; foreach ($xmlarr as $key=>$value) { if ($key[0]!='@') { if ($return) $str.=' '.$key.'="'.htmlspecialchars($value).'"'; else echo ' '.$key.'="'.htmlspecialchars($value).'"'; } } if ($return) $str.=">"; else echo ">"; if ($xmlarr['@text']) if ($return) $str.=htmlspecialchars($xmlarr['@text']); else echo htmlspecialchars($xmlarr['@text']); if ($xmlarr['@children']) foreach($xmlarr['@children'] as $key=>$sub) { for ($si=0;$si<sizeof($sub);$si++) { if ($return) $str.=array2XMLString($sub[$si],$key,$return,false,''); else echo array2XMLString($sub[$si],$key,$return,false,''); } } if ($return) $str.="</$roottag>"; else echo "</$roottag>"; if ($return) return $str; } function remote_is_searchengine() { $bot_list =array( 'Teoma', 'alexa', 'froogle', 'Gigabot', 'inktomi', 'YoudaoBot', 'bingbot', 'looksmart', 'URL_Spider_SQL', 'Firefly', 'NationalDirectory', 'Ask Jeeves', 'TECNOSEEK', 'InfoSeek', 'WebFindBot', 'girafabot', 'crawler', 'www.galaxy.com', 'Googlebot', 'Scooter', 'Slurp', 'msnbot', 'appie', 'FAST', 'WebBug', 'Spade', 'ZyBorg', 'rabaz', 'Baiduspider', 'Feedfetcher-Google', 'TechnoratiSnoop', 'Rankivabot', 'Mediapartners-Google', 'Sogou web spider', 'WebAlta Crawler' ); foreach ($bot_list as $bot) { if (strpos($_SERVER['HTTP_USER_AGENT'],$bot)!==false) return true; } return false; } function parseURL($url,$component=-1) { $qmarkidx=strpos($url,'?'); $colonidx=strpos($url,':'); if ($qmarkidx!==false) { $query=substr($url,$qmarkidx+1); $url=substr($url,0,$qmarkidx); $returnval=parse_url($url,$component); if ($component==PHP_URL_QUERY) $returnval=$query; else if ($component==-1) $returnval['query']=$query; } else $returnval=parse_url($url,$component); return $returnval; } function filter_phone_number($phone) { $phone=trim($phone); if (ereg('^\+?[0-9]+(-[0-9]+)*(\*[0-9]+)?$',$phone)) return $phone; return false; } function filter_email($email) { $email=trim($email); if (is_valid_email($email)) return $email; return false; } function DEBUG($var,$detail_level=0) { echo '<pre>'; if ($detail_level==1) var_dump($var); else print_r($var); echo '</pre>'; } function fix_ordinal(&$key2ordinal) { asort($key2ordinal,SORT_NUMERIC); $ordinal=1; foreach ($key2ordinal as &$ord) $ord=$ordinal++; } function fix_ordinal_of_rows(&$rows,$ordinal_key) { $key2ord=array_projection($rows,$ordinal_key); fix_ordinal($key2ord); foreach ($rows as $key=>&$value) $value[$ordinal_key]=$key2ord[$key]; } function monthDays($year,$month) { switch ($month) { case 1: return 31; case 2: $time=mktime(0,0,0,2,29,$year); $ms=intval(date("m",$time),10); if ($ms==29) return 29; return 28; case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31; case 9: return 30; case 10: return 31; case 11: return 30; case 12: return 31; } } function random_alphanum($length) { $text=''; while (strlen($text)<$length) $text.=base_convert(mt_rand(100000,2000000000),10,36); return substr($text,0,$length); } function generate_random_id($sectionlength,$sectionnum=1,$separator='') { $id=''; for ($si=0;$si<$sectionnum;$si++) { if ($si) $id.=$separator; $id.=random_alphanum($sectionlength); } return $id; } function common_prefix_str_array($str_arr) { if (!is_array($str_arr)) $str_arr=array($str_arr); $prefix=''; $idx=0; $avail=sizeof($str_arr)>0; while ($avail) { for ($sai=0;$sai<sizeof($str_arr);$sai++) { if ($idx>=strlen($str_arr[$sai])) { $avail=false; break; } else if ($sai && $str_arr[$sai][$idx]!=$str_arr[$sai-1][$idx]) break; } if ($sai<sizeof($str_arr)) break; $prefix.=$str_arr[0][$idx++]; } return $prefix; } function or_default($value,$default) { return $value?$value:$default; } ?>