[1012]PHP進階開發及TadTools工具應用
<?php
/*-----------引入檔案區--------------*/
include_once "header_admin.php";
include_once "../up_file.php";
/*-----------function區--------------*/
//contact編輯表單
function contact_form($sn=""){
global $xoopsDB,$xoopsUser;
//抓取預設值
if(!empty($sn)){
$DBV=get_contact($sn);
}else{
$DBV=array();
}
//預設值設定
//設定「tel」欄位預設值
$tel=(!isset($DBV['tel']))?"":$DBV['tel'];
//設定「email」欄位預設值
$email=(!isset($DBV['email']))?"":$DBV['email'];
//設定「name」欄位預設值
$name=(!isset($DBV['name']))?"":$DBV['name'];
//設定「gsn」欄位預設值
$gsn=(!isset($DBV['gsn']))?null:$DBV['gsn'];
//設定「sn」欄位預設值
$sn=(!isset($DBV['sn']))?$sn:$DBV['sn'];
//設定「birthday」欄位預設值
$birthday=(!isset($DBV['birthday']))?"":$DBV['birthday'];
//設定「zip」欄位預設值
$zip=(!isset($DBV['zip']))?"":$DBV['zip'];
//設定「county」欄位預設值
$county=(!isset($DBV['county']))?"":$DBV['county'];
//設定「city」欄位預設值
$city=(!isset($DBV['city']))?"":$DBV['city'];
//設定「addr」欄位預設值
$addr=(!isset($DBV['addr']))?"":$DBV['addr'];
$op=(empty($sn))?"insert_contact":"update_contact";
$jquery=get_jquery();
include_once XOOPS_ROOT_PATH."/modules/tadtools/formValidator.php";
$formValidator= new formValidator("#myForm",false);
$formValidator_code=$formValidator->render();
$main="
$jquery
$formValidator_code
<script type='text/javascript' src='".TADTOOLS_URL."/My97DatePicker/WdatePicker.js'></script>
<script language='javascript' src='../class/twzipcode-1.3.1.js'> </script>
<script type='text/javascript'>
$(document).ready(function(){
$.post('ajax.php' , function(data){
$('#menu1').html(data);
$.post('ajax.php' , {parent_gsn: $('#menu1').val()} , function(data){
$('#menu2').html(data);
});
});
$('#menu1').change(function(){
$.post('ajax.php' , {parent_gsn: $('#menu1').val()} , function(data){
$('#menu2').html(data);
});
});
$('#AddrForm').twzipcode({
countyName: 'county',
areaName: 'city',
zipName: 'zip',
countySel: '$county',
areaSel: '$city',
zipSel: '$zip',
zipReadonly: false
});
});
</script>
<script src='" .TADTOOLS_URL. "/multiple-file-upload/jquery.MultiFile.js'></script>
<form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm' enctype='multipart/form-data'>
<table class='form_tbl'>
<!--群組-->
<tr><td class='title' nowrap>群組</td>
<td class='col'>
<select id='menu1'></select>
<select name='gsn' id='menu2'></select>
</td></tr>
<!--姓名-->
<tr><td class='title' nowrap>姓名</td>
<td class='col'><input type='text' name='name' size='20' value='{$name}' id='name' class='validate[required,minSize[2],maxSize[10]]'> </td></tr>
<!--電話-->
<tr><td class='title' nowrap>電話</td>
<td class='col'><input type='text' name='tel' size='20' value='{$tel}' id='tel' class='validate[required,custom[phone]]'> </td></tr>
<!--信箱-->
<tr><td class='title' nowrap>信箱</td>
<td class='col'><input type='text' name='email' size='20' value='{$email}' id='email' class='validate[required,custom[email]]'> </td></tr>
<!--生日-->
<tr><td class='title' nowrap>生日</td>
<td class='col'><input type='text' name='birthday' size='20' value='{$birthday}' id='birthday' onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd' , isShowWeek:true , skin:'whyGreen' , maxDate:'%y-%M-%d' , readOnly: true , isShowClear: false , firstDayOfWeek:1})\" class='Wdate'></td></tr>
<!--上傳-->
<tr><td class='title' nowrap>上傳圖片</td>
<td class='col'>
<input type='file' name='upfile[]' class='multi' maxlength='1' accept='gif|jpg|png|GIF|JPG|PNG'>".
list_del_file('photo',$sn)."
</td></tr>
<!--上傳-->
<tr><td class='title' nowrap>上傳相關檔案</td>
<td class='col'>
<input type='file' name='docs[]' class='multi' >".
list_del_file('files',$sn)."
</td></tr>
<!--地址-->
<tr><td class='title' nowrap>地址</td>
<td class='col'>
<div style='position:relative;'>
<span id='AddrForm'></span>
<input type='text' name='addr' size='30' value='{$addr}' id='addr'>
</div>
</td></tr>
<tr>
<td class='bar' colspan='2'>
<!--編號-->
<input type='hidden' name='sn' value='{$sn}'>
<input type='hidden' name='op' value='{$op}'>
<input type='submit' value='儲存'>
</td>
</tr>
</table>
</form>";
//raised,corners,inset
$main=div_3d("通訊錄管理",$main,"raised");
return $main;
}
//新增資料到contact中
function insert_contact(){
global $xoopsDB,$xoopsUser;
$myts =& MyTextSanitizer::getInstance();
$_POST['tel']=$myts->addSlashes($_POST['tel']);
$_POST['email']=$myts->addSlashes($_POST['email']);
$_POST['name']=$myts->addSlashes($_POST['name']);
$_POST['birthday']=$myts->addSlashes($_POST['birthday']);
$_POST['zip']=$myts->addSlashes($_POST['zip']);
$_POST['county']=$myts->addSlashes($_POST['county']);
$_POST['city']=$myts->addSlashes($_POST['city']);
$_POST['addr']=$myts->addSlashes($_POST['addr']);
$sql = "insert into `".$xoopsDB->prefix("contact")."`
(`tel` , `email` , `name` , `gsn` , `birthday` , `zip` , `county` , `city` , `addr`)
values('{$_POST['tel']}' , '{$_POST['email']}' , '{$_POST['name']}' , '{$_POST['gsn']}' , '{$_POST['birthday']}' , '{$_POST['zip']}' , '{$_POST['county']}' , '{$_POST['city']}' , '{$_POST['addr']}')";
$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
//取得最後新增資料的流水編號
$sn = $xoopsDB->getInsertId();
upload_file('photo' , $sn , '400');
upload_file('files' , $sn , '400' , 'docs');
return $sn;
}
//更新contact某一筆資料
function update_contact($sn=""){
global $xoopsDB,$xoopsUser;
$myts =& MyTextSanitizer::getInstance();
$_POST['tel']=$myts->addSlashes($_POST['tel']);
$_POST['email']=$myts->addSlashes($_POST['email']);
$_POST['name']=$myts->addSlashes($_POST['name']);
$_POST['birthday']=$myts->addSlashes($_POST['birthday']);
$_POST['zip']=$myts->addSlashes($_POST['zip']);
$_POST['county']=$myts->addSlashes($_POST['county']);
$_POST['city']=$myts->addSlashes($_POST['city']);
$_POST['addr']=$myts->addSlashes($_POST['addr']);
$sql = "update `".$xoopsDB->prefix("contact")."` set
`tel` = '{$_POST['tel']}' ,
`email` = '{$_POST['email']}' ,
`name` = '{$_POST['name']}' ,
`gsn` = '{$_POST['gsn']}' ,
`birthday` = '{$_POST['birthday']}' ,
`zip` = '{$_POST['zip']}' ,
`county` = '{$_POST['county']}' ,
`city` = '{$_POST['city']}' ,
`addr` = '{$_POST['addr']}'
where `sn` = '$sn'";
$xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
upload_file('photo' , $sn , '400');
upload_file('files' , $sn , '400' , 'docs');
return $sn;
}
//列出所有contact資料
function list_contact($show_function=1){
global $xoopsDB , $xoopsModule , $isAdmin;
//製作選項
$sql = "select gsn,title from `".$xoopsDB->prefix("contact_cate")."` where parent_gsn!='0' order by sort";
$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
while(list($gsn,$title)=$xoopsDB->fetchRow($result)){
$cate_arr[]="'$gsn':'$title'";
}
$cate_option=implode(" , ",$cate_arr);
include_once XOOPS_ROOT_PATH."/modules/tadtools/jeditable.php";
$file="save.php";
$jeditable = new jeditable();
//$jeditable->setTextCol("#id",$file,'140px','12px',"{'sn':$sn,'op' : 'save'}","點擊編輯");
//$jeditable->setTextAreaCol("#id",$file,'140px','12px',"{'sn':$sn,'op' : 'save'}","點擊編輯");
//$jeditable->setSelectCol("#id",$file,"{'boy':'男生' , 'girl':'女生'}","{'sn' : $sn , 'op' : 'save'}","點擊編輯");
$sql = "select * from `".$xoopsDB->prefix("contact")."` ";
$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
$function_title=($show_function)?"<th>功能</th>":"";
$all_content="";
while($all=$xoopsDB->fetchArray($result)){
//以下會產生這些變數: $tel , $email , $name , $gsn , $sn , $birthday , $zip , $county , $city , $addr
foreach($all as $k=>$v){
$$k=$v;
}
$fun=($show_function)?"
<td>
<a href='{$_SERVER['PHP_SELF']}?op=contact_form&sn=$sn' class='link_button'>編輯</a>
<a href=\"javascript:delete_contact_func($sn);\" class='link_button'>刪除</a>
<a href='pdf2.php?sn=$sn' class='link_button'>PDF</a>
</td>":"";
$jeditable->setSelectCol("#gsn_{$sn}",$file,"{{$cate_option}}","{'sn' : $sn , 'col' : 'gsn'}");
$jeditable->setTextCol("#name_{$sn}",$file,'100px','12px',"{'sn':$sn , 'col' : 'name'}");
$jeditable->setTextCol("#email_{$sn}",$file,'100px','12px',"{'sn':$sn , 'col' : 'email'}");
$cate=get_contact_cate_all();
$file_counter1=get_file_amount('photo' , $sn);
$file_counter2=get_file_amount('files' , $sn);
$all_content.="
<tr>
<td id='gsn_{$sn}'>{$cate[$gsn]['title']}</td>
<td id='name_{$sn}'>{$name}</td>
<td>{$tel}</td>
<td id='email_{$sn}'>{$email}</td>
<td>{$birthday}</td>
<td>{$zip}</td>
<td>{$county}</td>
<td>{$city}</td>
<td>{$addr}</td>
<td>{$file_counter1}</td>
<td>{$file_counter2}</td>
$fun
</tr>
";
}
$jeditable_set=$jeditable->render();
//if(empty($all_content))return "";
$add_button=($show_function)?"<a href='{$_SERVER['PHP_SELF']}?op=contact_form' class='link_button_r'>新增</a>":"";
//刪除確認的JS
$main="
$jeditable_set
<script>
function delete_contact_func(sn){
var sure = window.confirm('確定刪除此資料?');
if (!sure) return;
location.href=\"{$_SERVER['PHP_SELF']}?op=delete_contact&sn=\" + sn;
}
</script>
批次匯入:
<form action='index.php' method='post' enctype='multipart/form-data'>
<INPUT type='file' name='userfile'>
<INPUT type='hidden' name='op' value='import'>
<INPUT type='submit' value='匯入 CSV'>
<INPUT type='button' value='匯出 CSV' onClick=\"location.href='index.php?op=export'\">
</form>
<form action='index.php' method='post' enctype='multipart/form-data'>
<INPUT type='file' name='importfile'>
<INPUT type='hidden' name='op' value='import_excel'>
<INPUT type='submit' value='匯入 Excel'>
<INPUT type='button' value='匯出 Excel' onClick=\"location.href='excel.php'\">
</form>
<INPUT type='button' value='匯出 PDF' onClick = \"location.href='pdf.php'\">
<INPUT type='button' value='匯出所有單張 PDF' onClick = \"location.href='pdf_all.php'\">
<INPUT type='button' value='匯出 docx' onClick = \"location.href='docx.php'\">
<table summary='list_table' id='tbl' style='width:100%;'>
<tr>
<th>群組</th>
<th>姓名</th>
<th>電話</th>
<th>信箱</th>
<th>生日</th>
<th>郵遞區號</th>
<th>縣市</th>
<th>鄉鎮市區</th>
<th>地址</th>
<th>相片</th>
<th>檔案數</th>
$function_title
</tr>
<tbody>
$all_content
</tbody>
<tr>
<td colspan=11 class='bar'>
{$add_button}
</td>
</tr>
</table>";
//raised,corners,inset
$main=div_3d("",$main,"corners");
return $main;
}
//以流水號取得某筆contact資料
function get_contact($sn=""){
global $xoopsDB;
if(empty($sn))return;
$sql = "select * from `".$xoopsDB->prefix("contact")."` where `sn` = '{$sn}'";
$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
$data=$xoopsDB->fetchArray($result);
return $data;
}
//刪除contact某筆資料資料
function delete_contact($sn=""){
global $xoopsDB , $isAdmin;
$sql = "delete from `".$xoopsDB->prefix("contact")."` where `sn` = '{$sn}'";
$xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
del_files('' , 'photo' , $sn);
del_files('' , 'files' , $sn);
}
//取得所有contact_cate分類選單的選項(模式 = edit[編輯用] or show[顯示用],目前分類編號,目前分類的所屬編號)
function get_contact_cate_options($mode='show' , $default_gsn="0" , $default_parent_gsn="0" , $unselect_level="" , $start_search_sn="0" , $level=0){
global $xoopsDB , $xoopsModule;
$sql = "select `gsn` , `title` from `".$xoopsDB->prefix("contact_cate")."` where `parent_gsn` = '{$start_search_sn}' order by `sort`";
$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'] , 3, mysql_error());
$prefix=str_repeat(" " , $level);
$level++;
$unselect=explode("," , $unselect_level);
$main="";
while(list($gsn , $title)=$xoopsDB->fetchRow($result)){
if($mode=="edit"){
$selected=($gsn==$default_parent_gsn)?"selected=selected":"";
$selected.=($gsn==$default_gsn)?"disabled=disabled" : "";
$selected.=(in_array($level , $unselect))?"disabled=disabled" : "";
}else{
$selected=($gsn==$default_gsn)?"selected=selected" : "";
$selected.=(in_array($level , $unselect))?"disabled=disabled" : "";
}
$main.="<option value=$gsn $selected>{$prefix}{$title}</option>";
$main.=get_contact_cate_options($mode , $default_gsn , $default_parent_gsn , $unselect_level , $gsn , $level);
}
return $main;
}
//匯入
function import(){
global $xoopsDB;
//$main="<table>";
$handle = fopen($_FILES['userfile']['tmp_name'], "r") or die("無法開啟");
while (($data = __fgetcsv($handle, 1000)) !== FALSE) {
//判斷格式
if(!is_numeric($data[0])){
continue;
}
$data[1]=mb_convert_encoding($data[1], "UTF-8" , "Big5");
$data[6]=iconv("Big5" , "UTF-8" , $data[6]);
$data[7]=iconv("Big5" , "UTF-8" , $data[7]);
$data[8]=iconv("Big5" , "UTF-8" , $data[8]);
/*
$main.="
<tr>
<td>{$data[0]}</td>
<td>{$data[1]}</td>
<td>{$data[2]}</td>
<td>{$data[3]}</td>
<td>{$data[4]}</td>
<td>{$data[5]}</td>
<td>{$data[6]}</td>
<td>{$data[7]}</td>
<td>{$data[8]}</td>
</tr>
";
*/
$sql = "insert into `".$xoopsDB->prefix("contact")."` (`gsn` , `name` , `tel` , `email` , `birthday` , `zip` , `county` , `city` , `addr`) values('{$data[0]}' , '{$data[1]}' , '{$data[2]}' , '{$data[3]}' , '{$data[4]}' , '{$data[5]}' , '{$data[6]}' , '{$data[7]}' , '{$data[8]}')";
$xoopsDB->queryF($sql) or die($sql);
}
fclose($handle);
//$main.="</table>";
return $main;
}
function __fgetcsv(&$handle, $length = null, $d = ",", $e = '"') {
$d = preg_quote($d);
$e = preg_quote($e);
$_line = "";
$eof=false;
while ($eof != true) {
$_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
$itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
if ($itemcnt % 2 == 0)
$eof = true;
}
$_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
$_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
$_csv_data = $_csv_matches[1];
for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
$_csv_data[$_csv_i] = preg_replace("/^" . $e . "(.*)" . $e . "$/s", "$1", $_csv_data[$_csv_i]);
$_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
}
return empty ($_line) ? false : $_csv_data;
}
//匯出函數
function export(){
global $xoopsDB;
$sql = "select * from `".$xoopsDB->prefix("contact")."` ";
$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
$main="gsn,name,tel,email,birthday,zip,county,city,addr\n";
while($all=$xoopsDB->fetchArray($result)){
//以下會產生這些變數: $tel , $email , $name , $gsn , $sn , $birthday , $zip , $county , $city , $addr
foreach($all as $k=>$v){
$$k=$v;
}
$name=iconv("UTF-8" , "Big5" , $name);
$county=iconv("UTF-8" , "Big5" , $county);
$city=iconv("UTF-8" , "Big5" , $city);
$addr=iconv("UTF-8" , "Big5" , $addr);
$main.="$gsn,$name,$tel,$email,$birthday,$zip,$county,$city,$addr\n";
}
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=contact.csv");
echo $main;
exit;
}
//匯入Excel
function import_excel(){
global $xoopsDB;
include_once '../class/PHPExcel/IOFactory.php';
$reader = PHPExcel_IOFactory::createReader('Excel5');
$PHPExcel = $reader->load( $_FILES['importfile']['tmp_name'] ); // 檔案名稱
$sheet = $PHPExcel->getSheet(0); // 讀取第一個工作表(編號從 0 開始)
$highestRow = $sheet->getHighestRow(); // 取得總列數
// 一次讀取一列
for($row = 1; $row <= $highestRow; $row++) {
$v="";
//讀取一列中的每一格
for ($col = 0; $col <= 8; $col++) {
//格式檢查
if( PHPExcel_Shared_Date::isDateTime( $sheet->getCellByColumnAndRow($col , $row ) )){
$val = PHPExcel_Shared_Date::ExcelToPHPObject( $sheet->getCellByColumnAndRow( $col , $row )->getValue())->format('Y-m-d');
}else{
$val = $sheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();
}
if(!get_magic_quotes_runtime()) {
$v[$col]=addSlashes($val);
}
}
if(!is_numeric($v[0]) or empty($v[0]))continue;
$sql = "insert into `".$xoopsDB->prefix("contact")."` (`gsn` , `name` , `tel` , `email` , `birthday` , `zip` , `county` , `city` , `addr`) values('{$v[0]}' , '{$v[1]}' , '{$v[2]}' , '{$v[3]}' , '{$v[4]}' , '{$v[5]}' , '{$v[6]}' , '{$v[7]}' , '{$v[8]}')";
$xoopsDB->queryF($sql) or die($sql);
}
}
/*-----------執行動作判斷區----------*/
$op = empty($_REQUEST['op'])? "":$_REQUEST['op'];
$sn=empty($_REQUEST['sn'])?"":intval($_REQUEST['sn']);
$gsn=empty($_REQUEST['gsn'])?"":intval($_REQUEST['gsn']);
$files_sn=empty($_REQUEST['files_sn'])?"":intval($_REQUEST['files_sn']);
switch($op){
/*---判斷動作請貼在下方---*/
//新增資料
case "insert_contact":
$sn=insert_contact();
header("location: {$_SERVER['PHP_SELF']}?sn=$sn");
break;
//更新資料
case "update_contact":
update_contact($sn);
header("location: {$_SERVER['PHP_SELF']}");
break;
//輸入表格
case "contact_form":
$main=contact_form($sn);
break;
//刪除資料
case "delete_contact":
delete_contact($sn);
header("location: {$_SERVER['PHP_SELF']}");
break;
//匯入
case "import":
import();
header("location: {$_SERVER['PHP_SELF']}");
break;
//匯出
case "export":
export();
break;
//匯入Excel
case "import_excel":
import_excel();
header("location: {$_SERVER['PHP_SELF']}");
break;
//預設動作
default:
$main=list_contact();
break;
/*---判斷動作請貼在上方---*/
}
/*-----------秀出結果區--------------*/
module_admin_footer($main,0);
?>