<?php
//function.php 是將前後台都會用到的函數放到這裡

if(!empty($xoopsModule)){
if($xoopsModule->getVar("dirname")=="neothemesadmin"){
include_once XOOPS_ROOT_PATH."/modules/neillibrary/class/bar.php";	
}}


//引入Neil函數庫
include_once XOOPS_ROOT_PATH."/modules/neillibrary/function.php";

//郵寄程式
include_once XOOPS_ROOT_PATH."/modules/neothemesadmin/mailfunction.php";



// 主選單遞迴函式
function neothemesadmin_menurecursion($sortid="", $dbneme="", $sublayer="", $order="",$displaytype="",$limit="",$legal="") {
    $sublayer++;
    $menu = array(); // 新增一個陣列來儲存子層選單
    if (!empty($sortid)) {
        $namevar = $sublayer == 1 ? 'sortid' : 'of_sortid';
        $limit="";
        $legal="";
    } else {
        $namevar = $sublayer == 1 ? 'of_sortid' : 'sortid';
        $limit="limit ".$limit."";
        if(!empty($legal)) $legal="`sortid` IN (".implode(',', $legal).") &&";
    }
    $where = "  where ".$legal."  `".$namevar."` = '".$sortid."'  && `enable` = '1'  &&  FIND_IN_SET({$displaytype},`displaytype`)  ".$order." ".$limit."";
    foreach ($sortArr = databasetablewhile($dbneme, $where) as $key => $val) {
        $menu[$sortArr[$key]['sortid']] = $sortArr[$key];
        // 檢查是否有子層選單
        $subMenu = moduledb($dbneme, "where `of_sortid` = '".$sortArr[$key]['sortid']."'");
        if (!empty($subMenu)) {
            $menu[$sortArr[$key]['sortid']]['subMenu'] = neothemesadmin_menurecursion($sortid = $sortArr[$key]['sortid'], $dbneme, $sublayer, $order,$displaytype,$limit="",$legal="");
        }
    }
    return $menu; // 返回新的子層選單陣列

}



//跑馬燈設定
function neothemesadmin_m_settings($conversion=""){
	
//開啟跑馬燈設定
$m_config=phpconversion($conversion,$type="unserialize"); 
//預設值
if(empty($m_config)){
$m_config[0]=0;
$m_config[1]=10;
}

switch($m_config[0]) {
	case "0":  	   //最新建立
	$m_config[2]="order by  nsn  DESC";
	break;
	case "1":      //排序
	$m_config[2]="order by  nnumber  ASC";
	break;
	case "2":      //隨機
	$m_config[2]="order by RAND()";
	break;
}

return $m_config;
}






//右下浮動廣告
function neothemesadmin_lowerrightad($configvar){
global $xoopsDB,$xoopsModule,$xoopsTpl,$isAdmin;
new XoopsTpl();
//判斷啟用狀態(沒值false)
if(empty($configvar['neothemesadmin8'])) return false;

//到期時間判斷
foreach($timeArr=databasetablewhile($dbneme="neil_lowerrightad",$where="  where `enable` = '1'  && `maturity` < '".timedate($datevar="Y-m-d")."'   order by  btnsort  ASC")   as $key=> $val){
$setvar="set enable='0'  where rdad='".$timeArr[$key]['rdad']."'";  update($dbname="neil_lowerrightad",$set=$setvar);  
}



if(empty($configvar['neothemesadmin9'])){
//指定
$whereDB=" where `enable` != '0'  && `adenable` = '1' ";
}else{
//隨機
$whereDB=" where `enable` != '0'  order by RAND() ";
}

$adlist=moduledb($dbneme="neil_lowerrightad",$where=$whereDB);

if(empty($adlist)) return false;

//圖片
//已上傳圖片
$adlist['imgid']=cuttingfunction($cutting=$adlist['imgid'],$sign=",");
//廣告連結
$adlist['url']=cuttingfunction($cutting=$adlist['url'],$sign=",");
//連結開啟方式
$adlist['target']=cuttingfunction($cutting=$adlist['target'],$sign=",");

if(!empty($isAdmin) && check_mobiledefault()=='computer'){
$adminbtn="<div id='admindbox'><a title='"._MA_NEIL_POPUPADS_BLOCK04."' target='_blank' href='".XOOPS_URL."/modules/neothemesadmin/admin/advertise.php?op=advertise3&menutype=3'><span class='glyphicon glyphicon-cog' aria-hidden='true'></span></a></div>";		
$adpageadmin="<div id='adminlistdbox'><a title='".sprintf(_MA_NEIL_POPUPADS_BLOCK02,$adlist['title'])."' target='_blank' href='".XOOPS_URL."/modules/neothemesadmin/admin/advertise.php?op=advertise3&menutype=2&rdad=".$adlist['rdad']."'><span class='glyphicon glyphicon-edit' aria-hidden='true'></span></a></div>";		
}



//右上
if(file_exists(XOOPS_ROOT_PATH.'/uploads/neothemesadmin/'.$adlist['imgid']['0'].'.png')){
$target['0']=pagemethod($types=$adlist['target']['0']);	
$rtbox="<div id='rtbox'>
<a title='".$adlist['title']."' target='".$target['0']['way']."' href='".$adlist['url']['0']."'><img alt='".$adlist['title']."' src='".XOOPS_URL."/uploads/neothemesadmin/".$adlist['imgid']['0'].".png?state=".date("H:i:s")."' ></a>
</div>";
}

//右下
$target['1']=pagemethod($types=$adlist['target']['1']);	
$rbbox="<div id='rbbox'>
<a title='".$adlist['title']."' target='".$target['1']['way']."' href='".$adlist['url']['1']."'><img alt='".$adlist['title']."' src='".XOOPS_URL."/uploads/neothemesadmin/".$adlist['imgid']['1'].".png?state=".date("H:i:s")."' ></a>
</div>";

$box.="<div id='lowerrightadbox' aria-hidden='true'  tabindex='-1'>
".$rtbox.$rbbox.$adminbtn.$adpageadmin."
</div>";

$box.="
<script>	
$(window).scroll(function() {
    if (($(this).scrollTop()) > '150') {
        $('#lowerrightadbox').css({
            'display': 'block',
            'animation-name': 'lowerrightadbox',
            'opacity': '1'
        });
    } else {
        $('#lowerrightadbox').css({
            'display': 'none',
            'animation-name': '',
            'opacity': '0'
        });
    }
    var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
    if ((scrollBottom) < '250') {
        $('#lowerrightadbox').css({
            'display': 'none',
            'animation-name': '',
            'opacity': '0'
        });
    } else {
        if (($(this).scrollTop()) > '150') {
            $('#lowerrightadbox').css({
                'display': 'block',
                'animation-name': 'lowerrightadbox',
                'opacity': '1'
            });
        }
    }
});

</script>
";

return $box;
}



//彈出廣告
function neothemesadmin_popupads($configvar="",$fieldsplit=""){
global $xoopsDB,$xoopsModule,$xoopsTpl,$isAdmin;
new XoopsTpl();

//判斷啟用狀態(沒值false)
if(empty($configvar['neothemesadmin5'])) return false;

//判斷是否為首頁
if(!empty(trim($xoopsTpl->tpl_vars['xoops_contents']->value))  or !empty($_GET['designer'])) return false;


//到期時間判斷
foreach($timeArr=databasetablewhile($dbneme="neil_popupads",$where="  where `enable` = '1'  && `maturity` < '".timedate($datevar="Y-m-d")."'   order by  btnsort  ASC")   as $key=> $val){
$setvar="set enable='0'  where ad='".$timeArr[$key]['ad']."'";  update($dbname="neil_popupads",$set=$setvar);  
}

if(!empty($isAdmin)) $adminbtn="<div id='admindbox'><a title='"._MA_NEIL_POPUPADS_BLOCK03."' target='_blank' href='".XOOPS_URL."/modules/neothemesadmin/admin/advertise.php?op=advertise2&menutype=2'><span class='glyphicon glyphicon-cog' aria-hidden='true'></span></a></div>";		


if(empty($configvar['neothemesadmin7'])){
//指定
$whereDB=" where `enable` != '0'  && `adenable` = '1' ";
}else{
//隨機
$whereDB=" where `enable` != '0'  order by RAND() ";
}


$adlist=moduledb($dbneme="neil_popupads",$where=$whereDB);

if(empty($adlist)) return false;

$target=pagemethod($types=$adlist['target']);
if(!empty($isAdmin)) $adpageadmin="<div id='adminlistdbox'><a title='".sprintf(_MA_NEIL_POPUPADS_BLOCK02,$adlist['title'])."' target='_blank' href='".XOOPS_URL."/modules/neothemesadmin/admin/advertise.php?op=advertise2&menutype=2&ad=".$adlist['ad']."'><span class='glyphicon glyphicon-edit' aria-hidden='true'></span></a></div>";		



$box.="<div id='popupadsbox'>
<div id='popupadscontent'>
<div id='pcomtent'>	
<div id='adclosure' title='"._MA_NEIL_POPUPADS_BLOCK01."'><span class='glyphicon glyphicon-remove-circle' aria-hidden='true'></span></div>	
".$adpageadmin.$adminbtn."	
<a title='".$adlist['title']."' target='".$target['way']."'  href='".$adlist['url']."'><img alt='".$adlist['title']."' src='".XOOPS_URL."/uploads/neothemesadmin/".$adlist['imgid'].".png?state=".date("H:i:s")."' ></a>	
</div>
</div>	
</div>

";


//電腦版才執行
if(check_mobiledefault()=='computer'){	
$boxid=!empty($fieldsplit[4]) ? '#toplayerdiv' : 'body'; // get TRUE
$box.="
<script>
$(document).ready(function() {		
var boxwidth = $('".$boxid."').width();	
var leftvar=(boxwidth-".$adlist['imgwidth'].") / 2;
$('.indexpage #popupadscontent').css({
        'width': '".$adlist['imgwidth']."px',
        'left': ''+leftvar+'px'
      });
});
</script>
";
}


$box.="
<script>	
$(document).ready(function() {	
    $('body').on('click', '.indexpage #popupadsbox #adclosure', function() {
        adAnimationfunction();
    })
    $(this).mouseup(function(e) {
        if ($('.indexpage #popupadsbox').css('display') == 'block') {
            var container = $('#popupadscontent');
            if (!container.is(e.target) && container.has(e.target).length === 0) {
                adAnimationfunction();
            }
        }
    });
    function adAnimationfunction() {
        $('.indexpage #popupadsbox').css({
            'animation-name': 'popupadsclosure',
            'background-color': 'rgba(0, 0, 0, 0)',
            'opacity': '1'
        });
        $('.indexpage #popupadscontent').css({
            'animation-name': 'contentclosure'
        });
        setTimeout(function() {        	
            $('#popupadsbox').remove();            
        }, 400);
    }
});
</script>
";

return $box;
}





//按鈕數判斷樣式
function neothemesadmin_btnquantitystyle($menuval="",$key=""){
if($menuval<='2'){
$btnstyle[$key]='btnstyle1';
}elseif($menuval=='3'){
$btnstyle[$key]='btnstyle2';
}elseif($menuval=='4'){
$btnstyle[$key]='btnstyle3';
}elseif($menuval=='5'){
$btnstyle[$key]='btnstyle4';
}elseif($menuval=='6'){
$btnstyle[$key]='btnstyle5';
}elseif($menuval=='7'){
$btnstyle[$key]='btnstyle6';
}elseif($menuval=='8'){
$btnstyle[$key]='btnstyle7';
}elseif($menuval>='9'){
$btnstyle[$key]='btnstyle8';
}

return $btnstyle;
}	


//選單功能標籤文字
function neothemesadmin_labeltext($vartext=""){
switch($vartext){
  case "1":
$text.="<span class='label label-success'>"._MA_MENUTABLEPHP18."</span>  "; //顯示主選單
  break; 
  case "2":
$text.="<span class='label label-default'>"._MA_MENUTABLEPHP19."</span>  "; //顯示底區塊
  break;   
  default:
}	
return $text;
}	

//選單功能標籤功能
function neothemesadmin_labeltextfunction($textArr=""){
//切割字串
$Arr=cuttingfunction($cutting=$textArr,$sign=",");
foreach($Arr as $key=> $val){
$Arrbox.=neothemesadmin_labeltext($vartext=$val);
}
return $Arrbox;
}




//區塊權限檢查
function neothemesadmin_permissioncheck($where="",$dbneme1="",$dbneme2="",$total=""){	
	
$difference=differencefunction($dbneme1,$dbneme2,$where,$type="1",$total,$tvar='false');	

//$difference=(is_array($difference) ? array_unique($difference) : null) ;

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


return $DBdata;
}



//區塊選單小圖示
function glyphiconicon($sortimg){
switch ($sortimg){
case "0":
$icon='fa-solid fa-check';
break;
case "1":  	
$icon='fa-solid fa-bars';	
break;
case "2":  	
$icon='fa-solid fa-chevron-right';	
break;
case "3":  	
$icon='fa-solid fa-arrow-right-long';	
break;
case "4":  	
$icon='fa-regular fa-hand-point-right';	
break;
case "5":  	
$icon='fa-regular fa-heart';	
break;
case "6":  	
$icon='fa-solid fa-right-from-bracket';	
break;
case "7":  	
$icon='fa-solid fa-circle';	
break;
case "8":  	
$icon='fa-solid fa-sun';	
break;
case "9":  	
$icon='fa-solid fa-plus';	
break;
case "10":  	
$icon='fa-solid fa-pen';	
break;
case "11":  	
$icon='fa-solid fa-gear';	
break;
case "12":  	
$icon='fa-solid fa-star';	
break;
case "13":  	
$icon='fa-solid fa-pen-to-square';	
break;
case "14":  	
$icon='fa-solid fa-caret-right';	
break;
case "15":  	
$icon='fa-solid fa-circle-chevron-down';	
break;
case "16":  	
$icon='fa-solid fa-paperclip';	
break;
case "17":  	
$icon='fa-brands fa-pagelines';	
break;
case "18":  	
$icon='fa-regular fa-circle-right';	
break;
case "19":  	
$icon='fa-solid fa-record-vinyl';	
break;
case "20":  	
$icon='fa-regular fa-thumbs-up';	
break;




}
return $icon;
}



//下拉選單取值

//遞回
function tplsortselect($dbneme="",$sortselect=""){ 
$where="  where `sortid` = '".$sortselect."' && `enable` = '1'  order by  of_sortid  ASC";  //where數值
$sortselect=moduledb($dbneme,$where);
$sortselectvar.=$sortselect['sortid'].",";

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

//自動解析FB網址撈出會員ID的方法
function neothemesadmin_analyzefbid($fburl= "") {
	$urlarr=parse_url($fburl);
	//解析網址
	parse_str($urlarr['query'],$parr);
	// 存成陣列
	if(!empty($urlarr['scheme'])) {
		//如果網址中沒有HTTPS才執行以下程式
		if (strpos ($fburl, "-")) {
			//搜尋網址中有-
			$endfduserid=str_replace("/","",end(cuttingfunction($cutting=$urlarr['path'],$sign="-",$type="")));
			//取得陣列最後一組數值並去除/
		} elseif(strpos($fburl, "?") and !empty($parr['id'])) {
			//搜尋網址中有?
			$endfduserid=$parr['id'];
			//輸出ID數值
		} elseif(empty($parr['id'])) {
			$endfduserid=next(cuttingfunction($cutting=$urlarr['path'],$sign="\/",$type=""));
		}
	} else {
		$endfduserid=$fburl;
	}
	return $endfduserid;
}







//關鍵字查詢模組option
function modulesnameoption($modulesid="") {
	global $xoopsDB;
	$keyword=databasetablewhile($dbneme="neothemeskeyword",$where=" order by  nsn DESC");
	//去除已選擇模組
	foreach($keyword as $key=> $val) {
		if($modulesid!=$val['keywordid']) {
			$exclude[]=$val['keywordid'];
		}
	}
	$exclude=!empty($exclude) ? $exclude : array();
	if (!empty($exclude)) {
		// 每個元素周圍添加單引號
		$excludeWithQuotes = array_map(function($item) {
			return "'$item'";
		}, $exclude);
		// 使用implode連接每個元素
		$excludeDB = "&& `dirname` NOT IN (" . implode(',', $excludeWithQuotes) . ")";
	}
	//網站首頁
	if($modulesid!='modules' && !in_array("system", $exclude)) {
		$option="
        <option selected='selected'  value='system' >"._MA_NEODWADMIN_DISPLAYHOMEKEYWORD."</option>
        ";
	}
	//全部頁面
	if($modulesid!='system'  && !in_array("modules", $exclude)) {
		$option.="
        <option selected='selected'   value='modules' >"._MA_NEODWADMIN_DISPLAYALLPAGESKEYWORD."</option> 
        ";
	}
	$dbneme="modules";
	$where="  where `hasmain` !=0   &&  `dirname`  !='pm'  &&  `dirname`  !='profile'  &&  `dirname`  !='tadtools' &&  `dirname`  !='neothemesadmin' &&  `dirname`  !='neillibrary'  ".$excludeDB." ";
	//where數值 	
	$Arr=databasetablewhile($dbneme,$where);
	foreach($Arr as $key=> $val) {
		if($val['dirname']==$modulesid) {
			$selected="selected='selected'";
		}
		$option.="<option ".$selected."   value='".$val['dirname']."'   >".$val['name']."</option>";
		unset($selected);
	}
	return $option;
}




 
//關鍵字輸出
function keywordsfunction($xoops_meta_description="",$image="",$xoops_pagetitle=""){  
global $xoopsTpl;  
$xoops_theme = $GLOBALS['xoopsConfig']['theme_set'];

if(empty($image)){
//判斷社群代表圖片是否存在
if(file_exists(XOOPS_ROOT_PATH."/uploads/".$xoops_theme."/communityimg.png")){
$image="".XOOPS_URL."/uploads/".$xoops_theme."/communityimg.png";	
}else{
$image="".XOOPS_URL."/themes/".$xoops_theme."/default/communityimg.png";	
}
}	

if(!empty($xoops_pagetitle)) $xoopsTpl->assign("xoops_pagetitle", $xoops_pagetitle);
if(!empty($xoops_meta_description))  $xoopsTpl->assign("xoops_meta_description", $xoops_meta_description);
$xoopsTpl->assign("metaimage", $image);

return true; 
} 


?>