<?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("管理員提示信息","推薦至首頁成功"); } ); }
如何在數據安全與合規的前提下,高效地追蹤海外多媒體平臺的投放流量,有效歸因分析投放效果,持續優化企業在海外媒體的一系列營銷動作? 針對企業客戶的這一需求,神策數據從專業性和效率最佳兩個角度綜合考慮,接入多家第三方 MMP(Mobile
OpenAI 發佈 ChatGPT-4o,意味着人機交互進入新的時代。Chat-GPT4o 是一個跨文本、視覺和音頻端到端訓練的新模型,所有輸入和輸出都由同一個神經網絡處理。這也在告訴所有人,GenAI 連接非結構化數據,非結構化數據之間跨
persistent 持久化的下次重啓仍然生效 transient 臨時的下次重啓失效 PUT /_cluster/settings { "persistent": { "search.max_buckets": 2147483
GET _nodes/stats indexing 顯示已經索引了多少文檔。這個值是一個累加計數器。在文檔被刪除的時候,數值不會下降。還要注意的是,在發生內部 索引 操作的時候,這個值也會增加,比如說文檔更新。 還列出了索引操作耗費
Ai technology 前言 AppBuilder上線了低代碼製作組件功能,可以通過工作流的方式構建自定義組件,完成簡單Agent無法完成的複雜功能,使得生成的文本更加定製化,
最近在刷一些問題的時候看到有下面一個問題 上面問的是當輸入的字符串爲什麼的時候返回 True 總結 在做題目的時候,第一次還做錯了。 這是因爲解答這個題目的時間只有 3 分鐘,沒有自己看題目 後來拿着程序跑了下。 p
簡介: 搶紅包是我們生活常用的社交功能, 這個功能最主要的特點就是用戶的併發請求高, 在系統設計上, 可以使用非常多的辦法來扛住用戶的高併發請求, 在本文中簡要介紹使用Redis緩存中間件來實現搶紅包算法, Redis是一個在內存中基
字符串是 Java 程序中最常用的數據結構之一。在 Java 中 String 類已經重載了"+",字符串可以直接使用"+"進行連接,也可以用StringBuilder/StringBuffer(StringBuilder是J2SE5 及以
Java 平臺提供了兩種類型的字符串操作方式:String 和 StringBuffer/StringBuilder,它們都可以儲存和操作字符串,區別如下: String 是隻讀字符串,也就意味着 String 引用的字符串內容是不能被改
前端面試題 - 說一下原型和原型鏈? JavaScript 中,萬物皆對象,對象分爲普通對象和函數對象。 所有的函數都是函數對象(typeof f === 'function'),其他都是普通對象(typeof o === 'object'
唯一索引(Unique Index):保證索引列的值是唯一的,即重複值不允許。 非唯一索引(Non-Unique Index):允許重複值存在。 組合索引(Composite Index):在表的多個列上創建索引。 反向鍵索引(Rever
IPD(集成產品開發)模型的核心價值在於它改變了企業對於產品研發的固有觀點,將企業產研的重點由“技術爲導向”升級爲“用戶需求爲導向”,強調企業在產品的研發過程中堅持以用戶/客戶爲中心。 在IPD(集成產品開發)的模式中,需要企業或者團隊在限
1-前言 瀏覽器早已已經全面支持ESM即ES模塊化,可以實現前端代碼的模塊化,以及按需加載/下載,甚至還提供了一個非常貼心的ES特性:importmap 通過importmap,可以代碼零修改實現按需加載: 1.1 在html中聲明模塊的
DevExtreme擁有高性能的HTML5 / JavaScript小部件集合,使您可以利用現代Web開發堆棧(包括React,Angular,ASP.NET Core,jQuery,Knockout等)構建交互式的Web應用程序。從Ang