ThinkPHP/Common/extend.php

98201 ワード

<?php

// +----------------------------------------------------------------------

// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]

// +----------------------------------------------------------------------

// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.

// +----------------------------------------------------------------------

// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )

// +----------------------------------------------------------------------

// | Author: liu21st <[email protected]>

// +----------------------------------------------------------------------

// $Id$



/**

 +------------------------------------------------------------------------------

 * Think                        

 +------------------------------------------------------------------------------

 * @category   Think

 * @package  Common

 * @author   liu21st <[email protected]>

 * @version  $Id$

 +------------------------------------------------------------------------------

 */



//      IP  
//getenv() , phpinfo()
//strcasecmp() , 0 function get_client_ip(){ if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return($ip); } /** * IP * /addons/libs/misc/sry.dat ip , ip * @param string $ip * @return string */ function convert_ip($ip) { $return = '';
// ip
if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) { $iparray = explode('.', $ip); if($iparray[0] == 10 || $iparray[0] == 127 || ($iparray[0] == 192 && $iparray[1] == 168) || ($iparray[0] == 172 && ($iparray[1] >= 16 && $iparray[1] <= 31))) { $return = '- LAN'; } elseif($iparray[0] > 255 || $iparray[1] > 255 || $iparray[2] > 255 || $iparray[3] > 255) { $return = '- Invalid IP Address'; } else { $fullipfile = SITE_PATH . '/addons/libs/misc/wry.dat'; $return = convert_ip_full($ip, $fullipfile); } } $return = iconv('GBK', 'UTF-8', $return); return $return; } /** * @see convert_ip() */ function convert_ip_full($ip, $ipdatafile) { if (! $fd = @fopen ( $ipdatafile, 'rb' )) { return '- Invalid IP data file'; } $ip = explode ( '.', $ip ); $ipNum = $ip [0] * 16777216 + $ip [1] * 65536 + $ip [2] * 256 + $ip [3]; if (! ($DataBegin = fread ( $fd, 4 )) || ! ($DataEnd = fread ( $fd, 4 ))) return; @$ipbegin = implode ( '', unpack ( 'L', $DataBegin ) ); if ($ipbegin < 0) $ipbegin += pow ( 2, 32 ); @$ipend = implode ( '', unpack ( 'L', $DataEnd ) ); if ($ipend < 0) $ipend += pow ( 2, 32 ); $ipAllNum = ($ipend - $ipbegin) / 7 + 1; $BeginNum = $ip2num = $ip1num = 0; $ipAddr1 = $ipAddr2 = ''; $EndNum = $ipAllNum; while ( $ip1num > $ipNum || $ip2num < $ipNum ) { $Middle = intval ( ($EndNum + $BeginNum) / 2 ); fseek ( $fd, $ipbegin + 7 * $Middle ); $ipData1 = fread ( $fd, 4 ); if (strlen ( $ipData1 ) < 4) { fclose ( $fd ); return '- System Error'; } $ip1num = implode ( '', unpack ( 'L', $ipData1 ) ); if ($ip1num < 0) $ip1num += pow ( 2, 32 ); if ($ip1num > $ipNum) { $EndNum = $Middle; continue; } $DataSeek = fread ( $fd, 3 ); if (strlen ( $DataSeek ) < 3) { fclose ( $fd ); return '- System Error'; } $DataSeek = implode ( '', unpack ( 'L', $DataSeek . chr ( 0 ) ) ); fseek ( $fd, $DataSeek ); $ipData2 = fread ( $fd, 4 ); if (strlen ( $ipData2 ) < 4) { fclose ( $fd ); return '- System Error'; } $ip2num = implode ( '', unpack ( 'L', $ipData2 ) ); if ($ip2num < 0) $ip2num += pow ( 2, 32 ); if ($ip2num < $ipNum) { if ($Middle == $BeginNum) { fclose ( $fd ); return '- Unknown'; } $BeginNum = $Middle; } } $ipFlag = fread ( $fd, 1 ); if ($ipFlag == chr ( 1 )) { $ipSeek = fread ( $fd, 3 ); if (strlen ( $ipSeek ) < 3) { fclose ( $fd ); return '- System Error'; } $ipSeek = implode ( '', unpack ( 'L', $ipSeek . chr ( 0 ) ) ); fseek ( $fd, $ipSeek ); $ipFlag = fread ( $fd, 1 ); } if ($ipFlag == chr ( 2 )) { $AddrSeek = fread ( $fd, 3 ); if (strlen ( $AddrSeek ) < 3) { fclose ( $fd ); return '- System Error'; } $ipFlag = fread ( $fd, 1 ); if ($ipFlag == chr ( 2 )) { $AddrSeek2 = fread ( $fd, 3 ); if (strlen ( $AddrSeek2 ) < 3) { fclose ( $fd ); return '- System Error'; } $AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) ); fseek ( $fd, $AddrSeek2 ); } else { fseek ( $fd, - 1, SEEK_CUR ); } while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) ) $ipAddr2 .= $char; $AddrSeek = implode ( '', unpack ( 'L', $AddrSeek . chr ( 0 ) ) ); fseek ( $fd, $AddrSeek ); while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) ) $ipAddr1 .= $char; } else { fseek ( $fd, - 1, SEEK_CUR ); while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) ) $ipAddr1 .= $char; $ipFlag = fread ( $fd, 1 ); if ($ipFlag == chr ( 2 )) { $AddrSeek2 = fread ( $fd, 3 ); if (strlen ( $AddrSeek2 ) < 3) { fclose ( $fd ); return '- System Error'; } $AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) ); fseek ( $fd, $AddrSeek2 ); } else { fseek ( $fd, - 1, SEEK_CUR ); } while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) ) $ipAddr2 .= $char; } fclose ( $fd ); if (preg_match ( '/http/i', $ipAddr2 )) { $ipAddr2 = ''; } $ipaddr = "$ipAddr1 $ipAddr2"; $ipaddr = preg_replace ( '/CZ88\.NET/is', '', $ipaddr ); $ipaddr = preg_replace ( '/^\s*/is', '', $ipaddr ); $ipaddr = preg_replace ( '/\s*$/is', '', $ipaddr ); if (preg_match ( '/http/i', $ipaddr ) || $ipaddr == '') { $ipaddr = '- Unknown'; } return '- ' . $ipaddr; } /** +---------------------------------------------------------- * , +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $str * @param string $start * @param string $length * @param string $charset * @param string $suffix +---------------------------------------------------------- * @return string +----------------------------------------------------------
*/ function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { if(function_exists("mb_substr")) return mb_substr($str, $start, $length, $charset); elseif(function_exists('iconv_substr')) { return iconv_substr($str,$start,$length,$charset); } $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("",array_slice($match[0], $start, $length)); if($suffix) return $slice."…"; return $slice; } /** +---------------------------------------------------------- * , 6 +---------------------------------------------------------- * @param string $len * @param string $type * 0 1 * @param string $addChars +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function rand_string($len=6,$type='',$addChars='') { $str =''; switch($type) { case 0: $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars; break; case 1: $chars= str_repeat('0123456789',3); break; case 2: $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars; break; case 3: $chars='abcdefghijklmnopqrstuvwxyz'.$addChars; break; case 4: $chars = " ".$addChars; break; default : // oOLl 01, addChars $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars; break; } if($len>10 ) {// $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5); } if($type!=4) { $chars = str_shuffle($chars); $str = substr($chars,0,$len); }else{ // for($i=0;$i<$len;$i++){ $str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1); } } return $str; } /** +---------------------------------------------------------- * 4 +---------------------------------------------------------- * @param string $fmode +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function build_verify ($length=4,$mode=1) { return rand_string($length,$mode); } /** +---------------------------------------------------------- * B K M G T +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function byte_format($size, $dec=2) { $a = array("B", "KB", "MB", "GB", "TB", "PB"); $pos = 0; while ($size >= 1024) { $size /= 1024; $pos++; } return round($size,$dec)." ".$a[$pos]; } /** +---------------------------------------------------------- * UTF8 +---------------------------------------------------------- * @param string $string +---------------------------------------------------------- * @return Boolean +---------------------------------------------------------- */ function is_utf8($string) { return preg_match('%^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*$%xs', $string); } /** +---------------------------------------------------------- * +---------------------------------------------------------- * @param String $str * @param Boolean $show +---------------------------------------------------------- * @return String +---------------------------------------------------------- */ function highlight_code($str,$show=false) { if(file_exists($str)) { $str = file_get_contents($str); } $str = stripslashes(trim($str)); // The highlight string function encodes and highlights // brackets so we need them to start raw $str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str); // Replace any existing PHP tags to temporary markers so they don't accidentally // break the string out of PHP, and thus, thwart the highlighting. $str = str_replace(array('&lt;?php', '?&gt;', '\\'), array('phptagopen', 'phptagclose', 'backslashtmp'), $str); // The highlight_string function requires that the text be surrounded // by PHP tags. Since we don't know if A) the submitted text has PHP tags, // or B) whether the PHP tags enclose the entire string, we will add our // own PHP tags around the string along with some markers to make replacement easier later $str = '<?php //tempstart'."
".$str.'//tempend ?>'; // <? // All the magic happens here, baby! $str = highlight_string($str, TRUE); // Prior to PHP 5, the highlight function used icky font tags // so we'll replace them with span tags. if (abs(phpversion()) < 5) { $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str); $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str); } // Remove our artificially added PHP $str = preg_replace("#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>
", $str); $str = preg_replace("#\<code\>.+?//tempstart\<br />#is", "<code>
", $str); $str = preg_replace("#//tempend.+#is", "</span>
</code>", $str); // Replace our markers back to PHP tags. $str = str_replace(array('phptagopen', 'phptagclose', 'backslashtmp'), array('&lt;?php', '?&gt;', '\\'), $str); //<? $line = explode("<br />", rtrim(ltrim($str,'<code>'),'</code>')); $result = '<div class="code"><ol>'; foreach($line as $key=>$val) { $result .= '<li>'.$val.'</li>'; } $result .= '</ol></div>'; $result = str_replace("
", "", $result); if( $show!== false) { echo($result); }else { return $result; } } // html function h($text, $tags = null){ $text = trim($text); // $text = preg_replace('/<!--?.*-->/','',$text); // $text = preg_replace('/<\?|\?'.'>/','',$text); // js $text = preg_replace('/<script?.*\/script>/','',$text); $text = str_replace('[','&#091;',$text); $text = str_replace(']','&#093;',$text); $text = str_replace('|','&#124;',$text); // $text = preg_replace('/\r?
/','',$text); //br $text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text); $text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text); // , : on lang js while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1],$text); } while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1].$mat[3],$text); } if(empty($tags)) { $tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a'; } // HTML $text = preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text); // html $text = preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$text); // html while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){ $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text); } // while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text); } // while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){ $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text); } // < > $text = str_replace('<','&lt;',$text); $text = str_replace('>','&gt;',$text); $text = str_replace('"','&quot;',$text); // $text = str_replace('[','<',$text); $text = str_replace(']','>',$text); $text = str_replace('|','"',$text); // $text = str_replace(' ',' ',$text); return $text; } function ubb($Text) { $Text=trim($Text); //$Text=htmlspecialchars($Text); $Text=preg_replace("/\\t/is"," ",$Text); $Text=preg_replace("/\[h1\](.+?)\[\/h1\]/is","<h1>\\1</h1>",$Text); $Text=preg_replace("/\[h2\](.+?)\[\/h2\]/is","<h2>\\1</h2>",$Text); $Text=preg_replace("/\[h3\](.+?)\[\/h3\]/is","<h3>\\1</h3>",$Text); $Text=preg_replace("/\[h4\](.+?)\[\/h4\]/is","<h4>\\1</h4>",$Text); $Text=preg_replace("/\[h5\](.+?)\[\/h5\]/is","<h5>\\1</h5>",$Text); $Text=preg_replace("/\[h6\](.+?)\[\/h6\]/is","<h6>\\1</h6>",$Text); $Text=preg_replace("/\[separator\]/is","",$Text); $Text=preg_replace("/\[center\](.+?)\[\/center\]/is","<center>\\1</center>",$Text); $Text=preg_replace("/\[url=http:\/\/([^\[]*)\](.+?)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\2</a>",$Text); $Text=preg_replace("/\[url=([^\[]*)\](.+?)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\2</a>",$Text); $Text=preg_replace("/\[url\]http:\/\/([^\[]*)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\1</a>",$Text); $Text=preg_replace("/\[url\]([^\[]*)\[\/url\]/is","<a href=\"\\1\" target=_blank>\\1</a>",$Text); $Text=preg_replace("/\[img\](.+?)\[\/img\]/is","<img src=\\1>",$Text); $Text=preg_replace("/\[color=(.+?)\](.+?)\[\/color\]/is","<font color=\\1>\\2</font>",$Text); $Text=preg_replace("/\[size=(.+?)\](.+?)\[\/size\]/is","<font size=\\1>\\2</font>",$Text); $Text=preg_replace("/\[sup\](.+?)\[\/sup\]/is","<sup>\\1</sup>",$Text); $Text=preg_replace("/\[sub\](.+?)\[\/sub\]/is","<sub>\\1</sub>",$Text); $Text=preg_replace("/\[pre\](.+?)\[\/pre\]/is","<pre>\\1</pre>",$Text); $Text=preg_replace("/\[email\](.+?)\[\/email\]/is","<a href='mailto:\\1'>\\1</a>",$Text); $Text=preg_replace("/\[colorTxt\](.+?)\[\/colorTxt\]/eis","color_txt('\\1')",$Text); $Text=preg_replace("/\[emot\](.+?)\[\/emot\]/eis","emot('\\1')",$Text); $Text=preg_replace("/\[i\](.+?)\[\/i\]/is","<i>\\1</i>",$Text); $Text=preg_replace("/\[u\](.+?)\[\/u\]/is","<u>\\1</u>",$Text); $Text=preg_replace("/\[b\](.+?)\[\/b\]/is","<b>\\1</b>",$Text); $Text=preg_replace("/\[quote\](.+?)\[\/quote\]/is"," <div class='quote'><h5> :</h5><blockquote>\\1</blockquote></div>", $Text); $Text=preg_replace("/\[code\](.+?)\[\/code\]/eis","highlight_code('\\1')", $Text); $Text=preg_replace("/\[php\](.+?)\[\/php\]/eis","highlight_code('\\1')", $Text); $Text=preg_replace("/\[sig\](.+?)\[\/sig\]/is","<div class='sign'>\\1</div>", $Text); $Text=preg_replace("/\
/is","<br/>",$Text); return $Text; } // function build_count_rand ($number,$length=4,$mode=1) { if($mode==1 && $length<strlen($number) ) { // return false; } $rand = array(); for($i=0; $i<$number; $i++) { $rand[] = rand_string($length,$mode); } $unqiue = array_unique($rand); if(count($unqiue)==count($rand)) { return $rand; } $count = count($rand)-count($unqiue); for($i=0; $i<$count*3; $i++) { $rand[] = rand_string($length,$mode); } $rand = array_slice(array_unique ($rand),0,$number); return $rand; } function remove_xss($val) { // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as <java\0script> // note that you have to handle splits with
, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements, the user should never need these since they're normal characters // this prevents like <IMG SRC=@avascript:alert('XSS')> $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search .= '1234567890!@#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { // ;? matches the ;, which is optional // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars // @ @ search for the hex values $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; // @ @ 0{0,7} matches '0' zero to seven times $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } // now the only remaining whitespace attacks are \t,
, and \r
$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) { $val_before = $val; for ($i = 0; $i < sizeof($ra); $i++) { $pattern = '/'; for ($j = 0; $j < strlen($ra[$i]); $j++) { if ($j > 0) { $pattern .= '('; $pattern .= '(&#[xX]0{0,8}([9ab]);)'; $pattern .= '|'; $pattern .= '|(&#0{0,8}([9|10|13]);)'; $pattern .= ')*'; } $pattern .= $ra[$i][$j]; } $pattern .= '/i'; $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags if ($val_before == $val) { // no replacements were made, so exit the loop $found = false; } } } return $val; } /** +---------------------------------------------------------- * Tree +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $list * @param string $pid parent * @param string $level level +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) { // Tree $tree = array(); if(is_array($list)) { // $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] =& $list[$key]; } foreach ($list as $key => $data) { // parent $parentId = $data[$pid]; if ($root == $parentId) { $tree[] =& $list[$key]; }else{ if (isset($refer[$parentId])) { $parent =& $refer[$parentId]; $parent[$child][] =& $list[$key]; } } } } return $tree; } /** +---------------------------------------------------------- * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $list * @param string $field * @param array $sortby * asc desc nat +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ function list_sort_by($list,$field, $sortby='asc') { if(is_array($list)){ $refer = $resultSet = array(); foreach ($list as $i => $data) $refer[$i] = &$data[$field]; switch ($sortby) { case 'asc': // asort($refer); break; case 'desc':// arsort($refer); break; case 'nat': // natcasesort($refer); break; } foreach ( $refer as $key=> $val) $resultSet[] = &$list[$key]; return $resultSet; } return false; } /** +---------------------------------------------------------- * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $list * @param mixed $condition * array('name'=>$value) name=$value +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ function list_search($list,$condition) { if(is_string($condition)) parse_str($condition,$condition); // $resultSet = array(); foreach ($list as $key=>$data){ $find = false; foreach ($condition as $field=>$value){ if(isset($data[$field])) { if(0 === strpos($value,'/')) { $find = preg_match($value,$data[$field]); }elseif($data[$field]==$value){ $find = true; } } } if($find) $resultSet[] = &$list[$key]; } return $resultSet; } // Http function send_http_status($code) { static $_status = array( // Informational 1xx 100 => 'Continue', 101 => 'Switching Protocols', // Success 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', // Redirection 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', // 1.1 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', // 306 is deprecated but reserved 307 => 'Temporary Redirect', // Client Error 4xx 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', // Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); if(array_key_exists($code,$_status)) { header('HTTP/1.1 '.$code.' '.$_status[$code]); } } // // function service($name,$params=array()) { return X($name,$params=array(),'Service'); } // model function model($name,$params=array()) { return X($name,$params=array(),'Model'); } // function X($name,$params=array(),$domain='Service') { static $_service = array(); //if(empty($app)) $app = C('DEFAULT_APP'); if(isset($_service[$domain.'_'.$app.'_'.$name])) return $_service[$domain.'_'.$app.'_'.$name]; $class = $name.$domain; require_cache(SITE_PATH.'/addons/'.strtolower($domain).'s/'.$class.'.class.php'); // if(class_exists($class)){ $obj = new $class($params); $_service[$domain.'_'.$app.'_'.$name] = $obj; return $obj; }else{ throw_exception(L('_CLASS_NOT_EXIST_').':'.$class); } } ?>