<?php	
include_once "phpinput.php";        //引入input函數
include_once "fieldverification.php";        //引入欄位驗證函數
include_once "function/themesfunction.php"; //引入布景布局設定
	
if(!empty($_POST)) $_POST= neillibrary_special_chars_replace($_POST);		
if(!empty($_GET)) $_GET= neillibrary_special_chars_replace($_GET);




//引入模組設定-以佈景ID來區分	
if(!file_exists(XOOPS_ROOT_PATH."/modules/neillibrary/modulessetting/".$GLOBALS['xoopsConfig']['theme_set'].".php")){
include_once "modulessetting/default.php";        
}else{
include_once "modulessetting/".$GLOBALS['xoopsConfig']['theme_set'].".php";     
}
include_once "function/custommenu.php"; //引入模組共用function-自訂按鈕


//註冊會員下拉選單(已啟用會員)
function neillibrary_user_dropdown_menu($name="",$suid="") {
//開啟會員資料表
$dbneme="users";
$where="where `user_sig` != 'NULL' &&  `last_login` != '0'  order by  uid  ASC";  //where數值 

foreach($usersArr=databasetablewhile($dbneme,$where)  as $i=> $val){
$optionname=!empty($usersArr[$i]['name']) ? $usersArr[$i]['uname']."->".$usersArr[$i]['name'] : $usersArr[$i]['uname']; 
$select_box.=optionselect($dataid=$usersArr[$i]['uid'],$optionname,$oid="".$suid."",$value=$usersArr[$i]['uid']);
}

$user_box="
<select id='uid_select' name='".$name."' class='form-control'>
<option  data-id='0' value='0'>"._MS_SHARED271."</option>
".$select_box."
</select>	
";

return  $user_box;
}





//區塊解自訂欄位指定KEY輸出
function neillibrary_block_customize($conversion="",$key=""){
$customize=phpconversion($conversion,$type="unserialize");
return $customize[$key];
}


//列數轉換col-md
function neillibrary_change_colmd($row="") {
switch($row){
  case "1":
  $val="col-md-12";
  break;
  case "2":
  $val="col-md-6";
  break;
  case "3":
  $val="col-md-4";
  break;
  case "4":
  $val="col-md-3";
  break;
  default:
  $val="col-md-4";
}
return  $val;
}







//年選單
function neillibrary_yearmenu($dbneme="",$where="",$keyval="",$year="",$url="",$variable="") {
global $xoopsConfig; 	
foreach($Arr=databasetablewhile($dbneme,$where,$selectkey="DISTINCT YEAR(".$keyval.") AS year") as $key=> $val){	
$optionname=$xoopsConfig['language']=='tchinese_utf8' ? sprintf(_MS_SHARED251,($Arr[$key]['year']-1911),$Arr[$key]['year']): $Arr[$key]['year']._MS_SHARED259; 		
if(empty($url)){	
$option.=optionselect($dataid=$Arr[$key]['year'],$optionname,$oid="".$year."",$value=$Arr[$key]['year']);
}else{
$option.=optionselect($dataid=$Arr[$key]['year'],$optionname,$oid="".$year."",$value=$url.$Arr[$key]['year'].$variable);
}
}
return  $option;
}


//遞迴分類-核取選單
function neillibrary_checkthemenu($sortid="",$dbneme="",$sublayer="",$cutting="",$name="",$DBval="") {
	$sublayer++;
	if(!empty($sortid)) {
		$namevar= $sublayer==1 ? 'sortid' : 'of_sortid';
	} else {
		$namevar= $sublayer==1 ? 'of_sortid' : 'sortid';
	}
	$where="  where  ".$DBval." `".$namevar."` = '".$sortid."'  && `enable` = '1' order by  sortidsort  ASC";
	foreach($sortArr=$sortArr=databasetablewhile($dbneme,$where) as $key=> $val) {
		if($sublayer==1) $sortvar.="<div style='clear: both;'></div>";
		//比對陣列	
		if(!empty(cuttingfunction($cutting,$sign=",")) &&  in_array($sortArr[$key]['sortid'], cuttingfunction($cutting,$sign=","))) {
			$goid[$key]=$sortArr[$key]['sortid'];
		} else {
			$goid[$key]=0;
		}
		$sortvar.="<div class='col-md-3 checkboxstyle".$sublayer."'>".checkbox($dataid="".$sortArr[$key]['sortid']."",$name,$value="".$sortArr[$key]['sortid']."",$optionname="".$sortArr[$key]['sorttitle']."",$oid="".$goid[$key]."")."</div>";
		//沒有子層結束遞迴
		if(!empty(moduledb($dbneme,$where="where `of_sortid` = '".$sortArr[$key]['sortid']."'"))) {
			$sortvar.=neillibrary_checkthemenu($sortid=$sortArr[$key]['sortid'],$dbneme,$sublayer,$cutting,$name,$DBval);
		}
	}
	return  $sortvar;
}

//時間格式轉換
function neillibrary_timeformatcnv($dbneme="",$where="",$keyArr="",$timechange="",$pkey="") {
	//$dbneme 資料表
	//$where  查詢where值
	//$keyArr=array("discounime","endtime") 要轉換的日期的name key 舊->新
	//$timechange=array("0000-00-00 00:00:00","'1970-01-01 00:00:00'") 將原本日期改為新日期的格式 查詢->寫入  寫入日期格式"'1970-01-01 00:00:00'"  NULL格式'NULL'
	//$pkey="productid" 查詢主鍵
	//時間格式轉換
	foreach($Arr=databasetablewhile($dbneme,$where) as $key=> $val) {
		foreach($keyArr as $value) {
			if($Arr[$key][$value]==$timechange[0]) {
				$setvar[$key]="set ".$value."={$timechange[1]}   where ".$pkey."='".$Arr[$key][$pkey]."'";
				update($dbneme,$setvar[$key]);
			}
		}
	}
}


//多語系標籤產生區塊
function  neillibrary_xLanguagetext(){	
foreach($Arrdate=databasetablewhile($dbneme='xlanguage_base',$where=" ") as $key=> $val){
$box.="
<div class='row'>
<label class='col-md-3'>"._MS_SHARED21.$Arrdate[$key]['lang_desc']."</label>	
<div class='col-md-9'>".inputtextarea($class="inputeach",$name=$Arrdate[$key]['lang_code'],$id="lang_desc",$rows="3",$cols="0",$value="",$placeholder=_MS_SHARED21.$Arrdate[$key]['lang_desc'])."<p>
</div> 
</div>";	
$text.="【".$Arrdate[$key]['lang_desc']."->".$Arrdate[$key]['lang_code']."】";
}
$corparr=json_encode(array('text1' => _MS_XLANGUAGETEXT08,'text2' => _MS_XLANGUAGETEXT09));
$val="<div style='clear: both;'></div><br /><div id='langbox' class='alert alert-green-shallow' role='alert'>
<div class='row'>
<div class='col-md-5'>
".$box."
<div class='row'>	
<div class='col-md-3'></div><div class='col-md-9'>"._MS_XLANGUAGETEXT07."</div> 
</div>	
</div>
<div class='col-md-2'><a target='_blank' href='https://translate.google.com.tw/' class='btn btn-darkred btn-block'>"._MS_SHARED277."</a><button type='button' id='langoperate' class='btn btn-darkgray btn-block'>"._MS_XLANGUAGETEXT03."</button></div>
<div class='col-md-5'><div class='row'>
<div class='col-md-12'>".inputtextarea($class="",$name="",$id="lang_textarea",$rows="6",$cols="0",$value="")."<p></div>
<div class='col-md-6'><button type='button' id='lang_copy' class='btn btn-darkred btn-block'>"._MS_XLANGUAGETEXT04."</button></div>
<div class='col-md-6'><button type='button' id='lang_clear'  class='btn btn-darkblue btn-block'>"._MS_XLANGUAGETEXT05."</button></div>
</div></div>      
</div>
</div>
<div class='alert alert-pink' role='alert'>".sprintf(_MS_XLANGUAGETEXT01,$text)."</div>
<script src='".XOOPS_URL."/modules/neillibrary/js/cdnjs/clipboard.min.js'></script>	
<script>var corparr='{$corparr}';</script>
";
return $val;
}


//遞迴替換資料庫禁用字元
function neillibrary_special_chars_replace($value="") {
  if (is_array($value)) {
    return array_map('neillibrary_special_chars_replace', $value);
  } else {
    $replacements = array(
        'where' => 'Where', 
        '\'' => '&#039;'
    );
    return str_replace(array_keys($replacements), array_values($replacements), $value);
  }
}
//替換&#039;->'
function neillibrary_replaceHtmlEntity($string) {
  $pattern = "/&#039;/";
  $replacement = "'";
  return preg_replace($pattern, $replacement, $string);
}

//編號加上前置0000-超過最大值向左填充
function neillibrary_numberleadingdigits($cutting="",$number=""){	
$frontArr=cuttingfunction($cutting,$sign="-");
$num[0] = ($number+1); //編號+1
$str_length = mb_strlen($frontArr[1], "utf-8");  //預設值
if(mb_strlen($num[0], "utf-8") > $str_length){ //如果編號大於預設值	
//新預設值+(編號-預設值)
$str_length = $str_length+(mb_strlen($num[0], "utf-8")-$str_length);  //預設值
}
// 如果 number < $str_length 
$str = substr ( "{$frontArr[1]}{$num[0]}" , - $str_length );
//建立編號(英文+數字)
$num[1]=$frontArr[0].'-'.$str;
return $num;
}

//文字區塊編碼連結處理
/*function neillibrary_textprocessing($val = "", $item = "") {
	// 字元轉編碼
	if (empty($item)) $val = htmlentities($val, ENT_QUOTES, "UTF-8");
	// URL 自動加上連結
	$val = preg_replace_callback(
		    '#(<img[^>]*>|<a[^>]*>.*?</a>|<link[^>]*>|<area[^>]*>|<script[^>]*>|<audio[^>]*>|<video[^>]*>|<iframe[^>]*>|<form[^>]*>|<base[^>]*>|<object[^>]*>|<embed[^>]*>|<applet[^>]*>|<source[^>]*>)|((http|https|ftp|telnet)://[0-9a-z\.\-]+(:?[0-9]*)([0-9a-z\_\/\?\&\=\%\.\;\#\-\~\+]*))#i',
		    function ($matches) {
		// 如果匹配到 <img> 或 <a> 標籤，直接返回
		if (!empty($matches[1])) {
			return $matches[1];
		}
		// 如果是URL，則進行替換
		$url = htmlspecialchars(html_entity_decode($matches[2]));
		return '<a target="_blank"  title="'._MS_SHARED274.'"  href="' . $url . '" rel="nofollow">' . $url . '</a>';
	},$val
		);
	// 保留原格式
	return empty($item) ? nl2br($val) : $val;
}*/
// 文字區塊編碼連結處理
function neillibrary_textprocessing($val = "", $item = "") {
    // 字元轉編碼
    if (empty($item)) {
        $val = htmlentities($val, ENT_QUOTES, "UTF-8");
    }

    // URL 自動加上連結，排除帶有 data-oembed-url 屬性的標籤
    $val = preg_replace_callback(
        '#(<img[^>]*>|<a[^>]*>.*?</a>|<link[^>]*>|<area[^>]*>|<script[^>]*>|<audio[^>]*>|<video[^>]*>|<iframe[^>]*>|<form[^>]*>|<base[^>]*>|<object[^>]*>|<embed[^>]*>|<applet[^>]*>|<source[^>]*>|<[^>]*\sdata-oembed-url=["\'][^"\']*["\'][^>]*>)|((http|https|ftp|telnet)://[0-9a-z\.\-]+(:?[0-9]*)([0-9a-z\_\/\?\&\=\%\.\;\#\-\~\+]*))#i',
        function ($matches) {
            // 如果匹配到標籤（包括帶有 data-oembed-url 的標籤），直接返回
            if (!empty($matches[1])) {
                return $matches[1];
            }
            // 如果是 URL，則進行替換
            $url = htmlspecialchars(html_entity_decode($matches[2]));
            return '<a target="_blank" title="' . _MS_SHARED274 . '" href="' . $url . '" rel="nofollow">' . $url . '</a>';
        },
        $val
    );

    // 保留原格式
    return empty($item) ? nl2br($val) : $val;
}


//下載遠端檔案回本地端
function neillibrary_curlsave_file($inPath="",$outPath=""){ 
//$inPath 遠端路徑
//$outPath 儲存本地端路徑

set_time_limit(0); //如果文件很大，請設置超時。
//文件處理
$new_file = fopen($outPath, "w") or die("cannot open" . $outPath);
//curl操作
$cd = curl_init();
curl_setopt($cd, CURLOPT_URL, $inPath);
curl_setopt($cd, CURLOPT_FILE, $new_file);
curl_setopt($cd, CURLOPT_TIMEOUT, 30); // 超時為 30 秒，要下載大文件，您可能需要增加超時限制。

//運行 curl 下載文件
curl_exec($cd);
/*if (curl_errno($cd)) {
  echo "the cURL error is : " . curl_error($cd);
} else {
  $status = curl_getinfo($cd);
 echo $status["http_code"] == 200 ? "The File is Downloaded" : "The error code is : " . $status["http_code"] ;
 the http status 200 means everything is going well. the error codes can be 401, 403 or 404.
}*/

//關閉並完成操作。
curl_close($cd);
fclose($new_file);
}


//jpge轉png function
function neillibrary_jpgtopng($input_file="",$output_file=""){
//$input_file;  原始JPG檔路徑+檔名
//$output_file; 轉成PNG檔路徑+檔名
//檔案存在才執行
if(file_exists($input_file)) {
$input = imagecreatefromjpeg($input_file);
$width = imagesx($input);
$height = imagesy($input);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output,  255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
imagepng($output, $output_file);
//刪除原始jpg檔
fileadminfunction($fileurl=$input_file,$type="2",$fileex="",$from="");	
}

}
	
//自行建立USER帳號function
function neillibrary_createuser($grouparr=""){
global $xoopsModule,$_POST,$xoopsConfigUser; 

//註冊會員設定
$config_handler  = xoops_getHandler('config');
$xoopsConfigUser = $config_handler->getConfigsByCat(XOOPS_CONF_USER);

//判斷帳號長度-最小
if(mb_strlen($_POST['uname'], "utf-8") < $xoopsConfigUser['minuname']) redirect_header(XOOPS_URL. "/modules/".$xoopsModule->getVar("dirname")."/index.php" ,0 , sprintf(_MS_REGISTERUSER10,mb_strlen($_POST['uname'], "utf-8"),$xoopsConfigUser['minuname']));  
//判斷帳號長度-最大
if(mb_strlen($_POST['uname'], "utf-8") > $xoopsConfigUser['maxuname']) redirect_header(XOOPS_URL. "/modules/".$xoopsModule->getVar("dirname")."/index.php" ,0 , sprintf(_MS_REGISTERUSER11,mb_strlen($_POST['uname'], "utf-8"),$xoopsConfigUser['maxuname']));  
//判斷密碼長度-最小
if(mb_strlen($_POST['pass'], "utf-8") < $xoopsConfigUser['minpass']) redirect_header(XOOPS_URL. "/modules/".$xoopsModule->getVar("dirname")."/index.php" ,0 , sprintf(_MS_REGISTERUSER12,mb_strlen($_POST['pass'], "utf-8"),$xoopsConfigUser['minpass']));  
//判斷重複帳號
if(empty($_POST['uname'])  ||  !empty(moduledb($dbneme="users",$where="   where `uname` = '".$_POST['uname']."'"))) redirect_header(XOOPS_URL. "/modules/".$xoopsModule->getVar("dirname")."/index.php" ,0 , sprintf(_MS_REGISTERUSER04,$_POST['uname']));  
//判斷重複MAIL
if(empty($_POST['uemail'])  || !empty(moduledb($dbneme="users",$where="   where `email` = '".$_POST['uemail']."'"))) redirect_header(XOOPS_URL. "/modules/".$xoopsModule->getVar("dirname")."/index.php" ,0 , sprintf(_MS_REGISTERUSER05,$_POST['uemail']));  

//uname uemail pass
//建立會員帳號
$valuesvar="(name,uname,email,url,user_avatar,user_regdate,user_icq,user_from,user_sig,user_viewemail,actkey,user_aim,user_yim,user_msnm,pass,posts,attachsig,rank,level,theme,timezone_offset,last_login,umode,uorder,notify_method,notify_mode,user_occ,bio,user_intrest,user_mailok) values('', '{$_POST['uname']}', '{$_POST['uemail']}', '', 'blank.gif', '".timedate($datevar=timedate($datevar="Y-m-d H:i:s"),$type="5")."', '', '', NULL, '0', '', '', '', '', '".md5($_POST['pass'])."', '0', '0', '0', '1', '".$GLOBALS['xoopsConfig']['theme_set']."', '0.0', '0', 'flat', '0', '1', '0', '', NULL, '', '1')";	
$uid=insert($dbname="users",$values=$valuesvar);

//建立群組
foreach($grouparr as  $val){	
$valuesvar="(groupid,uid) values('".$val."','".$uid."')";	
insert($dbname="groups_users_link",$values=$valuesvar);
}

return $uid;
}

	

    	
//判斷檔案類型-對應開啟方式	
function neillibrary_openmethod($ftype="",$ftitle="",$modulesid="",$furl="",$browse=""){
global $themefolder;
if(!empty($browse)) $browsebox="<div id='browsebox' title='".$ftitle."'><i class='fa-solid fa-magnifying-glass'><span class='sr-only'>"._MS_SHARED212."</span></i></div>";


switch($ftype){
  case "jpg":
  case "jpeg":
  case "png":
  case "gif":
  case "webp":  
  case "jfif":
 	  	  
  if(file_exists(XOOPS_ROOT_PATH.'/uploads/'.$modulesid.'/'.$furl.'')){ 
  $box="
	<a  aria-label='".sprintf(_MS_SHARED278,$ftitle)."' class='small-img' data-fancybox='gallery' title='".sprintf(_MS_SHARED278,$ftitle)."'  href='".XOOPS_URL."/uploads/".$modulesid."/".$furl."' >
    <div class='fimgbox'>".$browsebox."<img alt='".sprintf(_MS_SHARED278,$ftitle)."'  src='".XOOPS_URL.'/uploads/'.$modulesid.'/'.$furl."'></div>
    </a>";
  }else{
  $box="<div class='fimgbox'>".$browsebox."<img  alt='nofilel' src='".XOOPS_URL."/modules/neillibrary/images/nofilel.png'></div>";
  }    
  break;
  
  case "pdf":
  if(file_exists(XOOPS_ROOT_PATH.'/uploads/'.$modulesid.'/'.$furl.'')){ 
  if($themefolder=='computer') $fancybox_setup="class='small-img' data-fancybox='gallery'  ";
  $box="
	<a ".$fancybox_setup." aria-label='".sprintf(_MS_SHARED278,$ftitle)."'  title='".sprintf(_MS_SHARED278,$ftitle)."'  href='".XOOPS_URL."/uploads/".$modulesid."/".$furl."' >
    <div class='fimgbox'>".$browsebox."<img   src='".XOOPS_URL."/modules/neillibrary/images/".neillibrary_filenameimg($filevar=$furl,$itype="1")."' alt='".$ftitle."'></div>
    </a>";
  }else{
  $box="<div class='fimgbox'>".$browsebox."<img alt='nofilel'  src='".XOOPS_URL."/modules/neillibrary/images/nofilel.png'></div>";
  }    
  break;  
  default:
  if(file_exists(XOOPS_ROOT_PATH.'/uploads/'.$modulesid.'/'.$furl.'')){ 
  if($themefolder=='computer') $fancybox_setup="target='_blank'";  	  
  $box="
	<a  ".$fancybox_setup." title='".$ftitle."'  href='".neillibrary_filenameimg($filevar=$furl,$itype="2").XOOPS_URL."/uploads/".$modulesid."/".$furl."' >
    <div class='fimgbox'>".$browsebox."<img   src='".XOOPS_URL."/modules/neillibrary/images/".neillibrary_filenameimg($filevar=$furl,$itype="1")."' alt='".$ftitle."'></div>
    </a>";
  }else{
  $box="<div class='fimgbox'>".$browsebox."<img  alt='nofilel' src='".XOOPS_URL."/modules/neillibrary/images/nofilel.png'></div>";
  }  

}
return $box;
}
	
	
	
	
//判斷檔案類型-對應代表圖	
function neillibrary_filenameimg($filevar="",$itype=""){

switch(strtolower(pathinfo($filevar, PATHINFO_EXTENSION))){
  case "pdf":
  $ival1='folder-pdf.png';
  break;
  case "docx":
  case "doc": 
  $ival1='folder-word.png';
  $ival2='https://view.officeapps.live.com/op/view.aspx?src=';
  break;
  
  case "odt":   
  $ival1='folder-opt.png';
  $ival2='https://view.officeapps.live.com/op/view.aspx?src=';
  break;
  
  case "rtf":   
  $ival1='folder-rtf.png';
  $ival2='https://view.officeapps.live.com/op/view.aspx?src=';
  break;  
  
  case "xlsx":
  case "xls":   	  
  $ival1='folder-excel.png';
  $ival2='https://view.officeapps.live.com/op/view.aspx?src=';  
  break;
  
  case "pptx":
  case "ppt":   	  
  $ival1='folder-ppt.png';
  $ival2='https://view.officeapps.live.com/op/view.aspx?src=';  
  break;
  case "mp3":
  case "mp4":   	  
  $ival1='folder-videopng.png';
  break;
  case "zip":     	  	  
  $ival1='folder-density.png';
  break;
  default:
  $ival1='folder.png';
}

return ${"ival".$itype};
}	
	
	

//判斷模組版本是否比現在的版本新(更新通知)
function neillibrary_modulesversion($modulesid=""){	
global $xoopsConfig; 
include XOOPS_ROOT_PATH."/modules/".$modulesid."/language/{$xoopsConfig['language']}/modinfo.php";	
include XOOPS_ROOT_PATH.'/modules/'.$modulesid.'/xoops_version.php';
$versionList=moduledb($dbneme="modules",$where=" where `dirname` = '".$modulesid."'");
if($versionList['version'] < $modversion['version']){
//define("_MA_VERSIONRENEW","您目前的%s模組版本為：%s最新版本為：%s<a title='請您前往更新模組' href='%s'>請您前往更新模組</a>");  	
$versionval['text']=sprintf(_MA_VERSIONRENEW,$versionList['name'],$versionList['version'],$modversion['version'],"".XOOPS_URL."/modules/system/admin.php?fct=modulesadmin&op=update&module=".$modulesid."");
}
return $versionval;
}


	

//垃圾留言判斷-資料表
function neillibrary_rubbishmessage($dbneme="",$where="",$cvar="",$kname="",$modulesid="",$configkey=""){
global $xoopsModuleConfig; 
$configvar=configvar($modulesid);

$mArr=databasetablewhile($dbneme,$where);  
$i=0;
//比對相同內容
foreach($mArr as $key=> $val){	
if(preg_match("/".phpstrip_tags($notags=sqlinjectionfound($val=$mArr[$key][$kname]))."+/i", phpstrip_tags($notags=sqlinjectionfound($val=$cvar)))) $i++;
}
//超過張貼上限封鎖
if($i >= $configvar['neillibrary12']){
robottime($var="2");
$valreturn=true;	
} 

return $valreturn;
}



//垃圾留言判斷-陣列
function neillibrary_spamjudgmentArr($content="",$cvar="",$modulesid=""){
//$content->傳入陣列值
//$cvar->比對內容	
	
global $xoopsModuleConfig; 
$configvar=configvar($modulesid);

$i=0;
//比對相同內容
foreach($content as $val){	
if(preg_match("/".phpstrip_tags($notags=sqlinjectionfound($val))."+/i", phpstrip_tags($notags=sqlinjectionfound($cvar)))) $i++;
}

//超過張貼上限封鎖
if($i >= $configvar['neillibrary12']){
robottime($var="2");
$valreturn=true;	
}
 
return $valreturn;
}



	
	
//非會員未啟用cookie判斷
function neillibrary_cookietypes(){
global $xoopsUser;
if(empty($_COOKIE['neil']['cookieid'])  && empty($xoopsUser))  return true;
}

	
	
//瀏覽次數
function neillibrary_counter($counter="",$dbname="",$keyname="",$val="",$DBname=""){
$DBname=!empty($DBname) ? $DBname : 'counter'; // get TRUE		
$setvar="set ".$DBname."='".$counter."' where ".$keyname."='".$val."'";
update($dbname,$set=$setvar);

return $counter;
}
	
	
	
	
	
//模組區塊載入bootstrap	
function neillibrary_bootstrap3blockscss($typevar=""){	
global $xoopsTpl,$xoopsModule;
$conf_name=moduledb($dbneme="config",$where=" where `conf_name` = 'cpanel'");
switch($typevar){
  case "1":
//模組頁面
if($conf_name['conf_value']=='tad'){
$val="<script>
$(document).ready(function() {  
$('#tad_adm_head').remove();
$('link').each(function(i, item){
if(($(this).attr('href').indexOf('bootstrap4')>-1) || ($(this).attr('href').indexOf('bootstrap5')>-1)){
$(this).remove();
}
});
$('script').each(function(i, item){
if(($(this).attr('src').indexOf('bootstrap4')>-1) || ($(this).attr('src').indexOf('bootstrap5')>-1)){
$(this).remove();
}
});
});		
</script>";
}else{
$val="<meta name='viewport' content='width=device-width, initial-scale=1.0'>";	
}
  break;
  
  
  
  case "2":
//模組頁面//http://localhost/xoops2511/modules/system/themes/transition/css/style.css
if($conf_name['conf_value']=='tad'){
$val="<script>
$(document).ready(function() {  
$('#tad_adm_head').remove();
$('link').each(function(i, item){
if($(this).attr('href').indexOf('bootstrap5')>-1){
$(this).remove();
}
});
$('script').each(function(i, item){
if($(this).attr('src').indexOf('bootstrap5')>-1){
$(this).remove();
}


});
});		
</script>";
}else{
$val="<meta name='viewport' content='width=device-width, initial-scale=1.0'>";	
}
break;
  
case "3":
//區塊後台布景不是tad時讀取bootstrap.css
if($conf_name['conf_value']!='tad' || $xoopsModule->getVar("dirname")=='system'){
$xoopsTpl->assign('xoops_module_header', "	
<link rel='stylesheet' type='text/css' media='screen' href='" . XOOPS_URL . "/modules/neillibrary/css/bootstrap4/css/bootstrap.css'>
<link rel='stylesheet' type='text/css' media='screen' href='" . XOOPS_URL . "/modules/neillibrary/css/admin.css'>
 ");
}
	
break;
  
  
  
  default:
//區塊後台布景不是tad時讀取bootstrap.css
if($conf_name['conf_value']!='tad' || $xoopsModule->getVar("dirname")=='system'){
$xoopsTpl->assign('xoops_module_header', "	
<link rel='stylesheet' type='text/css' media='screen' href='" . XOOPS_URL . "/modules/neillibrary/css/bootstrap3/css/bootstrap.css'>
<link rel='stylesheet' type='text/css' media='screen' href='" . XOOPS_URL . "/modules/neillibrary/css/admin.css'>
 ");
}
}


return $val;
}		
	

//可管理群組&&可觀看群組選單
function neillibrary_permissionmenu($types='',$admingroup='',$browsegroup='',$groupArr='',$groupid=''){	
//可管理群組
$dbneme="groups";
$where=" order by  groupid  ASC";  //where數值 	
$sortoption=databasetablewhile($dbneme,$where);  
//下拉選單
foreach($sortoption as $key=> $val){
//可管理群組
if($types=='1' || empty($types)){
if($sortoption[$key]['group_type']!='User' && $sortoption[$key]['group_type']!='Anonymous'){	
if(!empty(phpconversion($conversion=$admingroup,$type="unserialize")) && in_array($sortoption[$key]['groupid'], phpconversion($conversion=$admingroup,$type="unserialize"))){  //單值-> 陣列
$oidvar['1'][$key]=$sortoption[$key]['groupid'];
}
$groups['1'].=optionselect($dataid=$sortoption[$key]['groupid'],$optionname=$sortoption[$key]['name'],$oid=$oidvar['1'][$key],$value=$sortoption[$key]['groupid'],$id=$groupid);
}
}
//可觀看群組
//預設群組
if($types=='2' || empty($types)){	
if(!empty($groupArr)){
if(!empty($groupArr) && in_array($sortoption[$key]['groupid'], $groupArr)){  //單值-> 陣列
$oidvar['2'][$key]=$sortoption[$key]['groupid'];
}
}else{
if(!empty(phpconversion($conversion=$browsegroup,$type="unserialize")) && in_array($sortoption[$key]['groupid'], phpconversion($conversion=$browsegroup,$type="unserialize"))){  //單值-> 陣列
$oidvar['2'][$key]=$sortoption[$key]['groupid'];
}
}
$groups['2'].=optionselect($dataid=$sortoption[$key]['groupid'],$optionname=$sortoption[$key]['name'],$oid=$oidvar['2'][$key],$value=$sortoption[$key]['groupid'],$id=$groupid);
}
} 
return $groups;
}





	
	
//QR CODE 產生器	
function neillibrary_qrcodeGenerator($url='',$level='',$size='',$qrcodeimg=''){	
	
//$url 產生QRcode連結
//$level 容錯級別	H 30% 校正 /  L = ~7% 校正 / M = ~15% 校正 / Q = ~25% 校正
//$size 生成圖片大小 max10
//$qrcodeimg 產生QRcode圖檔名
	
include_once XOOPS_ROOT_PATH."/modules/neillibrary/class/phpqrcode/phpqrcode.php";	
$value = $url;         //二維碼內容
$errorCorrectionLevel = $level;  //容錯級別
$matrixPointSize = $size;      //生成圖片大小
//生成二維碼圖片
$filename = XOOPS_ROOT_PATH.'/uploads/neillibrary/qrcode/'.microtime().'.png';
QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
$QR = $filename;        //已經生成的原始二維碼圖片檔案
$QR = imagecreatefromstring(file_get_contents($QR));
//輸出圖片
imagepng($QR, ''.XOOPS_ROOT_PATH.'/uploads/neillibrary/qrcode/'.$qrcodeimg.'.png');
imagedestroy($QR);
//清除暫存圖檔
fileadminfunction($fileurl=$filename,$type="2",$fileex="",$from="",$fileurlnew="",$exclude="");
return $qrcodeimg;
}


//QR CODE 區塊	
function neillibrary_qrcodrebox($qrcodeimg="",$alt="",$class="",$type="",$url=""){	


//判斷QRCODE圖檔是否存在
if($type!='1'){
if(!file_exists(XOOPS_ROOT_PATH.'/uploads/neillibrary/qrcode/'.$qrcodeimg.'.png')){
//QRCODE圖檔不存在重建產生QRCODE
neillibrary_qrcodeGenerator($url,$level='H',$size='10',$qrcodeimg);
}
}


switch($type){
  case "1":
  //刪除QRCODE
fileadminfunction($fileurl=XOOPS_ROOT_PATH.'/uploads/neillibrary/qrcode/'.$qrcodeimg.'.png',$type="2",$fileex="",$from="",$fileurlnew="",$exclude="");
  break;
  
  case "2":
$qrcodebox="
  <img tabindex='0'    title='".$alt."'  alt='".$alt."' class='qrcodebox thumbnail a11y_box' src=".XOOPS_URL."/uploads/neillibrary/qrcode/".$qrcodeimg.".png>
 ";  
    break;    
    
  default:
  //QRCODE預設區塊
$qrcodebox="
<div class='panel ".$class." panelCustom'>
  <div class='panel-heading text-center'><i class='fa-solid fa-qrcode'></i> "._MS_SHARED170."</div>
  <div class='panel-body '>
  <img title='".$alt."'  alt='".$alt."' class='qrcodebox thumbnail' src=".XOOPS_URL."/uploads/neillibrary/qrcode/".$qrcodeimg.".png>
  </div>
</div>  
 ";  
  
  
}


	



return $qrcodebox;
}	
	

//數字轉字母
function neillibrary_IntToChr($index="", $start=65){
/*
* 數字轉字母 （類似於Excel列標）
 * @param Int $index 索引值
 * @param Int $start 字母起始值
 * @return String 返回字母
 */		
    $str = '';
    if (floor($index / 26) > 0) {
        $str.= neillibrary_IntToChr(floor($index / 26)-1);
    }
    return $str.chr($index % 26 + $start);
}


//自動刪除caches及log與temp功能
function neillibrary_autodeletecaches(){
 global $xoopsModuleConfig; 
 

 
 
$configvar=configvar($modulesid="neillibrary"); 
 
//超過設定清除temp
if(fileadminfunction($fileurl=$configvar['neillibrary7'],$type="",$fileex="") >=$configvar['neillibrary10']){
fileadminfunction($fileurl="",$type="5",$fileex="",$from=$configvar['neillibrary7'],$fileurlnew="",$exclude=array('')); 
} 
 

//判斷紀錄時間是否有值~若為空值存入目前時間
if(empty($configvar['neillibrary6'])) update($dbname="config",$set="set conf_value='".timedate($datevar="Y-m-d H:i:s")."'  where conf_name='neillibrary6'");
$delettime=timedate($datevar="".$configvar['neillibrary6']."",$type="2",$calculate="+",$m="",$d=$configvar['neillibrary5'],$y="");

//清除暫存
if(strtotime(timedate($datevar="Y-m-d H:i:s")) > strtotime($delettime)){
neillibrary_deletecaches();

//清除temp
if(file_exists($configvar['neillibrary7'])){
fileadminfunction($fileurl="",$type="5",$fileex="",$from=$configvar['neillibrary7'],$fileurlnew="",$exclude=array(''));
}
//清除qrcode圖檔
fileadminfunction($fileurl="",$type="5",$fileex="",$from=$from=XOOPS_ROOT_PATH.'/uploads/neillibrary/qrcode',$fileurlnew="",$exclude=array(''));



//清除neillibrary_layoutcsslog
$dbneme="neillibrary_layoutcsslog";
$where="  where  `logtime` <= '".timedate($datevar="Y-m-d H:i:s")."'   order by  logid  DESC";  //where數值 
$delettimeArr=databasetablewhile($dbneme,$where);  

foreach($delettimeArr as $key=> $val){
$where=" where `logid` = '".$delettimeArr[$key]['logid']."'";
$DBname="neillibrary_layoutcsslog";  
deletefunction($where,$DBname);
}

//儲存清除caches時間
update($dbname="config",$set="set conf_value='".timedate($datevar="Y-m-d H:i:s")."'  where conf_name='neillibrary6'");
header("refresh:0;URL={$_SERVER['PHP_SELF']}");
exit;
}
}


//刪除暫存
function neillibrary_deletecaches(){	
//清空smarty_cache	
fileadminfunction($fileurl="",$type="5",$fileex="",$from=XOOPS_VAR_PATH.'/caches/smarty_cache',$fileurlnew="",$exclude=array('index.html','index.php'));
//清空smarty_compile
fileadminfunction($fileurl="",$type="5",$fileex="",$from=XOOPS_VAR_PATH.'/caches/smarty_compile',$fileurlnew="",$exclude=array('index.html','index.php'));
//清空xoops_cache
if(empty(modulesmidvar($modulesid="xLanguage",$var="isactive"))){
fileadminfunction($fileurl="",$type="5",$fileex="",$from=XOOPS_VAR_PATH.'/caches/xoops_cache',$fileurlnew="",$exclude=array('index.html','index.php'));
}
}






//產生GD文字圖片
function fonttoimageGDfunction($width="",$height="",$x="",$y="",$font_size="",$word=""){
	
//$width 區塊寬度
//$height區塊高度
//$x內容的x位置
//$y內容的y位置
//$font_size文字大小1~5(最大值為5)
//$word顯示圖片文字內容		
	
    $im            = imagecreatetruecolor($width, $height);
    //製作白底黑字
    $text_color =imagefilledrectangle($im, 0, 0, 300, 300, imagecolorallocate($im, 255, 255, 255)); // 設定底色白色
    imagestring($im, $font_size, $x, $y, $word, $text_color);
    ob_start(); // 打開輸出控制緩衝
    imagepng($im);
    $output = base64_encode(ob_get_clean()); //取得當前內容並刪除緩衝
    imagedestroy($im);
    return $output;
}

//群組管理
function xoopsgroupadminfunction(){
 global $xoopsModule,$groupid; 
//群組
$dbneme="groups";
$where=" order by  groupid  ASC";  //where數值 	
$sortoption=databasetablewhile($dbneme,$where);  
//下拉選單(分類)
foreach($sortoption as $key=> $val){
if($sortoption[$key]['group_type']!='Anonymous'){		
$groupsbox['1'].=optionselect($dataid=$sortoption[$key]['groupid'],$optionname=$sortoption[$key]['name'],$oid=$groupid,$value="groupadmin.php?groupid=".$sortoption[$key]['groupid']."",$id="");
} }   

if(!empty($groupid)){ //群組有值
$groupsbox['2']="<div id='groupoperating' name='158,".$groupid."'></div><script>xoopsgroupadminfunction();</script>	 ";
}else{ //群組空值
$groupsbox['2']="<div class='alert alert-danger text-center' role='alert'>"._MS_GROUPADMIN05."</div>";
}

$main="<div id='groupadminbox' class='container'>
 <div class='page-header'>
 <h2>"._MS_GROUPADMIN02."      <a  href='" .XOOPS_URL. "/modules/". $xoopsModule->getVar("dirname")."/admin/groupadmin.php' class='btn  btn-info btn-xs active'>"._MS_SHARED25."</a> <a  href='" .XOOPS_URL. "/modules/system/admin.php?fct=groups' target='_blank' class='btn btn-warning btn-xs active'>"._MS_GROUPADMIN11."</a>  </h2>
<label for='sel2'>"._MS_GROUPADMIN03."</label>  
</div>

<div class='text-center' id='groupoptionbox'>
	<select id='FriendLink1' class='form-control groupoption' name='groupid' >
    <option value='groupadmin.php?groupid=0'  data-id='' >"._MS_GROUPADMIN04."</option>
   ".$groupsbox['1']."
  </select>
</div> 	
<div class='col-md-12'>
	".$groupsbox['2']."
	
	</div>


 </div>
<script src='".XOOPS_URL."/modules/neillibrary/js/menujs/newbase.js'></script>
 ";  
 return $main;
}




//模組加入防護模組網路爬蟲例外
function protectorexception($modulesid=""){
 global $xoopsDB;
$conf_name=moduledb($dbneme="config",$where=" where `conf_name` = 'dos_skipmodules'");
//比對字串中是否有模組ID
if(!preg_match("/".$modulesid."/i", $conf_name['conf_value'])) {
$conf_nameDB=!empty($conf_name['conf_value']) ? $conf_name['conf_value']."|".$modulesid."": "".$modulesid.""; // get TRUE	
update($dbname="config",$set="set conf_value = '".$conf_nameDB."'  where conf_name= 'dos_skipmodules'");    
} 
}



//區塊權限檢查-(準備廢除)
function blockspermissioncheck($DBdata="",$order="",$dbneme1="",$dbneme2="",$total=""){
global $typesid;

//權限檢查
$where="  ".$DBdata." ".$order." ";  //where數值
$difference=differencefunction($dbneme1,$dbneme2,$where,$type="1");	



foreach((is_array($difference) ? array_unique($difference) : null ) as $key=> $val){
$valid.="`sortid` = '".$val."' ||";
}
//權限為空值
if(empty($difference)) $valid.="`sortid` = '' ||";
$sortidDB=substr($valid,0,-2);	
$separate=empty($sortidDB) ? '' : '&&'; // get TRUE
$DBdata="where  (".$sortidDB.") ".$separate."  `enable` = '1'   ";	



return $DBdata;
}





//檔案管理
function fileadminfunction($fileurl="",$type="",$fileex="",$from="",$fileurlnew="",$exclude="") {
	switch($type) {
		case "1":
		//刪除資料夾及底下資料
		$Filevar=fileunlink_r($from);
		//無法刪除時變更檔名
		if(empty($Filevar)) changedirectory($changedate=$from);
		break;
		//刪除檔案
		case "2":
		if(file_exists($fileurl)) {
			chmod($fileurl, 0777);
			//更改檔案權限
			unlink($fileurl);
			//將檔案刪除
		}
		break;
		//複製檔案 
		case "3":   	   
		 copy($fileurl , $fileurlnew);
		//舊->新
		break;
		//建立目錄
		case "4":    	  
		    //若目錄不存在建立目錄    
		if(empty(is_dir($from))) {
			umask(000);
			mkdir($from, 0777);
		}
		break;
		//刪除目錄中內容物件(不包含刪除目錄)
		case "5":    	  
		$Filevar=filedeletionArr($from,$exclude);
		break;
		default:
		//取得資料夾內檔案數
		$Filevar = is_array(glob("$fileurl/*".$fileex."*")) ? count(glob("$fileurl/*".$fileex."*")) : 0 ;
	}
	//刪除目錄
	return $Filevar;
}
//變更資料夾檔名
function changedirectory($changedate="",$newdate="",$type="") {
 switch($type){
  case "1":
  if(!empty(rename($changedate, $newdate)))   return true; //新產生新檔名
  break;
  
  default:
  if(!empty(rename($changedate, $changedate."_bak_".date("Ymd")."")))   return true; //新產生_bak_時間檔名
}


}

//刪除目錄包含內容物件
function fileunlink_r($from="") {
	if (!file_exists($from)) {
		return false;
	}
	$dir = opendir($from);
	while (false !== ($file = readdir($dir))) {
		if ($file == '.' OR $file == '..') {
			continue;
		}
		if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
			fileunlink_r($from . DIRECTORY_SEPARATOR . $file);
		} else {
			unlink($from . DIRECTORY_SEPARATOR . $file);
		}
	}
	if(!empty(rmdir($from))) $returnvar=true;
	closedir($dir);
	return $returnvar;
}


//刪除目錄中內容物件(不包含刪除目錄)
/*function filedeletionArr($from="",$exclude="") {
    if (!file_exists($from)) {return false;}
    $dir = opendir($from);
    while (false !== ($file = readdir($dir))) {
        if ($file == '.' OR $file == '..') {continue;}
        if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
            filedeletionArr($from . DIRECTORY_SEPARATOR . $file);
        }
        else {        	
       if(!empty($exclude) &&  empty(in_array($file, $exclude))){
        	unlink($from . DIRECTORY_SEPARATOR . $file);
        	}         
        }
    }
    closedir($dir);    
     return true;
}*/

//刪除目錄中內容物件(含刪除目錄)
function filedeletionArr($from="", $exclude="") {
	if (!file_exists($from)) {
		return false;
	}
	$dir = opendir($from);
	while (false !== ($file = readdir($dir))) {
		if ($file == '.' OR $file == '..') {
			continue;
		}
		if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
			filedeletionArr($from . DIRECTORY_SEPARATOR . $file, $exclude);
			rmdir($from . DIRECTORY_SEPARATOR . $file);
		} else {
			if(!empty($exclude) && in_array($file, $exclude)) {
				continue;
			}
			unlink($from . DIRECTORY_SEPARATOR . $file);
		}
	}
	closedir($dir);
	return true;
}



//批次輸出變數
function batchoutputvariables($variable="",$Arr=""){	
	
foreach($variable as  $val){
global ${$val}; 	
$Arr[$val]=${$val};	
}


return $Arr;
}



//批次串接變數
function combinationvar($Arrvar="",$type=""){
foreach($Arrvar as $var=> $value){
global ${$value}; 		
if(!empty(${$value}) || ${$value}==='0'){		
$val.="&".$value."=".urlencode(${$value})."";
}
}
return $val;
}




//批次轉換htmlspecialchars
function htmlspecialcharsbatch($allowvar="",$eachvar=""){	
foreach($eachvar as $var=> $value){
if(in_array($var,$allowvar)){
 $valuevar[$var]=htmlspecialchars(htmlspecialchars_decode($value, ENT_QUOTES));
}else{
 $valuevar[$var]=$value;
} 
}
return $valuevar;
}
	
//xlanguage輔助插件-資料轉換	
/*function xlanguagePlugin($var=""){	
global $xoopsConfig;	


//判斷xLanguage是否啟用
if(empty(modulesmidvar($modulesid="xLanguage",$val="isactive"))) return $var;

//$var=htmlspecialchars($var);
$var=neillibrary_replaceHtmlEntity($var);
//讀取xlanguage_base資料表
$dbneme="xlanguage_base";
$where=" where  lang_name='".$xoopsConfig['language']."'";
$langvar=moduledb($dbneme,$where);
//起始標籤
$startvar="[".$langvar['lang_code']."]";
//結束標籤
$endvar="[/".$langvar['lang_code']."]";

if(!empty(substr(CatchStrfunction($var,$startvar,$endvar),mb_strlen($startvar, "utf-8"),-mb_strlen($endvar, "utf-8")))){	
$resultvar=substr(CatchStrfunction($var,$startvar,$endvar),mb_strlen($startvar, "utf-8"),-mb_strlen($endvar, "utf-8"));
}else{
$resultvar=$var;
}	

return $resultvar;
}*/


//xlanguage輔助插件-資料轉換	
function xlanguagePlugin($var = "") {
	global $xoopsConfig;
	// 判斷xLanguage是否啟用
	if (empty(modulesmidvar($modulesid="xLanguage",$val="isactive"))) {
		return $var;
	}
	$var = neillibrary_replaceHtmlEntity($var);
	$langvar = moduledb($dbname = "xlanguage_base", $where = " where lang_name = '" . $xoopsConfig['language'] . "'");
	// 起始標籤
	$startvar = "[".$langvar['lang_code']."]";
	// 結束標籤
	$endvar = "[/".$langvar['lang_code']."]";
	$pos_start = strpos($var, $startvar);
	// 如果找到了標籤
	if ($pos_start !== false) {
		// 找到標籤的結束位置
		$pos_end = strpos($var, $endvar, $pos_start);
		// 如果找到了結束標籤
		if ($pos_end !== false) {
			// 取得標籤內容
			$tag_content = substr($var, $pos_start + strlen($startvar), $pos_end - $pos_start - strlen($startvar));
			// 遞迴處理標籤內容
			$resultvar = xlanguagePlugin($tag_content);
			// 將處理後的標籤內容插入原始字串
			$var = substr_replace($var, $resultvar, $pos_start, $pos_end - $pos_start + strlen($endvar));
			// 遞迴處理下一個標籤
			$var = xlanguagePlugin($var);
		}
	}else{
	// 如果沒找到標籤直接輸出原始使內容
	$tag_content=$var;
	}
	return $tag_content;
}




//批次刪除function
function deleteArr($Arrdate=""){		
//刪英預設值
//相同where欄位
//$whereDB=" where `basid` = '$dbid'";
//$i=0;
//$Arrdate[$i]['dbneme']="neilbasicinformation"; //刪除資料表
//$Arrdate[$i]['where']=$whereDB;  //開啟查詢刪除資料(迴圈)
//$Arrdate[$i]['id']="basid";  //刪除資料表ID
foreach($Arrdate as $key=> $val){  
$dbneme=$Arrdate[$key]['dbneme'];
$where=$Arrdate[$key]['where'];
$deleteArr=databasetablewhile($dbneme,$where); 
foreach($deleteArr as $k=> $val){  	
$where=" where `".$Arrdate[$key]['id']."` = '".$deleteArr[$k][$Arrdate[$key]['id']]."'";
$DBname=$Arrdate[$key]['dbneme'];
deletefunction($where,$DBname);    
}	}

}







//區塊樣式
function blocksclassbox($key="",$i="",$type="",$prefix="") {
	switch($type) {
		case "1":  
		if($key%2==0) {
			$nthchilds="box02";
			//偶數
		} else {
			$nthchilds="box01";
			//奇數
		}
		break;
		case "2":  	  
		if($key >2) {
			$nthchilds='bottombox';
		} else {
			$nthchilds='topbox';
		}
		break;
		case "3":  	  
		$nthchilds="".$prefix."box01";
		//初始值
		if($key==2 or (($key+$i+2) % 3)==0) $nthchilds="".$prefix."box02";
		//輸出2.5.8
		if(($key%3)==0)  $nthchilds="".$prefix."box03";
		//輸出3的整除  	  
		break;
		default:
		  //預設動作
	}
	return $nthchilds;
}




//計算扣除權限不顯示後數量
function differencefunction($dbneme1="",$dbneme2="",$where="",$types="",$total="",$tvar="",$breakkey="") {
	global $uid,$typesid;
	$Arr=databasetablewhile($dbneme=$dbneme1,$where);
	$typesidDB=!empty($typesid) && $tvar!='false'   ? "`typesid` = '".$typesid."' &&" : '';
	switch($types) {
		case "1":  	    //分類抓出權限內資料
		$i=1;
		foreach($Arr as $key=> $val) {
			if(!empty(grouppermission($dbneme=$dbneme2,$where=" where ".$typesidDB."  `sortid` = '".$Arr[$key]['sortid']."'  && `enable` = '1'  order by  sortid  ASC",$var="browsegroup",$type=true)) || (!empty($typesidDB)  &&  !empty(admingroupfunction($dbneme="neilmfdcmstypes",$where=" where ".$typesidDB."  `enable` = '1'  ",$admintype="admingroup"))  )) {
				if(empty(sorttruefunction($dbneme=$dbneme2,$of_sortid=$Arr[$key]['sortid']))) {
					$sortidreturn[$key]=$Arr[$key]['sortid'];
				}
				$i++;
			}
			if($i>$total && !empty($total)) break;
		}
		//回傳
		$difference=$sortidreturn;
		break;
		case "2": //抓出內容資料-返回id->新 
		foreach($Arr as $key=> $val) {
			if(empty(grouppermission($dbneme2,$where=" where ".$typesidDB." `sortid` = '".$Arr[$key]['sortid']."' && `enable` = '1'   order by  sortid  ASC",$var="browsegroup",$type=true))  ) {
		    $breakArr[$key]=$Arr[$key][$breakkey];
			}
		}
        $difference =$breakArr;			
		break;
		
		default:  //抓出內容資料補差-舊(廢除)
		$i=0;
		foreach($Arr as $key=> $val) {
			if(!empty(grouppermission($dbneme=$dbneme2,$where=" where ".$typesidDB." `sortid` = '".$Arr[$key]['sortid']."' && `enable` = '1'   order by  sortid  ASC",$var="browsegroup",$type=true)) || (!empty($typesid)  &&  !empty(admingroupfunction($dbneme="neilmfdcmstypes",$where=" where `typesid` = '".$typesid."' && `enable` = '1'  ",$admintype="admingroup"))) ) {
				$i++;
			}
		}
		$difference = is_array($Arr) ? count($Arr)-$i : 0 ;
	}
	return $difference;
}



//影片下拉選單
function onlinevideomenuselect($oid){
//選擇影片類型
$arrangeArr = array(); //建構陣列
//youtube影片
$i=0;
$arrangeArr[$i]['id']='y'; 
$arrangeArr[$i]['title']=_MS_SHARED104;
//facebook影片
$i++;
$arrangeArr[$i]['id']='f';  
$arrangeArr[$i]['title']=_MS_SHARED105;
$i++;

//下拉選單(呈現方式)
foreach($arrangeArr as $key=> $val){
$arrangebox.=optionselect($dataid=$arrangeArr[$key]['id'],$optionname=$arrangeArr[$key]['title'],$oid,$value=$arrangeArr[$key]['id']);
}

return $arrangebox;

}








//影片播放區塊
function onlinevideobox($width="",$height="",$url="",$type="",$img="",$tmburl="",$where="",$dbname="",$typesof="",$alt="",$title="") {
	$thumbnail=!empty($img) ? '' : "thumbnail";
	// get TRUE
	$imgtype=$type=='y' ? 'youtubeimg.jpg' : 'facebookimg.jpg';
	// get TRUE
	$imgurl=XOOPS_URL."/modules/neillibrary/images/".$imgtype."";
	$thumbnailtypeimg="<img alt='".strriposfunction($val=$imgtype,$typevar="1")."' id='thumbnailtypeimg' class='thumbnail' src='".$imgurl."'>";
	// get TRUE
	switch($type) {
		case "y":   //youtube播放器及縮圖區塊
		if(!empty($img)) {
			$box="".$thumbnailtypeimg."<img alt='".$alt."' class='imgbox lazy' data-original='".$url."'  src='".$url."'  width='".$width."' height='".$height."'/>";
		} else {
			$box="<iframe title='".$title."' class='".$thumbnail."' width='".$width."' height='".$height."' src='https://www.youtube.com/embed/".$url."' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
		}
		break;
		case "f":  //FB播放器及縮圖區塊
		if(!empty($img)) {
			$url= empty($url) ? $imgurl=XOOPS_URL."/modules/neilonlinevideo/images/noimg.jpg" : $url;
			// get TRUE	
			$box="".$thumbnailtypeimg."<img alt='".$alt."' class='imgbox lazy' data-original='".$url."' src='".$url."'  width='".$width."'  height='".$height."'/>";
		} else {
			$box="
     <div id='fb-root'></div>
     <script async defer src='https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2'  ></script>
     <!-- Your embedded video player code -->
     <div id='fbimg'></div>
     <div class='fb-video ".$thumbnail."' data-href='".$url."' data-width='".$width."' data-height='".$height."'  data-autoplay='false' data-show-text='false' data-allowfullscreen='false'  >
     <div class='fb-xfbml-parse-ignore' >
     <blockquote cite='".$url."'>
     <a href='".$url."'>How to Share With Just Friends</a>
     <p>How to share with just friends.</p>
     Posted by <a href='https://www.facebook.com/facebook/'>Facebook</a> on Friday, December 5, 2014
     </blockquote>
     </div>
     </div>";
		}
		break;
		case "t": //取得FB縮圖
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, "https://www.facebook.com/plugins/video.php?href=".$url."");
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array ('X-Forwarded-For: '.mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255),));
		curl_setopt($ch, CURLOPT_USERAGENT, "Google Bot");
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		$box = curl_exec($ch);
		curl_close($ch);
		break;
		/*	case "fr": //重建擷取FB縮圖   	   
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, "".$tmburl."");
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array ('X-Forwarded-For: '.mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255).'.'.mt_rand(0, 255),));
		curl_setopt($ch, CURLOPT_USERAGENT, "Google Bot");
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 1);
		//成功連線伺服器前等時間/秒
		curl_setopt ($ch, CURLOPT_TIMEOUT, 100);
		//超過指令碼將會斷開連線/秒
		$boxcurl_exec = curl_exec($ch);
		curl_close($ch);
		if(preg_match("/URL signature expired/", $boxcurl_exec) || preg_match("/Bad URL/", $boxcurl_exec) ||  empty($tmburl)) {
			//比對縮圖是否存在
			$fbbox=onlinevideobox($width="",$height="",$url=$url,$type="t",$img="");
			$tmburl=substr(CatchStrfunction($fbbox," img"," alt"),11,-5);
			//擷取字串
			//寫入資料表
			$setvar="set  tmburl='".phpstrip_tags($notags=$tmburl,$type="")."' ".$where."";
			update($dbname=$dbname,$set=$setvar);
		}
		break; */
		case "n": //擷取FB縮圖   	   
		$fbbox=onlinevideobox($width="",$height="",$url=$url,$type="t",$img="");
		$box=htmlspecialchars_decode(substr(CatchStrfunction($fbbox," img"," alt"),11,-5));
		//擷取字串
		break;
		case "b": //取得youtube縮圖   	   
		$box="https://i.ytimg.com/vi/".youtubeurl($youtubeurl=$url)."/0.jpg";
		break;
		case "i": //影音標籤 	   
		switch($typesof) {
			case "y":
						$box="<span class='label label-danger'>youtube</span>";
			break;
			case "f":
						$box="<span class='label label-primary'>facebook</span>";
			break;
		}
		break;
		case "m": //取得meta資訊  
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3);		
		//成功連線伺服器前等時間/秒
		curl_setopt ($ch, CURLOPT_TIMEOUT, 200);		
		$output = curl_exec($ch);
		curl_close($ch);
		//----- 擷取 title
		preg_match("/<title>(.*)<\/title>/s", $output, $match);
		$box['title']= $match[1];		
		//----- 擷取 Description
		$metatag = get_meta_tags($url);
		$box['description'] = $metatag["description"];
		break;
	}
	return $box;
}


//指定範圍擷取字串
function CatchStrfunction($Str, $StaKey, $EndKey){
$sp=strpos($Str,$StaKey);
$ep=strpos($Str,$EndKey);
$sl=strlen($StaKey);
$el=strlen($EndKey);
$res=substr($Str,$sp,$ep-$sp+$el);
return $res;
}


//顯示群組標籤
function groupslabel($Arr="",$type="",$style=""){
foreach($Arr as $key=> $var){
$dbneme="groups";
$where="where `groupid` = '".$var."'   order by  groupid  ASC";  //where數值 	
$groupidvar=moduledb($dbneme,$where);
$groupbox.="<span class='label ".$style."'>".$groupidvar['name']."</span>  ";
}
return $groupbox;
}



//管理權限判斷(用uid判斷權限)
function neillibrary_uidadmingroupfunction($uid="",$conversion="") {
global $xoopsUser,$isAdmin;	

$uidArr=databasetablewhile($dbnemeuser="groups_users_link",$where="where `uid` = '".$uid."'   order by  uid  ASC");
$admingroup=phpconversion($conversion,$type="unserialize"); 

foreach($uidArr as $key=> $val){
if(!empty($admingroup) && in_array("".$uidArr[$key]['groupid']."",$admingroup)){
$group=true;
}
//管理員
if($uidArr[$key]['groupid']=='1') $group=true;
}


return $group;
}




//管理權限判斷(單一欄位取值)
function admingroupfunction($dbneme="",$where="",$admintype=""){
global $xoopsUser,$isAdmin;	



if($isAdmin==false){	
$neilmfdcmstypesList=moduledb($dbneme,$where);
$admingroup=phpconversion($conversion=$neilmfdcmstypesList[$admintype],$type="unserialize"); 
if(!empty($xoopsUser)){ //會員
foreach($xoopsUser->getGroups() as $i){
if(!empty($admingroup) && in_array("$i",$admingroup)){
$group=true;
}
}
}else{ //訪客
if(!empty($admingroup) && in_array("3",$admingroup)){
$group=true;
} 
}
}else{
$group=true;
}

if($admintype=='browsegroup'  && (empty($admingroup) &&  $neilmfdcmstypesList[$admintype]!='N;') ) $group=true;  //更新空值預設狀態-限瀏覽

return $group;
}





//群組權限判斷(資料表全體欄位取值)
function grouppermission($dbneme="",$where="",$var="",$type=""){
global $xoopsUser,$isAdmin;	


if($isAdmin==false && !empty($type)){	
$groupsArr=databasetablewhile($dbneme,$where);  
foreach($groupsArr as $key=> $val){		
$admingroup[$key]=phpconversion($conversion=$groupsArr[$key][$var],$type="unserialize"); 
if(!empty($xoopsUser)){ //會員
foreach($xoopsUser->getGroups() as $i){
if(!empty($admingroup[$key]) && in_array("$i",$admingroup[$key])){
$group=true;
}

}
}else{ //訪客
if(!empty($admingroup[$key]) && in_array("3",$admingroup[$key])){
$group=true;
} 
}
if(empty($groupsArr[$key][$var]) &&  $groupsArr[$key][$var]=='N;') $group=true;  //預設空值$group=true
}
}else{
$group=true;
}
if($var=='browsegroup'  && (empty($admingroup[$key]) &&  $groupsArr[$key][$var]!='N;') ) $group=true;  //更新空值預設狀態-限瀏覽

return $group;
}




//群組權限判斷(模組全體Config取值)
function neillibrary_modulesgrouppermission($conf_value=""){
global $xoopsUser,$isAdmin;	

if($isAdmin==false ){	
$admingroup=phpconversion($conversion=$conf_value,$type="unserialize"); 
if(!empty($xoopsUser)){ //會員
foreach($xoopsUser->getGroups() as $i){
if(!empty($admingroup) && in_array("$i",$admingroup)){
$group=true;
}
}
}else{ //訪客
if(!empty($admingroup) && in_array("3",$admingroup)){
$group=true;
} 
}
if(empty($admingroup)  &&  $admingroup=='N;' ) $group=true;  //預設空值$group=true
}else{
$group=true;
}


return $group;

}





//刪除紀錄及解除表單IP封鎖時間(天)
function autodeleterobotip($module=""){
global $xoopsModuleConfig,$xoopsModule;	

$configvar=configvar($modulesid="neillibrary");
$delettime=timedate($datevar="".timedate($datevar="Y-m-d H:i:s")."",$type="2",$calculate="-",$m="",$d=$configvar['neillibrary2'],$y="");

$dbneme="robotip";
$where="  where  `riptime` <= '".$delettime."'   order by  rip  DESC";  //where數值 
$delettimeArr=databasetablewhile($dbneme,$where);  

foreach($delettimeArr as $key=> $val){
$where=" where `rip` = '".$delettimeArr[$key]['rip']."'";
$DBname="robotip";  
deletefunction($where,$DBname);
}






return $fileName;	
}



//去除副檔名跟取得副檔名
function strriposfunction($val="",$type="") {
$val=strtolower($val); //大寫轉小寫	
	switch($type) {
		case "1": 
		 //取得檔名
		$fileName = $val;
		if (false !== $pos = strripos($fileName, '.')) {
			//  $fileName = ;
			$fileName =phpstrip_tags($notags=substr($fileName, 0, $pos),$type="2")  ;
		}
		break;
		case "2":
	   //取得副檔名
		$fileName = $val;
		if(false !== $pos = strripos($fileName, '.')) {
			$fileName =  substr($fileName, $pos+1, strlen($fileName));
		}
		break;
		case "3": 
		 //取得檔名(保留原格式)
		$fileName = $val;
		if (false !== $pos = strripos($fileName, '.')) {
			//  $fileName = ;
			$fileName =substr($fileName, 0, $pos);
		}
		break;
		
		
	}
	return $fileName;
}



//判斷分類是否有啟用
function  sorttruefunction($dbneme="",$of_sortid="",$sorting="") {
	if(empty($of_sortid)) return true;
	$sorting=empty($sorting) ? 'sortidsort' : $sorting;
	// get TRUE
	$where=" where  `sortid` = '".$of_sortid."' && `enable` = '0'   order by  ".$sorting."  DESC";
	//where數值
	$Arrdate=databasetablewhile($dbneme,$where);
	//遞回開始
	foreach($Arrdate as $key=> $val) {
		$sortvar.=$Arrdate[$key]['sortid'].",";
		$sortvar.=sortretorted($dbneme,$sortid="".$Arrdate[$key]['sortid']."");
	}
	//去除最後一個字元
	$sortvar=substr($sortvar,0,-1);
	//切割陣列
	$sortvarArr=cuttingfunction($cutting=$sortvar,$sign=",");
	if(!empty($sortvarArr) && in_array("$of_sortid",$sortvarArr)) {
		$var=true;
	}
	return $var;
}

//判斷分類是否有啟用
/*function sorttruefunction($dbneme="", $of_sortid="", $sorting="sortidsort") {
    if (empty($of_sortid)) {
        return true;
    }
    $sorting = empty($sorting) ? 'sortidsort' : $sorting;
    $where = " where `sortid` = '".$of_sortid."' && `enable` = '0' order by $sorting DESC";
    $Arrdate = databasetablewhile($dbneme, $where);
    $sortvarArr = array();
    foreach ($Arrdate as $key => $val) {
        $sortid = $Arrdate[$key]['sortid'];
        $sortvarArr[] = $sortid;
        $sortvarArr = array_merge($sortvarArr, sortretorted($dbneme, $sortid));
    }
    $sortvarArr = array_unique($sortvarArr);
    return in_array($of_sortid, $sortvarArr);
}
*/

//遞回抓出分類id包括父層id
function  categoryidfunction($dbneme="",$of_sortid="",$type="",$var="",$varname="",$DVnane="",$ctype="") {
	global $basid;
	//抓子層分類
	$varname=empty($varname) ? "sortid" : $varname;
	$DVnane=empty($DVnane) ? "of_sortid" : $DVnane;
	switch($type) {
		case "1": //遞迴解出關閉分類
		if(!empty($basid)) $DBver="&& ".$var."";
		$of_sortidDB=!empty($of_sortid) ? "where  `".$varname."` = '".$of_sortid."'   &&  `enable` = '0'" : "where   `enable` = '0' ";
		$where="  ".$of_sortidDB." ".$DBver."  order by  sortidsort  DESC";
		//遞回開始
		foreach($Arrdate=databasetablewhile($dbneme,$where) as $key=> $val) {
			$sortvar.=$Arrdate[$key][$varname].",";
			$sortvar.=sortretorted($dbneme,$sortid="".$Arrdate[$key][$varname]."");
		}
		//切割陣列
		$sortvarArr=cuttingfunction($cutting=substr($sortvar,0,-1),$sign=",",$type="1");
		foreach($sortvarArr as $key=> $val) {
			if(!empty($val)) {
				if(!empty($ctype)){
				$valid.=$val.','; //只返回串接變數-新 
				}else{
				$valid.="`".$varname."` != '".$val."' &&";	 //返回完整語法-舊(廢棄)			
				}
			}
		}
		break;
		
		default: //遞迴解出開啟分類
		$where=" where `".$DVnane."` = '".$of_sortid."'  &&  `enable` = '1'   order by  sortidsort  DESC";
		//遞回開始
		foreach($Arrdate=databasetablewhile($dbneme,$where) as $key=> $val) {
			$sortvar.=$Arrdate[$key][$varname].",";
			$sortvar.=sortretorted($dbneme,$sortid="".$Arrdate[$key][$varname]."");
		}
		//切割陣列
		$sortvarArr=cuttingfunction($cutting=substr($sortvar,0,-1),$sign=",",$type="1");
       	if(!empty($ctype)){
 		$valid.=$of_sortid.',';      //只返回串接變數-新  
       	}else{
 		$valid.="`".$varname."` = '".$of_sortid."' ||";     //返回完整語法-舊(廢棄)	  	
       	}		
		foreach($sortvarArr as $key=> $val) {
			if(!empty($val)) {
        	if(!empty($ctype)){
    			$valid.=$val.','; //只返回串接變數-新     		
        		}else{
				$valid.="`".$varname."` = '".$val."' ||"; //返回完整語法-舊(廢棄)	
				}
			}
		}
	}
	return $valid;
}






//下拉選單取值
//遞回
function sortselect($dbneme="",$sortselect="",$basid="",$enfunction="",$type="",$DBval="",$keyvar=""){ 




switch($type){
  case "1":  //由底往上抓單值
$where="  where `sortid` = '".$sortselect."' &&  `basid` = '".$basid."' &&  `enfunction` = '".$enfunction."'    order by  of_sortid  ASC";  //where數值
$sortselect=moduledb($dbneme,$where);
$sortselectvar.=$sortselect['sortid'].",";

if(!empty($sortselect['of_sortid'])){
$sortselectvar.=sortselect($dbneme,$sortselect="".$sortselect['of_sortid']."",$basid=$basid,$enfunction=$enfunction);
}

  break;
  
  
  
  case "2":  //由上往底抓全部(萬用)
	  
$DBval=!empty($DBval) ? $DBval : 'of_sortid'; // get of_sortid  
$keyvar=!empty($keyvar) ? $keyvar : 'sortid'; // get val name 		  
  	  
$where=" where `".$DBval."` = '".$sortselect."' ";   //where數值
$sortArr=databasetablewhile($dbneme,$where);
foreach($sortArr as $key=> $val){
$sortselectvar.=$sortArr[$key][$keyvar].",";
$sortselectvar.=sortselect($dbneme,$sortselect="".$sortArr[$key][$keyvar]."",$basid="",$enfunction="",$type="2",$DBval,$keyvar);
}
  
   break;   
   
  case "3":  //城市管理 由底往上抓單值
$where="  where `cityid` = '".$sortselect."'  ";  //where數值
$sortselect=moduledb($dbneme,$where);
$sortselectvar.=$sortselect['cityid'].",";

if(!empty($sortselect['of_cityid'])){
$sortselectvar.=sortselect($dbneme,$sortselect="".$sortselect['of_cityid']."",$basid="",$enfunction="",$type="3");
}  
   break;
   

  
  default: //由底往上抓單值(萬用)
  
$DBval=!empty($DBval) ? $DBval : 'sortid'; // get of_sortid  
$keyvar=!empty($keyvar) ? $keyvar : 'of_sortid'; // get val name 		   
  
$where="  where `".$DBval."` = '".$sortselect."'  ";  //where數值
$sortselect=moduledb($dbneme,$where);
$sortselectvar.=$sortselect[$DBval].",";

if(!empty($sortselect[$keyvar])){
$sortselectvar.=sortselect($dbneme,$sortselect="".$sortselect[$keyvar]."",$basid="",$enfunction="",$type="",$DBval,$keyvar);
}	  
	  
	  
}

	

	

return $sortselectvar;
}








//下載檔案壓縮ZIP格式
function  zipArchivefunction($url="",$zipname="",$type=""){

switch($type){
  case "phone":
  //執行對應函數

    $file = $url;
    header("content-Type: text/html; charset=Utf-8");    
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: '.filesize($file));
    ob_clean(); //清除緩存
    flush();
    readfile($file);
    exit;  
  
  break;
  
  
   case "zipArr": 


//ZIP多檔打包下載
//$url 檔案原始路徑+檔名
//$zipname 檔案名稱
//$temp 檔案暫存路徑+檔名(廢除)




//$file = tempnam("/tmp", "zip"); //創建一個zip臨時文件
//$file = tempnam("/httpdocs/uploads", "zip"); // 創建一個zip臨時文件
$file = tempnam(XOOPS_ROOT_PATH."/uploads", "zip"); // 創建一個zip臨時文件
			
$zip = new ZipArchive;
$res = $zip->open($file, ZipArchive::OVERWRITE);

if ($res) {
//檔案迴圈加入zip中
foreach ($url as $newfile) {
$new_filename = substr($newfile, strrpos($newfile, '/') + 1);  //重新定義壓縮檔路徑
$zip->addFile($newfile, $new_filename);
}
}

$zip->close();
/********使用header命令php下載zip檔************/
header('Content-Type: application/zip');
//指定文件或目錄的類型
header("Content-type: ".filetype($file));
//指定下載時的檔名
header("Content-Disposition: attachment; filename=".$zipname."");

//輸出下載的內容。
readfile($file);
unlink($file ); //刪除暫存檔 
  
    break;
    
    
  
  
  default:
  	  
//$url 檔案原始路徑+檔名
//$zipname 檔案名稱
//$temp 檔案暫存路徑+檔名(廢除)

/********利用ZipArchive產生壓縮檔************/

$file = tempnam("/tmp", "zip"); //創建一個zip臨時文件
	
$zip = new ZipArchive;
$res = $zip->open($file, ZipArchive::OVERWRITE);

if ($res) {
//$zip->addFile($dir); //添加檔案 (若有大量檔案可使用迴圈)
$new_filename = substr($url, strrpos($url, '/') + 1);  //重新定義壓縮檔路徑
$zip->addFile($url, $new_filename);
}

$zip->close();
/********使用header命令php下載zip檔************/
header('Content-Type: application/zip');
//指定文件或目錄的類型
header("Content-type: ".filetype($file));
//指定下載時的檔名
header("Content-Disposition: attachment; filename=".$zipname."");

//輸出下載的內容。
readfile($file);
unlink($file ); //刪除暫存檔 





}
}




	
//綠界金流
//include "ecpaycheck.php";

//單位換算
function formatBytes($size) { 
    $units = array(' B', ' KB', ' MB', ' GB', ' TB'); 
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024; 
    return round($size, 2).$units[$i]; 
}



//base64格式判斷
function base64Judge($var=""){	
if($var==base64_encode(base64_decode($var))){
$Judg=true;
}else{
$Judg=false;
}
 return $Judg;
}





//建立表單驗證時間格式-初始化
function robotformtimecreate(){
global $xoopsUser;

$uid=!empty($xoopsUser) ? $xoopsUser->getVar('uid') : '0'; // get TRUE

//新增加時間驗證
$abnormaltime=substr(timedate($datevar="".timedate($datevar="Y-m-d")."",$type="2",$calculate="-",$m="",$d=rand(1,1000),$y=""), 0, 10);
$robottime = array(); //建構時間陣列
$robottime['0']=timedate($datevar="Y-m-d"); //正常時間
$robottime['1']=$abnormaltime; //異常時間
//隨機取值
$robottimedate=$robottime[rand(0,1)];


//開啟robotip資料表
$dbneme="robotip";	
    if(!empty($uid)){
    $where=" where   `uid` = '".$uid."' ";   //where數值-修改	
    }else{
    $where=" where  `ip` = '".get_real_ip()."'  &&   `cookieid` = '".$_COOKIE['neil']['cookieid']."'  ";   //where數值-修改	
    }	
$robottimeip=moduledb($dbneme,$where);

//判斷是否已記錄
if(!empty($robottimeip)){
//時間存入robotip資料表	
$setvar="set robottime='".$robottimedate."'  where rip='".$robottimeip['rip']."'";
update($dbname="robotip",$set=$setvar);   
}else{	
//時間存入robotip資料表
$valuesvar="(ip,robottime,cookieid,operate,uid) values('".get_real_ip()."','".$robottimedate."','".$_COOKIE['neil']['cookieid']."','0','".$uid."')";	  
insert($dbname="robotip",$values=$valuesvar); 
}

return $robottimedate;
}



//時間驗證核對
function robottime($var="") {	
global $xoopsUser;
$uid=!empty($xoopsUser) ? $xoopsUser->getVar('uid') : '0'; // get TRUE
	
	//開啟robotip資料表
	$dbneme="robotip"; 	    	
    if(!empty($uid)){
    $where=" where   `uid` = '".$uid."' ";   //where數值-修改	
    }else{
    $where=" where  `ip` = '".get_real_ip()."'  &&   `cookieid` = '".$_COOKIE['neil']['cookieid']."'  ";   //where數值-修改	
    }
    	
    	
	//where數值-修改
	$robottimeip=moduledb($dbneme,$where);
	$configvar=configvar($modulesid="neillibrary");
	switch($var) {
		case "2":
		//重複留言次數	  
		//判斷輸入次數
		if($robottimeip['counter']>=$configvar['neillibrary9']) {
			robottimeipwrite($type="",$enable="",$counter="",$operate="2");
		} else {
			robottimeipwrite($type="2",$enable="0",$counter=($robottimeip['counter']+1),$operate="2");
		}
		break;
		case "1":
		//時間不正確   	   
		//驗證時間
		if($robottimeip['robottime']!=timedate($datevar="Y-m-d")) {
			$robottime=true;
		} else {
			$robottime=false;
			//判斷答錯次數
			if($robottimeip['counter']>=$configvar['neillibrary9']) {
				robottimeipwrite($type="",$enable="",$counter="",$operate="1");
			} else {
				robottimeipwrite($type="2",$enable="0",$counter=($robottimeip['counter']+1),$operate="1");
			}
		}
		break;
		case "0":
		//時間正確	   
		//驗證時間
		if($robottimeip['robottime']==timedate($datevar="Y-m-d")) {
			$robottime=true;
		} else {
			$robottime=false;
			//判斷答錯次數
			if($robottimeip['counter']>=$configvar['neillibrary9']) {
				robottimeipwrite($type="",$enable="",$counter="",$operate="1");
			} else {
				robottimeipwrite($type="2",$enable="0",$counter=($robottimeip['counter']+1),$operate="1");
			}
		}
		break;
	}
	return $robottime;
}

//寫入資料表
function  robottimeipwrite($type="",$enable="",$counter="",$operate="",$ip="",$cookieid="",$uid=""){
global $xoopsUser;	
//引入網址函數
$httphosturl=httphosturl();




$uid=!isset($uid) ? (!empty($xoopsUser) ? $xoopsUser->getVar('uid') : '0') : $uid; // get TRUE
	
	
$ip=empty($ip) ? get_real_ip() : $ip; // get TRUE
$cookieid=empty($cookieid) ? $_COOKIE['neil']['cookieid'] : $cookieid; // get TRUE



//開啟robotip資料表
$dbneme="robotip";
if(!empty($uid)){
$where=" where  `uid` = '".$uid."' ";   //where數值-修改
}else{
$where=" where  `ip` = '".$ip."'  &&   `cookieid` = '".$cookieid."'  ";   //where數值-修改
}


	
$robottimeip=moduledb($dbneme,$where);


switch($type){
  case "1":
//時間存入robotip資料表-封鎖
$operate=!empty($operate) ? $operate : '1'; // get TRUE

if(empty($robottimeip)){
$valuesvar="(ip,robottime,riptime,enable,url,counter,cookieid,operate,uid) values('".get_real_ip()."','".timedate($datevar="Y-m-d")."','".timedate($datevar="Y-m-d H:i:s")."','1','".$httphosturl['url']."','0','".$_COOKIE['neil']['cookieid']."','".$operate."','".$uid."')";	  
insert($dbname="robotip",$values=$valuesvar); 
}else{
robottimeipwrite($type="",$enable="",$counter="",$operate);
}

  break;
 
  case "2": 
$setvar="set enable='0' , url='".$httphosturl['url']."' , counter='".$counter."'  , operate='".$operate."'  where rip='".$robottimeip['rip']."'";
update($dbname="robotip",$set=$setvar);   
   break; 


  case "3": 
$setvar="set enable='0' ,  counter='0'  , operate='0'  where rip='".$robottimeip['rip']."'";
update($dbname="robotip",$set=$setvar);   
   break; 
  
  
  case "4": 
if(!empty($robottimeip['enable'])) $returnval=true;
   break;   
  
  default:
$setvar="set enable='1' , url='".$httphosturl['url']."'  , operate='".$operate."'    where rip='".$robottimeip['rip']."'";
update($dbname="robotip",$set=$setvar);   
}


return $returnval;
}




//表單機器人IP判斷及封鎖
function  robottimeip($type=""){
global $xoopsUser;
$uid=!empty($xoopsUser) ? $xoopsUser->getVar('uid') : '0'; // get TRUE
	
$dbneme="robotip";
if(!empty($uid)){
$where=" where   `uid` = '".$uid."' ";   //where數值-修改	
}else{
$where=" where  `ip` = '".get_real_ip()."'  &&   `cookieid` = '".$_COOKIE['neil']['cookieid']."'  ";   //where數值-修改	
}

	
$robottimeip=moduledb($dbneme,$where);
switch($type){
  case "1":
if(empty($robottimeip['ip'])) return true;
  break;
  
  case "2":
if(!empty($robottimeip['enable'])) return true;
  break;
}

}





//防機器人驗證
function defenserobot($var="",$type=""){
switch($type){
  case "1":
//產生AES 資料加密
 $encrypt=encryptdecode($var,$types="encrypt",$key=XOOPS_LICENSE_KEY);
 $_SESSION['defenserobot']=$encrypt; 
  break;
  case "2":
//產生AES 資料解密
$encrypt=encryptdecode($var,$types="decryption",$key=XOOPS_LICENSE_KEY);

//判斷傳入值跟$_SESSION值是否相符
if($encrypt==$_SESSION['defenserobot']){
$encrypt=true;
}
unset($_SESSION['defenserobot']);

  break;
}

//建立加密資料		
return $encrypt;
}


//被封鎖狀態回覆
function  neillibrary_blockingreason(){
global $xoopsUser;
$uid=!empty($xoopsUser) ? $xoopsUser->getVar('uid') : '0'; // get TRUE
	
$dbneme="robotip";
if(!empty($uid)){
$where=" where   `uid` = '".$uid."' ";   //where數值-修改	
}else{
$where=" where  `ip` = '".get_real_ip()."'  &&   `cookieid` = '".$_COOKIE['neil']['cookieid']."'  ";   //where數值-修改	
}
		
$robotlist=moduledb($dbneme,$where);

switch($robotlist['operate']){
  case "1":
$val=_MS_SHARED75;
  break;
  
  case "2":
$val=_MS_SHARED206;
  break;
  
   case "3":
$val=_MS_SHARED207;
  break;   
  
}
return $val;
}




//true跟false轉換-字元轉數字/英文轉數字
function characterexchange($change="",$item=""){
	
	
switch($item){
  case "1": //英文轉數字   	  
  	  
switch($change){
  case "zero":
$changevar='0';
  break;
  
  case "one":
$changevar='1';
  break;
 
  case "two":
$changevar='2';
  break;  
  
  case "three":
$changevar='3';
  break;  
  
  
  
}  	  

  break;
  
  default:
$changevar=$change=='true' ? '1' : '0'; // get TRUE
}
	
	
return $changevar;
}


//資料交叉查詢組合
function crossquery($where="",$type=""){
foreach($where as $key=> $val){
$wherevar.=$val;
}

//$wherevar=!empty($wherevar) ? "where ".$wherevar."" : " "; // get TRUE
//去除最後字元
$wherevar=substr($wherevar,0,-4);  


return $wherevar;
}





//學年度計算
function  schoolyear(){

//上學期：每年8月1日至翌年1月31日
//下學期：每年2月1日至7月31日

//年度判斷1~7月底年減1 8~12月顯示原始年度
$schoolyear['year']=timedate($datevar="Y")-1911-(timedate($datevar="m") >='08' || timedate($datevar="m") < '02' ? (timedate($datevar="m") == '01' ? 1 : 0) : (timedate($datevar="m") > '01' && timedate($datevar="m") < '08'  ? 1 : 0)); // 上學期/下學期
//學年度
$schoolyear['month']=timedate($datevar="m") >='08' || timedate($datevar="m") < '02' ? _MS_SHARED262 : _MS_SHARED263; // 上學期/下學期
	
return  $schoolyear;
}



//區塊取得bid
function bidnamefunction($op="",$bid="",$type="",$var="",$id="",$selectkey="") {
	//取得newblocks資料表最新一筆編號
	$dbneme="newblocks";
	//資料表名稱  
	switch($type) {
		case "1":  //取得newblocks陣列
		$where="  where `bid` = '".$bid."'   order by  bid  DESC";
		//where數值
		$newblocksList=moduledb($dbneme,$where);
		return $newblocksList;
		break;
		
		case "2":  //取得newblocks陣列->options
		$where="  where `bid` = '".$bid."'   order by  bid  DESC";
		//where數值
		$newblocksvar=moduledb($dbneme,$where);
		$newblocksList=cuttingfunction($cutting=$newblocksvar['options'],$sign="\|");
		return $newblocksList;
		break;
		
		case "3":  //取得newblocks區塊內容(開啟區塊)
	    $where="  where ".$var."   order by  ".$id."  DESC";
		//where數值
		$newblocksList=databasetablewhile($dbneme,$where,$selectkey);
		return $newblocksList;
		break;
		
		case "4":  //取得newblocks區塊單一筆內容
		$where="  where ".$var."  order by  ".$id."  DESC  ";
		//where數值
		return moduledb($dbneme,$where);
		break;
		
		default:  //取的BID
		$where="  order by  bid  DESC";
		//where數值
		$newblocksList=moduledb($dbneme,$where);
		//最新編號+1
		$newbid=$newblocksList['bid']+1;
		//判斷複製還是編輯
		$bid=$op=="edit" ? $bid : $newbid;
		// get TRUE
		return $bid;
	}
}


//分類指定sortid解遞回到底
function sortretorted($dbneme="",$sortid="",$typs="") {
	switch($typs) {
		case "1":
		  //城市鄉鎮遞迴
		$where=" where `of_cityid` = '".$sortid."'   order by sortidsort DESC";
		//where數值
		$sortArr=databasetablewhile($dbneme,$where);
		foreach($sortArr as $key=> $val) {
			$sortvar.=$sortArr[$key]['cityid'].",";
			$sortvar.=sortretorted($dbneme,$sortid="".$sortArr[$key]['cityid']."");
		}
		break;
		case "2":
		  //班級管理遞迴
		$where=" where `of_classid` = '".$sortid."'   order by sortidsort DESC";
		//where數值
		$sortArr=databasetablewhile($dbneme,$where);
		foreach($sortArr as $key=> $val) {
			$sortvar.=$sortArr[$key]['classid'].",";
			$sortvar.=sortretorted($dbneme,$sortid="".$sortArr[$key]['classid']."");
		}
		break;
		default:
		  //分類遞迴
		$where=" where `of_sortid` = '".$sortid."'   order by sortidsort DESC";
		//where數值
		$sortArr=databasetablewhile($dbneme,$where);
		foreach($sortArr as $key=> $val) {
			$sortvar.=$sortArr[$key]['sortid'].",";
			$sortvar.=sortretorted($dbneme,$sortid="".$sortArr[$key]['sortid']."");
		}
	}
	return $sortvar;
}

//小數點進為
function fCeil($val,$pressision=2){
$p = pow(10,$pressision);
$val = $val*$p;
$val = ceil($val);
return $val /$p;
}



//判斷字數
function mbstrlen($wcount="",$text="",$types=""){
$mbstrlen=mb_strlen(phpstrip_tags($notags=$text), "utf-8");
switch($types){
  case "1":  //字數小於設定值
  if($mbstrlen < $wcount){
  $result=$mbstrlen;
  }  
  break;  
  case "2":  //字數大於設定值
  if($mbstrlen > $wcount){
  $result=$mbstrlen;
  }  
  break;  
}
return $result;	
}

//openssl資料加密
function encryptdecode($var="",$types="",$key=""){
//加密
if($types=="encrypt"){
$id=serialize($var);//加密資料
$data['iv']=base64_encode(substr('fdakinel;injajdji',0,16));
$data['value']=openssl_encrypt($id, 'AES-256-CBC',$key,0,base64_decode($data['iv']));
$encrypt=base64_encode(json_encode($data));
$returnvar=$encrypt;

}
//解密
if($types=="decryption"){
$encrypt=$var; //解密資料
$encrypt = json_decode(base64_decode($encrypt), true);
$iv = base64_decode($encrypt['iv']);
$decrypt = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $iv);
$id = unserialize($decrypt);
if(!empty($id)) $returnvar= $id; 
}
return  $returnvar;	
}
//加密
//echo encryptdecode($var="cola is bear",$types="encrypt",$key=XOOPS_LICENSE_KEY);
//解密
//echo encryptdecode($var="AwAxRERJsuRYhXZyE7wIaA==",$types="decryption",$key=XOOPS_LICENSE_KEY);



//頁面開啟方式
function pagemethod($types=""){

switch($types){
  case "0":
if(defined('_MS_SHARED31')) $pagemethod['text']=_MS_SHARED31;
$pagemethod['way']="_self";  
  break;  
   case "1":
if(defined('_MS_SHARED32')) $pagemethod['text']=_MS_SHARED32;
$pagemethod['way']="_blank";   
  break;
}


 return $pagemethod;	
}



//黑名單
function blacklistfunction($suid=""){
$dbneme="neilshoppurchaser";
$where=" where `uid` = '".$suid."' ";   //where數值-修改
$blacklistfunction=moduledb($dbneme,$where);

$blacklist=$blacklistfunction['blacklist']==1 ? true : false; // get TRUE
return $blacklist; 	
}






//讀取頁面權限檢查
function readpermission($user_uid="",$type="",$dbvar="",$where="",$modulesid=""){
global  $xoopsDB,$xoopsUser,$isAdmin;


//取的UID
if(!empty($xoopsUser)){ 
$xoops_uid=$xoopsUser->getVar('uid');
}

switch($type){
  case "1":  	  
$dbneme="".$dbvar."";
$readpermissionlist=moduledb($dbneme,$where);
if($readpermissionlist['uid']==$xoops_uid  or !empty($isAdmin)){ 
$readpermission=true;
}
  break;
  
  case "2":  

$configvar=configvar($modulesid=$modulesid);
//字串轉陣列
$configvarArr=phpconversion($conversion=$configvar[$dbvar],$type="unserialize"); 
	
if(!empty($configvarArr) && in_array("$xoops_uid",$configvarArr) or !empty($isAdmin)){
$readpermission=true;
} 

  

  
  
   break; 
  
  
  default:
  	  
if($xoops_uid==$user_uid or $isAdmin==true){
$readpermission=true;
}
  	  

}









return $readpermission;
}



/*
//取得客戶端ip位置
function get_real_ip() {
	static $ip = false;
	$ip = $_SERVER['REMOTE_ADDR'];
	if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
		$ip = $_SERVER['HTTP_CDN_SRC_IP'];
	} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		foreach ($matches[0] AS $xip) {
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}
*/

//取得客戶端ip位置
function get_real_ip() {
	static $ip = false;
	$ip = $_SERVER['REMOTE_ADDR'];
	
	if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
		$ip = $_SERVER['HTTP_CDN_SRC_IP'];
	} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && (filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$forwarded_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
		foreach ($forwarded_ips as $forwarded_ip) {
			$forwarded_ip = trim($forwarded_ip);
			if (filter_var($forwarded_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
				if (filter_var($forwarded_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
					// 跳過私有IP地址
					if (!preg_match('#^(10|172\.16|192\.168)\.#', $forwarded_ip)) {
						$ip = $forwarded_ip;
						break;
					}
				} else {
					$ip = $forwarded_ip;
					break;
				}
			}
		}
	}
	return $ip;
}



//陣列轉字串AND字串轉陣列
function phpconversion($conversion="",$type="") {

if($type=='serialize'){	 //陣列轉字串
$conversion=serialize($conversion);
}
if($type=='unserialize'){	//字串轉陣列
$conversion=unserialize($conversion);
}
return  $conversion;
}


//youtube取得網址ID
function youtubeurl($url=""){
//解析youtube網址?v值
//網址類型：https://www.youtube.com/watch?v=zIE8htt4HLg	
$urlarr=parse_url($url);
parse_str($urlarr['query'],$parr);   	 	 
$vid=$parr['v']; 

//解析複製網址後ID值
//網址類型：https://youtu.be/SfPeulcfbSI
if(empty($vid)){
$vid=end(cuttingfunction($cutting=reset(cuttingfunction($cutting=$url,$sign="\?",$type="")),$sign="\/",$type=""));
} 



return $vid;
}



//去資料表標籤-去除空白跟HTML標籤
function strip_tagsremovesqlArr($allowvar="",$postvar="",$sqltags="") { 
	
//$allowvar=""  去資料表標籤-去除空白跟HTML標籤
//$postvar=""   傳入值
//$sqltags=""	只去資料表標籤


foreach($postvar as $var=> $value){	
//去資料表標籤-去除空白跟HTML標籤	



if(!empty($allowvar) && in_array($var,$allowvar)){
$postvar[$var]=phpstrip_tags($notags=sqlinjectionfound($val=$value));
}

//去資料表標籤
if(!empty($sqltags) && in_array($var,$sqltags)){
$postvar[$var]=sqlinjectionfound($val=$value);
}

}



return  $postvar;
}





//PHP斷行去HTML標籤
function phpstrip_tags($notags='',$type="") {
	global $xoopsConfig;
	//php去除段行
	$notags = strip_tags($notags);
	switch($type) {
		case "1": 
		$notags=preg_replace( "/\&gt;/", "" , $notags);
		$notags = preg_replace('/\s(?=\s)/', '', $notags);
		$notags = preg_replace('/[\n\r\t]/', '', $notags);
		break;
		case "2": //去除檔名不可用符號 
		$notags = preg_replace('/< > \/ \\ \| \: " \* \?/', '', $notags);
		$notags = preg_replace('/\(/', '_', $notags);
		$notags = preg_replace('/\)/', '', $notags);
		$notags = preg_replace('/\./', '', $notags);
		$notags = preg_replace('/-+/i', '', $notags);
		$notags = preg_replace('/=+/i', '', $notags);
		$notags = preg_replace('/[@\!#\$%\^]+/', '', $notags);
		$notags = preg_replace('/__/', '_', $notags);
		$notags = preg_replace('/~/', '_', $notags);
		$notags = preg_replace('/\[(.*?)\]/', '$1', $notags);
		//去除[]
		$notags = preg_replace('/"([^"]*)"/', '$1', $notags);
		//去除引號""
		$notags = preg_replace('/"/', '', $notags);
		// 去掉所有引號		
		$notags = preg_replace('/\((.*?)\)/', '$1', $notags);
		//去除()			
		$notags = phpstrip_tags($notags, $type="");
		//去除空格--在正規表示法的範圍 [^\p{L}\p{N}\s] 中加入 _，表示允許下劃線 _ 不被移除。
        $notags = preg_replace('/[^\p{L}\p{N}\s_]/u', '', $notags);
		//去除全部符號
		break;
		default:  
			if($xoopsConfig['language']=='tchinese_utf8') {
			$notags=preg_replace('/\s(?=)/', '', trim($notags));
			$notags=preg_replace( "/\&gt;/", "" , $notags);
			$notags = preg_replace('/\s(?=\s)/', '', $notags);
			$notags = preg_replace('/[\n\r\t]/', '', $notags);
			$notags = preg_replace('/&nbsp;/', '', $notags);
			$notags = preg_replace('/&quot;/', '', $notags);
			$notags = preg_replace('/&nb/', '', $notags);
			$notags = preg_replace('/\&amp;/', '&', $notags);
			$notags=neillibrary_myTrim($str=$notags);
			//去除空格
		} else {
			$notags = preg_replace('/[\n\r\t]/', '', $notags);
		}
		$notags = preg_replace('/"([^"]*)"/', '$1', $notags);
		//去除引號""
		$notags = preg_replace('/"/', '', $notags);
		// 去掉所有引號
	}
	return  $notags;
}



//去除空格
function neillibrary_myTrim($str){
$search = array(" ","　","\n","\r","\t");
$replace = array("","","","","");
return str_replace($search, $replace, $str);
}




//迴圈去除SQL標籤

function removesqlforeach($sqlinjectionArr="",$coderemove=""){
	
foreach($sqlinjectionArr as $key=> $val){
$remove[$key]=sqlinjectionfound($var=$sqlinjectionArr[$key],$coderemove);
}
  return $remove; 
}



//去除資料庫標籤SQL Injection found
function sqlinjectionfound($var='',$coderemove='') {            //php去除段行	
$varclean=neillibrary_special_chars_replace($var); //遞迴替換資料庫禁用字元	
//$varclean= preg_replace("/['*+]/", '',trim($varclean)); //去除'*+
if (!preg_match('/data:image/', $varclean)) {
    $varclean = preg_replace("/['*+]/", '', trim($varclean)); //排除data:image->去除'*+
}	

$varclean= preg_replace("/(mysql)/i", '',$varclean); //去除mysql
$varclean= preg_replace("/(SELECT)/i", '',$varclean); //去除SELECT	
$varclean= sqlinjectionfilterEmoji($str=$varclean); //去除emoji表情符號字符反斜線
if(!empty($coderemove)) $varclean=neillibrary_removejscssscript($str=$varclean); //去除js,smarty,css,php代碼
return  $varclean;
} 

//去除js,smarty,css,php標籤
function neillibrary_removejscssscript($str) {
//移除js	
$str = str_replace("\r\n", PHP_EOL, htmlspecialchars_decode($str));
$str = preg_replace('/<.*script.*>/', '', $str);
//移除css
$str = preg_replace('/<.*style.*>/', '', $str);
$str = preg_replace('/<.*link.*>/', '', $str);
//移除smarty
$str = preg_replace('/<\{+/i', '', $str);
$str = preg_replace('/\}>+/i', '', $str);
//移除php
$str = preg_replace('/<\?php+/i', '', $str);
$str = preg_replace('/\?>+/i', '', $str);
return  $str;
}



//去除emoji表情符號字符反斜線
function sqlinjectionfilterEmoji($str){
    $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
     return $str;
 }





//時間函數
function timedate($datevar="",$type="",$calculate="",$m="",$d="",$y="",$format="") {
	switch($type) {
		case "1":
		//當前時間計算-時,分,秒,月,日,年 +10
		$timedate=date("".$datevar."" , mktime(date("H"),date("i"),date("s"),date("m")+$m,date("d")+$d,date("Y")+$y));
		break;
		case "2":  
		if(empty($datevar) || empty($d))	return  false;			
		//自訂時間計算天數  	  
		if($calculate=="-") {
			//減去天數
			$date = date_create($datevar);
			date_sub($date, date_interval_create_from_date_string("{$d} days"));
			$timedate=date_format($date, 'Y-m-d H:i:s');
		} else {
			//加上天數
			$date = date_create($datevar);
			date_add($date, date_interval_create_from_date_string("{$d} days"));
			$timedate= date_format($date, 'Y-m-d H:i:s');
		}
		break;
		case "3":  
		 //解析time();

	//	$timedate=date($format,$datevar);
	//	if(empty($timedate)) $timedate=date($datevar,$format);
	
	   //$datevar=日期格式
	   //$format=值
	
        $timedate=date($datevar,$format);
		break;
		case "4":
		 //移除時分秒-可自訂 
	    if(empty($format))	 $format=10; //預設值		 	      
		$timedate = substr($datevar, 0, $format);
		break;
		case "5":
		 //Unix 時間戳 	      
		$timedate =strtotime(date("".$datevar.""));
		break;
		case "6": //時間相減
		$timedate= (strtotime($datevar['time1']) - strtotime($datevar['time2']))/ (60*60*24);
		//計算相差之天數
		break;
		case "7": //月份轉英文
		$timedate=monthtoenglishfunction($val=timedate($datevar="m",$type="3",$calculate="",$m="",$d="",$y="",$format));
		break;
		case "8": //月份轉中文  	  
		$timedate=moonchinesefunction($val=timedate($datevar="m",$type="3",$calculate="",$m="",$d="",$y="",$format));
		break;
		case "9": //月份轉數字  	  
		if(timedate($datevar="m",$type="3",$calculate="",$m="",$d="",$y="",$format) < '10') {
			$timedate=str_replace ("0","",timedate($datevar="m",$type="3",$calculate="",$m="",$d="",$y="",$format));
		} else {
			$timedate=timedate($datevar="m",$type="3",$calculate="",$m="",$d="",$y="",$format);
		}
		break;
		case "10": //取得中文星期  	 
        //$format=輸入日期內容例如2024-12-16 16:41
        $weekdays = [
        "Sunday" => _MS_CHINESE_NUMERALS_07,  //日
        "Monday" => _MS_CHINESE_NUMERALS_01, //一
        "Tuesday" => _MS_CHINESE_NUMERALS_02, //二
        "Wednesday" => _MS_CHINESE_NUMERALS_03, //三
        "Thursday" => _MS_CHINESE_NUMERALS_04, //四
        "Friday" => _MS_CHINESE_NUMERALS_05, //五
        "Saturday" => _MS_CHINESE_NUMERALS_06 //六
        ];

        $englishDay = date("l", strtotime($format)); // 英文星期幾
        $timedate = $weekdays[$englishDay]; // 對應的中文星期幾
			
		break;
		
		
		default:
		//原生時間-Y-m-d H:i:s	  	  
		$timedate=date("".$datevar."");
	}
	return  $timedate;
}


//數字月份轉英文
 function monthtoenglishfunction($val=""){  
 switch($val){
  case "01":
$month="January";
  break;
  
  case "02":
$month="February";
  break;
  
  case "03":
$month="March";
  break;
  
  case "04":
$month="April";
  break;
  
  case "05":
$month="May";
  break;
  
  case "06":
$month="June";
  break;
  
  case "07":
$month="July";
  break;
  
  case "08":
$month="August";
  break;
  
  case "09":
$month="September";
  break;
  
  case "10":
$month="October";
  break;  
  
  case "11":
$month="November";
  break;
  
  case "12":
$month="December";
  break;
  
  default:
  //預設動作
} 
  return  $month;
 }



//數字月份轉轉中文
 function moonchinesefunction($val=""){  
 switch($val){
  case "01":
$month=_MS_MOONCHINESE01;
  break;
  
  case "02":
$month=_MS_MOONCHINESE02;
  break;
  
  case "03":
$month=_MS_MOONCHINESE03;
  break;
  
  case "04":
$month=_MS_MOONCHINESE04;
  break;
  
  case "05":
$month=_MS_MOONCHINESE05;
  break;
  
  case "06":
$month=_MS_MOONCHINESE06;
  break;
  
  case "07":
$month=_MS_MOONCHINESE07;
  break;
  
  case "08":
$month=_MS_MOONCHINESE08;
  break;
  
  case "09":
$month=_MS_MOONCHINESE09;
  break;
  
  case "10":
$month=_MS_MOONCHINESE10;
  break;  
  
  case "11":
$month=_MS_MOONCHINESE11;
  break;
  
  case "12":
$month=_MS_MOONCHINESE12;
  break;
  
  default:
  //預設動作
} 
  return  $month;
 }





//切割字串(組合字串)
 function cuttingfunction($cutting="",$sign="",$type=""){ 
 
 	 
switch($type){
  case "1": //去除相同值  	  
$cuttingfunction = is_array(preg_split("/{$sign}/",$cutting)) ? array_unique(preg_split("/{$sign}/",$cutting)) : null ;
  break;
  
  case "2": //組合字串
foreach($cutting as $key=> $val){
$cuttingval.=$val.$sign;
}
$cuttingfunction=substr($cuttingval,0,-1);   
  break;  
  

  
  default:
 $cuttingfunction=preg_split("/{$sign}/",$cutting); 
}

 	 

 
 
 
 return  $cuttingfunction;
 }




//擷取網址
function httphosturl($keywordid=""){  	 
//取得網址後方變數
$query=$_SERVER['QUERY_STRING'];
if(!empty($query)){
$httphosturl['querytrue']='&';	
	}else{
$httphosturl['querytrue']='?';	
} 	 
 	 
//取得當前頁面完整網址
$httphost = $_SERVER['HTTP_HOST']; 
$httphosturl['phpself']=$_SERVER['PHP_SELF'];
$httphosturl['user']=$_SERVER['HTTP_USER_AGENT'];
$httphosturl['request_uri']=$_SERVER['REQUEST_URI'];
$httphosturl['query_string']=$_SERVER['QUERY_STRING'];
$httphosturl['httptype']=XOOPS_PROT;

if(empty($keywordid) and !empty($query)){
$httpstring='?'.$_SERVER['QUERY_STRING'];
}else{
$httphosturl['querytrue']='?';
}

$http = XOOPS_PROT;

$httphosturl['url']= $http.$httphost.$httphosturl['phpself'].$httpstring;
$httphosturl['page']=$httpstring;
//讀取上一頁連入網址
$httphosturl['posturl']=$_SERVER['HTTP_REFERER'];   

return $httphosturl; 
 }

//檢查傳入網址 
function urlpregmatch($url) {
    return preg_replace("/[^a-zA-Z0-9]+/", "", $url);
}
 
//比對網址(防外部傳參)
function alignmenturl() {
    // 讀取傳入網址
    $httphosturl = httphosturl();
    // 本地端網址
    $url1 = urlpregmatch(XOOPS_URL);
    // 傳入端網址
    $url2 = urlpregmatch($httphosturl['posturl']);
    // 判斷傳入網址是否為同網站
    return strpos($url2, $url1) === 0;
}
 
 

//合併資料表查詢
function mergetablewhile($table="",$tablenane="",$where="",$order="",$type="",$onepage="",$allpage=""){ 
  global $xoopsDB;    
//參數
/*
$table['0']="neilenmovie";  //資料表名稱
$table['1']="neilenalbum";  //資料表名稱
$table['2']="neilennews";  //資料表名稱	
$table['3']="neilenfile";  //資料表名稱	
$tablenane="reviewtime,setuptime,basid,sortid,title,enable,review,id,enfunction";	 //相同欄位
$where="where `basid` = '6'";
$order="order by   setuptime desc";  
 */
  
$wherevar=!empty($where) ? "where" :""; //相簿搜尋有值

foreach($table as $key=> $val){
$selectvar.="SELECT ".$tablenane." FROM ".$xoopsDB->prefix($val)." ".$wherevar." ".$where."   UNION ALL ";
}
$selectvar=substr($selectvar,0,-10);	  	  
$sql = "".$selectvar."  ".$order."";
$result = $xoopsDB -> query($sql);    
  
 switch($type){
  case "1":  //無Bbar  	
$i=1;
while($tableArray= $xoopsDB ->fetchArray($result)){
$tableArrayArr[$i]=$tableArray;
$i++;
};  

	  
return $tableArrayArr; 
  break;
  
  case "2":  //有Bbar
$total=$xoopsDB->getRowsNum($result);
$navbar = new tadPageBar($total, $onepage, $allpage);
$mybar = $navbar->makeBar();
$bar= sprintf($mybar['total'],$mybar['current'])."{$mybar['left']}{$mybar['center']}{$mybar['right']}";
$sql.=$mybar['sql'];
//分頁工具列為 $bar
$result = $xoopsDB -> query($sql) or die($sql);

$i=1;
while($tableArray= $xoopsDB ->fetchArray($result)){
$tableArrayArr[$i]=$tableArray;
$i++;
};  


return array($tableArrayArr, $bar); 
  	  

  break;
}

 
 
  }
 
 
 
//查詢資料表while全部數值
function databasetablewhile($dbneme="",$where="",$selectkey=""){    
global $xoopsDB;  
$selectkey=empty($selectkey) ? '*' : "{$selectkey}"; // get TRUE
$sql = "select ".$selectkey." from " . $xoopsDB->prefix($dbneme) . "  ".$where."";
$result = $xoopsDB -> query($sql); 
if(empty($result)) return false; 
$i=1;
while($db= $xoopsDB ->fetchArray($result)){
$dbArr[$i]=$db;
$i++;
}; 
return $dbArr; 
 }
 
 
//查詢資料表while全部數值有bar值
function databasetablewhilebar($dbneme="",$where="",$onepage="",$allpage=""){    
global $xoopsDB;  
$sql = "select * from " . $xoopsDB->prefix($dbneme) . "  ".$where."";
$result = $xoopsDB -> query($sql);  

$total=$xoopsDB->getRowsNum($result);
$navbar = new tadPageBar($total, $onepage, $allpage);
$mybar = $navbar->makeBar();
$bar= sprintf($mybar['total'],$mybar['current'])."{$mybar['left']}{$mybar['center']}{$mybar['right']}";
$sql.=$mybar['sql'];
//分頁工具列為 $bar
$result = $xoopsDB -> query($sql) or die($sql);

$i=1;
while($keyword= $xoopsDB ->fetchArray($result)){
$keywordArr[$i]=$keyword;
$i++;
}; 


return array($keywordArr, $bar); 

 }
  
 
 
 
 
 

//查詢資料表單一筆數值
function moduledb($dbneme="",$where=""){    
    global $xoopsDB;  
    $sql = "select * from " . $xoopsDB->prefix($dbneme)  ." " .trim($where);
    $result = $xoopsDB->query($sql);
    if (!$result) {
        return null; // 避免輸出 SQL 錯誤
    }
    return $xoopsDB->fetchArray($result); 
}



 
//更新資料單一筆
function update($dbname="",$set="",$back=""){
global $xoopsDB;   
$sql = "update " . $xoopsDB->prefix($dbname) . " ".$set."";
$xoopsDB->queryF($sql) or web_error($sql); 
//判斷xLanguage是否啟用
if(!empty(modulesmidvar($modulesid="xLanguage",$var="isactive"))) xlanguageCheck($dbname,$dbdata=moduledb($dbneme=$dbname,$where=" ".strstr($set,'where')." "),$type=""); //xlanguage模組標籤檢查無害化處理
$returnid=empty($back) ? $returnid : true; // get TRUE
return $returnid;
}



//新增一筆資料
function insert($dbname="",$values=""){
global $xoopsDB;   
$sql = "insert into " . $xoopsDB->prefix($dbname) . " ".$values."";
$xoopsDB -> queryF($sql) ;
$returnid=$xoopsDB->getInsertId();
//判斷xLanguage是否啟用
if(!empty(modulesmidvar($modulesid="xLanguage",$var="isactive"))) xlanguageCheck($dbname,$dbdata=moduledb($dbneme=$dbname,$where=" where `".reset(array_keys(moduledb($dbneme=$dbname,$where="")))."`='".$returnid."'  "),$type=""); //xlanguage模組標籤檢查無害化處理	
return $returnid; 
}



//xlanguage模組標籤檢查無害化處理
function xlanguageCheck($dbname="",$dbdata="",$type=""){
global $xoopsConfig;

$dbdata=is_array($dbdata) ? array_keys($dbdata) : array();
$whereDB=" where `".reset($dbdata)."`='".reset($dbdata)."'";
//讀取xlanguage_base資料表
$langvar=databasetablewhile($dbneme="xlanguage_base",$where="");

//標籤檢查區
//while (list($var, $value) = each($langvar)) {
foreach($langvar as $var=> $value){	
foreach($dbdata as $key=> $val){
if( preg_match("/(?:".$langvar[$var]['lang_code'].")/i", $val)   and  (preg_match("/(\[".$langvar[$var]['lang_code']."\])/i", $val)  or preg_match("/(\[\/".$langvar[$var]['lang_code']."\])/i", $val)    )){  //抓出符合條件  
if ((!preg_match("/(\[".$langvar[$var]['lang_code']."\])/i", $val) or !preg_match("/(\[\/".$langvar[$var]['lang_code']."\])/i", $val)  )) {  //比對完全符合條件
$updatevar[$key]="[".$langvar[$var]['lang_code']."][error]".$val."[/error][/".$langvar[$var]['lang_code']."]";  //無害化處理
}
}
}
}

//組合資料生成set
if(!empty($updatevar)){	
$setvar.=" set";
//while (list($var, $value) = each($updatevar)) {
foreach($updatevar as $var=> $value){		
$setvar.=" ".$var."='".$value."'  ,";
 }
$set=" ".substr($setvar,0,-1)." ".$whereDB."";
update($dbname,$set);  //寫入資料表
}
}










//狀態顯示
function enable($envar="",$type=""){
switch ($envar){
case "0":  	 
$enable=empty($type) ? _MS_SHARED04 : _MS_SHARED48; // get TRUE

break; 
case "1":  	
$enable=_MS_SHARED03;
break; 
default:
$enable=_MS_SHARED03;
}
return $enable; 
}

//刪除資料
function deletefunction($where="",$DBname=""){ 
global $xoopsDB;  	
$sql = "delete from " . $xoopsDB->prefix($DBname). " ".$where."";
return  $xoopsDB->queryF($sql); 
}


//清空資料表
function truncatefunction($DBname=""){ 
global $xoopsDB;  
$sql = "truncate " . $xoopsDB->prefix($DBname);
$xoopsDB->queryF($sql); 
}




//抓取TAD模組中的FB-ID
function tad_loginappid() {
      $modhandler = xoops_gethandler('module');
      $config_handler =xoops_gethandler('config');
      $xoopsModule = &$modhandler->getByDirname("tad_login");
      if(!empty($xoopsModule)){
      $modConfig= &$config_handler->getConfigsByCat(0, $xoopsModule->getVar('mid'));
      $xoopsModuleConfig = & $config_handler->getConfigsByCat(0, $mid);
      }
 
     return  $modConfig['appId'];
    } 

//取得指定模組config資料表欄位值
function configvar($modulesid="",$type="",$where=""){	
  switch($type){
  case "1":
  //取得全部欄位值	  
  $configList=moduledb($dbneme="config",$where);
  break;  
  default:
  //取得$xoopsModuleConfig設定
  $modhandler        = &xoops_gethandler('module');
  $xoopsModule       = &$modhandler->getByDirname($modulesid);
  if(!empty($xoopsModule)){   
  $config_handler    = &xoops_gethandler('config');
  $configList = &$config_handler->getConfigsByCat(0, $xoopsModule->getVar('mid'));   
  }
  }
       
  return $configList;
} 

//取得指定模組module資料表值
function modulesmidvar($modulesid="",$var=""){
//$modulesid 模組id
//$var 查詢欄位
//return 返回欄位值	
	
$modulevar=empty($var) ? 'mid' : $var; // get TRUE			
$module_handler =& xoops_gethandler('module'); 
$xoopsModule =& $module_handler->getByDirname($modulesid); 
if(!empty($xoopsModule)) $field = $xoopsModule->getVar($modulevar); 
return $field;
}

//瀏覽裝置-常用設定
function check_mobile_default($valArr="",$mobile=""){  
//瀏覽裝置判斷
if(check_mobile()){  
//手機
$mobile['separate']=$valArr[0];
$mobile['btn']=$valArr[0];
}else{
//電腦
$mobile['separate']=$valArr[1];	
$mobile['btn']=$valArr[1];
}  	
return $mobile;
 }


//瀏覽裝置判斷
function check_mobile(){    
//讀出$xoopsModuleConfig值
$xoopsModuleConfig=configvar($modulesid="neillibrary");
$regex_match= empty($xoopsModuleConfig['neillibrary1']) ? '' : mobile_version(); // get TRUE  	
return preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
//return preg_match($regex_match, 'android');
}

//瀏覽裝置-預設值
function check_mobiledefault(){  
	//瀏覽裝置判斷
	if(check_mobile()) {
		//手機
		$val="phone";
	} else {
		//電腦
		$val="computer";
	} 	
return $val;
}


//瀏覽裝置判斷
if(check_mobile()){  //手機
$themefolder='phone';
}else{
 //電腦
$themefolder='computer';	
}


//行動裝置版本-可擴充
function mobile_version(){
    $regex_match="/(nokia|ipod|blackberry|mobile|ipad|windows phone|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
    $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
    $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
    $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";   
    $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
    $regex_match.=")/i";
    
return $regex_match;
}



?>