12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631 |
- <?php
- /*
- * global.php
- * 公共函数库
- * 更新: Jacky.Chen 2013/10/20 15:45
- */
- /*
- * 返回经addslashes处理过的字符串或数组
- * @param $string 需要处理的字符串或数组
- * @return mixed
- */
- function new_add_slashes($string)
- {
- if(!is_array($string))return addslashes($string);
- foreach($string as $key=>$val)
- {
- $string[$key] = new_add_slashes($val);
- }
- return $string;
- }
- /*
- * 返回经stripslashes处理过的字符串或数组
- * @param $string 需要处理的字符串或数组
- * @return mixed
- */
- function new_stripslashes($string) {
- if(!is_array($string)) return stripslashes($string);
- foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
- return $string;
- }
- /*
- * 返回经htmlspecialchars处理过的字符串或数组
- * @param $obj 需要处理的字符串或数组
- * @return mixed
- */
- function new_htmlspecialchars($string) {
- if(!is_array($string)) return htmlspecialchars($string);
- foreach($string as $key => $val) $string[$key] = new_htmlspecialchars($val);
- return $string;
- }
- //filterkeys 指定了排除在外的键值
- function safe_replace_array($array,$filterKeys=array())
- {
- foreach($array as $k=>$v)
- {
- if(!in_array($k,$filterKeys)) $array[$k] = safe_replace($v);
- }
- return $array;
- }
- /*
- * 安全过滤函数
- * @parame $string
- * @return string
- */
- function safe_replace($string)
- {
- $string = str_replace('%20','',$string);
- $string = str_replace('%27','',$string);
- $string = str_replace('%2527','',$string);
- $string = str_replace('*','',$string);
- $string = str_replace('"','"',$string);
- $string = str_replace("'",'',$string);
- $string = str_replace('"','',$string);
- $string = str_replace(';','',$string);
- $string = str_replace('>','>',$string);
- $string = str_replace('<','<',$string);
- $string = str_replace('{','',$string);
- $string = str_replace('}','',$string);
- $string = str_replace('\\','',$string);
- return $string;
- }
- /**
- * xss过滤函数
- *
- * @param $string
- * @return string
- */
- function remove_xss($string) {
- $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
- $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
- $parm2 = 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');
- $parm = array_merge($parm1, $parm2);
- for ($i = 0; $i < sizeof($parm); $i++) {
- $pattern = '/';
- for ($j = 0; $j < strlen($parm[$i]); $j++) {
- if ($j > 0) {
- $pattern .= '(';
- $pattern .= '(&#[x|X]0([9][a][b]);?)?';
- $pattern .= '|(�([9][10][13]);?)?';
- $pattern .= ')?';
- }
- $pattern .= $parm[$i][$j];
- }
- $pattern .= '/i';
- $string = preg_replace($pattern, '', $string);
- }
- return $string;
- }
- /**
- * 转义 javascript 代码标记
- *
- * @param $str
- * @return mixed
- */
- function trim_script($str) {
- if(is_array($str)){
- foreach ($str as $key => $val){
- $str[$key] = trim_script($val);
- }
- }else{
- $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str );
- $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str );
- $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str );
- $str = str_replace ( 'javascript:', 'javascript:', $str );
- }
- return $str;
- }
- /*
- * 过滤ASCII码从0-28的控制字符
- * @return String
- */
- function trim_unsafe_control_chars($str) {
- $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
- return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
- }
- /*
- * 格式化文本域内容
- *
- * @param $string 文本域内容
- * @return string
- */
- function trim_textarea($string) {
- $string = nl2br ( str_replace ( ' ', ' ', $string ) );
- return $string;
- }
- /**
- * 安全过滤表单输入
- *
- * @param $string
- * @return string
- */
- function safe_filter_input($string) {
- if(!is_array($string)) {
- $string = trim($string);
- $string = stripslashes($string);
- $string = htmlspecialchars($string);
- return $string;
- }
- foreach($string as $key => $val) {
- $val = trim($val);
- $val = stripslashes($val);
- $val = htmlspecialchars($val);
- $string[$key] = $val;
- }
- return $string;
- }
- /*
- * 将文本格式成适合js输出的字符串
- * @param string $string 需要处理的字符串
- * @param intval $isjs 是否执行字符串格式化,默认为执行
- * @return string 处理后的字符串
- */
- function format_js($string, $isjs = 1) {
- $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
- return $isjs ? 'document.write("'.$string.'");' : $string;
- }
- /*
- * 获取当前页面完整URL地址
- */
- function get_url() {
- $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
- $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
- $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
- $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
- return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
- }
- /**
- * 字符串截取,支持中英文
- * @param $str
- * @param int $start
- * @param $length
- * @param string $charset
- * @param bool $suffix
- * @return false|string
- * @author 肆月
- */
- function str_cut($str, $start = 0, $length, $dot = '...')
- {
- $charset = CHARSET;
- if (function_exists("mb_substr")) {
- if ($dot) {
- if (strlen($str) > $length)
- return mb_substr($str, $start, $length, $charset) . $dot;
- else
- return mb_substr($str, $start, $length, $charset);
- } else {
- return mb_substr($str, $start, $length, $charset);
- }
- } elseif (function_exists('iconv_substr')) {
- if ($dot) {
- if (strlen($str) > $length)
- return iconv_substr($str, $start, $length, $charset). $dot;
- else
- return iconv_substr($str, $start, $length, $charset);
- } else {
- return iconv_substr($str, $start, $length, $charset);
- }
- }
- }
- //隐藏用户名中间字符仅保留头尾
- function hide_user_name($user_name, $repeatStr = '*', $encode = 'utf-8')
- {
- if (empty($user_name)) {
- return '***';
- }
- $length = mb_strlen($user_name, $encode);
- $firstStr = mb_substr($user_name, 0, 1, $encode);
- $lastStr = mb_substr($user_name, -1, 1, $encode);
- if($length ==1){
- return $user_name;
- }
- return $length == 2 ? $firstStr . str_repeat($repeatStr, $length - 1) : $firstStr . str_repeat($repeatStr, $length - 2) . $lastStr;
- }
- /*
- * 获取请求ip
- * @return ip地址(整数形式)
- */
- function ip() {
- if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
- $ip = getenv('HTTP_CLIENT_IP');
- } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
- $ip = getenv('HTTP_X_FORWARDED_FOR');
- } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
- $ip = getenv('REMOTE_ADDR');
- } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- return preg_match ( '/[\d\.]{7,23}/', $ip, $matches ) ? ip2long($matches [0]) : 0;
- }
- /*
- * 程序执行时间
- * @return int 单位ms
- *
- */
- function execute_time() {
- $stime = explode ( ' ', SYS_START_TIME );
- $etime = explode ( ' ', microtime () );
- return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
- }
- /*
- * 产生随机字符串
- * @param int $length 输出长度
- * @param string $chars 可选的 ,默认为 0123456789
- * @return string 字符串
- *
- */
- function random($length, $chars = '0123456789') {
- $hash = '';
- $max = strlen($chars) - 1;
- for($i = 0; $i < $length; $i++) {
- $hash .= $chars[mt_rand(0, $max)];
- }
- return $hash;
- }
- /*
- * 将字符串转换为数组
- * @param string $data 字符串
- * @return array 返回数组格式,如果,data为空,则返回空数组
- *
- */
- function string2array($data) {
- $array = array();
- if($data == '') return array();
- eval("\$array = $data;");
- return $array;
- }
- /**
- * 将数组转换为字符串
- *
- * @param array $data 数组
- * @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
- * @return string 返回字符串,如果,data为空,则返回空
- */
- function array2string($data, $isformdata = 1) {
- if($data == '') return '';
- if($isformdata) $data = new_stripslashes($data);
- return var_export($data, TRUE);
- }
- /*
- * 转换字节数为其他单位
- * @param string $filesize 字节大小
- * @return string 返回大小
- */
- function sizecount($filesize) {
- if ($filesize >= 1073741824) {
- $filesize = round($filesize / 1073741824 * 100) / 100 .'GB';
- } elseif ($filesize >= 1048576) {
- $filesize = round($filesize / 1048576 * 100) / 100 .'MB';
- } elseif($filesize >= 1024) {
- $filesize = round($filesize / 1024 * 100) / 100 . 'KB';
- } else {
- $filesize = $filesize.'Bytes';
- }
- return $filesize;
- }
- /**
- * @param int $num 要转换的阿拉伯数字
- * @return string 转换成的字符串
- */
- function numconvert($num)
- {
- if ($num >= 100000000) {
- $num = round($num / 100000000, 1) . '亿+';
- } else if ($num >= 10000000) {
- $num = round($num / 10000000, 1) . '万+';
- } else if ($num >= 10000) {
- $num = round($num / 10000, 1) . '万+';
- }
- return $num;
- }
- /*
- * 对用户密码进行加密,用于后台
- * @parame $password
- * @parame $encrypt //加密因子
- * @return string
- *
- */
- function password($password,$encrypt='')
- {
-
- $pwd = array();
- $pwd['encrypt'] = $encrypt?$encrypt:random(6, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
- $pwd['password'] = md5(md5($password).$pwd['encrypt']);
- return $encrypt?$pwd['password']:$pwd;
- }
- /*
- * 判断是否为非法输入
- * @parame $string
- * return boolean
- *
- */
- function is_bad_word($string)
- {
- $array = array('"','\\',' ','&','*','#','/','<','>','\r','\t','\n','#',"'");
- foreach($array as $value)
- {
- if(strpos($string,$value)!==false)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- /*
- * 对数据进行编码转换
- * @param array/string $data 数组
- * @param string $input 需要转换的编码
- * @param string $output 转换后的编码
- *
- */
- function array_iconv($data,$input='gbk',$output='utf-8')
- {
- if(!is_array($data))
- {
- $data = iconv($input,$output."//IGNORE",$data);
- }
- else
- {
- foreach($data as $key=>$value)
- {
- $data[$key] = iconv($input,$output."//IGNORE",$value);
- }
- }
- return $data;
- }
- /**
- * 字符串加密、解密函数
- * @param string $txt 字符串
- * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
- * @param string $key 密钥:数字、字母、下划线
- * @param string $expiry 过期时间
- * @return string
- *
- */
- function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
- $key_length = 4;
- $key = md5($key != '' ? $key : AUTH_KEY);
- $fixedkey = md5($key);
- $egiskeys = md5(substr($fixedkey, 16, 16));
- $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
- $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
- $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
- $i = 0; $result = '';
- $string_length = strlen($string);
- for ($i = 0; $i < $string_length; $i++){
- $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
- }
- if($operation == 'ENCODE') {
- return $runtokey . str_replace('=', '', base64_encode($result));
- } else {
- if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
- return substr($result, 26);
- } else {
- return '';
- }
- }
- }
- // 函数返回当前 Unix 时间戳和微秒数
- function getmicrotime() {
- list($usec, $sec) = explode(" ",microtime());
- return ((float)$usec + (float)$sec);
- }
- /*
- * 取得文件扩展
- * @param $filename 文件名
- * @return 扩展名
- *
- */
- function fileext($filename) {
- return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
- }
- /**
- * 查询字符是否存在于某字符串
- *
- * @param $haystack 字符串
- * @param $needle 要查找的字符
- * @return bool
- */
- function str_exists($haystack, $needle)
- {
- return !(strpos($haystack, $needle) === FALSE);
- }
- //判断远程文件
- function check_remote_file_exists($url)
- {
- $handle = @fopen($url, 'r');
- if(!$handle){
- return false;
- }else{
- return true;
- }
- }
- function check_remote_file_exists1($url)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
- curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
- // 不取回数据
- curl_setopt($curl, CURLOPT_NOBODY, true);
- // 发送请求
- $result = curl_exec($curl);
- $found = false;
- // 如果请求没有发送失败
- if ($result !== false)
- {
- // 再检查http响应码是否为200
- $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- if ($statusCode == 200)
- {
- $found = true;
- }
- }
- curl_close($curl);
- return $found;
- }
- //获取远程文件大小
- function remote_file_size($url)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
- curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
- // 不取回数据
- curl_setopt($curl, CURLOPT_NOBODY, true);
- // 发送请求
- $result = curl_exec($curl);
- $size = 0;
- // 如果请求没有发送失败
- if ($result !== false)
- {
- $size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
- }
- curl_close($curl);
- return $size;
- }
- /*
- * 判断是否为图片
- *
- */
- function is_image($file) {
- $ext_arr = array('jpg','gif','png','bmp','jpeg','tiff');
- $ext = fileext($file);
- return in_array($ext,$ext_arr) ? $ext_arr :false;
- }
- /*
- * 判断是否为视频
- *
- */
- function is_video($file) {
- $ext_arr = array('rm','mpg','avi','mpeg','wmv','flv','asf','rmvb');
- $ext = fileext($file);
- return in_array($ext,$ext_arr) ? $ext_arr :false;
- }
- //保存远程图片
- function save_remote_file($remote_url,$local_path)
- {
- $file = https_request($remote_url);
- file_put_contents($local_path,$file);
- return $local_path;
- }
- //根据路径判断是否网络文件
- function is_net_file($url)
- {
- if(preg_match('/^https?.*$/',$url))//网络文件
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- /*
- * 检查id是否存在于数组中
- * @param $id
- * @param $ids
- * @param $s
- *
- */
- function check_in($id, $ids = '', $s = ',') {
- if(!$ids) return false;
- $ids = explode($s, $ids);
- return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
- }
- //判断目录是否可写
- function dir_writeable($dir) {
- $writeable = 0;
- if(is_dir($dir)) {
- if($fp = @fopen("$dir/chkdir.test", 'w')) {
- @fclose($fp);
- @unlink("$dir/chkdir.test");
- $writeable = 1;
- } else {
- $writeable = 0;
- }
- }
- return $writeable;
- }
- /**
- * 图片水印:gif,jpeg,png
- * @param $imgSrc
- * @param $markImg:水印图
- * @param $markPos:水印位置 0:随机位置,在1~9之间随机选取一个位置
- 1:顶部居左 2:顶部居中 3:顶部居右 4:左边居中
- 5:图片中心 6:右边居中 7:底部居左 8:底部居中 9:底部居右
- */
- function set_img_water($imgSrc,$markImg,$markQty=100,$markPos=9){
- if(intval($markQty)==0)$markQty=100;
- $srcInfo = @getimagesize($imgSrc);
- $srcImg_w = $srcInfo[0];
- $srcImg_h = $srcInfo[1];
- $srcim = null; $markim = null;
- switch ($srcInfo[2])
- {
- case 1:
- $srcim =imagecreatefromgif($imgSrc); break;
- case 2:
- $srcim =imagecreatefromjpeg($imgSrc); break;
- case 3:
- $srcim =imagecreatefrompng($imgSrc); break;
- default:
- die('unsupport file type'); exit();
- }
- if(!file_exists($markImg) || empty($markImg)){return;}
-
- $markImgInfo = @getimagesize($markImg);
- $markImg_w = $markImgInfo[0];
- $markImg_h = $markImgInfo[1];
-
- if($srcImg_w < $markImg_w || $srcImg_h < $markImg_h){return false;}
-
- switch ($markImgInfo[2])
- {
- case 1:
- $markim =imagecreatefromgif($markImg); break;
- case 2:
- $markim =imagecreatefromjpeg($markImg); break;
- case 3:
- $markim =imagecreatefrompng($markImg); break;
- default:
- return false;//die('不支持的水印图片文件类型');exit();
- }
-
- $logow = $markImg_w;
- $logoh = $markImg_h;
-
- if($markPos == 0){$markPos = rand(1, 9);}
-
- switch($markPos)
- {
- case 1: $x = +5; $y = +5; break;//顶部居左
- case 2: $x = ($srcImg_w-$logow)/2; $y = +5; break;//顶部居中
- case 3: $x = $srcImg_w- $logow-5; $y = +15; break;//顶部居右
- case 4: $x = +5; $y = ($srcImg_h-$logoh)/2; break;//左边居中
- case 5: $x = ($srcImg_w-$logow)/2; $y = ($srcImg_h-$logoh)/2; break;//图片中心
- case 6: $x = $srcImg_w-$logow-5; $y = ($srcImg_h-$logoh)/2; break;//右边居中
- case 7: $x = +5; $y = $srcImg_h-$logoh-5; break;//底部居左
- case 8: $x = ($srcImg_w-$logow)/2; $y = $srcImg_h-$logoh-5; break;//底部居中
- case 9: $x = $srcImg_w-$logow-5; $y = $srcImg_h-$logoh-5; break;//底部居右
- default:
- return false;//die('此位置不支持');exit;
- }
-
- $dst_img = @imagecreatetruecolor($srcImg_w, $srcImg_h);
- imagecopy($dst_img, $srcim, 0, 0, 0, 0, $srcImg_w, $srcImg_h);
- imagecopy($dst_img, $markim, $x, $y, 0, 0, $logow, $logoh);
- imagedestroy($markim);
-
- switch ($srcInfo[2])
- {
- case 1: imagegif($dst_img, $imgSrc); break;
- case 2: imagejpeg($dst_img, $imgSrc);break;
- case 3: imagepng($dst_img, $imgSrc); break;
- default: break;
- }
- imagedestroy($dst_img);
- imagedestroy($srcim);
- return true;
- }
- //获取一个唯一文件名
- function get_unique_file_name($path,$ext)
- {
- $fileName = TIMESTAMP.random(6, '0123456789abcdefghijklmnopqrstuvwxyz').".".$ext;//文件重命名
- if(!file_exists($path.$fileName))
- {
- return $fileName;
- }
- else
- {
- return get_unique_file_name($path,$ext);
- }
- }
- //转换数组为可适应SQL语句插入语法值集合
- function change_array_to_sql_string($array=array()){ //转换数组为可适应SQL语句插入语法值集合
- $array=str_replace("'","\'",$array);
- return "'".implode("','",$array)."'";
- }
- // 截取某部分字符
- function interception_of_string($string='',$start='',$end='')
- {
- if($string==''){return '';}
- if($start!='')
- {
- $pos = strpos($string,$start);
- if($pos===false)
- {
- return '';
- }
- else
- {
- $pos += strlen($start);
- $string = substr($string,$pos);
- }
- }
-
- if($end!='')
- {
- $pos = strpos($string,$end);
- if($pos)
- {
- $string = substr($string,0,$pos);
- }
- }
-
- return $string;
- }
- //Curl
- function https_request($url,$options = null,$data = null,$header = null){
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
- curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
- if (!empty($data)){
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
- }
- (isset($options['header'])&&$options['header'])?curl_setopt($curl, CURLOPT_HEADER, 1): curl_setopt($curl, CURLOPT_HEADER, 0);//如果有响应头
- if(!empty($header))//如果有请求头
- {
- $curl_header = array();
- foreach($header as $key=>$value)
- {
- $curl_header[] = "$key:$value";
- }
- curl_setopt($curl,CURLOPT_HTTPHEADER, $curl_header);
- }
- if(isset($options['gzip'])&&$options['gzip']==1) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); //如果页面开启了GZIP压缩
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0');
- if(!empty($options['time_out']))
- {
- curl_setopt($curl, CURLOPT_TIMEOUT, $options['time_out']);
- }
- else
- {
- curl_setopt($curl, CURLOPT_TIMEOUT, 15);
- }
- curl_setopt ($curl, CURLOPT_REFERER, get_url());
- $output = curl_exec($curl);
- curl_close($curl);
- return $output;
- }
- /**批量替换敏感词
- * @param array $badwords 敏感词数组
- * @param array $replacement 替换词数组
- * @param string $str 待替换内容
- * @return string
- */
- function multi_replace($badwords,$replacement,$str)
- {
- $replaceList = array();
- if(is_array($badwords))
- {
- foreach($badwords as $badword)
- {
- $length = mb_strlen($badword,CHARSET);
- $temp='';
- for($i=0;$i<$length;$i++)
- {
- $temp .= $replacement;
- }
- $replaceList[] = $temp;
- }
- }
- return $str = str_replace($badwords,$replaceList,$str);
- }
- /**封装后的配置文件包含方法
- */
- function require_config($file)
- {
- if(defined('SITE_MODE'))
- {
- return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.SITE_MODE.DIRECTORY_SEPARATOR.$file;
- }
- else
- {
- return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.$file;
- }
- }
- //格式正则校验
- function pattern_check($type,$value)
- {
- switch($type)
- {
- case 'url':
- $pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
- break;
- case 'email':
- $pattern = '/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/';
- break;
- default:break;
- }
- if(!empty($pattern)&&preg_match($pattern,$value)){
- return true;
- }
- else{
- return false;
- }
- }
- //请求安全检测
- function check_safe_request_params(){
- $getfilter="'|<[^>]*?>|^\\+\/v(8|9)|\\b(and|or)\\b.+?(>|<|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
- $postfilter="^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
- $cookiefilter="\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
- $referer=empty($_SERVER['HTTP_REFERER']) ? array() : array($_SERVER['HTTP_REFERER']);
- foreach($_GET as $key=>$value){
- if (!check_request_params_ok($key,$value,$getfilter)){exit;}
- }
- foreach($_POST as $key=>$value){
- if (!check_request_params_ok($key,$value,$postfilter)){exit;}
- }
- foreach($_COOKIE as $key=>$value){
- if (!check_request_params_ok($key,$value,$cookiefilter)){exit;}
- }
- foreach($referer as $key=>$value){
- if (!check_request_params_ok($key,$value,$getfilter)){exit;}
- }
- }
- //请求安全检测:子方法
- function check_request_params_ok($StrFiltKey,$StrFiltValue,$ArrFiltReq){
- $StrFiltValue=arr_foreach($StrFiltValue);
- if (preg_match('/'.$ArrFiltReq.'/is',$StrFiltValue)==1 || preg_match('/'.$ArrFiltReq.'/is',$StrFiltKey)==1){return false;}
- return true;
- }
- function arr_foreach($arr) {
- static $str;
- if (!is_array($arr)) {return $arr;}
- foreach ($arr as $key => $val ) {
- if (is_array($val)) {arr_foreach($val);} else {$str[] = $val;}
- }
- return implode($str);
- }
- //带超时时间设置的file_get_contents
- function new_file_get_contents($url,$timeout=null)
- {
- if(isset($timeout))
- {
- $opts = array(
- 'http'=>array(
- 'method'=>"GET",
- 'timeout'=>$timeout,//单位秒
- )
- );
- return file_get_contents( $url, false, stream_context_create($opts));
- }
- else
- {
- return file_get_contents($url);
- }
- }
- //判断是否蜘蛛请求
- function checkrobot($useragent = '') {
- static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla','haosouspider','baidu','sogou','yisouspider','360spider','baiduspide','soso','yahoo','bingbot');
- static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
- $useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
- if(strpos($useragent, 'http://') === false && dstrpos($useragent, $kw_browsers)) return false;
- if(dstrpos($useragent, $kw_spiders)) return true;
- return false;
- }
- function dstrpos($string, &$arr, $returnvalue = false) {
- if(empty($string)) return false;
- foreach((array)$arr as $v) {
- if(strpos($string, $v) !== false) {
- $return = $returnvalue ? $v : true;
- return $return;
- }
- }
- return false;
- }
- //压缩html
- function compress_html($str){
- $str = trim($str);
- $str = str_replace("\t","",$str);
- $str = str_replace("\r\n","",$str);
- $str = str_replace("\r","",$str);
- $str = str_replace("\n","",$str);
- $str=preg_replace("/>[ ]+/si",">",$str); //过滤>(">"号后面带空格)
- $str=preg_replace("/[ ]+</si","<",$str); //过滤<("<"号前面带空格)
- return trim($str);
- }
- //字符串过滤,只保留汉字数字英文标点符号
- function removeHtml($html,$filter=1)
- {
- $html = htmlspecialchars_decode($html); //把一些预定义的 HTML 实体转换为字符
- $html = strip_tags($html); //函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
- $html = trim($html); //清除字符串两边的空格
- $html = str_replace(" ","",$html);
- $html = preg_replace("/\t/","",$html); //使用正则表达式替换内容,如:空格,换行,并将替换为空。
- $html = preg_replace("/\r\n/","",$html);
- $html = preg_replace("/\r/","",$html);
- $html = preg_replace("/\n/","",$html);
- $html = preg_replace("/ /","",$html);
- $html = preg_replace("/ /","",$html); //匹配html中的空格
- $html = preg_replace('/($s*$)|(^s*^)/m', '',$html);
- if($filter)
- {
- preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
- return implode('', $result[0]);
- }
- else
- {
- return $html;
- }
- }
- //对转换过程中获取的内容做初始处理
- function beforeProcessHtml($html)
- {
- preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u', $html, $testResult);
- if(empty($testResult[0]))
- {
- $html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');
- preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
- return implode('', $result[0]);
- }
- else
- {
- return $html;
- }
- }
- //获取所有的cookie内容
- function get_all_cookie_str(){
- $ckeStr='';
- foreach ($_COOKIE as $ckeName=>$ckeVal){
- if(!is_array($ckeVal)){
- $ckeStr.= $ckeName.'='.$ckeVal.';';
- }
- }
- $ckeStr = substr($ckeStr, 0,-1);//去除最后的 ;
- return $ckeStr;
- }
- //PHP默认serialize有时会出错 http://us.php.net/manual/en/function.unserialize.php#71270
- function mb_unserialize($serial_str) {
- $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
- $serial_str= str_replace("\r", "", $serial_str);
- return unserialize($serial_str);
- }
- //判断是否是移动端访问
- function check_mobile($debug = false) {
- static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
- 'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
- 'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
- 'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
- 'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
- 'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
- 'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
- static $mobilebrowser_list =array('windows phone');
- static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
- 'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
- 'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
- $pad_list = array('pad', 'gt-p1000');
- $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
- if(($v = dstrpos($useragent, $mobilebrowser_list, true))){
- return '1'; //windows phone
- }
- if(($v = dstrpos($useragent, $touchbrowser_list, true))){
- return '2';
- }
- if(($v = dstrpos($useragent, $wmlbrowser_list))) {
- return '3'; //wml版
- }
- $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
- if(dstrpos($useragent, $brower)) return false;
- return false;
- }
- //时间换算
- function info_last_time($time,$ac="Y年m月d日") {
- $now=TIMESTAMP-$time;
- $timestr = (substr_count($ac,'-')>0?'Y-m-d':'Y年m月d日');
- if ($now>3456000) return get_date($time,$timestr);
- elseif ($now>345600) return get_date($time,$ac);
- elseif ($now>259200) return "三天前";
- elseif ($now>172800) return "两天前";
- elseif ($now>86400) return "一天前";
- elseif ($now>72000) return "二十小时前";
- elseif ($now>54000) return "十五小时前";
- elseif ($now>43200) return "十二小时前";
- elseif ($now>36000) return "十小时前";
- elseif ($now>28800) return "八小时前";
- elseif ($now>21600) return "六小时前";
- elseif ($now>18000) return "五小时前";
- elseif ($now>10800) return "三小时前";
- elseif ($now>7200) return "两小时前";
- elseif ($now>3600) return "一小时前";
- elseif ($now>1800) return "半小时前";
- elseif ($now>1200) return "二十分钟前";
- elseif ($now>900) return "十五分钟前";
- elseif ($now>600) return "十分钟前";
- elseif ($now>300) return "五分钟前";
- elseif ($now>180) return "三分钟前";
- elseif ($now>120) return "两分钟前";
- elseif ($now>=0) return "一分钟前";
- elseif ($now<0) return "一秒钟前";
- return get_date($time,$ac);
- }
- /**
- * 格式化时间戳为日期字符串
- * @global string $db_datefm
- * @global string $db_timedf
- * @global string $_datefm
- * @global string $_timedf
- * @param int $timestamp
- * @param string $format
- * @return string
- */
- function get_date($timestamp, $format = null) {
- if(empty($timestamp))return '';
- $obj = new \DateTime("@$timestamp"); // 这里时间戳前要写一个@符号
- $timezone = timezone_open(TIME_ZONE); // 设置时区
- $obj->setTimezone($timezone);
- $sDefaultFormat = $format ? $format : 'Y-m-d H:i';
- return $obj->format($sDefaultFormat);
- }
- //日期转时间戳
- function str_to_time($str)
- {
- $date = new \DateTime($str);
- return $date->format('U');
- }
- //301跳转
- function header_goto($str) {
- Header("HTTP/1.1 301 Moved Permanently");
- Header($str);exit;
- }
- /**
- * 截断字符串
- *
- * @param string $content 内容
- * @param int $length 截取字节数
- * @param string $add 是否带省略号,Y|N
- * @return string
- */
- function substrs($content, $length, $add = 'Y') {
- if (strlen($content) > $length) {
- if (CHARSET != 'utf-8') {
- $cutStr = '';
- for ($i = 0; $i < $length - 1; $i++) {
- $cutStr .= ord($content[$i]) > 127 ? $content[$i] . $content[++$i] : $content[$i];
- }
- $i < $length && ord($content[$i]) <= 127 && $cutStr .= $content[$i];
- return $cutStr . ($add == 'Y' ? ' ..' : '');
- }
- return utf8_trim(substr($content, 0, $length)) . ($add == 'Y' ? ' ..' : '');
- }
- return $content;
- }
- /**
- * utf8字符串整齐化
- *
- * @param string $str
- * @return string
- */
- function utf8_trim($str) {
- $hex = '';
- $len = strlen($str) - 1;
- for ($i = $len; $i >= 0; $i -= 1) {
- $ch = ord($str[$i]);
- $hex .= " $ch";
- if (($ch & 128) == 0 || ($ch & 192) == 192) {return substr($str, 0, $i);}
- }
- return $str . $hex;
- }
- function echo_json($arr){
- ob_clean();
- header('Content-type: application/json');
- echo json_encode($arr);exit;
- }
- //生成唯一订单号
- function getUniOrderNo()
- {
- $order_id = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
- $exists = \app\modules\shopping\models\ShoppingOrder::find()->where("order_sn='".$order_id."'")->exists();
- if($exists)
- {
- return getUniOrderNo();
- }
- else
- {
- return $order_id;
- }
- }
- //生成唯一券号
- function getUniCouponNo()
- {
- $coupon_no = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
- $exists = \app\modules\ucenter\models\UserVipCoupon::find()->where("coupon_no='".$coupon_no."'")->exists();
- if($exists)
- {
- return getUniCouponNo();
- }
- else
- {
- return $coupon_no;
- }
- }
- //生成唯一订单号(毫秒级)
- function getProUniOrderNo()
- {
- $order_id_main = get_date(TIMESTAMP,'YmdHis') . rand(10,99);
- $order_id_len = strlen($order_id_main);
- $order_id_sum = 0;
- for($i=0; $i<$order_id_len; $i++){
- $order_id_sum += (int)(substr($order_id_main,$i,1));
- }
- $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
- return $order_id;
- }
- /**
- * 二維数组排序
- */
- function array_sort($arr,$sort)
- {
- /* $sort = array(
- 'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
- 'field' => 'length', //排序字段
- );*/
- $arrSort = array();
- foreach($arr AS $uniqid => $row){
- foreach($row AS $key=>$value){
- $arrSort[$key][$uniqid] = $value;
- }
- }
- if($sort['direction']){
- array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arr);
- }
- return $arr;
- }
- /**
- * 可以统计中文字符串长度的函数
- * @param $str 要计算长度的字符串
- * @param $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
- */
- function abslength($str)
- {
- if(empty($str)){
- return 0;
- }
- if(function_exists('mb_strlen')){
- return mb_strlen($str,'utf-8');
- }
- else {
- preg_match_all("/./u", $str, $ar);
- return count($ar[0]);
- }
- }
- //过滤微信表情
- function filterEmoji($nickname)
- {
- $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
- $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
- $nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
- $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
- $nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
- $nickname = str_replace(array('"','\''), '', $nickname);
- return $nickname;
- }
- //单条对象记录转数组
- function single_object_to_array($result,$needfield = array())
- {
- $info = array();
- if(is_object($result))
- {
- foreach($result as $key=>$value)
- {
- if(!empty($needfield)&&in_array($key,$needfield))
- {
- $info[$key] = $value;
- }
- if(empty($needfield))
- {
- $info[$key] = $value;
- }
- }
- return $info;
- }
- else
- {
- return $result;
- }
- }
- //获得文件绝对路径
- function getFileUrl($path,$internal=0)
- {
- if(empty($path)) return;
- if(strpos($path,'http')!==false)
- {
- $path = str_replace(array('https://','http://'),array(SITE_PROTOCOL,SITE_PROTOCOL),$path);
- }
- else
- {
- //如果开启了OSS
- if(Yii::$app->params['oss']['OPEN_OSS'])
- {
- if($internal==1)
- {
- $path = getOssInterUrl().$path;
- }
- else
- {
- $path = getOssUrl().$path;
- }
- }
- else
- {
- $path = UPLOAD_URL.$path;
- }
- }
- if(IN_WAP)
- {
- $path = str_replace(WEB_URL,WAP_URL,$path);
- }
- return $path;
- }
- //获得文件转换结果路径
- function getFileWorkPath($file)
- {
- $result = parse_url($file);
- $path= str_replace('/upload/','',$result['path']);
- $ext = fileext($path);
- $workpath = dirname($path).DIRECTORY_SEPARATOR.md5(basename($path,'.'.$ext)).DIRECTORY_SEPARATOR;
- $workpath = ltrim(str_replace(DIRECTORY_SEPARATOR,'/',$workpath),'/');
- return $workpath;
- }
- //获得文件相对路径
- function getFilePath($file)
- {
- $result = parse_url($file);
- $path= str_replace('/upload/','',$result['path']);
- return $path;
- }
- function unserializeFileRealUrl($string,$first=true)
- {
- $fileList = string2array($string);
- $urls = '';
- if($first)
- {
- if(isset($fileList['filepath']))
- {
- if(!empty($fileList['filepath']))
- {
- $urls = getFileUrl($fileList['filepath']);
- }
- }
- else
- {
- if(!empty($fileList[0]['filepath']))
- {
- if(strpos($fileList[0]['fileurl'],'http')!==false)
- {
- return $fileList[0]['fileurl'];
- }
- else
- {
- $urls = getFileUrl($fileList[0]['filepath']);
- }
- }
- }
- }
- else
- {
- $urls = array();
- if(is_array($fileList))foreach($fileList as $file)
- {
- if(!empty($file['filepath']))$urls[] = getFileUrl($file['filepath']);
- }
- }
- return $urls;
- }
- //判断是否是手机站
- function is_wap_site()
- {
- if(IN_WAP==true)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //判断是IOS或安卓系统
- function get_device_type()
- {
- //全部变成小写字母
- $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
- $type ='other';
- //分别进行判断
- if(strpos($agent,'iphone') || strpos($agent,'ipad'))
- {
- $type ='ios';
- }
- if(strpos($agent,'android'))
- {
- $type ='android';
- }
- return $type;
- }
- //判断是否是微信访问
- function check_micromsg()
- {
- $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
- if (stripos($agent, 'MicroMessenger') !== false)
- {
- return true;
- } else {
- return false;
- }
- }
- //判断是否是百度小程序访问
- function check_baiduapp()
- {
- $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
- if (stripos($agent, 'baiduboxapp') !== false)
- {
- return true;
- } else {
- return false;
- }
- }
- //判断是否是微信小程序访问
- function check_wxapp()
- {
- $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
- if (stripos($agent, 'miniprogram') !== false)
- {
- return true;
- } else {
- return false;
- }
- }
- /*
- * 作用:用*号替代姓名除第一个字之外的字符
- * 参数:
- *
- *
- * 返回值:string
- */
- function starReplace($name, $num = 0)
- {
- if ($num && mb_strlen($name, 'UTF-8') > $num) {
- return mb_substr($name, 0, 4) . '*';
- }
- if ($num && mb_strlen($name, 'UTF-8') <= $num) {
- return $name;
- }
- $doubleSurname = [
- '欧阳', '太史', '端木', '上官', '司马', '东方', '独孤', '南宫',
- '万俟', '闻人', '夏侯', '诸葛', '尉迟', '公羊', '赫连', '澹台', '皇甫', '宗政', '濮阳',
- '公冶', '太叔', '申屠', '公孙', '慕容', '仲孙', '钟离', '长孙', '宇文', '司徒', '鲜于',
- '司空', '闾丘', '子车', '亓官', '司寇', '巫马', '公西', '颛孙', '壤驷', '公良', '漆雕', '乐正',
- '宰父', '谷梁', '拓跋', '夹谷', '轩辕', '令狐', '段干', '百里', '呼延', '东郭', '南门', '羊舌',
- '微生', '公户', '公玉', '公仪', '梁丘', '公仲', '公上', '公门', '公山', '公坚', '左丘', '公伯',
- '西门', '公祖', '第五', '公乘', '贯丘', '公皙', '南荣', '东里', '东宫', '仲长', '子书', '子桑',
- '即墨', '达奚', '褚师', '吴铭'
- ];
- $surname = mb_substr($name, 0, 2);
- if (in_array($surname, $doubleSurname)) {
- $name = mb_substr($name, 0, 2) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 2));
- } else {
- $name = mb_substr($name, 0, 1) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 1));
- }
- return $name;
- }
- //比如找回密码当中邮件验证码用到的
- function randString($length=32)
- {
- return Yii::$app->getSecurity()->generateRandomString($length);
- }
- //生成密码
- function generatePwd($password)
- {
- return Yii::$app->getSecurity()->generatePasswordHash($password);
- }
- //校验密码
- function validatePwd($password,$hash)
- {
- return Yii::$app->getSecurity()->validatePassword($password, $hash);
- }
- //页面元素 name 转ID
- function nameToId($name)
- {
- $name = str_replace('[','-',$name);
- $name = str_replace(']','',$name);
- return strtolower($name);
- }
- //抛出404
- function do404()
- {
- throw new \Exception('页面未找到',404);
- }
- function isSpider() {
- $agent= strtolower($_SERVER['HTTP_USER_AGENT']);
- if (!empty($agent)) {
- $spiderSite= array(
- "TencentTraveler",
- "Baiduspider+",
- "BaiduGame",
- "Googlebot",
- "msnbot",
- "Sosospider+",
- "Sogou web spider",
- "ia_archiver",
- "Yahoo! Slurp",
- "YoudaoBot",
- "Yahoo Slurp",
- "MSNBot",
- "Java (Often spam bot)",
- "BaiDuSpider",
- "Voila",
- "Yandex bot",
- "BSpider",
- "twiceler",
- "Sogou Spider",
- "Speedy Spider",
- "Google AdSense",
- "Heritrix",
- "Python-urllib",
- "Alexa (IA Archiver)",
- "Ask",
- "Exabot",
- "Custo",
- "OutfoxBot/YodaoBot",
- "yacy",
- "SurveyBot",
- "legs",
- "lwp-trivial",
- "Nutch",
- "StackRambler",
- "The web archive (IA Archiver)",
- "Perl tool",
- "MJ12bot",
- "Netcraft",
- "MSIECrawler",
- "WGet tools",
- "larbin",
- "Fish search",
- );
- foreach($spiderSite as $val) {
- $str = strtolower($val);
- if (strpos($agent, $str) !== false) {
- return true;
- }
- }
- } else {
- return false;
- }
- }
- /**
- * @param array $_define 默认seo配置
- * @param unknown_type $_values 对应 targets 的一组值
- * @param unknown_type $_targets
- * @return multitype:string
- */
- function seoSettings($_define = array(), $_replaceconfig = array(),$_default = array()) {
- if (!empty($_define)) {
- $cTitle = $_define[$_replaceconfig['pre'].'meta_title'];
- $cKeywords = $_define[$_replaceconfig['pre'].'meta_keywords'];
- $cDescription = $_define[$_replaceconfig['pre'].'meta_description'];
- }
- $_values = $_replaceconfig['values'];
- $_targets = $_replaceconfig['targets'];
- /* 过滤参数 */
- foreach ($_values as $key => $value) {
- $_values[$key] = empty($value) ? '' : trim(strip_tags($value));
- }
- /*设置默认值*/
- empty($cTitle) && $cTitle = $_default['meta_title'];
- empty($cKeywords) && $cKeywords = $_default['meta_keywords'];
- empty($cDescription) && $cDescription = $_default['meta_description'];
- /* 参数处理 */
- $webPageTitle = parseSeoTargets($cTitle, $_values, $_targets);
- $metaDescription = parseSeoTargets($cDescription, $_values, $_targets);
- $metaKeywords = trim(parseSeoTargets($cKeywords, $_values, $_targets),',');
- $metaKeywords = str_replace(',',',',trim($metaKeywords,','));
- //如果关键词为空,用标题替代
- if(empty($metaKeywords))$metaKeywords = $webPageTitle;
- return array($webPageTitle, $metaKeywords, $metaDescription);
- }
- /**
- * @param string $content
- * @param array $_replace
- * @param array $_targets
- * @return string
- */
- function parseSeoTargets($content, $_values, $_targets) {
- $content = str_replace($_targets, $_values, $content);
- $content = trim(preg_replace(array('((\s*\,\s*)+)', '((\s*\|\s*)+)', '((\s*\t\s*)+)'), array(
- ',', '|', '', ''), $content), ' -,|');
- return $content;
- }
- //获取目录(含子目录)下所有文件
- function get_allfiles($path,&$files) {
- if(is_dir($path)){
- $dp = dir($path);
- while ($file = $dp ->read()){
- if($file !="." && $file !=".."){
- get_allfiles($path."/".$file, $files);
- }
- }
- $dp ->close();
- }
- if(is_file($path)){
- $files[] = $path;
- }
- }
- function get_filenamesbydir($dir){
- $files = array();
- get_allfiles($dir,$files);
- return $files;
- }
- ?>
|