/code/core/sociax/extend.php
PHP | 2071 lines | 1620 code | 93 blank | 358 comment | 141 complexity | 7a79da836c7e9be0ab83a12f6a232bc5 MD5 | raw file
Possible License(s): LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- // +----------------------------------------------------------------------
- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +----------------------------------------------------------------------
- // | Author: liu21st <liu21st@gmail.com>
- // +----------------------------------------------------------------------
- // $Id$
-
- /**
- +------------------------------------------------------------------------------
- * Think????? ??????????????????
- +------------------------------------------------------------------------------
- * @category Think
- * @package Common
- * @author liu21st <liu21st@gmail.com>
- * @version $Id$
- +------------------------------------------------------------------------------
- */
-
- /**
- * ?????IP??
- */
- 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);
- }
-
- /**
- +----------------------------------------------------------
- * ???????????????
- +----------------------------------------------------------
- * @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"))
- $slice = mb_substr($str, $start, $length, $charset);
- elseif(function_exists('iconv_substr')) {
- $slice = iconv_substr($str,$start,$length,$charset);
- }else{
- $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 && $str != $slice) return $slice."...";
- return $slice;
- }
- /**
- +----------------------------------------------------------
- * ???????????????
- +----------------------------------------------------------
- * @static
- * @access public
- +----------------------------------------------------------
- * @param string $str ????????
- * @param string $length ????
- * @param string $charset ????
- * @param string $suffix ??????
- +----------------------------------------------------------
- * @return string
- +----------------------------------------------------------
- */
- function mStr($str, $length, $charset="utf-8", $suffix=true){
- return msubstr($str, 0, $length, $charset, $suffix);
- }
- /**
- +----------------------------------------------------------
- * ???????????????? ????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;
- default :
- // ????????????oOLl???01???????addChars??
- $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
- break;
- }
- if($len>10 ) {//?????????????
- $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
- }
- $chars = str_shuffle($chars);
- $str = substr($chars,0,$len);
- 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('<', '>'), 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('<?php', '?>', '\\'), 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'."\n".$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>\n", $str);
- $str = preg_replace("#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str);
- $str = preg_replace("#//tempend.+#is", "</span>\n</code>", $str);
-
- // Replace our markers back to PHP tags.
- $str = str_replace(array('phptagopen', 'phptagclose', 'backslashtmp'), array('<?php', '?>', '\\'), $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("\n", "", $result);
- if( $show!== false) {
- echo($result);
- }else {
- return $result;
- }
- }
- /**
- * ???????html
- * @param string $text ???????
- * @param string $type ???string,???:INT,FLOAT,BOOL,WORD,ALNUM,CMD,BASE64,ARRAY,PATH,USERNAME
- * @param bool $tagsMethod true?????????????false????????????.
- * @param bool $attrMethod ??
- * @param array $tags ????????
- * @param array $attr ?????????
- * @param array $tagsBlack ????????
- * @param array $attrBlack ???????????
- */
- //function h($text,$type,$tagsMethod=true,$attrMethod=true,$xssAuto = 1,$tags=array(),$attr=array(),$tagsBlack=array(),$attrBlack=array()){
- // if(!class_exists('Security')){
- // vendor('libs.SamLib.filter.Security','','.class.php');
- // }
- // $inputConfig ['tagsMethod'] = 1; //???????
- // $inputConfig ['attrMethod'] = 1; //???????
- // $inputConfig ['xssAuto'] = 1 ; //???????
- // $inputConfig ['tagsFilter'] = array(); //???????
- // $inputConfig ['attrFilter'] = array(); //???????
- // $inputConfig ['tagBlacklist'] = array ('applet', 'body', 'bgsound', 'base', 'basefont', 'frame', 'frameset', 'head',
- // 'html', 'id', 'iframe', 'ilayer', 'layer', 'link', 'meta', 'name', 'script',
- // 'style', 'title', 'xml','vbscript','javascript','input','form','textarea','select','option','button'); //??????
- // $inputConfig ['attrBlacklist'] = array ('action', 'codebase', 'dynsrc', 'lowsrc','onclick','onload','onsubmit'); //??????
- //
- //
- //
- // $filter = Security::getInstance($type,$inputConfig);
- //
- // $filter->setTagsMethod($tagsMethod);
- // $filter->setAttrMethod($attrMethod);
- // $filter->setXss($xssAuto);
- // //???.?$tagsMethod=false?????
- // !empty($tags) && $filter->setTagsFilter($tags);
- // !empty($attr) && $filter->setAttrFilter($attr);
- // //???.?$tagsMethod=true????
- // !empty($tagsBlack) && $filter->setTagBlacklist($tagsBlack);
- // !empty($attrBlack) && $filter->setAttrBlacklist($attrBlack);
- // return $filter->inputFilter($text);
- //}
-
- //?????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('[','[',$text);
- $text = str_replace(']',']',$text);
- $text = str_replace('|','|',$text);
- //?????
- $text = preg_replace('/\r?\n/','',$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('<','<',$text);
- $text = str_replace('>','>',$text);
- $text = str_replace('"','"',$text);
- //???
- $text = str_replace('[','<',$text);
- $text = str_replace(']','>',$text);
- $text = str_replace('|','"',$text);
- //??????
- $text = str_replace(' ',' ',$text);
- return $text;
- }
-
- //?????
- function t($text,$parseBr=false){
- //$text = strip_tags($text);
- if(!$parseBr){
- $text = str_replace(array("\r","\n","\t"),' ',$text);
- }else{
- $text = nl2br($text);
- }
- $text = stripslashes($text);
- $text = htmlspecialchars($text, ENT_NOQUOTES,'UTF-8 ');
-
- return $text;
- }
-
- //??jsescape
- function unescape($str) {
- $str = rawurldecode($str);
- preg_match_all("/(?:%u.{4})|.+/",$str,$r);
- $ar = $r[0];
- foreach($ar as $k=>$v) {
- if(substr($v,0,2) == "%u" && strlen($v) == 6)
- $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
- }
- return join("",$ar);
- }
-
- //??UBB
- 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("/\\n/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 \n, \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,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
- }
-
- // now the only remaining whitespace attacks are \t, \n, 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,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($status) {
- 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]);
- }
- }
-
- // ????http header??
- function send_http_header($type='utf8'){
- //utf8,html,wml,xml,??????? ???header
- switch($type){
- case 'utf8':
- header("Content-type: text/html; charset=utf-8");
- break;
- case 'xml':
- header("Content-type: text/xml; charset=utf-8");
- break;
- }
- }
-
- // bmp????????
- function imagecreatefrombmp($fname) {
-
- $buf = @file_get_contents($fname);
-
- if(strlen($buf)<54) return false;
-
- $file_header=unpack("sbfType/LbfSize/sbfReserved1/sbfReserved2/LbfOffBits",substr($buf,0,14));
-
- if($file_header["bfType"]!=19778) return false;
- $info_header=unpack("LbiSize/lbiWidth/lbiHeight/sbiPlanes/sbiBitCountLbiCompression/LbiSizeImage/lbiXPelsPerMeter/lbiYPelsPerMeter/LbiClrUsed/LbiClrImportant",substr($buf,14,40));
- if($info_header["biBitCountLbiCompression"]==2) return false;
- $line_len=round($info_header["biWidth"]*$info_header["biBitCountLbiCompression"]/8);
- $x=$line_len%4;
- if($x>0) $line_len+=4-$x;
-
- $img=imagecreatetruecolor($info_header["biWidth"],$info_header["biHeight"]);
- switch($info_header["biBitCountLbiCompression"]){
- case 4:
- $colorset=unpack("L*",substr($buf,54,64));
- for($y=0;$y<$info_header["biHeight"];$y++){
- $colors=array();
- $y_pos=$y*$line_len+$file_header["bfOffBits"];
- for($x=0;$x<$info_header["biWidth"];$x++){
- if($x%2)
- $colors[]=$colorset[(ord($buf[$y_pos+($x+1)/2])&0xf)+1];
- else
- $colors[]=$colorset[((ord($buf[$y_pos+$x/2+1])>>4)&0xf)+1];
- }
- imagesetstyle($img,$colors);
- imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
- }
- break;
- case 8:
- $colorset=unpack("L*",substr($buf,54,1024));
- for($y=0;$y<$info_header["biHeight"];$y++){
- $colors=array();
- $y_pos=$y*$line_len+$file_header["bfOffBits"];
- for($x=0;$x<$info_header["biWidth"];$x++){
- $colors[]=$colorset[ord($buf[$y_pos+$x])+1];
- }
- imagesetstyle($img,$colors);
- imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
- }
- break;
- case 16:
- for($y=0;$y<$info_header["biHeight"];$y++){
- $colors=array();
- $y_pos=$y*$line_len+$file_header["bfOffBits"];
- for($x=0;$x<$info_header["biWidth"];$x++){
- $i=$x*2;
- $color=ord($buf[$y_pos+$i])|(ord($buf[$y_pos+$i+1])<<8);
- $colors[]=imagecolorallocate($img,(($color>>10)&0x1f)*0xff/0x1f,(($color>>5)&0x1f)*0xff/0x1f,($color&0x1f)*0xff/0x1f);
- }
- imagesetstyle($img,$colors);
- imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
- }
- break;
- case 24:
- for($y=0;$y<$info_header["biHeight"];$y++){
- $colors=array();
- $y_pos=$y*$line_len+$file_header["bfOffBits"];
- for($x=0;$x<$info_header["biWidth"];$x++){
- $i=$x*3;
- $colors[]=imagecolorallocate($img,ord($buf[$y_pos+$i+2]),ord($buf[$y_pos+$i+1]),ord($buf[$y_pos+$i]));
- }
- imagesetstyle($img,$colors);
- imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
- }
- break;
- default:
- return false;
- break;
- }
- return $img;
- }
- // bmp????????
- function imagebmp(&$im, $filename = '', $bit = 8, $compression = 0) {
- if (!in_array($bit, array(1, 4, 8, 16, 24, 32)))
- {
- $bit = 8;
-
- }
- else if ($bit == 32) // todo:32 bit
- {
- $bit = 24;
- }
-
- $bits = pow(2, $bit);
-
- // ?????
- imagetruecolortopalette($im, true, $bits);
- $width = imagesx($im);
- $height = imagesy($im);
- $colors_num = imagecolorstotal($im);
-
- if ($bit <= 8)
- {
- // ????
- $rgb_quad = '';
- for ($i = 0; $i < $colors_num; $i ++)
- {
- $colors = imagecolorsforindex($im, $i);
- $rgb_quad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0"; }
-
- // ????
- $bmp_data = '';
-
- // ???
- if ($compression == 0 || $bit < 8)
- {
- if (!in_array($bit, array(1, 4, 8)))
- {
- $bit = 8;
- }
-
- $compression = 0;
-
- // ????????4???????
-
-
- $extra = '';
- $padding = 4 - ceil($width / (8 / $bit)) % 4;
- if ($padding % 4 != 0)
- {
- $extra = str_repeat("\0", $padding);
- }
-
- for ($j = $height - 1; $j >= 0; $j --)
- {
- $i = 0;
- while ($i < $width)
- {
- $bin = 0;
- $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
-
- for ($k = 8 - $bit; $k >= $limit; $k -= $bit)
- {
- $index = imagecolorat($im, $i, $j);
- $bin |= $index << $k;
- $i ++;
- }
-
- $bmp_data .= chr($bin);
- }
-
- $bmp_data .= $extra;
- }
- }
- // RLE8 ??
- else if ($compression == 1 && $bit == 8)
- {
- for ($j = $height - 1; $j >= 0; $j --)
- {
- $last_index = "\0";
- $same_num = 0;
- for ($i = 0; $i <= $width; $i ++)
- {
- $index = imagecolorat($im, $i, $j);
- if ($index !== $last_index || $same_num > 255)
- {
- if ($same_num != 0)
- {
- $bmp_data .= chr($same_num) . chr($last_index);
- }
-
- $last_index = $index;
- $same_num = 1;
- }
- else
- {
- $same_num ++;
- }
- }
-
- $bmp_data .= "\0\0";
- }
-
- $bmp_data .= "\0\1";
- }
-
- $size_quad = strlen($rgb_quad);
- $size_data = strlen($bmp_data);
- }
- else
- {
- // ????????4???????
- $extra = '';
- $padding = 4 - ($width * ($bit / 8)) % 4;
- if ($padding % 4 != 0)
- {
- $extra = str_repeat("\0", $padding);
- }
-
- // ????
- $bmp_data = '';
-
- for ($j = $height - 1; $j >= 0; $j --)
- {
- for ($i = 0; $i < $width; $i ++)
- {
- $index = imagecolorat($im, $i, $j);
- $colors = imagecolorsforindex($im, $index);
-
- if ($bit == 16)
- {
- $bin = 0 << $bit;
-
- $bin |= ($colors['red'] >> 3) << 10;
- $bin |= ($colors['green'] >> 3) << 5;
- $bin |= $colors['blue'] >> 3;
-
- $bmp_data .= pack("v", $bin);
- }
- else
- {
- $bmp_data .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
- }
-
- // todo: 32bit;
- }
-
- $bmp_data .= $extra;
- }
-
- $size_quad = 0;
- $size_data = strlen($bmp_data);
- $colors_num = 0;
- }
-
- // ?????
- $file_header = "BM" . pack("V3", 54 + $size_quad + $size_data, 0, 54 + $size_quad);
-
- // ?????
- $info_header = pack("V3v2V*", 0x28, $width, $height, 1, $bit, $compression, $size_data, 0, 0, $colors_num, 0);
- // ????
- if ($filename != '')
- {
- $fp = fopen("test.bmp", "wb");
-
- fwrite($fp, $file_header);
- fwrite($fp, $info_header);
- fwrite($fp, $rgb_quad);
- fwrite($fp, $bmp_data);
- fclose($fp);
-
- return 1;
- }
-
- // ?????
- header("Content-Type: image/bmp");
- echo $file_header . $info_header;
- echo $rgb_quad;
- echo $bmp_data;
-
- return 1;
- }
-
- /**
- * ???????
- *
- * @param int $sTime ??????
- * @param string $type ??. normal | mohu | full | ymd | other
- * @param string $alt ???
- * @return string
- */
- function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
- //sTime=????cTime=?????dTime=???
- $cTime = time();
- $dTime = $cTime - $sTime;
- $dDay = intval(date("Ymd",$cTime)) - intval(date("Ymd",$sTime));
- $dYear = intval(date("Y",$cTime)) - intval(date("Y",$sTime));
- //normal?n???n????n??????
- if($type=='normal'){
- if( $dTime < 60 ){
- return $dTime."??";
- }elseif( $dTime < 3600 ){
- return intval($dTime/60)."???";
- }elseif( $dTime >= 3600 && $dDay == 0 ){
- //return intval($dTime/3600)."???";
- return '??'.date('H:i',$sTime);
- }elseif($dYear==0){
- return date("m?d? H:i",$sTime);
- }else{
- return date("Y-m-d H:i",$sTime);
- }
- }elseif($type=='mohu'){
- if( $dTime < 60 ){
- return $dTime."??";
- }elseif( $dTime < 3600 ){
- return intval($dTime/60)."???";
- }elseif( $dTime >= 3600 && $dDay == 0 ){
- return intval($dTime/3600)."???";
- }elseif( $dDay > 0 && $dDay<3 ){
- return intval($dDay)."??";
- }elseif( $dDay >= 3 ){
- return "n??";
- }elseif( $dDay >= 30 ){
- return "n???";
- }
- //full: Y-m-d , H:i:s
- }elseif($type=='full'){
- return date("Y-m-d , H:i:s",$sTime);
- }elseif($type=='ymd'){
- return date("Y-m-d",$sTime);
- }else{
- if( $dTime < 60 ){
- return $dTime."??";
- }elseif( $dTime < 3600 ){
- return intval($dTime/60)."???";
- }elseif( $dTime >= 3600 && $dDay == 0 ){
- return intval($dTime/3600)."???";
- }elseif($dYear==0){
- return date("Y-m-d H:i:s",$sTime);
- }else{
- return date("Y-m-d H:i:s",$sTime);
- }
- }
- }
-
- //??????
- function getUserName($uid,$lang='zh'){
- static $_MapName = array();
- if(!isset($_MapName[$uid])){
- if(is_numeric($uid)){
- $map['uid'] = $uid;
- }else{
- $map['uname'] = $uid;
- }
- $userinfo = M('User')->where($map)->field('uname')->find();
- $_MapName[$uid] = $userinfo['uname'];
- }
- return htmlspecialchars($_MapName[$uid]);
- }
-
- //?????????
- function getUserSpace($uid,$class,$target,$text){
- static $_USERINFO = array();
- if(!isset($_USERINFO[$uid])){
- $map['uid'] = $uid;
- $_USERINFO[$uid] = M('User')->where($map)->field('uname,domain')->find();
- }
- $class = ($class)?$class:'username';
- $target = ($target)?$target:'_self';
- $text = ($text)?$text:$_USERINFO[$uid]['uname'];
-
- preg_match('|{(.*?)}|isU',$text,$t);
-
- if($t){
- if($t['1']=='uname'){
- $text = str_replace("{uname}", $_USERINFO[$uid]['uname'], $text);
- }else{
- $face = preg_replace("/{uavatar}|{uavatar\=(.*?)}/e", "getUserFace(\$uid, '\\1')", $text);
- //$face = preg_replace("/{uavatar}$/e", 'getUserFace(\$uid)', $text);
- $text = "<img src=".$face.">";
- }
- }
-
- if($_USERINFO[$uid]['domain']){
- $url = SITE_URL.'/'.$_USERINFO[$uid]['domain'];
- }else{
- $url = U('home/space/index',array('uid'=>$uid));
- }
- return "<a href='{$url}' class='{$class}' target='{$target}'>$text</a>";
-
- }
-
- //????????
- function getUserInfo($uid,$uname,$mid,$status=false){
- $data = array();
- if ( isset($uid) && $uid!=''){
- $map['uid'] = $uid;
- }elseif( isset($uname) && $uname!=''){
- $map['uname'] = $uname;
- }
- $user = M('user')->where($map)->find();
- if(!user) return false;
-
- $data['uid'] = $user['uid'];
- $data['uname'] = $user['uname'];
- $data['province'] = $user['province'];
- $data['city'] = $user['city'];
- $data['location'] = $user['location'];
- $data['face'] = getUserFace($user['uid']);
- $data['sex'] = getSex( $user['sex'] );
- $data['weibo_count'] = M('weibo')->where('uid='.$user['uid'])->count();
- $data['favorite_count'] = M('weibo_favorite')->where('uid='.$user['uid'])->count();
- $data['followers_count'] = M('weibo_follow')->where('fid='.$user['uid'].' AND type=0')->count();
- $data['followed_count'] = M('weibo_follow')->where('uid='.$user['uid'].' AND type=0')->count();
- $data['is_followed'] = getFollowState($mid,$uid);
- if($status){
- $status = M('weibo')->where('uid='.$user['uid'])->order('weibo_id DESC')->find();
- $data['status'] = ($status)?D('Weibo','weibo')->getOneApi('',$status):'';
- }
- return $data;
- }
-
- /**
- * ??????
- *
- * @param int $uid ??ID
- * @param int $fid ??ID
- * @return string eachfollow:???? | havefollow:??? | unfollow:??? | ?:?????
- */
- function getFollowState($uid,$fid){
- if($mid==$fid) return '';
-
- if(M('weibo_follow')->where("(uid=$uid AND fid=$fid AND type=0) OR (uid=$fid AND fid=$uid AND type=0)")->count()==2 ){
- return 'eachfollow';
- }elseif( M('weibo_follow')->where("uid=$uid AND fid=$fid AND type=0")->count() ){
- return 'havefollow';
- }else{
- return 'unfollow';
- }
- }
-
- /**
- * ??????????????
- *
- * @param int $weibo_id ??ID
- * @param int $uid ??ID
- * @return int ?????1, ????0
- */
- function isfavorited($weibo_id,$uid){
- return M('weibo_favorite')->where("weibo_id=$weibo_id AND uid=$uid")->count();
- }
-
- /**
- * ????????
- *
- * @param int $uid ??ID
- * @param int $fid ??ID
- * @return int
- */
- function isBlackList($uid,$fid){
- return M('user_blacklist')->where("uid=$uid AND fid=$fid")->count();
- }
-
- /**
- * ??????
- *
- * @param int $uid ??ID
- * @param string $size ???? m:?? | s:?? | ??:??
- * @return string ???URL??
- */
- function getUserFace($uid,$size){
- $size = ($size)?$size:'m';
- if($size=='m'){
- $type = 'middle.jpg';
- }elseif ($size=='s'){
- $type = 'small.jpg';
- }else{
- $type = 'big.jpg';
- }
- $userface = SITE_PATH.'/data/uploads/avatar/'.$uid.'/'.$type;
- if(is_file($userface)){
- return SITE_URL."/data/uploads/avatar/$uid/$type";
- }else{
- return THEME_URL."/images/user_pic.gif";
- }
- }
-
- //?????
- function getUserGroupIcon($uid){
- return Model('UserGroup')->getUserGroupIcon($uid);
- }
-
- //??????
- /*
- ?? 0?100 ??
- ?? 101?500 ??
- ?? 501?1000 ??
- ?? 1001?2500 ??
- ?? 2501?5000 ??
- ?? 5001?8000 ?????
- ?? 8001?12000 ?????
- ?? 12001?16000 ????
- ?? 16001?20000 ????
- ?? 20001?25000 ??
- ??? 25001?35000 ??
- ??? 35001?50000 ??
- ??? 50001?80000 ??
- ??? 80001?120000 ??
- ??? 120001?180000 ??
- ??? 180001?250000 ???
- ??? 250001?400000 ???
- ??? 400001? ????
- */
- function getUserTitle($uid,$exp=false) {
- $title = array(
- '0-100'=>'??',
- '101-500'=>'??',
- '501-1000'=>'??',
- '1001-2500'=>'??',
- '2501-5000'=>'??',
- '5001-8000'=>'?????',
- '8001-12000'=>'?????',
- '12001-16000'=>'????',
- '16001-20000'=>'????',
- '20001-25000'=>'??',
- '25001-35000'=>'??',
- '35001-50000'=>'??',
- '50001-80000'=>'??',
- '80001-120000'=>'??',
- '120001-180000'=>'??',
- '180001-250000'=>'???',
- '250001-400000'=>'???',
- '400001-99999999999'=>'????',
- );
- //????????
- if($exp===false){
- $space = M()->table(C('DB_PREFIX').'space')->field('credit_exp')->where(" uid = '$uid' ")->find();
- $exp = $space['credit_exp'];
- if(!$exp) return false;
- }
- //??????
- foreach($title as $k=>$v){
- $f = explode('-',$k);
- if($exp>=$f[0] && $exp<=$f[1]){
- return $v;
- }
- }
- return false;
- }
-
- /**
- * ?????????????????????????????????
- * @param $pArray ??????
- * @param $pKey ???????
- * @return ????????
- */
- function getSubByKey($pArray, $pKey="", $pCondition=""){
- $result = array();
- foreach($pArray as $temp_array){
- if(is_object($temp_array)){
- $temp_array = (array) $temp_array;
- }
- if((""!=$pCondition && $temp_array[$pCondition[0]]==$pCondition[1]) || ""==$pCondition) {
- $result[] = (""==$pKey) ? $temp_array : isset($temp_array[$pKey]) ? $temp_array[$pKey] : "";
- }
- }
- return $result;
- }
-
- function getMultiArraySubByKey($pArray,$pKey=""){
- $result = array();
- $result = getSubByKey($temp_array,$pKey);
- foreach($pArray as $temp_array){
- if(is_object($temp_array)){
- $temp_array = (array) $temp_array;
- }
- foreach ( $temp_array as $value){
- if(is_array($value)){
- $result = array_merge(getSubByKey($value,$pKey),$result);
- }
- }
- }
- return $result;
- }
-
- /**
- * ???????????????????????????sql??????
- * @param $pArray1 ??????
- * @param $pArray2 ??????
- * @param $pFields ?????????
- * @param $pType ????????????????????????????????????????
- * @return ??????
- */
- function arrayJoin($pArray1, $pArray2, $pFields, $pType="left"){
- $result = array();
- foreach($pArray1 as $row1)
- {
- $is_join = false;
- foreach($pArray2 as $row2)
- {
- if(canJoin($row1, $row2, $pFields))
- {
- $result[] = array_merge($row2, $row1);
- $is_join = true;
- break;
- }
- }
-
- //?????????????????
- if($is_join==false && $pType=="left")
- {
- $result[] = $row1;
- }
- }
- return $result;
- }
-
- /**
- * ?????????????
- * @author ??
- * @createTime 2004-07-15
- * @param $pRow1 ?????
- * @param $pRow2 ?????
- * @param $pFields ?????????
- * @return ??????
- */
- function canJoin($pRow1, $pRow2, $pFields)
- {
- $field_array = explode(",", $pFields);
- foreach($field_array as $key)
- {
- if(strtolower($pRow1[$key])!=strtolower($pRow2[$key]))
- return false;
- }
- return true;
- }
-
-
- /**
- * ???????????
- *
- * ???
- * @code php
- * $rows = array(
- * array('id' => 1, 'value' => '1-1', 'parent' => 1),
- * array('id' => 2, 'value' => '2-1', 'parent' => 1),
- * array('id' => 3, 'value' => '3-1', 'parent' => 1),
- * array('id' => 4, 'value' => '4-1', 'parent' => 2),
- * array('id' => 5, 'value' => '5-1', 'parent' => 2),
- * array('id' => 6, 'value' => '6-1', 'parent' => 3),
- * );
- *
- * $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
- * dump($rows);
- * // ??????
- * // array(
- * // array('id' => 6, 'value' => '6-1', 'parent' => 3),
- * // array('id' => 5, 'value' => '5-1', 'parent' => 2),
- * // array('id' => 4, 'value' => '4-1', 'parent' => 2),
- * // array('id' => 3, 'value' => '3-1', 'parent' => 1),
- * // array('id' => 2, 'value' => '2-1', 'parent' => 1),
- * // array('id' => 1, 'value' => '1-1', 'parent' => 1),
- * // )
- * @endcode
- *
- * @param array $array ??????
- * @param string $keyname ????
- * @param int $dir ????
- *
- * @return array ??????
- */
- function sortByCol($array, $keyname, $dir = SORT_ASC)
- {
- return sortByMultiCols($array, array($keyname => $dir));
- }
-
- /**
- * ??????????????????? SQL ???? ORDER BY
- *
- * ???
- * @code php
- * $rows = Helper_Array::sortByMultiCols($rows, array(
- * 'parent' => SORT_ASC,
- * 'name' => SORT_DESC,
- * ));
- * @endcode
- *
- * @param array $rowset ??????
- * @param array $args ????
- *
- * @return array ??????
- */
- function sortByMultiCols($rowset, $args)
- {
- $sortArray = array();
- $sortRule = '';
- foreach ($args as $sortField => $sortDir)
- {
- foreach ($rowset as $offset => $row)
- {
- $sortArray[$sortField][$offset] = $row[$sortField];
- }
- $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
- }
- if (empty($sortArray) || empty($sortRule)) { return $rowset; }
- eval('array_multisort(' . $sortRule . '$rowset);');
- return $rowset;
- }
-
-
- /**
- * ???????Email
- *
- * @param int $uid
- */
- function getUserEmail($uid) {
- $map ['uid'] = $uid;
- return model ( 'User' )->where ( $map )->getField ( 'email' );
- }
-
- /**
- * ??sexid????
- *
- * @param int $sexid
- */
- function getSex($sexid) {
- return ($sexid == '1') ? "?" : "?";
- }
- function matchImages($content = '') {
- $src = array ();
- preg_match_all ( '/<img.*src=(.*)[>|\\s]/iU', $content, $src );
- if (count ( $src [1] ) > 0) {
- foreach ( $src [1] as $v ) {
- $images [] = trim ( $v, "\"'" ); //??????? ' "
- }
- return $images;
- } else {
- return false;
- }
- }
-
- function matchReplaceImages($content = ''){
- $image = preg_replace_callback('/<img.*src=(.*)[>|\\s]/iU',"matchReplaceImagesOnce",$content);
- return $image;
- }
- function matchReplaceImagesOnce($matches){
- $matches[1] = str_replace('"','',$matches[1]);
- return sprintf("<a class='thickbox' href='%s'>%s</a>",$matches[1],$matches[0]);
- }
-
- function getShort($str,$length=40) {
- $str = htmlspecialchars($str);
- $str = strip_tags($str);
- $str = htmlspecialchars_decode($str);
- $strlenth = 0;
- $out = '';
- preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match);
- foreach($match[0] as $v){
- preg_match("/[\xe0-\xef][\x80-\xbf]{2}/",$v, $matchs);
- if(!empty($matchs[0])){
- $strlenth += 1;
- }elseif(is_numeric($v)){
- $strlenth += 0.545;
- }else{
- $strlenth += 0.475;
- }
-
- if($strlenth>$length){
- break;
- }
-
- $output .= $v;
- }
- return $output;
- }
-
- //????????????????
- function infoCss($info){
- if(empty($info)) return '';
- else return "<div class='ico_cite C_C'>$info<span class='ico_cite2'></span></div>";
- }
-
- //????
- function jiami($txt, $key = null) {
- if (empty ( $key ))
- $key = C ( 'SECURE_CODE' );
- $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+";
- $nh = rand ( 0, 64 );
- $ch = $chars [$nh];
- $mdKey = md5 ( $key . $ch );
- $mdKey = substr ( $mdKey, $nh % 8, $nh % 8 + 7 );
- $txt = base64_encode ( $txt );
- $tmp = '';
- $i = 0;
- $j = 0;
- $k = 0;
- for($i = 0; $i < strlen ( $txt ); $i ++) {
- $k = $k == strlen ( $mdKey ) ? 0 : $k;
- $j = ($nh + strpos ( $chars, $txt [$i] ) + ord ( $mdKey [$k ++] )) % 64;
- $tmp .= $chars [$j];
- }
- return $ch . $tmp;
- }
- //????
- function jiemi($txt, $key = null) {
- if (empty ( $key ))
- $key = C ( 'SECURE_CODE' );
- $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+";
- $ch = $txt [0];
- $nh = strpos ( $chars, $ch );
- $mdKey = md5 ( $key . $ch );
- $mdKey = substr ( $mdKey, $nh % 8, $nh % 8 + 7 );
- $txt = substr ( $txt, 1 );
- $tmp = '';
- $i = 0;
- $j = 0;
- $k = 0;
- for($i = 0; $i < strlen ( $txt ); $i ++) {
- $k = $k == strlen ( $mdKey ) ? 0 : $k;
- $j = strpos ( $chars, $txt [$i] ) - $nh - ord ( $mdKey [$k ++] );
- while ( $j < 0 )
- $j += 64;
- $tmp .= $chars [$j];
- }
- return base64_decode ( $tmp );
- }
-
- /**
- * Format a mySQL string correctly for safe mySQL insert (no mater if magic quotes are on or not)
- */
- function escape($str) {
- return mysql_escape_string(stripslashes($str));
- }
-
- /**
- * ????IP?????
- *
- * @param string $ip
- * @return string
- */
- function convert_ip($ip) {
- $return = '';
- 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 {
- $tinyipfile = ADDON_PATH . '/libs/misc/tinyipdata.dat';
- $fullipfile = ADDON_PATH . '/libs/misc/wry.dat';
- if(@file_exists($tinyipfile)) {
- $return = convert_ip_tiny($ip, $tinyipfile);
- } elseif(@file_exists($fullipfile)) {
- $return = convert_ip_full($ip, $fullipfile);
- }
- }
- }
- $return = iconv('GBK', 'UTF-8', $return);
- return $retu…
Large files files are truncated, but you can click here to view the full file