<?php
//php嗣脯杅郪睿勤砓腔蛌遙
function object_to_array($arr)
{
if (is_object($arr)) {
$arr = get_object_vars($arr);
}
if (is_array($arr)) {
return array_map(__FUNCTION__, $arr);
} else {
return $arr;
}
}
function array_to_object($arr)
{
if (is_array($arr)) {
return (object) array_map(__FUNCTION__, $arr);
} else {
return $arr;
}
}
//菰寥源宒腔勤曹講笢腔杻忷趼睫輛俴蛌砱
function addslashes_deep($value)
{
if (empty($value)) {
return $value;
} else {
return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
}
}
/**
* 殿隙蚕勤砓扽俶郪傖腔壽薊杅郪
*/
function get_object_vars_deep($obj)
{
if (is_object($obj)){
$obj = get_object_vars($obj);
}
if (is_array($obj)) {
foreach ($obj as $key => $value) {
$obj[$key] = get_object_vars_deep($value);
}
}
return $obj;
}
/*斐膘砉涴欴腔脤戙: "IN('a','b')";
* * @param mix $item_list 蹈桶杅郪麼趼睫揹,⺼彆峈趼睫揹奀,趼睫揹硐諉忳杅趼揹
* @param string $field_name 趼僇靡備
*/
function db_create_in($item_list, $field_name = '')
{
if (empty($item_list)) {
return $field_name . " IN ('') ";
} else {
if (!is_array($item_list)) {
$item_list = explode(',', $item_list);
foreach ($item_list as $k => $v) {
$item_list[$k] = intval($v);
}
}
$item_list = array_unique($item_list);
$item_list_tmp = '';
foreach ($item_list as $item) {
if ($item !== '') {
$item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
}
}
if (empty($item_list_tmp)) {
return $field_name . " IN ('') ";
} else {
return $field_name . ' IN (' . $item_list_tmp . ') ';
}
}
}
/**
* 蚚CURL懂杸測賸file_get_contentsㄛ價衾假睿俶夔蕉藉ㄛ壽敕allow_url_fopen
* @param $durl
*/
function curl_file_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
/**
* 刉壺恅璃標
* @param $dir 恅璃標繚噤
*/
function rm_dir($dir)
{
if (is_file($dir)) { //岆恅璃ㄛ眻諉刉壺
chmod($dir, 0777);
@unlink($dir);
return true;
} elseif (is_dir($dir)) {
if ($path = opendir($dir)) { //紨跺刉壺恅璃麼恅璃標
while ($file = readdir($path)) {
if (($file == '.') || ($file == '..')) {
continue;
}
//菰寥刉壺赽恅璃標
chmod($dir . '/' . $file, 0777);
rm_dir($dir . '/' . $file);
}
closedir($path);
chmod($dir, 0777);
rmdir($dir); //刉壺恅璃標
return true;
}
}
return false;
}
/**
* 蕭探恅璃標
* @param $from 恅璃標繚噤麼恅璃
* @param $to_dir 恅璃標繚噤
*/
function copy_dir($from, $to_dir)
{
if (!ecm_mkdir($to_dir)) { //醴梓祥岆恅璃標
return false;
}
if (is_file($from)) {
@copy($from, $to_dir);
return true;
} elseif (is_dir($from)) {
if ($path = opendir($from)) { //紨跺葩秶恅璃麼恅璃標
while ($file = readdir($path)) {
if (($file == '.') || ($file == '..')) {
continue;
}
if (is_dir($from . '/' . $file)) { //菰寥葩秶恅璃標
copy_dir($from . '/' . $file, $to_dir . '/' . $file);
} elseif (is_file($from . '/' . $file)) { //葩秶恅璃
copy($from . '/' . $file, $to_dir . '/' . $file);
}
}
closedir($path);
return true;
}
}
return false;
}
/**
* 斐膘醴翹ㄗ⺼彆蜆醴翹腔奻撰醴翹祥湔婓ㄛ頗珂斐膘奻撰醴翹ㄘ
* 甡懇衾 ROOT_PATH 都講ㄛブ硐夔斐膘 ROOT_PATH 醴翹狟腔醴翹
* 醴翹煦路睫斛剕岆 / 祥夔岆 \
*
* @param string $absolute_path 橈勤繚噤
* @param int $mode 醴翹癹
* @return bool
*/
function ecm_mkdir($absolute_path, $mode = 0777)
{
if (is_dir($absolute_path)) {
return true;
}
$root_path = ROOT_PATH;
$relative_path = str_replace($root_path, '', $absolute_path);
$each_path = explode('/', $relative_path);
$cur_path = $root_path; // 絞ゴ悜遠揭燴腔繚噤
foreach ($each_path as $path) {
if ($path) {
$cur_path = $cur_path . '/' . $path;
if (!is_dir($cur_path)) {
if (@mkdir($cur_path, $mode)) {
fclose(fopen($cur_path . '/index.htm', 'w'));//汜傖忑珜
} else {
return false;
}
}
}
}
return true;
}
/*
* Make a error message by JSON format utf-8
*
* @param string $msg
*/
function json_error($msg = '', $retval = null, $jqremote = false)
{
//登录
if ($msg == 'login_please') {
echo '<script language="javascript"> window.top.history.go(0);</script>';
return;
}
$result = array(
'done' => false,
'msg' => $msg
);
if (isset($retval)) {
$result['retval'] = $retval;
}
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-type:text/plain;charset=utf-8", true);
$json = json_encode($result);
if ($jqremote === false) {
$jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
}
if ($jqremote) {
$json = $jqremote . '(' . $json . ')';
}
echo $json;
}
/**
* Make a successfully message utf-8
*
* @param mixed $retval
* @param string $msg
*/
function json_result($retval = '', $msg = '', $jqremote = false)
{
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-type:text/plain;charset=utf-8", true);
$json = json_encode(array(
'done' => true,
'msg' => $msg,
'retval' => $retval
));
if ($jqremote === false) {
$jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
}
if ($jqremote) {
$json = $jqremote . '(' . $json . ')';
}
echo $json;
}
/**
* 嗣峎杅郪齬唗
*
* @author Doujia
* @param array $array
* @param array $cols
* @return array
*
* e.g. $data = array_msort($data, array('sort_order'=>SORT_ASC, 'add_time'=>SORT_DESC));
*/
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) {
$colarr[$col]['_' . $k] = strtolower($row[$col]);
}
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\'' . $col . '\'],' . $order . ',';
}
$eval = substr($eval, 0, -1) . ');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k, 1);
if (!isset($ret[$k]))
$ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
/**
*
* strlen function
*
* @param string $string
* @param bool $onlyCharacters 岆瘁硐呾艘善腔趼﹝
* 撼瞰ㄩ※扂淩邟§ㄩ涴岆3跺趼﹝※扂T邟§ㄩ涴岆3跺趼﹝
* 珨曆趕憩岆ㄛ笢荎恅肮欴勤渾
*
*/
public static function strlen($string, $onlyCharacters = false)
{
$strlen = 0;
$length = strlen($string);
$characterLength = 0;
while ($strlen < $length) {
$stringTMP = substr($string, $strlen, 1);
if (ord($stringTMP) >= 224) {
$strlen = $strlen + 3;
} elseif (ord($stringTMP) >= 192) {
$strlen = $strlen + 2;
} else {
$strlen = $strlen + 1;
}
$characterLength++;
}
return $onlyCharacters ? $characterLength : $strlen;
}
/**
* 汜傖呴儂躇鎢ㄗ呴儂8弇ㄛ4弇杅趼ㄛ4弇趼譫ㄘ
*
* @return string
*
*/
public static function create_password()
{
$numbers = '1234567890';
$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$numbers_create = array();
$letters_create = array();
for ($i = 0; $i < 4; $i++) {
$numbers_create[] = $numbers{rand(0, 9)};
$letters_create[] = $letters{rand(0, 25)};
}
$arr = array_merge($numbers_create, $letters_create);
shuffle($arr);
return implode('', $arr);
}
/**
*
* @param type $len
* @return type
*/
public static function generate_code($len = 15)
{
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0, $count = strlen($chars); $i < $count; $i++) {
$arr[$i] = $chars[$i];
}
mt_srand((double)microtime() * 1000000);
shuffle($arr);
$code = substr(implode('', $arr), 5, $len);
return $code;
}
/**
* 鳳龰恅璃 mime 濬倰
*
* @date 2011-12-21
*/
public static function get_mime_type ($filename)
{
preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
switch (strtolower($fileSuffix[1]))
{
case "js":
return "application/x-javascript";
case "json":
return "application/json";
case "jpg":
case "jpeg":
case "jpe":
return "image/jpeg";
case "png":
case "gif":
case "bmp":
case "tiff":
return "image/" . strtolower($fileSuffix[1]);
case "css":
return "text/css";
case "xml":
return "application/xml";
case "doc":
case "docx":
return "application/msword";
case "xls":
case "xlt":
case "xlm":
case "xld":
case "xla":
case "xlc":
case "xlw":
case "xll":
return "application/vnd.ms-excel";
case "ppt":
case "pps":
return "application/vnd.ms-powerpoint";
case "rtf":
return "application/rtf";
case "pdf":
return "application/pdf";
case "html":
case "htm":
case "php":
return "text/html";
case "txt":
return "text/plain";
case "mpeg":
case "mpg":
case "mpe":
return "video/mpeg";
case "mp3":
return "audio/mpeg3";
case "wav":
return "audio/wav";
case "aiff":
case "aif":
return "audio/aiff";
case "avi":
return "video/msvideo";
case "wmv":
return "video/x-ms-wmv";
case "mov":
return "video/quicktime";
case "rar":
return "application/x-rar-compressed";
case "zip":
return "application/zip";
case "tar":
return "application/x-tar";
case "swf":
return "application/x-shockwave-flash";
default:
if (function_exists("mime_content_type"))
{
$fileSuffix = mime_content_type($filename);
}
return "unknown/" . trim($fileSuffix[0], ".");
}
}
/**
* 諦誧傷淩妗 IP
*/
public static function real_ip_client ()
{
static $realip = NULL;
if ($realip !== NULL)
{
return $realip;
}
if (isset($_SERVER))
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
/* 龰X-Forwarded-For笢菴珨跺準unknown腔衄虴IP趼睫揹 */
foreach ($arr as $ip)
{
$ip = trim($ip);
if ($ip != 'unknown')
{
$realip = $ip;
break;
}
}
}
elseif (isset($_SERVER['HTTP_CLIENT_IP']))
{
$realip = $_SERVER['HTTP_CLIENT_IP'];
}
else
{
if (isset($_SERVER['REMOTE_ADDR']))
{
$realip = $_SERVER['REMOTE_ADDR'];
}
else
{
$realip = '0.0.0.0';
}
}
}
else
{
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$realip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_CLIENT_IP'))
{
$realip = getenv('HTTP_CLIENT_IP');
}
else
{
$realip = getenv('REMOTE_ADDR');
}
}
preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
return $realip;
}
/**
* 鳳龰督昢け腔ip
*
*
* @return string
* */
function real_ip_server ()
{
static $serverip = NULL;
if ($serverip !== NULL)
{
return $serverip;
}
if (isset($_SERVER))
{
if (isset($_SERVER['SERVER_ADDR']))
{
$serverip = $_SERVER['SERVER_ADDR'];
}
else
{
$serverip = '0.0.0.0';
}
}
else
{
$serverip = getenv('SERVER_ADDR');
}
return $serverip;
}
public static function is_url($str)
{
return preg_match("/((http[s]?|ftp):\/\/)?[^\/\.]+?\..+\w$/i", $str);
}
/**
* 旯爺痐
*
* @param string $id
* @return boolean
*/
public static function is_idcard($id)
{
$id = strtoupper($id);
$regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
$arr_split = array();
if (!preg_match($regx, $id))
{
return FALSE;
}
if (15 == strlen($id)) //潰脤15弇
{
$regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
@preg_match($regx, $id, $arr_split);
//潰脤汜゜゜ヽ岆瘁淏
$dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
if (!strtotime($dtm_birth))
{
return FALSE;
}
else
{
return TRUE;
}
}
else //潰脤18弇
{
$regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
@preg_match($regx, $id, $arr_split);
$dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
if (!strtotime($dtm_birth)) //潰脤汜゜゜ヽ岆瘁淏
{
return FALSE;
}
else
{
//潰桄18弇旯爺痐腔苺桄鎢岆瘁淏﹝
//苺桄弇偌桽ISO 7064:1983.MOD 11-2腔寞隅汜傖ㄛX褫眕'峈岆杅趼10﹝
$arr_int = array(
7,
9,
10,
5,
8,
4,
2,
1,
6,
3,
7,
9,
10,
5,
8,
4,
2
);
$arr_ch = array(
'1',
'0',
'X',
'9',
'8',
'7',
'6',
'5',
'4',
'3',
'2'
);
$sign = 0;
for ($i = 0; $i < 17; $i++)
{
$b = (int)$id{$i};
$w = $arr_int[$i];
$sign += $b * $w;
}
$n = $sign % 11;
$val_num = $arr_ch[$n];
if ($val_num != substr($id, 17, 1))
{
return FALSE;
}
else
{
return TRUE;
}
}
}
}
/**
* 桄痐怀⻌腔蚘璃華硊岆瘁磁楊
*
* @param string $email 剒猁桄痐腔蚘璃華硊
*
* @return bool
*/
public static function is_email($user_email)
{
$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
{
if (preg_match($chars, $user_email))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
//快速排序
function quick_sort($array){
if (count($array) <= 1) return $array;
$key = $array[0];
$left_arr = array();
$right_arr = array();
for ($i=1; $i<count($array); $i++){
if ($array[$i] <= $key)
$left_arr[] = $array[$i];
else
$right_arr[] = $array[$i];
}
$left_arr = quick_sort($left_arr);
$right_arr = quick_sort($right_arr);
return array_merge($left_arr, array($key), $right_arr);
}
//冒泡排序法
function bubble_sort($array){
$count = count($array);
if ($count <= 0) return false;
for($i=0; $i<$count; $i++){
for($j=$count-1; $j>$i; $j--){
if ($array[$j] < $array[$j-1]){
$tmp = $array[$j];
$array[$j] = $array[$j-1];
$array[$j-1] = $tmp;
}
}
}
return $array;
}
/**
* 潰脤岆瘁峈珨跺磁楊腔奀潔跡宒
*
* @param string $time
* @return void
*/
public static function is_time($time)
{
$pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';
return preg_match($pattern, $time);
}
/PHP倒计时
//php的时间是以秒算。js的时间以毫秒算
date_default_timezone_set('PRC');
//date_default_timezone_set("Asia/Hong_Kong");//地区
//配置每天的活动时间段
$starttimestr = "08:00:00";
$endtimestr = "22:00:00";
$starttime = strtotime($starttimestr);
$endtime = strtotime($endtimestr);
$nowtime = time();
if ($nowtime<$starttime){
die("活动还没开始,活动时间是:{$starttimestr}至{$endtimestr}");
}
$lefttime = $endtime-$nowtime; //实际剩下的时间(秒)
/*
<!--<script language="JavaScript">
<!-- //
var runtimes = 0;
function GetRTime(){
var nMS = <?=$lefttime?>*1000-runtimes*1000;
var nH=Math.floor(nMS/(1000*60*60))%24;
var nM=Math.floor(nMS/(1000*60)) % 60;
var nS=Math.floor(nMS/1000) % 60;
document.getElementById("RemainH").innerHTML=nH;
document.getElementById("RemainM").innerHTML=nM;
document.getElementById("RemainS").innerHTML=nS;
if(nMS>5*59*1000&&nMS<=5*60*1000)
{
alert("还有最后五分钟!");
}
runtimes++;
setTimeout("GetRTime()",1000);
}
window.onload=GetRTime;
// -->
</script>
<!--/*<h4><strong id="RemainH">XX</strong>:<strong id="RemainM">XX</strong>:<strong id="RemainS">XX</strong></h4>*/
//判断文件是否存在,远程
function es_file_exists($file){
if(preg_match('/^http:\/\//',trim($file))){
$file = str_replace(' ','%20',$file);
$file = trim($file);
$parseurl=parse_url($file);
if( ! isset($_ENV['base_url_flag'][$parseurl['host']])){//先判斷一下域名是否能訪問的了
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $parseurl['host']);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$contents = curl_exec($ch);
$_ENV['base_url_flag'][$parseurl['host']] = (!$contents || preg_match("/404/", $contents)) ? false : true;
}
if($_ENV['base_url_flag'][$parseurl['host']] === false){
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
$contents = curl_exec($ch);
if ($contents){
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
return true;
}
}
return false;
}
return file_exists(trim($file));//本地的
}
class Autoloader {
protected static $classPaths = array();
protected static $classFileSuffix = '.class.php';
protected static $cacheFilePath = null;
protected static $cachedPaths = null;
protected static $excludeFolderNames = '/^CVS|\..*$/'; // CVS directories and directories starting with a dot (.).
protected static $hasSaver = false;
/**
* Sets the paths to search in when looking for a class.
*
* @param array $paths
* @return void
**/
public static function setClassPaths($paths) {
self::$classPaths = $paths;
}
/**
* Adds a path to search in when looking for a class.
*
* @param string $path
* @return void
**/
public static function addClassPath($path) {
self::$classPaths[] = $path;
}
/**
* Set the full file path to the cache file to use.
*
* Example:
*
* <code>
* Autoloader::setCacheFilePath('/tmp/class_path_cache.txt');
* </code>
*
* @param string $path
* @return void
**/
public static function setCacheFilePath($path) {
self::$cacheFilePath = $path;
}
/**
* Sets the suffix to append to a class name in order to get a file name
* to look for
*
* @param string $suffix - $className . $suffix = filename.
* @return void
**/
public static function setClassFileSuffix($suffix) {
self::$classFileSuffix = $suffix;
}
/**
* When searching the {@link $classPaths} recursively for a matching class
* file, folder names matching $regex will not be searched.
*
* Example:
*
* <code>
* Autoloader::excludeFolderNamesMatchingRegex('/^CVS|\..*$/');
* </code>
*
* @param string $regex
* @return void
**/
public static function excludeFolderNamesMatchingRegex($regex) {
self::$excludeFolderNames = $regex;
}
/**
* Returns true if the class file was found and included, false if not.
*
* @return boolean
**/
public static function loadClass($className) {
$filePath = self::getCachedPath($className);
if ($filePath && file_exists($filePath)) {
// Cached location is correct
include($filePath);
return true;
} else {
// Scan for file
foreach (self::$classPaths as $path) {
if ($filePath = self::searchForClassFile($className, $path)) {
self::$cachedPaths[$className] = $filePath;
if (!self::$hasSaver) {
register_shutdown_function(array('Autoloader', 'saveCachedPaths'));
self::$hasSaver = true;
}
include($filePath);
return true;
}
}
}
return false;
}
protected static function getCachedPath($className) {
self::loadCachedPaths();
if (isset(self::$cachedPaths[$className])) {
return self::$cachedPaths[$className];
} else {
return false;
}
}
protected static function loadCachedPaths() {
if (is_null(self::$cachedPaths)) {
if (self::$cacheFilePath && is_file(self::$cacheFilePath)) {
self::$cachedPaths = unserialize(file_get_contents(self::$cacheFilePath));
}
}
}
/**
* Write cached paths to disk.
*
* @return void
**/
public static function saveCachedPaths() {
if (!file_exists(self::$cacheFilePath) || is_writable(self::$cacheFilePath)) {
$fileContents = serialize(self::$cachedPaths);
$bytes = file_put_contents(self::$cacheFilePath, $fileContents);
if ($bytes === false) {
trigger_error('Autoloader could not write the cache file: ' . self::$cacheFilePath, E_USER_ERROR);
}
} else {
trigger_error('Autoload cache file not writable: ' . self::$cacheFilePath, E_USER_ERROR);
}
}
protected static function searchForClassFile($className, $directory) {
if (is_dir($directory) && is_readable($directory)) {
$d = dir($directory);
while ($f = $d->read()) {
$subPath = $directory . $f;
if (is_dir($subPath)) {
// Found a subdirectory
if (!preg_match(self::$excludeFolderNames, $f)) {
if ($filePath = self::searchForClassFile($className, $subPath . '/')) {
return $filePath;
}
}
} else {
// Found a file
if ($f == $className . self::$classFileSuffix) {
return $subPath;
}
}
}
}
return false;
}
}