phpcms代码学习笔记(globle.function.php)

今天有事,先贴出来学习

//格式化字符串的函数,或者叫做字符串过虑
function new_htmlspecialchars($string)
{
 return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}

//格式化字符串

function new_addslashes($string)
{
 if(!is_array($string)) return addslashes($string);
 foreach($string as $key => $val) $string[$key] = new_addslashes($val);
 return $string;
}

//字符串处理

function new_stripslashes($string)
{
 if(!is_array($string)) return stripslashes($string);
 foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
 return $string;
}

//过滤js事件

function filter_xss($string, $allowedtags = '', $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
{
 if(is_array($string))
 {
  foreach($string as $key => $val) $string[$key] = filter_xss($val, ALLOWED_HTMLTAGS);
 }
 else
 {
  $string = preg_replace('/\s('.implode('|', $disabledattributes).').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/javascript:[^\"\']*/i', '/(".implode('|', $disabledattributes).")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($string, $allowedtags)));
 }
 return $string;
}

//字符填充并生成填充记录

function filter_word($data = '')
{
 global $PHPCMS;
 $filter_word = trim($PHPCMS['filter_word']);
 if(!$filter_word || (!$data && !$_GET && !$_POST)) return false;
 $filter_word = array_filter(array_map('trim', explode("\n", $filter_word)));
    if(!$filter_word) return false;
 $pattern = str_replace('\*', '.*', implode('|', array_map('preg_quote', $filter_word)));
 $data = array2string($_REQUEST);
 if($pattern && preg_match("/($pattern)/", $data, $m))
 {
  $pattern_word = $m[0];
  define('ILLEGAL_WORD', $pattern_word);
  unset($m[0]);
  $word = implode(' ', $m);
  $logdata = array(TIME, IP, $word, $pattern_word);
  $logfile = PHPCMS_ROOT.'data/filterlog/'.date('Ym', TIME).'.csv';
  $fp = fopen($logfile, 'a');
  fputcsv($fp, $logdata);
  fclose($fp);
  return true;
 }
 return false;
}

//格式化文本域(过滤空格)

function format_textarea($string)
{
 return nl2br(str_replace(' ', ' ', htmlspecialchars($string)));
}

格式化js(过滤)

function format_js($string, $isjs = 1)
{
 $string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
 return $isjs ? 'document.write("'.$string.'");' : $string;
}

if(!function_exists('file_put_contents'))
{
 define('FILE_APPEND', 8);
 function file_put_contents($file, $data, $append = '')
 {
  $mode = $append == '' ? 'wb' : 'ab';
  $fp = @fopen($file, $mode) or exit("Can not open file $file !");
  flock($fp, LOCK_EX);
  $len = @fwrite($fp, $data);
  flock($fp, LOCK_UN);
  @fclose($fp);
  return $len;
 }
}

if(!function_exists('http_build_query'))
{
    function http_build_query($data, $prefix = null, $sep = '', $key = '')
 {
        $ret = array();
  foreach((array)$data as $k => $v)
  {
   $k = urlencode($k);
   if(is_int($k) && $prefix != null)
   {
    $k = $prefix.$k;
   }
   if(!empty($key)) {
    $k = $key."[".$k."]";
   }
   if(is_array($v) || is_object($v))
   {
    array_push($ret,http_build_query($v,"",$sep,$k));
   }
   else
   {
    array_push($ret,$k."=".urlencode($v));
   }
  }
        if(empty($sep))
  {
            $sep = ini_get("arg_separator.output");
        }
        return implode($sep, $ret);
    }
}

if(!function_exists('image_type_to_extension'))
{
    function image_type_to_extension($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp' ,'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc', 'aiff', 'wbmp', 'xbm');
        $type = intval($type);
        if (!$type)
  {
            trigger_error( 'File Type is null...', E_USER_NOTICE );
            return null;
        }
        if(!isset($e[$type]))
  {
            trigger_error( 'Image type is wrong...', E_USER_NOTICE );
            return null;
        }
        return ($dot ? '.' : '') . $e[$type];
    }
}

if(!function_exists('array_intersect_key'))
{
 function array_intersect_key($isec, $keys)
 {
  $argc = func_num_args();
  if ($argc > 2)
  {
   for ($i = 1; !empty($isec) && $i < $argc; $i++)
   {
    $arr = func_get_arg($i);
    foreach (array_keys($isec) as $key)
    {
     if (!isset($arr[$key]))
     {
      unset($isec[$key]);
     }
    }
   }
   return $isec;
  }
  else
  {
   $res = array();
   foreach (array_keys($isec) as $key)
   {
    if (isset($keys[$key]))
    {
     $res[$key] = $isec[$key];
    }
   }
   return $res;
  }
 }
}

if(!function_exists('json_encode'))
{
 function json_encode($string)
 {
  require_once 'json.class.php';
  $json = new json();
  return $json->encode($string);
 }
}

if(!function_exists('json_decode'))
{
 function json_decode($string,$type = 1)
 {
  require_once 'json.class.php';
  $json = new json();
  return $json->decode($string,$type);
 }
}

if(!function_exists('iconv'))
{

 //初始化编码函数
 function iconv($in_charset, $out_charset, $str)
 {
  if(function_exists('mb_convert_encoding'))
  {
   return mb_convert_encoding($str, $out_charset, $in_charset);
  }
  else
  {

   require_once 'iconv.func.php';
   $in_charset = strtoupper($in_charset);
   $out_charset = strtoupper($out_charset);
   if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312'))
   {
    return utf8_to_gbk($str);
   }
   if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8')
   {
    return gbk_to_utf8($str);
   }
   return $str;
  }
 }
}

function str_charset($in_charset, $out_charset, $str_or_arr)
{
 if(is_array($str_or_arr))
 {
  foreach($str_or_arr as $k=>$v)
  {
   $str_or_arr[$k] = str_charset($in_charset, $out_charset, $v);
  }
 }
 else
 {
  $str_or_arr = iconv($in_charset, $out_charset, $str_or_arr);
 }
 return $str_or_arr;
}

//字符串过滤('..', "\n", "\r"),

function stripstr($str)
{
 return str_replace(array('..', "\n", "\r"), array('', '', ''), $str);
}

if(!function_exists('fputcsv'))
{

 //输出cvs文件
 function fputcsv(&$fp, $array, $delimiter = ',', $enclosure = '"')
 {
  $data = $enclosure.implode($enclosure.$delimiter.$enclosure, $array).$enclosure."\n";
  return fwrite($fp, $data);
 }
}

//生成随机数

function random($length, $chars = '0123456789')
{
 $hash = '';
 $max = strlen($chars) - 1;
 for($i = 0; $i < $length; $i++)
 {
  $hash .= $chars[mt_rand(0, $max)];
 }
 return $hash;
}

//设置cookie

function set_cookie($var, $value = '', $time = 0)
{
 $time = $time > 0 ? $time : ($value == '' ? PHP_TIME - 3600 : 0);
 $s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
 $var = COOKIE_PRE.$var;
 $_COOKIE[$var] = $value;
 if(is_array($value))
 {
  foreach($value as $k=>$v)
  {
   setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
  }
 }
 else
 {
  setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
 }
}

//读取cookie

function get_cookie($var)
{
 $var = COOKIE_PRE.$var;
 return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}

//文章生成

function content_set($contentid, $field, $data)
{
 return @file_put_contents(content_file($contentid, $field), $data);
}

//文章读取

function content_get($contentid, $field)
{
 return @file_get_contents(content_file($contentid, $field));
}

//文章删除

function content_del($contentid, $field)
{
 return @unlink(content_file($contentid, $field));
}

//文章文件

function content_file($contentid, $field)
{
 $id = str_pad($contentid, 4, '0', STR_PAD_LEFT);
 return CONTENT_ROOT.$field.'/'.substr($id, 0, 2).'/'.substr($id, 2, 2).'/'.$contentid.'.txt';
}

//文章

function content_init($field)
{
 @set_time_limit(300);
 @mkdir(CONTENT_ROOT.$field, 0777);
 for($i=1; $i<=9999; $i++)
 {
  $id = str_pad($i, 4, '0', STR_PAD_LEFT);
  $dir1 = CONTENT_ROOT.$field.'/'.substr($id, 0, 2);
  $dir2 = $dir1.'/'.substr($id, 2, 2);
  @mkdir($dir1, 0777);
  @mkdir($dir2, 0777);
 }
 return true;
}

//菜单

function menu($parentid, $code = '')
{
 global $db, $_userid, $_roleid, $_groupid;
 $code = str_replace('"', '\"', $code);
 $where = $parentid == 99 ? "AND userid=$_userid" : '';
 $menus = $db->select("SELECT * FROM `".DB_PRE."menu` WHERE `parentid`='$parentid' $where ORDER BY `listorder`,`menuid`", 'menuid');
 if($code)
 {
  foreach($menus as $m)
  {
   extract($m);

//权限判断,后台权限
   if(($roleids && defined('IN_ADMIN') && !check_in($_roleid, $roleids)) || ($groupids && !defined('IN_ADMIN') && !check_in($_groupid, $groupids))) continue;
   eval("\$menu .= \"$code\";");
  }
  $menus = $menu;
 }
 return $menus;
}

function url($url, $isabs = 0)
{
 if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;
 if($isabs || defined('SHOWJS'))
 {
  $url = strpos($url, PHPCMS_PATH) === 0 ? SITE_URL.substr($url, strlen(PHPCMS_PATH)) : SITE_URL.$url;
 }
 else
 {
  $url = strpos($url, PHPCMS_PATH) === 0 ? $url : PHPCMS_PATH.$url;
 }
 return $url;
}

//客户端浏览器判断

function is_ie()
{
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
 if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
 if(strpos($useragent, 'msie ') !== false) return true;
 return false;
}

//客户端判断

function is_websearch()
{
 if(!defined('IS_WEBSEARCH'))
 {
  $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  $browsers = 'msie|netscape|opera|konqueror|mozilla';
  $spiders = 'bot|spider|google|isaac|surveybot|baiduspider|yahoo|sohu-search|yisou|3721|qihoo|daqi|ia_archiver|p.arthur|fast-webcrawler|java|microsoft-atl-native|turnitinbot|webgather|sleipnir|msn';
  if(preg_match("/($browsers)/", $_SERVER['HTTP_USER_AGENT']))
  {
   define('IS_WEBSEARCH', FALSE);
  }
  elseif(preg_match("/($spiders)/", $_SERVER['HTTP_USER_AGENT']))
  {
   define('IS_WEBSEARCH', TRUE);
  }
  else
  {
   define('IS_WEBSEARCH', FALSE);
  }
 }
 return IS_WEBSEARCH;
}

//日期判断

function is_date($ymd, $sep='-')
{
 if(empty($ymd)) return FALSE;
 list($year, $month, $day) = explode($sep, $ymd);
 return checkdate($month, $day, $year);
}

//email判断

function is_email($email)
{
 return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//判断字符串是否存在

function str_exists($haystack, $needle)
{
 return !(strpos($haystack, $needle) === FALSE);
}

//是否下载文件

function file_down($filepath, $filename = '')
{
 if(!$filename) $filename = basename($filepath);
 if(is_ie()) $filename = rawurlencode($filename);
 $filetype = fileext($filename);
 $filesize = sprintf("%u", filesize($filepath));
 if(ob_get_length() !== false) @ob_end_clean();
 header('Pragma: public');
 header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
 header('Cache-Control: no-store, no-cache, must-revalidate');
 header('Cache-Control: pre-check=0, post-check=0, max-age=0');
 header('Content-Transfer-Encoding: binary');
 header('Content-Encoding: none');
 header('Content-type: '.$filetype);
 header('Content-Disposition: attachment; filename="'.$filename.'"');
 header('Content-length: '.$filesize);
 readfile($filepath);
 exit;
}

function fileext($filename)
{
 return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

//将id数组用 ',' 分割开来

function implodeids($array, $s = ',')
{
 if(empty($array)) return '';
 return is_array($array) ? implode($s, $array) : $array;
}

//提交检查

function check_submit($var)
{
 if(empty($GLOBALS[$var])) return false;
 if(empty($_SERVER['HTTP_REFERER'])) return true;
 return strpos($_SERVER['HTTP_REFERER'], DOMAIN) === 7;
}

//id检查

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);
}

//获取客户端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,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}

//获取被封ip列表

function ip_banned($ip)
{
 $ips = cache_read('ipbanned.php');
 if(!$ips) return false;
 foreach($ips as $k=>$v)
 {
  if($v < TIME) continue;
  if($ip == $k) return true;
  if(strpos($k, '*'))
  {
   $k = str_replace(array('.', '*'), array('\.', '[0-9]{1,3}'), $k);
      if(preg_match("/$v/", $ip)) return true;
  }
 }
 return false;
}

//字符串切割

function str_cut($string, $length, $dot = '...')
{
 $strlen = strlen($string);
 if($strlen <= $length) return $string;
 $string = str_replace(array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
 $strcut = '';
 if(strtolower(CHARSET) == 'utf-8')
 {
  $n = $tn = $noc = 0;
  while($n < $strlen)
  {
   $t = ord($string[$n]);
   if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
    $tn = 1; $n++; $noc++;
   } elseif(194 <= $t && $t <= 223) {
    $tn = 2; $n += 2; $noc += 2;
   } elseif(224 <= $t && $t < 239) {
    $tn = 3; $n += 3; $noc += 2;
   } elseif(240 <= $t && $t <= 247) {
    $tn = 4; $n += 4; $noc += 2;
   } elseif(248 <= $t && $t <= 251) {
    $tn = 5; $n += 5; $noc += 2;
   } elseif($t == 252 || $t == 253) {
    $tn = 6; $n += 6; $noc += 2;
   } else {
    $n++;
   }
   if($noc >= $length) break;
  }
  if($noc > $length) $n -= $tn;
  $strcut = substr($string, 0, $n);
 }
 else
 {
  $dotlen = strlen($dot);
  $maxi = $length - $dotlen - 1;
  for($i = 0; $i < $maxi; $i++)
  {
   $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  }
 }
 $strcut = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $strcut);
 return $strcut.$dot;
}

//缓存开始

function cache_page_start()
{
 define('CACHE_PAGE_ID', md5(RELATE_URL));
 define('CACHE_PAGE_DIR', CACHE_PAGE_PATH.substr(CACHE_PAGE_ID, 0, 2).'/');
 define('CACHE_PAGE_FILE', CACHE_PAGE_DIR.CACHE_PAGE_ID.'.html');
 $contents = @file_get_contents(CACHE_PAGE_FILE);
 if($contents && intval(substr($contents, 15, 25)) > TIME)
 {
  echo substr($contents, 29);
  exit;
 }
 return true;
}

//缓存页面

function cache_page($ttl = CACHE_PAGE_TTL, $isjs = 0)
{
 if($ttl == 0 || !defined('CACHE_PAGE_FILE')) return false;
 $contents = ob_get_contents();
 if($isjs) $contents = format_js($contents);
 dir_create(CACHE_PAGE_DIR);
 $contents = "\n".$contents;
 file_put_contents(CACHE_PAGE_FILE, $contents);
 @chmod(CACHE_PAGE_FILE, 0777);
}

//清除缓存

function cache_page_clear()
{
 @set_time_limit(600);
 $dirs = glob(CACHE_PAGE_PATH.'*');
 foreach($dirs as $dir)
 {
  $files = glob($dir.'/*');
  foreach($files as $file)
  {
   @unlink($file);
  }
  @rmdir($dir);
 }
}

 

function cache_count($sql)
{
 global $db, $TEMP;
 $id = md5($sql);
 if(!isset($TEMP['count'][$id]))
 {
  if(CACHE_COUNT_TTL)
  {
   $r = $db->get_one("SELECT `count`,`updatetime` FROM `".DB_PRE."cache_count` WHERE `id`='$id'");
   if(!$r || $r['updatetime'] < TIME - CACHE_COUNT_TTL)
   {
    $r = $db->get_one($sql);
    $TEMP['count'][$id] = $r['count'];
    $db->query("REPLACE INTO `".DB_PRE."cache_count`(`id`, `count`, `updatetime`) VALUES('$id', '".$r['count']."', '".TIME."')");
   }
  }
  else
  {
   $r = $db->get_one($sql);
  }
  $TEMP['count'][$id] = $r['count'];
 }
 return $TEMP['count'][$id];
}

//会员缓存

function cache_member()
{
 global $db;
 $status = $db->table_status(DB_PRE.'member_cache');
 if($status['Rows'] == 0)
 {
  @set_time_limit(600);
  $db->query("INSERT INTO `".DB_PRE."member_cache` SELECT * FROM `".DB_PRE."member`");
  return true;
 }
 return false;
}

//读取缓存

function cache_read($file, $path = '', $iscachevar = 0)
{
 if(!$path) $path = CACHE_PATH;
 $cachefile = $path.$file;
 if($iscachevar)
 {
  global $TEMP;
  $key = 'cache_'.substr($file, 0, -4);
  return isset($TEMP[$key]) ? $TEMP[$key] : $TEMP[$key] = @include $cachefile;
 }
 return @include $cachefile;
}

//写入缓存

function cache_write($file, $array, $path = '')
{
 if(!is_array($array)) return false;
 $array = "";
 $cachefile = ($path ? $path : CACHE_PATH).$file;
 $strlen = file_put_contents($cachefile, $array);
 @chmod($cachefile, 0777);
 return $strlen;
}

//删除缓存

function cache_delete($file, $path = '')
{
 $cachefile = ($path ? $path : CACHE_PATH).$file;
 return @unlink($cachefile);
}

function setting_set($tablename, $where, $setting)
{
 global $db;
 if(!is_array($setting)) return false;
 $setting = new_stripslashes($setting);
 $setting = addslashes(var_export($setting, TRUE));
 return $db->query("UPDATE `$tablename` SET `setting`='$setting' WHERE $where");
}

//获取设置信息

function setting_get($tablename, $where)
{
 global $db;
 $r = $db->get_one("SELECT `setting` FROM `$tablename` WHERE $where LIMIT 1");
 $setting = $r['setting'];
 if($setting) eval("\$setting = $setting;");
 else $setting = array();
 return $setting;
}

//字符串转换为数组

function string2array($data)
{
 if($data == '') return array();
 eval("\$array = $data;");
 return $array;
}

//数组转换为字符串

function array2string($data, $isformdata = 1)
{
 if($data == '') return '';
 if($isformdata) $data = new_stripslashes($data);
 return addslashes(var_export($data, TRUE));
}

//栏目

function subcat($module = 'phpcms', $parentid = NULL, $type = NULL)
{
 global $CATEGORY;
 $subcat = array();
 foreach($CATEGORY as $id=>$cat)
 {
  if($cat['module'] == $module && ($parentid === NULL || $cat['parentid'] == $parentid) && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
 }
 return $subcat;
}

//模型

function submodelcat($modelid = 1, $parentid = NULL, $type = NULL)
{
 global $CATEGORY;
 $subcat = array();
 foreach($CATEGORY as $id=>$cat)
 {
  if($cat['modelid'] == $modelid && ($parentid === NULL || $cat['parentid'] == $parentid) && $cat['parentid'] !=0 && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
 }

 return $subcat;
}

//栏目url规则

function catpos($catid, $urlrule = '')
{
 global $CATEGORY;
 if(!isset($CATEGORY[$catid])) return '';
 $pos = '';
 $arrparentid = array_filter(explode(',', $CATEGORY[$catid]['arrparentid'].','.$catid));
 foreach($arrparentid as $catid)
 {
  if($urlrule) eval("\$url = \"$urlrule\";");
  else $url = $CATEGORY[$catid]['url'];
  $pos .= ''.$CATEGORY[$catid]['catname'].'';
 }
 return $pos;
}

//地区

function subarea($parentid = 0)
{
 global $AREA;
 $subarea = array();
 foreach($AREA as $id=>$area)
 {
  if($area['parentid'] == $parentid) $subarea[$id] = $area;
 }
 return $subarea;
}

//地区

function areapos($areaid, $urlrule = '')
{
 global $AREA;
 if(!isset($AREA[$areaid])) return '';
 $pos = '';
 $arrparentid = array_filter(explode(',', $AREA[$areaid]['arrparentid'].','.$areaid));
 foreach($arrparentid as $areaid)
 {
  if($urlrule) eval("\$url = \"$urlrule\";");
  else $url = $AREA[$areaid]['url'];
  $pos .= ''.$AREA[$areaid]['name'].'';
 }
 return $pos;
}

//类型

function subtype($module = 'phpcms')
{
 global $TYPE;
 $subtype = array();
 foreach($TYPE as $id=>$type)
 {
  if($type['module'] == $module) $subtype[$id] = $type;
 }
 return $subtype;
}

//模板调用函数

function template($module = 'phpcms', $template = 'index', $istag = 0)
{
 $compiledtplfile = TPL_CACHEPATH.$module.'_'.$template.'.tpl.php';
 if(TPL_REFRESH && (!file_exists($compiledtplfile) || @filemtime(TPL_ROOT.TPL_NAME.'/'.$module.'/'.$template.'.html') > @filemtime($compiledtplfile) || @filemtime(TPL_ROOT.TPL_NAME.'/tag.inc.php') > @filemtime($compiledtplfile)))
 {
  require_once PHPCMS_ROOT.'include/template.func.php';
  template_compile($module, $template, $istag);
 }
 return $compiledtplfile;
}

//图片

function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1)
{
 global $image;
 if(empty($imgurl)) return 'images/nopic_small.gif';
 if(!extension_loaded('gd') || strpos($imgurl, '://')) return $imgurl;
 if(!file_exists(PHPCMS_ROOT.$imgurl)) return 'images/nopic.gif';
 $newimgurl = dirname($imgurl).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl);
 if(file_exists($newimgurl)) return $newimgurl;
 if(!is_object($image))
 {
  require_once 'image.class.php';
  $image = new image();
 }
 return $image->thumb(PHPCMS_ROOT.$imgurl, PHPCMS_ROOT.$newimgurl, $width, $height, '', $autocut) ? $newimgurl : $imgurl;
}

//ssi加密

function ssi($file)
{
 if(!file_exists(PHPCMS_ROOT.$file)) return false;
 return (SHTML && defined('CREATEHTML')) ? '' : @file_get_contents(PHPCMS_ROOT.$file);
}

//sql获取记录

function get($sql, $rows = 0, $page = 0, $dbname = '', $dbsource = '')
{
 if(!$sql) return false;
 if($dbsource)
 {
  $s = cache_read('db_'.$dbsource.'.php', '', 1);
  if(!$s) return false;
  if($s['status'])
  {
            global $db;
   $dbname = $s['dbname'];
  }
  else
  {
   $db = new db_mysql;
   $db->connect($s['dbhost'], $s['dbuser'], $s['dbpw'], $s['dbname'], 0, $s['dbcharset']);
  }
 }
 else
 {
  global $db;
  if(DB_PRE != 'phpcms_') $sql = str_replace('phpcms_', DB_PRE, $sql);
 }
 if($dbname) $db->select_db($dbname) or exit("The database $database is not exists!");
 $rows = intval($rows);
 if(!isset($page)) $page = 1;
 $page = max(intval($page), 0);
 $pages = $limit = '';
 if($page)
 {
  $offset = $rows*($page-1);
  $limit = " LIMIT $offset, $rows";
  if($dbname || $dbsource)
  {
   $r = $db->get_one("SELECT COUNT(*) AS `count` ".stristr($sql, 'from'));
   $total = $r['count'];
  }
  else
  {
   $total = cache_count("SELECT COUNT(*) AS `count` ".stristr($sql, 'from'));
  }
  $pages = pages($total, $page, $rows);
 }
 elseif($rows > 0)
 {
  $limit = " LIMIT $rows";
 }
 $data = $rows == -1 ? $db->get_one($sql) : $db->select($sql.$limit);
 if($dbname) $db->select_db(DB_NAME);
 if(isset($s['dbcharset']) && $s['dbcharset'] != DB_CHARSET) $data = str_charset($s['dbcharset'], DB_CHARSET, $data);
 if($page)
 {
  $count = count($data);
  if(!isset($total)) $total = $count;
  return array('data'=>$data, 'total'=>$total, 'count'=>count($data), 'pages'=>$pages);
 }
 else
 {
  return $data;
 }
}

//标签函数

function tag($module, $template, $sql, $page = 0, $number = 10, $setting = array(), $catid = 0)
{
 global $db, $CATEGORY, $MODULE, $URLRULE, $PHPCMS, $MODEL;
 if($sql)
 {
  @include_once PHPCMS_ROOT.$MODULE[$module]['path'].'include/output.func.php';
  $offset = 0;
  if($page !== 0)
  {
   $page = max(intval($page), 1);
   $offset = $number*($page-1);
   $count = cache_count("SELECT COUNT(*) AS `count` ".stristr($sql, 'from'));
   $urlruleid = isset($setting['urlruleid']) ? intval($setting['urlruleid']) : 0;
   $urlrule = $urlruleid > 0 ? $URLRULE[$urlruleid] : '';
   $pages = pages($count, $page, $number, $urlrule, $setting, $catid);
  }
  $i = 0;
  $data = array();
  $result = $db->query("$sql LIMIT $offset, $number");
  while($r = $db->fetch_array($result))
  {
   $data[++$i] = $r;
  }
  $rows = $db->num_rows($result);
  $db->free_result($result);
 }
 else
 {
  $data = array();
  $number = $rows = $count = $page = 0;
  $pages = '';
 }
 require_once template($module, $template, 1);
 $func = '_tag_'.$module.'_'.$template;
 $func($data, $number, $rows, $count, $page, $pages, $setting);
}

//模块信息

function block($pageid, $blockno)
{
 echo ssi('data/block/'.$pageid.'_'.$blockno.'.html');
}

//获取栏目

function get_sql_catid($catid)
{
 global $CATEGORY;
 $catid = intval($catid);
 if(!isset($CATEGORY[$catid])) return false;
 return $CATEGORY[$catid]['child'] ? " AND `catid` IN(".$CATEGORY[$catid]['arrchildid'].") " : " AND `catid`=$catid ";
}

//获取sql

function get_sql_in($string, $s = ' ')
{
 $array = array_map('trim', explode($s, $string));
 $array = new_addslashes($array);
 return "'".implode("','", $array)."'";
}

//获取分页信息

function pages($total, $page = 1, $perpage = 20, $urlrule = '', $array = array(), $catid = 0)
{
 global $PHPCMS;
 if($total < 1) return '';
 if($urlrule == '') $urlrule = url_par('page={$page}');
 $pages = ceil($total/$perpage);
 $page = min($pages, $page);
 $prepage = $page - 1;
 $prepage = max($prepage, 1);
 $nextpage = $page+1;
 $nextpage = min($nextpage, $pages);
 if($catid)
 {
  $url = load('url.class.php');
  $firstpage = $url->category($catid, 1, 1);
  $prepage = $url->category($catid, $prepage, 1);
  $nextpage = $url->category($catid, $nextpage, 1);
        $lastpage = $url->category($catid, $pages, 1);
  $urlpre = $url->category($catid, '', 1);
 }
 else
 {
  $firstpage = pageurl($urlrule, 1, $array);
  $prepage = pageurl($urlrule, $prepage, $array);
  $nextpage = pageurl($urlrule, $nextpage, $array);
        $lastpage = pageurl($urlrule, $pages, $array);
  $urlpre = pageurl($urlrule, '', $array);
 }
 $data = str_replace('"', '\"', $PHPCMS['pageshtml']);
 eval("\$url = \"$data\";");
 return $url;
}

//分页url

function pageurl($urlrule, $page, $array = array())
{
 extract($array, EXTR_SKIP);
 if(strpos($urlrule, '|'))
 {
  $urlrules = explode('|', $urlrule);
  $urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
 }
 eval("\$url = \"$urlrule\";");
 return $url;
}

//发送消息

function showmessage($msg, $url_forward = 'goback', $ms = 1250, $direct = 0)
{
 global $PHPCMS;
 if($url_forward && $url_forward != 'goback' && $url_forward != 'close') $url_forward = url($url_forward, 1);
    if($direct && $url_forward && $url_forward!='goback')
    {
        ob_clean();
        header("location:$url_forward");
        exit("");
    }
 include defined('IN_ADMIN') ? PHPCMS_ROOT.'admin/templates/showmessage.tpl.php' : template('phpcms','showmessage');
 exit;
}

//生成静态

function createhtml($file)
{
 $data = ob_get_contents();
 ob_clean();
 dir_create(dirname($file));
 $strlen = file_put_contents($file, $data);
 @chmod($file,0777);
 return $strlen;
}

//键值生成

function keyid_make($module, $tablename, $titlefield, $id)
{
 $keyid = $module.'-'.$tablename.'-'.$titlefield.'-'.$id;

 $verify = md5($keyid.AUTH_KEY);
 return array($keyid, $verify);
}

//获取键值

function keyid_get($keyid)
{
 global $db;
 list($module, $tablename, $titlefield, $id) = explode('-', $keyid);
 $tablename = DB_PRE.$tablename;
 $keyfield = $db->get_primary($tablename);
 return $db->get_one("SELECT `$titlefield` AS title,`url` FROM `$tablename` WHERE `$keyfield`='$id'");
}

function keyid_verify($keyid, $verify)
{
    $keyid = md5($keyid.AUTH_KEY);
 return $verify == $keyid;
}

//验证码

function checkcode($checkcode, $enable = 1, $forward = '')
{
 global $LANG;
 if(!$enable) return true;
 session_start();
 if(!isset($_SESSION['checkcode'])) showmessage($LANG['do_not_refresh'], $forward);
 if(strtolower($_SESSION['checkcode']) != strtolower($checkcode))
 {
  unset($_SESSION['checkcode']);
  showmessage($LANG['checkcode_error'], $forward);
 }
 unset($_SESSION['checkcode']);
 return true;
}

function usedtime()
{
 $stime = explode(' ', MICROTIME_START);
 $etime = explode(' ', microtime());
 return number_format(($etime[1] + $etime[0] - $stime[1] - $stime[0]), 6);
}

//错误报告

function debug()
{
 global $db;
 if(!DEBUG || defined('CREATEHTML')) return false;
 define('DEBUG_TIME', usedtime());
 define('DEBUG_QUERIES', $db->querynum);
 return true;
}

//tpl缓存

function tpl_data($module = 'phpcms', $template = 'index')
{
 @extract($GLOBALS, EXTR_SKIP);
 ob_start();
 include template($module, $template);
 $data = ob_get_contents();
 ob_clean();
 return $data;
}

//加载地区

function load($file, $module = 'phpcms', $dir = '', $isinit = 1)
{
 global $MODULE;
 if(!isset($MODULE[$module])) return false;
 $path = PHPCMS_ROOT.$MODULE[$module]['path'].($dir ? $dir.'/' : 'include/').$file;
 if(!(@include_once $path)) return false;
 if($isinit && strpos($file, '.class.php') !== false)
 {
  $classname = substr($file, 0, -10);
  return new $classname();
 }
 return true;
}

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;
}

function phpcms_auth($txt, $operation = 'ENCODE', $key = '')
{
 $key = $key ? $key : $GLOBALS['phpcms_auth_key'];
 $txt = $operation == 'ENCODE' ? $txt : base64_decode($txt);
 $len = strlen($key);
 $code = '';
 for($i=0; $i  $k  = $i % $len;
  $code  .= $txt[$i] ^ $key[$k];
 }
 $code = $operation == 'DECODE' ? $code : base64_encode($code);
 return $code;
}

function hash_string($str)
{
 $str = str_pad($str, 10, 0, STR_PAD_LEFT);
 $str = base64_encode($str);
 $str = substr($str,-5,-3).substr($str,0,-2);
 return $str;
}

function areaname($areaid)
{
 global $AREA;
 if(!isset($AREA[$areaid])) return '';
 $pos = array();
    $arrparentid = array_filter(explode(',', $AREA[$areaid]['arrparentid'].','.$areaid));
 foreach($arrparentid as $areaid)
 {
  $pos[] = $AREA[$areaid]['name'];
 }
 return join('.',$pos);
}

function magic_image($txt, $fonttype = 4)
{
 if(empty($txt)) return false;
 if(function_exists("imagepng"))
 {
  $txt = phpcms_auth($txt, 'ENCODE', AUTH_KEY);
  $txt = '';
 }
 return $txt;
}

function keylinks($txt, $replacenum = '')
{
 $linkdatas = cache_read('keylink.php','',1);
 if($linkdatas)
 {
  $word = $replacement = array();
  foreach($linkdatas as $v)
  {
   $word1[] = '/'.preg_quote($v[0], '/').'/';
   $word2[] = $v[0];
   $replacement[] = ''.$v[0].'';
  }
  if($replacenum != '')
  {
   $txt = preg_replace($word1, $replacement, $txt, $replacenum);
  }
  else
  {
   $txt = str_replace($word2, $replacement, $txt);
  }

 }
 return $txt;
}

function url_par($par, $url = '')
{
 if($url == '') $url = URL;
 $pos = strpos($url, '?');
 if($pos === false)
 {
  $url .= '?'.$par;
 }
 else
 {
  $querystring = substr(strstr($url, '?'), 1);
  parse_str($par, $pars);
  foreach($pars as $k=>$v)
  {
   $querystring = _url_par($k, $v, $querystring);
  }
  $url = substr($url, 0, $pos).'?'.$querystring;
 }
 return $url;
}

function _url_par($var, $value, $querystring)
{
 if($querystring)
 {
  $pattern = "/([&]?)(".preg_quote($var)."\=)([^&]+)([&]?)/";
  $querystring = preg_match($pattern, $querystring) ? preg_replace($pattern, '${1}${2}'.$value.'${4}', $querystring) : $querystring."&$var=$value";
 }
 else
 {
  $querystring = $var.'='.$value;
 }
 return $querystring;
}

function username($userid)
{
 global $db;
 $userid = intval($userid);
 $r = $db->get_one("SELECT `username` FROM `".DB_PRE."member_cache` WHERE `userid`=$userid");
 return $r ? $r['username'] : false;
}

function userid($username)
{
 global $db;
 $r = $db->get_one("SELECT `userid` FROM `".DB_PRE."member_cache` WHERE `username`='$username'");
 return $r ? $r['userid'] : false;
}

function phpcms_error($errno, $errmsg, $filename, $linenum, $vars)
{
 $filename = str_replace(PHPCMS_ROOT, '.', $filename);
 $filename = str_replace("\\", '/', $filename);
 if(!defined('E_STRICT')) define('E_STRICT', 2048);
 $dt = date('Y-m-d H:i:s');
 $errortype = array (
 E_ERROR           => 'Error',
 E_WARNING         => 'Warning',
 E_PARSE           => 'Parsing Error',
 E_NOTICE          => 'Notice',
 E_CORE_ERROR      => 'Core Error',
 E_CORE_WARNING    => 'Core Warning',
 E_COMPILE_ERROR   => 'Compile Error',
 E_COMPILE_WARNING => 'Compile Warning',
 E_USER_ERROR      => 'User Error',
 E_USER_WARNING    => 'User Warning',
 E_USER_NOTICE     => 'User Notice',
 E_STRICT          => 'Runtime Notice'
 );
 $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
 $err = "\n";
 $err .= "\t" . $dt . "\n";
 $err .= "\t" . $errno . "\n";
 $err .= "\t" . $errortype[$errno] . "\n";
 $err .= "\t" . $errmsg . "\n";
 $err .= "\t" . $filename . "\n";
 $err .= "\t" . $linenum . "\n";
 if (in_array($errno, $user_errors))
 {
  $err .= "\t" . wddx_serialize_value($vars, "Variables") . "\n";
 }
 $err .= "
\n\n";
 error_log($err, 3, PHPCMS_ROOT.'/data/php_error_log.xml');
 @chmod(PHPCMS_ROOT.'/data/php_error_log.xml', 0777);
}
?>

你可能感兴趣的:(PHP学习园)