常用的公用代码[未整理版]

<?php /** * 将每条新闻的新闻类别加入到对应的数据 * @param object $row 每一行记录 */ function CS_join_category(&$row) { $CI = &get_instance(); $CI->db->where('categories_id', $row->news_sub_categories); //查询条件 $CI->db->select('categories_name'); $query = $CI->db->get('categories'); if (sizeof($query->result()) > 0) { //如果类别存在时 CS_object_merge($row, $query->row()); //将新闻类别添加到新闻信息中去 } } /** * 将配置权限输出成checkbox * @param array $permissions 权限数组 * @param array $defaultValue 默认值 * @return string */ function CS_permissions_to_checkbox($permissions, $defaultValue) { $checkboxes = array(); foreach ($permissions as $key => $value) { $config_checkbox = array( 'name' => 'roles_permissions[]', 'id' => 'roles_permissions'.$key, 'class' => 'checkbox', 'value' => $value ); if (in_array($value, $defaultValue)) { //如果值存在于默认值中,那么设置checkbox为选中状态 $config_checkbox['checked'] = 'checked'; } array_push($checkboxes, '<label for="'.$config_checkbox['id'].'">'.form_checkbox($config_checkbox).$value.'</label> '); } return join('', $checkboxes); } /** * 加入日志信息 * @param array $data 插入数据库的数据 数组的键名为“字段名”,数组值为插入对应字段的值 * $data = array('logs_user_id' => '1', 'logs_type' => 'user', 'logs_text' => 'xxx在什么时候修改了什么') * 注意:logs_type 一般为模块的表名 * @return boolean 成功则返回true */ function CS_insert_log($data) { $CI = &get_instance(); return $CI->db->insert('logs', $data); } /** * 取得手机型号信息 * @param string or array $where 查询的条件 */ function CS_get_config_search($key) { $old_key = $key; $key = "se_".$key; static $STATIC_CONFIG_INFO = array(); if (!isset($STATIC_CONFIG_INFO[$key])) { $CI = &get_instance(); //读数据库模式. $CI->config->load("search/$old_key"); $val = $CI->config->item($key); if( !$val ) $val = "<hr/><font color = 'red'>尚无-[$key]-项配置文字,请及时添加相应的内容</font><hr/><br>"; $STATIC_CONFIG_INFO[$key] = $val; } return $STATIC_CONFIG_INFO[$key]; } /** * 加入日志信息 * @param array $data 插入数据库的数据 数组的键名为“字段名”,数组值为插入对应字段的值 * 注意:logs_type 一般为模块的表名 * @return boolean 成功则返回true */ function CS_insert_log_func($type = '' ,$text = '', $channel_type = '') { $data['logs_user_id'] = $_SESSION['admin_user_data']->user_id; $data['logs_type'] = $type; $data['logs_text'] = $_SESSION['admin_user_data']->user_name.'--'.$text; $data['logs_channel_type'] = $channel_type; return CS_insert_log($data); } /** * 根据手机号码,取得手机号段相关信息(所在省份,城市,省份编号,城市编号) * * @param int $mobile 手机号码 * @return mixed */ function CS_get_info_by_mobile($mobile, $data_path = 'inc/mobile_data'){ if (preg_match('/^([0-9]{4})([0-9]{3})/', $mobile, $path)) { $filename = $data_path."/$path[1]/$path[2]"; list($array['city_code'],$array['province_code'],$array['province'],,$array['city'],) = explode(",", file_get_contents($filename)); return $array; } else { return FALSE; } } /** * 根据产品ID和手机号,取得换分省的通道信息 * * @param int $mobile 手机号码 * @param int $product_id 产品ID * @return mixed 如果发生错误则返回错误信息 */ function CS_get_channel($mobile, $product_id) { if (!isset($static_channel) || !is_array($static_channel)) { //注册机模式 static $static_channel = array(); } if (!isset($static_channel[$mobile.$product_id])) { //如果没有取得手机的通道信息 $CI = & get_instance(); $mobile_facilitator = CS_get_mobile_facilitator($mobile); //取得手机号码的服务商(移动,联通,小灵通) $model_name = CS_get_model_name('config_channel'); $CI->load->model($model_name); //载入换分省模型 $where = array( 'config_channel_product_id' => $product_id, 'config_channel_type_id' => (string)$mobile_facilitator ); $rows = $CI->$model_name->get($where); if (sizeof($rows) === 0) { //如果没有设置通道 return 'error||专属通道还未设置'; } else { $mobile_info = CS_get_info_by_mobile($mobile); //取得手机号段的相关信息 $set = $rows[0]->config_channel_set_php; //取得换分省的通道设置 //取得通道编号(如果没有给省份设置指定的通道,那么使用默认设置通道) $channel_id = $set[$mobile_info['province_code']] == '' ? $set[0] : $set[$mobile_info['province_code']]; /* 查询该通道的信息 start */ $channel_model_name = CS_get_model_name('channel'); $CI->load->model($channel_model_name); //载入通道的数据库操作模型 $channel_row = $CI->$channel_model_name->row($channel_id); //取得通道的信息 /* 查询该通道的信息 end */ if ($channel_row !== FALSE) { if ($channel_row->channel_state == '2') { //如果通道是正常状态 $static_channel[$mobile.$product_id] = $channel_row; //注册通道信息到$static_channel数组,类似缓存功能 } else { $config_channel_status = CS_get('通道状态'); //取得通道状态的配置信息 return 'error||通道'.$config_channel_status[$channel_row->channel_state]; } } else { return 'error||通道不存在'.$CI->db->last_query(); } } } return $static_channel[$mobile.$product_id]; //返回通道信息 } /** * 得到查询参数,并 * * @param string $_POST 查询条件 * @return list($where,$parameters,$search_equal) ; * 注意:识别搜索的模式是通过给字段加前缀来实现的. * 字符串中 search_like_ 表式为like 查询.而post 模式则用search_like 数组来表式. * 字符串中 search_mult_ 表式一个字段下多值or查询,用 _xyx_ 进行间隔. * */ function CS_get_search_param(){ $CI = &get_instance(); //获取ci 的实例. $parameters = array(); //初始化parameters $where = array(); //初始化where //分页参数的处理,如果同有相关参数,则设为1. if(isset($parameters["page"]) && is_numeric($parameters["page"])) { $_GET["page"] = $parameters["page"]; //兼容分页类 } else { $parameters["page"] = 1; $_GET["page"] = 1; } $search_equal = $CI->input->post('search_equal'); //接收search_equal //相等条件查询配置. if(is_array($search_equal)): //遍历所有的参数,为空的不参与搜索,后期交由handle去处理. foreach ($search_equal as $key => $value): if (trim($value) == "") { unset($search_equal[$key]); //删除搜索条件中值为空的参数 }else { $search_equal[$key] = trim($value); $parameters += array_map('base_encode', array("search_equal_$key"=>"$value")); } endforeach; endif; //like条件查询配置. $search_like = $CI->input->post('search_like'); //接收search_like 的参数 if(is_array($search_like)): //遍历所有的参数,为空的不参与搜索,后期交由handle去处理. foreach ($search_like as $key => $value): if (trim($value) == "") unset($search_like[$key]); //删除搜索条件中值为空的参数 else { $value = trim($value); $where[]="($key LIKE '%".$value."%')"; $parameters += array_map('base_encode', array("search_like_$key"=>"$value")); } endforeach; endif; //>=条件配置 $search_start = $CI->input->post('search_start'); //接收search_like 的参数 if(is_array($search_start)): //遍历所有的参数,为空的不参与搜索,后期交由handle去处理. foreach ($search_start as $key => $value): if (trim($value) == "") unset($search_start[$key]); //删除搜索条件中值为空的参数 else { $value = trim($value); $where[]="($key >= '$value')"; $parameters += array_map('base_encode', array("search_start_$key"=>"$value")); } endforeach; endif; //<=条件配置 $search_end = $CI->input->post('search_end'); //接收search_like 的参数 if(is_array($search_end)): //遍历所有的参数,为空的不参与搜索,后期交由handle去处理. foreach ($search_end as $key => $value): if (trim($value) == "") unset($search_end[$key]); //删除搜索条件中值为空的参数 else { $value = trim($value); $where[]="($key <= '$value')"; $parameters += array_map('base_encode', array("search_end_$key"=>"$value")); } endforeach; endif; //<=时间条件配置 $search_end_day = $CI->input->post('search_end_day'); //接收search_like 的参数 if(is_array($search_end_day)): //遍历所有的参数,为空的不参与搜索,后期交由handle去处理. foreach ($search_end_day as $key => $value): if (trim($value) == "") unset($search_end_day[$key]); //删除搜索条件中值为空的参数 else { $value = trim($value); $value = dateAdd($value." 00:00:00",'1'); //$value = $where[]="($key <= '$value')"; $parameters += array_map('base_encode', array("search_end_day_$key"=>"$value")); } endforeach; endif; // 判断是否为空 $isnull = $CI->input->post('search_isnull'); //接收isnull 的参数 if(is_array($isnull)): foreach ($isnull as $key => $value): if (trim($value) == "" || trim($value) == 0 ) unset($isnull[$key]); //删除搜索条件中值为空的参数 else { if($value==1) { $where[]="($key is null)"; } else if($value==2) { $where[]="($key is not null)"; } $parameters += array_map('base_encode', array("search_isnull_$key"=>"$value")); } endforeach; endif; if($search_equal) $where +=$search_equal; //解决复选框搜索的问题. foreach($_POST as $key => $val): if( strpos($key,"earch_mult",1) == 1) //判断是否为复合搜索. { $str_val = array(); //生成parm所用参数数组. $str_cond = array(); //生成查询条件数组. $key_piece = str_replace("search_mult_","",$key); //找出mul 部分. if(sizeof($_POST["$key"]) >0): foreach($_POST["$key"] as $val) { $str_val[]= base_encode($val); //生成parm所用参数数组. $str_cond []= "$key_piece = '$val' "; //生成查询条件数组. } $str_mul = implode("_xyx_",$str_val); $parameters[$key] = $str_mul; //合并生成parameters. $where []= "(".implode("or ",$str_cond ).")"; //合并生成查询条件. endif; } endforeach; return array($where,$parameters); } /** * 得到查询参数,并 * * @param string $_POST 查询条件 * @return list($where,$parameters,$search_equal) ; */ function CS_get_search_get_param($index_tp = 4){ $CI = &get_instance(); //$CI->output->enable_profiler(TRUE); $parameters = $CI->uri->uri_to_assoc($index_tp); //解析URI中的参数 $where = array(); if(isset($parameters["page"]) && is_numeric($parameters["page"])) { $_GET["page"] = $parameters["page"]; //兼容分页类 } else { $parameters["page"] = 1; $_GET["page"] = 1; } /** * *解释parameter 参数,实现搜索条件配置. */ foreach($parameters as $key=>$val) { $str_cond = array(); //配置条件数组. if( intval(strpos($key,"earch_like_",1)) == 1) //like 查询处理 { $key = str_ireplace("search_like_","","$key"); $val = base_decode($val); $where[]="($key like '%".$val."%')"; }else if( intval(strpos($key,"earch_equal_",1)) == 1) //equal 查询处理 { $key = str_ireplace("search_equal_","","$key"); $val = base_decode($val); $where[]="($key = '$val')"; } else if( intval(strpos($key,"earch_start_",1)) == 1) //>= 条件查询处理 { $key = str_ireplace("search_start_","","$key"); $val = base_decode($val); $where[]="($key >= '$val')"; } else if( intval(strpos($key,"earch_end_",1)) == 1) //<=条件查询处理. { if(( intval(strpos($key,"earch_end_day",1)) == 1)) { $key = str_ireplace("search_end_day_","","$key"); $val = base_decode($val); }else { $key = str_ireplace("search_end_","","$key"); $val = base_decode($val); } $where[]="($key <= '$val')"; } else if( intval(strpos($key,"earch_isnull_",1)) == 1) //判断是否为空 { $key = str_ireplace("search_isnull_","","$key"); $val = base_decode($val); if($val=='1') { $where[]="($key is null)"; } else if($val=='2') { $where[]="($key is not null)"; } } else if( intval(strpos($key,"earch_mult_",1)) == 1){ //单字段多值查询处理,合并成or 条件. $key_piece = str_replace("search_mult_","",$key); //找出mul 部分. $item_array = explode("_xyx_",$val); foreach ($item_array as $val_piece) { $str_cond []= "$key_piece = '".base_decode($val_piece)."' "; //生成查询条件数组. } $where []= "(".implode("or ",$str_cond ).")"; //合并生成查询条件. }else { $search_equal[$key] = base_decode($val); } } unset($search_equal['page']); $where +=$search_equal; return array($where,$parameters); } function CS_get_search_get_3_param(){ $CI = &get_instance(); //$CI->output->enable_profiler(TRUE); $parameters = $CI->uri->uri_to_assoc(3); //解析URI中的参数 $where = array(); if(isset($parameters["page"]) && is_numeric($parameters["page"])) { $_GET["page"] = $parameters["page"]; //兼容分页类 } else { $parameters["page"] = 1; $_GET["page"] = 1; } /** * *解释parameter 参数,实现搜索条件配置. */ foreach($parameters as $key=>$val) { $str_cond = array(); //配置条件数组. if( intval(strpos($key,"earch_like_",1)) == 1) //like 查询处理 { $key = str_ireplace("search_like_","","$key"); $val = base_decode($val); $where[]="($key like '%".$val."%')"; }else if( intval(strpos($key,"earch_equal_",1)) == 1) //equal 查询处理 { $key = str_ireplace("search_equal_","","$key"); $val = base_decode($val); $where[]="($key = '$val')"; } else if( intval(strpos($key,"earch_start_",1)) == 1) //>= 条件查询处理 { $key = str_ireplace("search_start_","","$key"); $val = base_decode($val); $where[]="($key >= '$val')"; } else if( intval(strpos($key,"earch_end_",1)) == 1) //<=条件查询处理. { if(( intval(strpos($key,"earch_end_day",1)) == 1)) { $key = str_ireplace("search_end_day_","","$key"); $val = base_decode($val); }else { $key = str_ireplace("search_end_","","$key"); $val = base_decode($val); } $where[]="($key <= '$val')"; } else if( intval(strpos($key,"earch_isnull_",1)) == 1) //判断是否为空 { $key = str_ireplace("search_isnull_","","$key"); $val = base_decode($val); if($val=='1') { $where[]="($key is null)"; } else if($val=='2') { $where[]="($key is not null)"; } } else if( intval(strpos($key,"earch_mult_",1)) == 1){ //单字段多值查询处理,合并成or 条件. $key_piece = str_replace("search_mult_","",$key); //找出mul 部分. $item_array = explode("_xyx_",$val); foreach ($item_array as $val_piece) { $str_cond []= "$key_piece = '".base_decode($val_piece)."' "; //生成查询条件数组. } $where []= "(".implode("or ",$str_cond ).")"; //合并生成查询条件. }else { $search_equal[$key] = base_decode($val); } } unset($search_equal['page']); $where +=$search_equal; return array($where,$parameters); } /** * 得到查询参数,并 * * @param string $_POST 查询条件 * @return list($where,$parameters,$search_equal) ; */ function CS_get_search_get_front_param(){ $CI = &get_instance(); //$CI->output->enable_profiler(TRUE); $parameters = $CI->uri->uri_to_assoc(5); //解析URI中的参数 $where = array(); if(isset($parameters["page"]) && is_numeric($parameters["page"])) { $_GET["page"] = $parameters["page"]; //兼容分页类 } else { $parameters["page"] = 1; $_GET["page"] = 1; } /** * *解释parameter 参数,实现搜索条件配置. */ foreach($parameters as $key=>$val) { $str_cond = array(); //配置条件数组. if( intval(strpos($key,"earch_like_",1)) == 1) //like 查询处理 { $key = str_ireplace("search_like_","","$key"); $val = base_decode($val); $where[]="($key like '%".$val."%')"; }else if( intval(strpos($key,"earch_equal_",1)) == 1) //>= 条件查询处理 { $key = str_ireplace("search_equal_","","$key"); $val = base_decode($val); $where[]="($key >= '$val')"; } else if( intval(strpos($key,"earch_start_",1)) == 1) //>= 条件查询处理 { $key = str_ireplace("search_start_","","$key"); $val = base_decode($val); $where[]="($key >= '$val')"; } else if( intval(strpos($key,"earch_end_",1)) == 1) //<=条件查询处理. { $key = str_ireplace("search_end_","","$key"); $val = base_decode($val); $where[]="($key <= '$val')"; } else if( intval(strpos($key,"earch_isnull_",1)) == 1) //判断是否为空 { $key = str_ireplace("search_isnull_","","$key"); $val = base_decode($val); if($val=='1') { $where[]="($key is null)"; } else if($val=='2') { $where[]="($key is not null)"; } } else if( intval(strpos($key,"earch_mult_",1)) == 1){ //单字段多值查询处理,合并成or 条件. $key_piece = str_replace("search_mult_","",$key); //找出mul 部分. $item_array = explode("_xyx_",$val); foreach ($item_array as $val_piece) { $str_cond []= "$key_piece = '".base_decode($val_piece)."' "; //生成查询条件数组. } $where []= "(".implode("or ",$str_cond ).")"; //合并生成查询条件. }else { $search_equal[$key] = base_decode($val); } } unset($search_equal['page']); $where +=$search_equal; return array($where,$parameters); } //缩放图片 /** * * *等比缩放 * @param unknown_type $srcImage 源图片路径 * @param unknown_type $toFile 目标图片路径 * @param unknown_type $maxWidth 最大宽 * @param unknown_type $maxHeight 最大高 * @param unknown_type $imgQuality 图片质量 * @return unknown */ function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) { list($width, $height, $type, $attr) = getimagesize($srcImage); if($width < $maxWidth || $height < $maxHeight) return ; switch ($type) { case 1: $img = imagecreatefromgif($srcImage); break; case 2: $img = imagecreatefromjpeg($srcImage); break; case 3: $img = imagecreatefrompng($srcImage); break; } $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例 if($scale < 1) { $newWidth = floor($scale*$width); $newHeight = floor($scale*$height); $newImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $newName = ""; $toFile = preg_replace("/(\.gif|\.jpg|\.jpeg|\.png)/i","",$toFile); switch($type) { case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality)) return "$newName.gif"; break; case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality)) return "$newName.png"; break; default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; } imagedestroy($newImg); } imagedestroy($img); return false; } //直接压制指定大小,不进行等比处理 function resize_2($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) { list($width, $height, $type, $attr) = getimagesize($srcImage); switch ($type) { case 1: $img = imagecreatefromgif($srcImage); break; case 2: $img = imagecreatefromjpeg($srcImage); break; case 3: $img = imagecreatefrompng($srcImage); break; } $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例 $newWidth = $maxWidth; $newHeight = $maxHeight; $newImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $newName = ""; switch($type) { case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality)) return "$newName.gif"; break; case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality)) return "$newName.png"; break; default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; imagedestroy($newImg); } imagedestroy($img); return false; } //裁剪图片 function cutImg($o_file,$x1,$x2,$y1,$y2){ //设置文件参数 //$o_file="./uploadfiles/200902/13/1234515154_QcA.jpg";//原文件文件路径 $file=basename($o_file);//文件 $ext=end(explode(".", $file));//扩展名 $filename=basename($file,$ext);//文件名 $filelen=strlen($file); $path=substr($o_file,0,strlen(($o_file))-$filelen);//文件夹 $newfile=$path."edit_".$file;//新文件名 $newthufile=$path."thumb_".$file;//新文件名 header('Content-type: image/jpeg'); list($width, $height) = getimagesize($o_file); $new_width = $x2-$x1; $new_height = $y2-$y1; $image_n = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromjpeg($o_file); imagecopyresampled($image_n, $image, 0, 0, $x1, $y1, $new_width, $new_height, $new_width, $new_height); //输出文件 imagejpeg($image_n, $newfile, 100); $newfileName = $newfile; return $newfile; } /** * 取得手机型号信息 * @param string or array $where 查询的条件 */ function CS_get_office($where = array()) { $CI = &get_instance(); $CI->load->model('office_model'); $rows = $CI->office_model->get_all(); //取得指定条件的区域 return $rows; } /** * 取得手机型号信息 * @param string or array $where 查询的条件 */ function CS_get_office_child($where = array()) { $CI = &get_instance(); $CI->load->model('office_model'); $rows = $CI->office_model->get_all_child(); //取得指定条件的区域 return $rows; } /** * 取手机型号信息,并且格式化成json * @param string or array $where 查询的条件 */ function CS_office_to_json($where = array()) { $rows = CS_get_office_child($where); $new_rows = array(); foreach ($rows as $row) { if (!isset($new_rows[$row->office_pid])) { $new_rows[$row->office_pid] = array(); } array_push($new_rows[$row->office_pid], array('office_id' => $row->office_id, 'office_title' => $row->office_title)); } return json_encode($new_rows); } /** * 搜索条件合并使用 * @param string or array $where 查询的条件 */ function CS_search_merge($array_search,$array__parameters) { if( !isset($array__parameters) || !is_array($array__parameters) || !sizeof($array__parameters) ) { return $array_search; }else { foreach($array__parameters as $key => $val) { foreach($array_search as &$search_item) { if(CS_check_search_merge($key,$search_item)) { $search_item["fieldValue"] = CS_merge_search_data($key,$val,$search_item); } } } } return $array_search; } /** * 检验是否对应的规则. * @param string or array $where 查询的条件 */ function CS_check_search_merge($key,$search_item) { if($search_item["search_type"]."_".$search_item["name"] == $key) { return true; } if(preg_match("/search_mult/",$key)) { $key_name_piece = str_replace("search_mult_","",$key); if($search_item["name"] == $key_name_piece){ return true; } } if(preg_match("/search_isnull_/",$key)) { $key_name_piece = str_replace("search_isnull_","",$key); if($search_item["name"] == $key_name_piece){ return true; } } return false; } /** * 向. * @param string or array $where 查询的条件 */ function CS_merge_search_data($key,$val,$search_item) { $me = array(); //search_mult 多值时处理. if(preg_match("/search_mult/",$key)){ if(preg_match("_xyx_",$val)) { $val_piece = explode("_xyx_",$val); foreach( $val_piece as $val_piece) { $me[] = trim(base_decode($val_piece)); } return $me; } } $me = array( trim(base_decode($val))); return $me; } /** * 根据图片路径获取小图片路径 * 例如 upload/2010-1-23/3.jpg 将得到 upload/2010-1-23/small_3.jpg * */ function get_small_path($str){ $r = pathinfo($str); return $r["dirname"]."/small_".$r["basename"]; } /** * * * */ function CS_get_newspath_byid($id) { $ids = str_pad($id,6,"0",STR_PAD_LEFT); $dest_path = substr($ids,0,3)."/".substr($ids,3,3).".html"; $dest_path = base_url()."news/".$dest_path; return $dest_path; } function CS_get_newsurl_byid($id,$key) { $ids = str_pad($id,6,"0",STR_PAD_LEFT); if($key == 0 ){ $dest_path = substr($ids,0,3)."/".substr($ids,3,3).".html"; }else { $dest_path = substr($ids,0,3)."/".substr($ids,3,3)."_$key.html"; } $dest_path = base_url()."news/".$dest_path; return $dest_path; }

string相关


<?php function base_encode($str) { $src = array("/","+","="); $dist = array("-a","-b","-c"); $old = base64_encode($str); $new = str_replace($src,$dist,$old); return $new; } function base_decode($str) { $src = array("-a","-b","-c"); $dist = array("/","+","="); $old = str_replace($src,$dist,$str); $new = base64_decode($old); return $new; } //获取文章的摘要信息,如果有图片,则显示第一张图片. function get_brief($newContent,$length = 100) { $pattern = "/<img[^>]*src\=('|\")(([^>]*)(jpg|gif|png|bmp|jpeg))\\1/i"; //获取所有图片标签的全部信 preg_match_all($pattern, $newContent, $matches); $str_out = ""; if( sizeof( $matches[2] )) { $str_out = "<img width = '30' src = '".$matches[2][0]."' onclick = 'resize_pic(this,30,176)'/>"; } $content = strip_tags($newContent); if(strlen($content)>$length) { $str_out .= sub_string_utf8($content,0,$length); } else { $str_out .= $content; } return $str_out; } function sub_string_utf8($str, $start, $lenth) { $len = strlen($str); $r = array (); $n = 0; $m = 0; for ($i = 0; $i < $len; $i++) { $x = substr($str, $i, 1); $a = base_convert(ord($x), 10, 2); $a = substr('00000000' . $a, -8); if ($n < $start) { if (substr($a, 0, 1) == 0) { } elseif (substr($a, 0, 3) == 110) { $i += 1; } elseif (substr($a, 0, 4) == 1110) { $i += 2; } $n++; } else { if (substr($a, 0, 1) == 0) { $r[] = substr($str, $i, 1); } elseif (substr($a, 0, 3) == 110) { $r[] = substr($str, $i, 2); $i += 1; } elseif (substr($a, 0, 4) == 1110) { $r[] = substr($str, $i, 3); $i += 2; } else { $r[] = ''; } if (++ $m >= $lenth) { break; } } } return join("", $r); } // End subString_UTF8 function Generate_Brief($text,$Briefing_Length = 'ddd'){ if(mb_strlen($text) <= $Briefing_Length ) { echo "here"; return $text;} $Foremost = mb_substr($text, 0, $Briefing_Length); $re = "<(\/?) (P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|TABLE|TR|TD|TH|INPUT|SELECT|TEXTAREA|OBJECT|A|UL|OL|LI| BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|SPAN)[^>]*(>?)"; $Single = "/BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|BR/i"; $Stack = array(); $posStack = array(); mb_ereg_search_init($Foremost, $re, 'i'); while($pos = mb_ereg_search_pos()){ $match = mb_ereg_search_getregs(); /* [Child-matching Formulation]: $matche[1] : A "/" charactor indicating whether current "<...>" Friction is Closing Part $matche[2] : Element Name. $matche[3] : Right > of a "<...>" Friction */ if($match[1]==""){ $Elem = $match[2]; if(mb_eregi($Single, $Elem) && $match[3] !=""){ continue; } array_push($Stack, mb_strtoupper($Elem)); array_push($posStack, $pos[0]); }else{ $StackTop = $Stack[count($Stack)-1]; $End = mb_strtoupper($match[2]); if(strcasecmp($StackTop,$End)==0){ array_pop($Stack); array_pop($posStack); if($match[3] ==""){ $Foremost = $Foremost.">"; } } } } $cutpos = array_shift($posStack) - 1; $Foremost = mb_substr($Foremost,0,$cutpos,"UTF-8"); return $Foremost; }; /** * 过滤特殊字符 * * @param string $string 待过滤的字符 * @param boolean $is_trim 是否去掉字符串两边的空格 TRUE为去掉,FALSE为不去掉,默认值为FALSE * @return string */ function str_filter($string, $is_trim = false) { if (trim($string) == "") return ""; if (!get_magic_quotes_gpc()) { $string = addslashes($string); } $string = htmlspecialchars($string); $string = strip_tags($string); return $is_trim ? trim($string) : $string; } function strip_html($string) { $search = array ("'<mce:script[^><!-- ]*?>.*? // --></mce:script>'si", // 去掉 javascript 4B+1ZsmMd "'<[/!]*?[^<>]*?>'si", // 去掉 HTML 标记 "'([rn])[s]+'", // 去掉空白字符 "'&(quot|#34);'i", // 替换 HTML 实体 "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(d+);'e"); $replace = array( "", "", "\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(\1)"); return preg_replace($search, $replace, $string); } function str_nl($string) { return nl2br(str_replace(' ', ' ', $string)); } ?>

公用


<?php /** * 获取真实的IP地址 */ function CS_get_ip(){ if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return $ip; } /** * 获取来访地址 * * @return string 如果来访地址存在,则返回来访地址,否则返回空 */ function CS_get_referer() { return isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != '' ? $_SERVER['HTTP_REFERER'] : ''; } /** * *取得下载页面的地址 * * @param unknown_type $url */ function CS_file_get_contents($url) { $t = 5; $cont = ""; while ($t-- >0) { $time = 5-$t; //echo "第$time 次下载 $url"; $cont = file_get_contents($url); if($cont) { //echo "下载成功"; break; } } return $cont; } /** * 取得当前页面的完整地址 */ function CS_get_current_url() { return 'http://'.$_SERVER[ 'HTTP_HOST'].$_SERVER[ 'REQUEST_URI']; } /** * 取得手机型号信息 * @param string or array $where 查询的条件 */ function CS_get_text($key) { static $STATIC_Text_INFO = array(); if (!isset($STATIC_Text_INFO[$key])) { $CI = &get_instance(); //读数据库模式. // $CI->load->model('Text_model'); // $text = $CI->Text_model->get_info_by_title($key); //取得指定的值. $CI->config->load("cfg_text"); //$CI->config->load('cfg_text'); $val = $CI->config->item($key); if( !$val ) $val = "<hr/><font color = 'red'>尚无-[$key]-项配置文字,请及时添加相应的内容</font><hr/><br>"; $STATIC_Text_INFO[$key] = $val; } return $STATIC_Text_INFO[$key]; } /** * 判断是否是post提交 * */ function CS_is_post() { return strtolower($_SERVER['REQUEST_METHOD']) == 'post'; } /** * 判断是否是GET提交 * * @return boolean 如果是get则返回true */ function CS_is_get() { return strtolower($_SERVER['REQUEST_METHOD']) == 'get'; } /** * 跳转到上一页,如果指定了$location并且没有来路时,则跳转到指定页 * * @param string $location 指定跳转的页面 */ function CS_header_referer($location = '') { if ($_SERVER['HTTP_REFERER'] != '') { header('location:'.$_SERVER['HTTP_REFERER']); exit(); } else if ($location != '') { redirect($location); } } function CS_log($str,$Path) { $fp=fopen($Path,"a+"); if(is_array($str)) { foreach($str as $key=>$val) { $tempstr=$key."=>".$val."\n"; fwrite($fp,$tempstr); } }else{ fwrite($fp,$str."\n"); } fclose($fp); } /** * 验证文件是否是图片 * * @param string $path 文件路径 * @return boolean 如果是则返回True,否则返回False */ function CS_check_img($path) { $extension = CS_get_extension($path); return $extension == 'jpg' || $extension == 'png' || $extension == 'jpeg' || $extension == 'gif'; } /** * 取得文件的扩展名 * * @param string $path 文件路径 * @return string */ function CS_get_extension($path) { $path_parts = pathinfo($path); $extension = strtolower($path_parts['extension']); return $extension; } /** * 输入浏览器信息标头 * @param string $content_type[text/html] 网页输出类型 * @param string $charset[utf-8] 网页输入编码 */ function CS_header($content_type = 'text/html', $charset = 'utf-8') { header('Content-type:'.$content_type.'; charset='.$charset); if(function_exists("date_default_timezone_set")){ // date_default_timezone_set('asia/shanghai'); } } /** * 输出JS报错提示,并且跳转页面 * @param string $message 提示语句 * @param string $location 跳转页面 * @param string $title 提示框的标题 */ function CS_js_alert($message, $location, $title = '提示信息', $js_scope = '') { CS_header(); //发送浏览器信息头 echo '<mce:script type="text/javascript"><!-- '.$js_scope.'LD_alert("'.$title.'", "'.$message.'");location.href="'.$location.'" // --></mce:script>'; exit(); } /** * 取得对应表名的模型名称 * * @param string $table 表名 * @return string 模型名称 */ function CS_get_model_name($table) { return ucfirst(strtolower($table.'_model')); } /** * 获取手机号对应的服务商 * * @param string $mobile * @return int [0=>移动, 1=>联通, 2=>小灵通, -1=>不可识别] */ function CS_get_mobile_facilitator($mobile) { $channel_regex_map = array( 0 => '/^0?(13[0-9]|15[0|1|3|6|8|9])\d{8}$/', // 移动 1 => '/^0?1(3[0-2]|5[56]|8[56])\d{8}$/', // 联通 2 => '/^(0[1-9][0-9]{9,10})$/', // 小灵通 ); foreach ($channel_regex_map as $channel => $regex) { if (preg_match($regex, $mobile, $match)) { return $channel; } } return -1; // 不可识别的类型 } /** * 动态执行数据库中一个字段的值,并将返回值赋给该字段 * * @param mixed $var 一行[一个对象]或多行数据[一个数组] * @param array $fields 字段名称(可以是多个) */ function CS_eval_fields($var, $fields) { if (is_object($var)) { foreach ($fields as $field) { if (isset($var->$field) && $var->$field != '') $var->{$field.'_php'} = @eval($var->$field); //如果字段存在 } } else if (is_array($var)) { foreach ($var as $row) { //循环每一行 foreach ($fields as $field) { if (isset($row->$field) && $row->$field != '') $row->{$field.'_php'} = @eval($row->$field); //如果字段存在 } } } return $var; } /** * 反序列化数据库中一个字段的值,并将返回值赋给该字段 * * @param mixed $var 一行[一个对象]或多行数据[一个数组] * @param array $fields 字段名称(可以是多个) */ function CS_unserialize_fields($var, $fields) { if (is_object($var)) { foreach ($fields as $field) { if (isset($var->$field) && $var->$field != '') $var->{$field.'_php'} = @unserialize($var->$field); //如果字段存在 } } else if (is_array($var)) { foreach ($var as $row) { //循环每一行 foreach ($fields as $field) { if (isset($row->$field) && $row->$field != '') $row->{$field.'_php'} = @unserialize($row->$field); //如果字段存在 } } } return $var; } /** * 将一个数组格式化为GET传参格式 * @param array $params 待格式化的数组,数组的键值是参数名,数组的值是参数值 * @return string 如果$params不是数组或是一个空数组,那么返回空,否则返回格式化后的字符串 */ function CS_to_query_string($params) { if (is_array($params) && sizeof($params) > 0) { //如果参数是数组,并且不是一个空数组 $new_params = array(); foreach ($params as $key => $value) { array_push($new_params, $key.'='.rawurlencode($value)); } return join('&', $new_params); } else { return ''; } } /** * 格式化数字 * @param int $number 数字 * @return 格式化的数字。 * */ function CS_numeric_format($number){ return number_format($number,1,'.',''); } /** * 选择颜色 * */ function CS_select_color($num){ if($num > 0){ $color = '#999999'; }else{ $color = '#996600'; } return $color; } /** * 计算百分比 * @param int $input 输入量 * @param int $pass 同步量 * @return 百分比 * */ function CS_counting_per($input,$pass){ if($input <1 && $pass > $input){ return '100%'; } if($pass>0 && $input>0){ return CS_numeric_format((($pass/$input)*100))."%"; //百分比 } if($input < 1 && $pass < 1){ return ' '; } return ' '; } /** * 利用CI中方法,清除特殊数据 (主要是对$this->input->xss_clean()方法的扩展) */ function CS_xss_clean($var) { if (is_array($var)) { foreach ($var as $key => $value) { $var[$key] = CS_xss_clean($value); } } else { $CI = & get_instance(); $var = $CI->input->xss_clean($var); } return $var; } /** * 设置浏览器的缓存时间 * * @param string $interval 缓存时间间隔 * @return NULL */ function cache_browser($interval = 60) { $now = time(); $pretty_lmtime = gmdate('D, d M Y H:i:s', $now) . ' GMT'; $pretty_extime = gmdate('D, d M Y H:i:s', $now + $interval) . ' GMT'; // 向后兼容HTTP/1.0 header("Last Modified: $pretty_lmtime"); header("Expires: $pretty_extime"); // 支持HTTP/1.1 header("Cache-Control: private,max-age=$interval,s-maxage=0"); } /** * 设置数据置查询的where * * @param string $where 查询条件,多态表现.可能是数组. * @return string 模型名称 */ function CS_set_where($where) { $CI = &get_instance(); if (is_array($where)) { //当条件是数组的时候 foreach ($where as $key => $value) { //循环条件 //当元素是数组或元素是字符串并且元素的键名是数字 if (is_array($value) || (is_string($value) && is_numeric($key))) $CI->db->where($value); //元素是字符串并且元素的键名不是数字 else if (is_string($value) && !is_numeric($key)) $CI->db->where($key, $value); } } else if (is_string($where)) { $CI->db->where($where); } } /** * BREADCRUMB 导航条面包屑 * * @param string $array * @return no return. */ function bread_crumb($array) { $i = 0; foreach($array as $key=>$val) { if($i) echo ">>";$i++; $url = $val["url"]; $title = $val["title"]; echo "<a href = '$url'>$title</a>"; } } /** * *创建文件夹 * * @param unknown_type $dir */ function CS_mkdir($dir) { if (!is_dir($dir)) { $temp = explode('/', $dir); $cur_dir = ''; for ($i = 0; $i < count($temp); $i++) { $cur_dir .= $temp[$i] . '/'; if (!is_dir($cur_dir)) { @ mkdir($cur_dir, 0777); @ fopen("$cur_dir/index.htm", "a"); } } } } //验证地址是否为图片 function CS_is_pic($url) { $pic_arr = array("jpg","jpeg","png","gif"); $pinfo = pathinfo($url); $ext_name = $pinfo["extension"]; $ext_name = strtolower($ext_name) ; if(in_array($ext_name,$pic_arr)) { return true; } else { return false; } } /** * 预格式化输出数组 * * @param string $array * @return no return. */ function pr($array) { print("<pre>"); print_r($array); print("</pre>"); } /** * * 将指定表格的指定健名和值名称生成配置文件,并写入到指定文件中. * @param char $table_name * @param char $key_name * @param char $val_name * @param char $cfg_var_name * @param char $dest_path */ function CS_mk_cfg($table_name,$key_name,$val_name,$cfg_var_name ='cfg',$dest_file) { $str_config = "<?php\n"; $CI = &get_instance(); $CI->db->from($table_name); //设置查询表格 $CI->db->select($key_name.",".$val_name); //设置查询字段. $CI->load->helper('file'); $query = $CI->db->get(); foreach($query->result() as $key=>$item) { $info = str_replace("'","\"",$item->$val_name); $str_config .= '$config[\''.$item->$key_name.'\']=\''.$info.'\';'; $str_config .= "\n"; } $dest_path_dir = $_SERVER['DOCUMENT_ROOT']."/system/application/config/"; $dest_file = $dest_path_dir.$dest_file.".php"; write_file($dest_file, $str_config, 'w+'); } /** * 删除指应对象里面的 upload/ 以gif|jpg|jpeg|zip|swf|doc 结尾的文件。 * * @param object $row */ function delete_file($row) { if(sizeof($row)){ foreach($row as $val) { //查找里面相应的文件 preg_match_all("/(upload[^\.]*\.(gif|jpg|jpeg|zip|swf|doc))/i",$val,$matches); if(sizeof($matches[0])) { foreach($matches[0] as $file_piece) { if(file_exists($_SERVER['DOCUMENT_ROOT']."/".$file_piece)) { // unlink($_SERVER['DOCUMENT_ROOT']."/".$file_piece) or die("file"); } } } } } } /** * * 将http下的图片文件指向到下载到本地,并对内容进行替换。 * */ function img2local($arr) { if(is_array($arr) and sizeof($arr)) { foreach($arr as $key => $val) { preg_match_all("/(http:\/\/(?!.*http.*)[^<]*\.(jpg|gif|jpeg|png))/iU",$val,$matches); if(sizeof($matches[0])) { foreach ($matches[0] as $val_img) { $old_file_name = $val_img; $img_info = pathinfo($old_file_name); //创建临时文件夹. $temp_dir = "upload/down/".date("y-m-d"); if(!is_dir($temp_dir)) CS_mkdir($temp_dir); //生成随机文件,并将远程文件写入到相应的目录下去. $myPath= "upload/down/".date("y-m-d")."/".date("His").rand(0,1000).".".$img_info["extension"]; $file=$old_file_name; $data=file_get_contents($file); fwrite(fopen($myPath,"wb+"),$data); //对数组的内容进行替换 $arr[$key] = str_ireplace($val_img,"/".$myPath,$arr[$key]); } } } } return $arr; }

日期处理


<?php /** * 返回给指定的日期添加天数后的日期 * * @param string $date 被添加的日期 * @param int $addDay 添加的天数 * @return string */ function dateAdd($date, $addDay){ $parts = explode(' ', $date); $date = $parts[0]; $time = $parts[1]; $ymd = explode('-', $date); $hms = explode(':', $time); $year = $ymd[0]; $month = $ymd[1]; $day = $ymd[2]; $hour = $hms[0]; $minute = $hms[1]; $second = $hms[2]; $day = $day+$addDay; if($month=='1' || $month=='3' || $month=='5' || $month=='7' || $month=='8' || $month=='10' || $month=='12'){ if($day>31){ $day = $day - 31; $month++; } } if($month=='4' || $month=='6' || $month=='9' || $month=='11'){ if($day>30){ $day = $day - 30; $month++; } } if($month=='2'){ if(checkRun($year)){ //Feb has 29 days in leap year if($day>29){ $day = $day - 29; $month++; } } else{ if($day>28){ $day = $day - 28; $month++; } } } if($month==13){ $month = 1; $year++; } if(strlen($month)==1){$month = "0".$month;} if(strlen($day)==1){$day = "0".$day;} return $year . "-" . $month . "-" . $day; } /** * 验证是否是润年 * * @param int $year 年份 * @return boolean 如果是则返回True,否则返回False */ function checkRun($year){ if($year%4==0 && ($year%100!=0 || $year%400==0) ) return true; else return false; } /** * 将时间转化成秒 * @param string $time */ function time_to_second($time) { if (is_time($time)) { $array_time = explode(':', $time); return $array_time[0]*3600+$array_time[1]*60+$array_time[2]; } else { return 0; } } /** * 将时间转化为unix时间戳 * * @param string $date * @return int 如果转化成功则返回unix时间戳,否则返回-1 */ function format_date_to_unix($date){ $date = trim($date); $regexp = '^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})( ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}))?$'; if(ereg($regexp,$date,$regs)){ return mktime($regs[5],$regs[6],$regs[7],$regs[2],$regs[3],$regs[1]); }else{ return -1; } } /** * Calculation of the time the auction closes * @param int $begin unix timestamp * @param int $end unix timestamp * @return string The time the auction closes */ function date_between($begin, $end = 0, $between = FALSE) { if ($end === 0) $end = time(); if ($between === FALSE) $between = $begin - $end; if($between < 0) return ''; if ($between < 60) { return $between.'秒'; } else { $second = $between % 60; $between = $between / 60; if ($between < 60) { return (int)$between."分".$second."秒"; } else if($between === 60) { return "1小时"; } else { $minute = $between % 60; $between = ($between - $minute) / 60; if ($between < 24) { $string = (int)$between."小时"; if ($minute > 0) { $string .= $minute."分"; } return $string; } else if($between === 24) { return "1天"; } else { $hour = $between % 24; $between = $between - $hour; $day = $between / 24; $string = (int)$day."天"; if ($hour > 0) { $string .= $hour."小时"; } if ($minute > 0) { $string .= $minute."分"; } return $string; } } } }


function CS_authcode() { session_start(); //生成验证码图片 Header("Content-type: image/PNG"); srand((double)microtime()*1000000);//播下一个生成随机数字的种子,以方便下面随机数生成的使用 //session_start();//将随机数存入session中 $_SESSION['authnum']=""; $authnum = ""; $im = imagecreate(52,22) or die("Cant's initialize new GD image stream!"); //制定图片背景大小 $red = ImageColorAllocate($im, 0,0,0); //设定三种颜色 $white = ImageColorAllocate($im, 255,255,255); $gray = ImageColorAllocate($im, 200,200,200); //imagefill($im,0,0,$gray); //采用区域填充法,设定(0,0) imagefill($im,0,0,$white);//ed //生成数字和字母混合的验证码方法 $ychar="1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z"; $list=explode(",",$ychar); for($i=0;$i<4;$i++){ $randnum=rand(0,33); $authnum.=$list[$randnum];//ed 加入一个空格 } //while(($authnum=rand()%100000)<10000); //生成随机的四位数 //将四位整数验证码绘入图片 $_SESSION['authnum']=$authnum; //int imagestring(resource image,int font,int x,int y,string s, int col) imagestring($im, 5, 10, 3, $authnum, $red); //用col颜色将字符串s画到image所代表的图像的x,y座标处(图像的左上角为0,0)。 //如果 font 是 1,2,3,4 或 5,则使用内置字体 for($i=0;$i<400;$i++){ //加入干扰象素 { $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255)); // imagesetpixel($im, rand()%90 , rand()%30 , $randcolor); imagesetpixel($im, rand()%90 , rand()%30 , $gray); } ImagePNG($im); ImageDestroy($im); exit(); }


/** * 使用此文件的js,必须在页面中载入jquery.js */ var LD_Event = { /** * 取得兼容浏览器的事件对象 * @param object event 事件对象参数,IE以外的浏览器有效 * @return object 事件对象 */ realEvent: function(event) { return window.event || event; }, /** * 取得触发事件的对象 * * @param object event 事件对象 * @return HTMLElement */ element: function(event) { var evt = this.realEvent(event); return evt.srcElement || evt.target; } } /** * 创建类 */ var LD_Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } Function.prototype.bind = function() { var __method = this, args = jQuery.makeArray(arguments), object = args.shift(); return function() { __method.apply(object, args.concat(jQuery.makeArray(arguments))); } } Function.prototype.bindEvent = function() { var __method = this, args = jQuery.makeArray(arguments), object = args.shift(); return function(event) { __method.apply(object, [window.event || event].concat(args)); } } /** * 预先截入图片 */ function LD_loadImages() { if (argments.length === 0) return; //当没有传递参数时 for (var i = 0, n = arguments.length; i < n; i ++) { if (arguments[i] && arguments[i].constructor === Array) { //当参数是数组时 arguments.callee(arguments[i]); //递归 } else { new Image().src = arguments[i]; } } } /** * 取得指定ID的节点 * * @param string id 节点对象的ID属性 * @param mixed 如果对象取得成功则返回对象,否则返回False */ function getId(id){ if(document.getElementById(id)){ //当对象存在时 return document.getElementById(id); }else{ return false; } } /** * 创建编辑器 * @param string elementName 输入框的名称 * @param int width 编辑器的宽度 * @param int height 编辑器的高度 * @param string basePath fck所在的文件夹 * @param int readCookie 是否自动保存 * @param function callback */ function LD_createEditor(event, elementName, width, height, basePath, readCookie, callback) { if (readCookie === undefined) readCookie = 0; if (!jQuery('iframe#'+elementName+'_editor').get(0)) { //如果编辑器已经创建 jQuery("textarea[name='"+elementName+"']").after('<iframe id="'+elementName+'_editor" name ="'+elementName+'_editor" src="'+basePath+'inc/javascript/sina_editor/edit/editor.htm?id='+elementName+'&ReadCookie='+readCookie+'" mce_src="'+basePath+'inc/javascript/sina_editor/edit/editor.htm?id='+elementName+'&ReadCookie='+readCookie+'" width="'+width+'" height="'+height+'" frameborder="0" scrolling="no"></iframe>'); } else { jQuery('iframe#'+elementName+'_editor').show(); } jQuery("textarea[name='"+elementName+"']").hide(); //隐藏textarea if (event !== null) jQuery(LD_Event.element(event)).hide(); if (jQuery.isFunction(callback)) callback.apply(null, arguments); } /** * 设置错误信息 * * @param string message 报错语句 */ function LD_setError(message) { getId('error').innerHTML = message; getId('error').style.display = 'block'; } /** * 清除错误信息 */ function LD_clearError() { getId("error").innerHTML = ' '; } /** * 验证删除信息表单 * * @param HTMLElement elementForm 表单对象 */ function checkDeleteForm(elementForm) { if (jQuery("input[name='id[]']").isAllNotChecked()) { LD_alert(undefined, '请至少选中一条记录!'); return false; } LD_confirm(undefined, '您确定删除选中的记录吗', {}, function(){elementForm.submit()}) //elementForm.submit(); } /** * 自定义提示框 * @param string title 提示标题 * @param string content 提示内容 * @param object buttons 和jquery ui中的buttons参数一样 */ function LD_alert(title, content, _options, callback) { if (jQuery.isUndefined(title)) title = '错误提示'; var buttonOk = function() { //点击确定按钮后,执行的函数 if (jQuery.isFunction(callback)) callback(); //呼叫回调函数,这里一般是让表单元素获取焦点 jQuery(this).dialog('close'); //隐藏dialog } var options = { bgiframe: true, //蒙板 resizable: true, //设置为不可改变大小 draggable: true, //设置为不可拖动 height: 180, modal: true, overlay: { backgroundColor: '#000', opacity: 0.5 }, buttons: {'确定':buttonOk} }; //默认参数 if (typeof _options == 'object') jQuery.extend(options, _options); if (!jQuery('#ui_dialog').get(0)) { //如果没有创建dialog对象时 jQuery('body').append('<div id="ui_dialog" title="'+title+'"><p id="ui_dialog_content">'+content+'</p></div>') jQuery("#ui_dialog").dialog(options); jQuery('#ui_dialog_content').dialog('open'); } else { jQuery('#ui_dialog').dialog('option', 'title', title); //设置提示标题 jQuery('#ui_dialog_content').html(content); //设置提示内容 jQuery('#ui_dialog').dialog('option', 'buttons', {'确定':buttonOk}); jQuery('#ui_dialog').dialog('open'); //打开提示框 } } /** * 自定义确定提示框 * @param string title 提示标题 * @param string content 提示内容 * @param object _options 可以复盖确定框的默认属性 * @param function onDefinite 点击确定以后的回调函数 * @param function onCancel 点击取消后的回调函数 */ function LD_confirm(title, content, _options, onDefinite, onCancel) { if (jQuery.isUndefined(title) || title === null) title = '提示'; var buttonOk = function() { //点击确定按钮后,执行的函数 if (jQuery.isFunction(onDefinite)) onDefinite(); //呼叫回调函数,这里一般是让表单元素获取焦点 jQuery(this).dialog('close'); //隐藏dialog } var buttonCancel = function() { //点击取消按钮后,执行的函数 if (jQuery.isFunction(onCancel)) onCancel(); //呼叫回调函数,这里一般是让表单元素获取焦点 jQuery(this).dialog('close'); //隐藏dialog } options = { bgiframe: true, //蒙板 resizable: false, //设置为不可改变大小 draggable: false, //设置为不可拖动 height: 140, modal: true, overlay: { backgroundColor: '#000', opacity: 0.5 }, buttons: {'取消':buttonCancel, '确定':buttonOk} }; //默认参数 if (typeof _options == 'object') jQuery.extend(options, _options); if (!jQuery('#ui_dialog').get(0)) { //如果没有创建dialog对象时 jQuery('body').append('<div id="ui_dialog" title="'+title+'"><p id="ui_dialog_content">'+content+'</p></div>') jQuery("#ui_dialog").dialog(options); jQuery('#ui_dialog_content').dialog('open'); } else { jQuery('#ui_dialog').dialog('option', 'title', title); //设置提示标题 jQuery('#ui_dialog_content').html(content); //设置提示内容 jQuery('#ui_dialog').dialog('option', 'buttons', {'取消':buttonCancel, '确定':buttonOk}) jQuery('#ui_dialog').dialog('open'); //打开提示框 } return false; } /** * 使标签获取焦点 * @param HTMLElement or jQuery or string element */ function LD_focusToElement(element) { jQuery(element).focus(); } /*********************************************************** * Two terms of the product * Function name fxMultiply() * @param number a * @param number b * @return int ***************************************************************/ function LD_fxMultiply(a,b){ var f1 = String(a).split(".").length>1 ? String(a).split(".")[1].length : 0; var f2 = String(b).split(".").length>1 ? String(b).split(".")[1].length : 0; var aa = String(a).replace(/^0*|\./g,''); var bb = String(b).replace(/^0*|\./g,''); return Number(aa)*Number(bb)/Math.pow(10,f1+f2); } /** * 除法,小数运算问题 * @param number arg1 数字1 * @param number arg2 数字2 * @return number */ function LD_fxDiv(arg1,arg2){ var t1=0,t2=0,r1,r2; try{ t1=arg1.toString().split(".")[1].length } catch (e) {} try{ t2=arg2.toString().split(".")[1].length } catch (e) {} with (Math) { r1=Number(arg1.toString().replace(".","")) r2=Number(arg2.toString().replace(".","")) return (r1/r2)*pow(10,t2-t1); } } /** * 加法,小数运算问题 * @param number arg1 数字1 * @param number arg2 数字2 * @return number */ function LD_fxAdd(arg1,arg2){ var r1,r2,m; try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (arg1*m+arg2*m)/m } /** * 减法,小数运算问题 * @param number arg1 数字1 * @param number arg2 数字2 * @return number */ function LD_fxComp(arg1,arg2){ var r1,r2,m,n; try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)); //last modify by deeka //动态控制精度长度 n=(r1>=r2)?r1:r2; return ((arg1*m-arg2*m)/m).toFixed(n); } /*********************************************************** * Description: Prevent the calculation error javascript * Function name: fx() * @param: int intString * returnValue: int ***************************************************************/ function LD_fx(intString){ return Math.round(intString*100)/100; } /** * 页面加载完成后所执行的程序 */ jQuery(document).ready(function() { jQuery("input[type='reset']").click(function() { return confirm('您确定要重新填写吗?'); }); }); /** * 去掉冒泡事件.[注意,当前未完成兼容性.] */ function cancelBubble() { var evt = window.event || event; if(evt.preventDefault) { // Firefox evt.preventDefault(); evt.stopPropagation(); } else { // IE evt.cancelBubble=true; evt.returnValue = false; } } /** * 指定对象进行样式切换. */ function change_style(obj,style_1,style_2) { if(obj.attr("class") == style_1) { obj.attr("class",style_2); } else { obj.attr("class",style_1); } } /** * 删除形为. */ function deleteAction() { location.href = this.href; } //ajax 提交表单. function ajax_submit() { var queryString = $('#myform').formSerialize(); $.post( $('#myform').attr("action"), queryString, function(data){ eval(data); }); } /** *编辑器提交表单的回代处理. */ function handle_editor_sub() { if(validate()){ ajax_submit(); } } /** *提交交上传文件的回代处理.图片版. */ function uploadfile(upload_control_id,value_control_id,thumb_pic_id,upload_url,base_url) { if(!upload_validate()) { return false; } $.blockUI({message:"图片上传中"}); //开始上传图片 //2.上传 $.ajaxFileUpload ( { url:upload_url, secureuri:false, fileElementId:upload_control_id, dataType: 'json', success: function (data, status) { //$.blockUI({message:data.msg}); $("[id='"+value_control_id+"']").val(data.pic_url); $("[id='"+thumb_pic_id+"']").attr("src",base_url+data.pic_url); }, error: function (data, status, e) { $.blockUI({message:'上传异常'}); } } ) //3 $.unblockUI(); } /** *提交交上传文件的回代处理.非图片版 */ function uploadfile2(upload_control_id,value_control_id,thumb_pic_id,upload_url,base_url) { if(!upload_validate()) { return false; } $.blockUI({message:"文件上传中"}); //开始上传图片 //2.上传 $.ajaxFileUpload ( { url:upload_url, secureuri:false, fileElementId:upload_control_id, dataType: 'json', success: function (data, status) { //$.blockUI({message:data.msg}); $("[id='"+value_control_id+"']").val(data.pic_url); //$("[id='"+thumb_pic_id+"']").attr("src",base_url+data.pic_url); }, error: function (data, status, e) { $.blockUI({message:'上传异常'}); } } ) $.unblockUI(); } /** * 显示二级联动菜单 * * @param int parent_value 一级菜单的值 * @param array data 二级菜单的数据 * @param HTMLElement element 显示二级区域的SELECT */ function show_sub(parent_value, data, element ,titlename,id_name) { if (jQuery.isArray(eval(data[parent_value]))) { var current_items = eval(data[parent_value]); element.options.length = 0; //删除所有的option jQuery.each(current_items, function(key, value) { element.options[element.options.length] = new Option( eval("value."+titlename), eval("value."+id_name)); }); } } //显示tooltip 提示信息 function show_info(title,info) { $.blockUI({message:info}); //开始上传图片 } //显示tooltip 提示信息 function hid() { $.unblockUI(); //开始上传图片 } //批处理提交功能函数 function save_batch(url,set_table,set_field,set_value,data,href) { $.post(url, { id: data,set_table:set_table,set_field:set_field,set_value:set_value}, function(data){ nav_page(href ,'正在重载批处理数据') } ); } //重载分页函数. function nav_page(href,title) { href = href.replace('/index/', '/index_list_data/'); show_info('分页提示',title); $.get(href, function(data){ hid(); $("#list_data").html(data); } ); href = href.replace('/index_list_data/', '/index_list_nav/'); $.get(href, function(data){ $("#list_nav").html(data); } ); return false; } //重设图片大小. function resize_pic(obj,min_width,max_width) { obj.width = (obj.width == min_width)?max_width:min_width; } //滚动缩放图片大小 function wheel_big(o) { var zoom=parseInt(o.style.zoom, 10)||100;zoom+=window.event.wheelDelta/12; if (zoom>0) o.style.zoom=zoom+'%'; return false; } //判断所给的地址是否为图片. function check_is_pic(url){ var locArray = url.split("."); url_ext = locArray[locArray.length-1].toLowerCase(); pic_array = new Array("jpg","png","gif","jpeg"); for (key in pic_array) { if(pic_array[key]==url_ext){ return true; } } return false }

后台所用的js

// JavaScript Document jQuery(document).ready(function() { jQuery('#all').checkCall("input[name='id[]']"); //设置公用的日历控件. $.datepicker.setDefaults($.datepicker.regional['zh-CN']); $(".datepicker").datepicker( { dateFormat: 'yy-mm-dd'} ); //分页处理 //设置ajax分页效果. $("#pager a").click( function() { var href = $(this).attr("href"); //内容页加载 href = href.replace('/index/', '/index_list_data/'); show_info('分页提示','分页数据加载中'); $.get(href, function(data){ hid(); $("#list_data").html(data); } ); //分页栏架载 href = href.replace('/index_list_data/', '/index_list_nav/'); $.get(href, function(data){ $("#list_nav").html(data); } ); return false; }); //批处理操作 $(".button_style").click( function() { var title = $(this).attr("value"); var data = $("[name=id[]]").serialize(); //验证是否有选中数据进行处理 . if(!data) { LD_alert("管理员操作提示","请选择被<font color = 'blue'>["+title.toString()+"]</font>的数据"); return false; } //获取要处理的参数. url = '/index.php/opera/send_batch'; if(title.toString() =='删除选中') { url = '/index.php/opera/del_batch'; } if(title.toString() =='爬至新闻') { url = '/index.php/opera/add_to_news'; } if(title.toString() =='归并类别') { url = '/index.php/opera/merge_storycate'; } set_table = $(this).attr("set_table"); set_field = $(this).attr("set_field"); set_value = $(this).attr("set_value");href=$(this).attr("href"); text_value = $(this).val(); needConfirm = $(this).attr("needConfirm"); batch_check = $("#batch_check").attr("checked"); //非常规button处理 set_type = $(this).attr("set_type"); if(set_type == 'text'){ if( !$("#target_"+set_field).val()){ LD_alert("管理员操作提示","请输入你要设置的<font color = 'red'>["+text_value.toString()+"]</font>",null,function(){$("#target_"+set_field).focus();}); return false; } set_value = $("#target_"+set_field).val(); } //提示用户选择处理. 管理员设置大于用户自定义设置. if(needConfirm == "0" && !batch_check){ save_batch(url,set_table,set_field,set_value,data,href); return; } LD_confirm("管理员操作提示","您<font color = 'blue'>确定</font>要对选中数据进行<font color = 'blue'>["+title.toString()+"]</font>操作",null,function(){save_batch(url,set_table,set_field,set_value,data,href)},''); } ); //设置datagrid 的样式. $(".table_style tr").mouseover( function() { $(this).addClass("over"); }); $(".table_style tr").mouseout( function() { $(this).removeClass("over"); }); $(".table_style tr:even").addClass("alt"); }); /**显示隐藏推至至首页面版*/ function send_to_home() { if($("#select_div").css("display").toString() != 'block') { $("#select_div").css("display","block"); } else{ $("#select_div").css("display","none"); } } function send_it(table) { var data = $("[name=id[]]").serialize(); var data_str = $("[name=recomm[]]").serialize(); var dest_data = data+"&"+data_str; dest_data = dest_data+"&table="+table; //验证是否有选中数据进行处理 . if(!data) { LD_alert("管理员操作提示","请选择被<font color = 'blue'>[推送至首页]</font>的数据"); return false; } url = '/index.php/opera/send_home_batch'; $.post(url, dest_data, function(data){ LD_alert("管理员提示信息","推荐至首页成功"); } ); }

转载于:https://www.cnblogs.com/murain/archive/2010/04/07/1947263.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值