#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

public_file=/www/server/panel/install/public.sh
. $public_file
publicFileMd5=$(md5sum ${public_file} 2>/dev/null|awk '{print $1}')
md5check="f94b33b66e8a6bc378245070e3d1b1b9"
if [ "${publicFileMd5}" != "${md5check}"  ] && [ -z "${NODE_URL}" ]; then
	wget -O Tpublic.sh https://download.bt.cn/install/public.sh -T 20;
	publicFileMd5=$(md5sum Tpublic.sh 2>/dev/null|awk '{print $1}')
	if [ "${publicFileMd5}" == "${md5check}"  ]; then
		\cp -rpa Tpublic.sh $public_file
	fi
	rm -f Tpublic.sh
	. $public_file
fi

download_Url=$NODE_URL
if [ -z "${cpuCore}" ]; then
	cpuCore="1"
fi
Root_Path=`cat /var/bt_setupPath.conf`
Setup_Path=$Root_Path/server/php
php_path=$Root_Path/server/php
mysql_dir=$Root_Path/server/mysql
mysql_config="${mysql_dir}/bin/mysql_config"
is64bit=`getconf LONG_BIT`
run_path='/root'
apacheVersion=`cat /var/bt_apacheVersion.pl`

php_70='7.0.34'
php_71='7.1.34'
php_72='7.2.35'
php_73='7.3.34'
opensslVersion="1.0.2u"
openssl111Version="1.1.1w"
nghttp2Version="1.42.0"
curlVersion="7.70.0"
AA_PANEL_CHECK=$(cat /www/server/panel/config/config.json | grep "English")
UBUNTU_VER=$(cat /etc/issue|grep -i ubuntu|awk '{print $2}'|cut -f 1 -d '.')
CentOS_Stream_10_Check=$(grep -i "CentOS Stream" /etc/os-release 2>/dev/null | grep -i "10")
UBUNTU_22=$(cat /etc/issue|grep Ubuntu|grep 22)
Env_check(){
	DEBIAN_VER=$(cat /etc/issue|grep -i debian|awk '{print $3}')
	if [ "${DEBIAN_VER}" == "13" ] || [ "${UBUNTU_VER}" == "26" ];then
		apt-get install gcc-13 g++-13 -y
		if [ -f "/usr/bin/gcc-13" ];then 
			export CC=/usr/bin/gcc-13
		fi
		if [ -f "/usr/bin/g++-13" ];then 
			export CXX=/usr/bin/g++-13
		fi
		USE_GCC_13="True"
	fi

	if ! perl -MFindBin -e 1 2>/dev/null; then
		if [ "${PM}" == "apt-get" ]; then
			apt-get install -y perl-modules libssl-dev 2>/dev/null
		else
			${PM} install -y perl perl-FindBin lksctp-tools-devel epel-release brotli-devel libssh2-devel c-ares-devel 2>/dev/null
		fi
	fi
}
Set_Centos7_Repo(){
    if [ -f "/etc/yum.repos.d/docker-ce.repo" ];then
        mv /etc/yum.repos.d/docker-ce.repo /etc/yum.repos.d/docker-ce.repo_backup
    fi
	MIRROR_CHECK=$(cat /etc/yum.repos.d/CentOS-Base.repo |grep "[^#]mirror.centos.org")
	if [ "${MIRROR_CHECK}" ] && [ "${is64bit}" == "64" ];then
		[ -d /etc/yumBak ] || \cp -rpa /etc/yum.repos.d/ /etc/yumBak
		sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
	fi

	TSU_MIRROR_CHECK=$(cat /etc/yum.repos.d/CentOS-Base.repo |grep "tuna.tsinghua.edu.cn")
	if [ "${TSU_MIRROR_CHECK}" ];then
		[ -d /etc/yumBak ] || \cp -rpa /etc/yum.repos.d/ /etc/yumBak
		sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=https://mirrors.tuna.tsinghua.edu.cn|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=http://mirrors.tuna.tsinghua.edu.cn|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
	fi
	
	ALI_CLOUD_CHECK=$(grep Alibaba /etc/motd)
	Tencent_Cloud=$(cat /etc/hostname |grep -E VM-[0-9]+-[0-9]+)
	
	yum install tree -y
	if [ "$?" != "0" ] ;then
		[ -d /etc/yumBak ] || \cp -rpa /etc/yum.repos.d/ /etc/yumBak
		if [ -z "${download_Url}" ];then
			download_Url="http://download.bt.cn"
		fi
		curl -Ss --connect-timeout 5 -m 60 -O ${download_Url}/src/el7repo.tar.gz
		rm -f /etc/yum.repos.d/*.repo
		tar -xvzf el7repo.tar.gz -C /etc/yum.repos.d/

		yum install tree -y
		if [ "$?" != "0" ] ;then
			sed -i "s/vault.epel.cloud/mirrors.cloud.tencent.com/g" /etc/yum.repos.d/*.repo
		fi
	fi
}
check_limit(){
	if [ "${version}" == "7.0" ] || [ "${version}" == "7.1" ] || [ "${version}" == "7.2" ] || [ "${version}" == "7.3" ] || [ "${version}" == "7.4" ] || [ "${version}" == "8.0" ];then
		if [ "${UBUNTU_VER}" == "26" ];then
			echo "当前系统暂不支持php-8.0及以下的版本 "
			echo "建议安装php-8.1及以上的版本"
			exit 1
		fi
	fi
}
Error_Send(){
    MIN_O=$(date +%M)
    if [ $((MIN_O % 2)) -eq 0 ]; then
        exit 1
    fi
    if [ ! -f "/tmp/php_i.pl" ];then
        touch /tmp/php_i.pl
        TIME=$(date "+%Y-%m-%d %H:%M:%S")
        P_VERSION=$(cat /www/server/panel/class/common.py|grep g.version|grep -oE 8.0.[0-9]+)
        ls /etc/init.d/ | xargs -n 5 | pr -t -5 > /tmp/php_err.pl
        tail -n 15 /tmp/php_config.pl /tmp/php_make.pl /tmp/php_install.pl >> /tmp/php_err.pl
        echo  Bit:${SYS_BIT} Mem:${MEM_TOTAL}M Core:${CPU_INFO} gcc:${GCC_VER} cmake:${CMAKE_VER} >> /tmp/php_err.pl
        echo ${SYS_VERSION} ${SYS_INFO} >> /tmp/php_err.pl
        echo "$php_version install Failed" >> /tmp/php_err.pl
        ERR_MSG=$(cat /tmp/php_err.pl)
        rm -f /tmp/php_config.pl /tmp/php_make.pl /tmp/php_install.pl /tmp/php_err.pl
        curl --request POST \
          --url "http://api.bt.cn/bt_error/index.php" \
          --data "UID=89045" \
          --data "PANEL_VERSION=${P_VERSION}"\
          --data "REQUEST_DATE=${TIME}" \
          --data "OS_VERSION=${SYS_VERSION}" \
          --data "REMOTE_ADDR=192.168.168.1641" \
          --data "REQUEST_URI=php" \
          --data "USER_AGENT=${SYS_INFO}" \
          --data "ERROR_INFO=${ERR_MSG}" \
          --data "PACK_TIME=${TIME}" \
          --data "TYPE=3"
    fi
    exit 1
}
Error_Msg(){
	SYS_UNAME=$(uname -a)
	if [ "${actionType}" == "install" ];then
		AC_TYPE="安装"
	elif [ "${actionType}" == "update" ]; then
		AC_TYPE="升级"
	fi

	echo '========================================================'
	echo -e "ERROR: php-${phpVersion} ${actionType} failed.";
	if [ "${AA_PANEL_CHECK}" ];then
		echo -e "Please submit to https://forum.aapanel.com for help"
		exit 1
	else
	    if [ -z "${SYS_VERSION}" ];then
            echo -e "============================================"
            echo -e "检测到为非常用系统安装,请尝试安装其他php版本看是否正常"
            echo -e "如无法正常安装，建议更换至Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板"
            echo -e "详情请查看系统兼容表：https://docs.qq.com/sheet/DUm54VUtyTVNlc21H?tab=BB08J2"
            echo -e "特殊情况可通过以下联系方式寻求安装协助情况"
            echo -e "============================================"
        fi 
		echo -e "${AC_TYPE}失败，请截图以上报错信息发帖至论坛www.bt.cn/bbs求助"
	fi
    
    if [ ! -f "/www/server/panel/install/php_down.pl" ];then
        FILE_KEY=("confdefs.h: No such file or directory" "conftest.c: No such file or directory"  "./configure: No such file or directory")
        for key in "${FILE_KEY[@]}"; do
        	if grep -q "$key" /tmp/php_config.pl; then
        		echo -e "检测到文件下载不完整导致安装失败，请尝试重新安装php看是否正常"
        		echo -e "或使用极速安装看是否正常"
        		touch /www/server/panel/install/php_down.pl
        		exit 1
        	fi
        done
    fi
    
    CC_KILL_CHECK=$(cat /tmp/php_make.pl |grep  "Killed")
    if [ "${CC_KILL_CHECK}" ];then
        echo "检测到编译进程被杀死，一般由以下原因造成"
        echo "1.服务器内存不足，建议增加服务器内存/设置swap虚拟内存/更换低版本php/使用极速方式安装"
        echo "2.开启了安全防护软件导致进程被kill，请关闭安全防护软件后再进行安装"
        exit 1
    fi
    
    Centos8Check=$(cat /etc/redhat-release | grep ' 8.' | grep -iE 'centos')
    if [ "${Centos8Check}" ];then
        echo -e "Centos8官方已经停止支持"
        echo -e "如是新安装系统服务器建议更换至Centos-7/Debian-11/Ubuntu-22系统安装宝塔面板"
        exit 1
    fi
    
    WSL_CHECK=$(echo "${SYS_UNAME}"|grep Microsoft)
    if [ "${WSL_CHECK}" ];then
        echo -e "宝塔未兼容测试过Microsoft WSL子系统进行安装"
        echo -e "建议使用虚拟机安装ubuntu-22安装宝塔面板"
        exit 1
    fi
    VELINUX_CHECK=$(echo "${SYS_UNAME}"|grep velinux1)
    if [ "$VELINUX_CHECK" ];then
        echo -e "宝塔未兼容测试过velinux系统进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
        exit 1
    fi
    rockchip64_CHECK=$(echo "${SYS_UNAME}"|grep rockchip64)
    if [ "$rockchip64_CHECK" ];then
        echo -e "宝塔未兼容测试过rockchip64系统进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+服务器系统安装宝塔面板板"
        exit 1
    fi
    KALI_CHECK=$(echo "${SYS_UNAME}"|grep Kali)
    if [ "${KALI_CHECK}" ];then
        echo -e "宝塔未兼容测试过Kali系统进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
        exit 1
    fi
    ARMBIAN_CHECK=$(echo "${SYS_UNAME}"|grep Armbian)
    if [ "${ARMBIAN_CHECK}" ];then
        echo -e "宝塔未详细兼容测试过Armbian系统进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
        exit 1
    fi
    RJ3328_CHECK=$(echo "${SYS_UNAME}"|grep rk3328)
    if [ "${RJ3328_CHECK}" ];then
        echo -e "宝塔未兼容测试过电视盒子进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
        exit 1
    fi
    XIAOMI_CHECK=$(echo "${SYS_UNAME}"|grep xiaomi)
    if [ "${XIAOMI_CHECK}" ];then
        echo -e "宝塔未兼容测试过安卓手机进行安装"
        echo -e "建议更换至Centos-7或Debian-10+或Ubuntu-20+服务器系统安装宝塔面板板"
        exit 1
    fi
    UNOFFICIAL_CHECK=$(echo "${SYS_UNAME}"|grep unofficial)
    if [ "${UNOFFICIAL_CHECK}" ];then
        echo -e "宝塔未兼容测试过此系统环境下进行安装"
        echo -e "建议更换至服务器系统Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
        exit 1
    fi
    
    if [ -f "/etc/redhat-release" ];then
        LINUX_KIT_CHECK=$(echo "${SYS_UNAME}"|grep linuxkit)
        if [ "${LINUX_KIT_CHECK}" ];then
            echo -e "宝塔未兼容测试过linuxkit(docker)环境下进行安装"
            echo -e "建议更换至服务器系统Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
            exit 1
        fi
        OPENDCLOUD8_CHECK=$(cat /etc/redhat-release | grep -i 'OpenCloudOS' | grep -E '8\.')
        if [ "${OPENDCLOUD8_CHECK}" ];then
            echo -e "宝塔未兼容测试过OpenCloudOS-8环境下进行安装"
            echo -e "建议更换至服务器系统Centos-7或Debian-10+或Ubuntu-20+系统安装宝塔面板板"
            echo -e "也可以选择OpenCloudOS-9进行安装"
            exit 1
        fi
        BBR_CHECK=$(echo "${SYS_UNAME}"|grep bbrplus)
        if [ "${BBR_CHECK}" ];then
            echo -e "检测已使用bbr更新过内核，建议更新完内核在安装宝塔面板然后再安装软件"
            echo -e "或如需高版本内核，可使用Ubuntu-22/Debian-12进行安装宝塔面板"
            exit 1
        fi
        ELREPO_CHECK=$(echo "${SYS_UNAME}"|grep elrepo)
        if [ "${ELREPO_CHECK}" ];then
            echo -e "检测更新过内核，建议更新完内核在安装宝塔面板然后再安装软件"
            echo -e "或如需高版本内核，可使用Ubuntu-22/Debian-12进行安装宝塔面板"
            exit 1
        fi
    fi
    
    if [ "${PM}" == "apt-get" ];then
        UBUNTU_23_CHECK=$(cat /etc/issue|grep Ubuntu|grep 23)
        if [ "${UBUNTU_23_CHECK}" ];then
            echo -e "宝塔未兼容测试过Ubuntu-23（预览版）环境下进行安装"
            echo -e "建议更换至服务器系统Centos-7或Debian-12或Ubuntu-22系统安装宝塔面板板"
            exit 1
        fi
        POP_CHECK=$(cat /etc/issue|grep Pop)
        if [ "${POP_CHECK}" ];then
            echo -e "宝塔未兼容测试过Pop!_OS 环境下进行安装"
            echo -e "建议更换至服务器系统Centos-7或Debian-12或Ubuntu-22系统安装宝塔面板板"
            exit 1
        fi
    fi
    if [ "${i_make_args}" ];then
        echo -e "检测到使用自定义编译参数进行安装php"
        echo -e "请根据报错自行排查问题，或取消自定义编译参数重新安装"
        exit 1
    fi
	#Error_Send
	exit 1;
}
MD5_check(){
    \cp -rpa /www/server/php/${php_version}/bin/php /www/backup/php${php_version}.Bak
    \cp -rpa /www/server/php/${php_version}/sbin/php-fpm /www/backup/php-fpm${php_version}.Bak
    chmod -x /www/backup/php${php_version}.Bak
    chmod -x /www/backup/php-fpm${php_version}.Bak
    md5sum /www/server/php/${php_version}/bin/php > /www/server/panel/data/php${php_version}_md5.pl
    md5sum /www/server/php/${php_version}/sbin/php-fpm > /www/server/panel/data/php-fpm${php_version}_md5.pl
}
System_Lib(){
	if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ] ; then
		Centos8Check=$(cat /etc/redhat-release|grep ' 8.'|grep -i centos)
		CentosStream8Check=$(cat /etc/redhat-release |grep -i "Centos Stream"|grep 8)
		Opencloud8Check=$(cat /etc/redhat-release |grep -i 'OpenCloudOS'|grep '8.6')
		if [ "${Centos8Check}" ] || [ "${CentosStream8Check}" ] || [ "${Opencloud8Check}" ]; then
			yum config-manager --set-enabled PowerTools
			yum config-manager --set-enabled powertools
		fi
		${PM} install -y epel-release 2>/dev/null || true
		${PM} install -y perl-FindBin 2>/dev/null || true
		OptPack="libsodium-devel libmcrypt-devel autoconf automake libtool libssh2-devel pkg-config gettext gettext-devel brotli brotli-devel"
		Pack="perl gcc gcc-c++ make c-ares-devel libjpeg-devel libpng-devel curl-devel libcurl-devel libcurl-devel sqlite-devel krb5-devel oniguruma-devel libwebp-devel libvpx-devel libxml2-devel libcurl-devel openssl-devel gd-devel"
	elif [ "${PM}" == "apt-get" ]; then
		OptPack="libsodium-dev libmcrypt-dev libxml2 libxml2-devel libssh2-1-dev"
		Pack="perl gcc g++ cmake libfreetype6-dev libkrb5-dev libonig-dev libsqlite3-dev libcurl4-openssl-dev libwebp-dev libvpx-dev libpng-dev libc-ares-dev libssl-dev"
	fi
	${PM} install ${OptPack} -y 2>/dev/null || true
	${PM} install ${Pack} -y
	for chkPkg in ${OptPack} ${Pack}; do
		case "${PM}" in
			apt-get) dpkg -s "${chkPkg}" >/dev/null 2>&1 && continue ;;
			*)       rpm -q "${chkPkg}"   >/dev/null 2>&1 && continue ;;
		esac
		${PM} install -y ${chkPkg} >/dev/null 2>&1 && continue
		case " ${OptPack} " in
			*" ${chkPkg} "*) echo "  [依赖] 可选包不可用（已跳过）：${chkPkg}" ;;
			*) echo "  [依赖] ⚠ 必需包不可用，后续编译可能失败：${chkPkg}" ;;
		esac
	done

	if [ "${Centos7Check}" ] && { [ "${php_version}" == "81" ] || [ "${php_version}" == "82" ] || [ "${php_version}" == "83" ] || [ "${php_version}" == "84" ] || [ "${php_version}" == "85" ]; }; then
		if ! yum install devtoolset-8-gcc devtoolset-8-gcc-c++ -y; then
			echo "error： devtoolset-8 安装失败，后续将使用系统 gcc 编译（版本过低可能导致编译失败）"
		else
			DEVTOOLSET8_OK=1
		fi
	fi
}
Service_Add(){
	\cp ${php_setup_path}/src/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm-${php_version}
	sed -i "s/# Provides:          php-fpm/# Provides:          php-fpm-"${php_version}"/g" /etc/init.d/php-fpm-${php_version}
	chmod +x /etc/init.d/php-fpm-${php_version}
	if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ]; then
		chkconfig --add php-fpm-${php_version}
		chkconfig --level 2345 php-fpm-${php_version} on

	elif [ "${PM}" == "apt-get" ]; then
		update-rc.d php-fpm-${php_version} defaults
	fi

	if [ "$?" == "127" ];then
		wget -O /usr/lib/systemd/system/php-fpm-${php_version}.service ${download_Url}/init/systemd/php-fpm-${php_version}.service
		systemctl enable php-fpm-${php_version}.service
	fi

	/etc/init.d/php-fpm-${php_version} start 
}
Service_Del(){
	if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ]; then
		chkconfig --del php-fpm-${php_version}
		chkconfig --level 2345 php-fpm-${php_version} off
	elif [ "${PM}" == "apt-get" ]; then
		update-rc.d php-fpm-${php_version} remove
	fi
	if [ -f "/usr/lib/systemd/system/php-fpm-${php_version}.service" ];then
		systemctl disable php-fpm-${php_version}.service
	fi
	rm -f /etc/init.d/php-fpm-$php_version
}
Install_Openssl_1_0_2(){
	if [ ! -f "/usr/local/openssl/bin/openssl" ];then
		cd ${run_path}
		wget ${download_Url}/src/openssl-${opensslVersion}.tar.gz
		tar -zxf openssl-${opensslVersion}.tar.gz
		cd openssl-${opensslVersion}
		./config --openssldir=/usr/local/openssl zlib-dynamic shared
		make -j${cpuCore} 
		make install
		echo  "/usr/local/openssl/lib" > /etc/ld.so.conf.d/zopenssl.conf
		ldconfig
		cd ..
		rm -f openssl-${opensslVersion}.tar.gz
		rm -rf openssl-${opensslVersion}
	fi
}
Install_Openssl_1_1_1(){
	openssl111Check=$(openssl version |grep 1.1.1)
	if [ ! -f "/usr/local/openssl111/bin/openssl" ] && [ -z "${openssl111Check}" ];then
		cd ${run_path}
		wget ${download_Url}/src/openssl-${openssl111Version}.tar.gz -T 20
		tar -zxf openssl-${openssl111Version}.tar.gz
		rm -f openssl-${openssl111Version}.tar.gz
		cd openssl-${openssl111Version}
		./config --prefix=/usr/local/openssl111 --openssldir=/usr/local/openssl111 enable-md2 enable-rc5 sctp zlib-dynamic shared -fPIC
		make -j${cpuCore}
		make install
		[ $? -ne 0 ] && Error_Msg
		echo "/usr/local/openssl111/lib" >> /etc/ld.so.conf.d/zopenssl111.conf
		ldconfig
		cd ..
		rm -rf openssl-${openssl111Version} 
	fi
}
Install_Curl(){
	if [ "${PM}" == "yum" ];then
		CURL_OPENSSL_LIB_VERSION=$(/usr/local/curl/bin/curl -V|grep -oE OpenSSL.*[0-9][a-z]|cut -f 2 -d "/")
		OPENSSL_LIB_VERSION=$(/usr/local/openssl/bin/openssl version|awk '{print $2}')
	fi
	if [ ! -f "/usr/local/curl/bin/curl" ] || [ "${CURL_OPENSSL_LIB_VERSION}" != "${OPENSSL_LIB_VERSION}" ];then
		wget ${download_Url}/src/curl-${curlVersion}.tar.gz
		tar -zxf curl-${curlVersion}.tar.gz
		cd curl-${curlVersion}
		rm -rf /usr/local/curl	
		./configure --prefix=/usr/local/curl --enable-ares --without-nss --with-ssl=/usr/local/openssl
		make -j${cpuCore}
		make install
		cd ..
		rm -f curl-${curlVersion}.tar.gz
		rm -rf curl-${curlVersion}
	fi
}
Install_Curl_New(){
	if [ ! -f "/usr/local/curl_2/bin/curl" ];then
		curlVersion="7.74.0"
		wget ${download_Url}/src/curl-${curlVersion}.tar.gz
		tar -zxf curl-${curlVersion}.tar.gz
		cd curl-${curlVersion}
		rm -rf /usr/local/curl_2
		./configure --prefix=/usr/local/curl_2 --enable-ldap --enable-ldaps --with-brotli --with-libssh2 --with-libssh --enable-ares --with-gssapi --without-nss --enable-smb --with-libidn2 --with-ssl=/usr/local/openssl111
		[ $? -ne 0 ] && Error_Msg
		make -j${cpuCore}
		if [ $? -ne 0 ];then
			make clean
			./configure --prefix=/usr/local/curl_2 --disable-ldap --disable-ldaps --with-brotli --with-libssh2 --with-libssh --enable-ares --with-gssapi --without-nss --enable-smb --with-libidn2 --with-ssl=/usr/local/openssl111
			make -j${cpuCore}
		fi
		make install
		cd ..
		rm -f curl-${curlVersion}.tar.gz
		rm -rf curl-${curlVersion}
	fi
}
Install_Curl2(){
	LibCurlVer=$(/usr/local/curl/bin/curl -V|grep curl|awk '{print $2}'|cut -d. -f2)
	if [[ "${LibCurlVer}" -le "60" ]]; then
		if [ ! -f "/usr/local/curl2/bin/curl" ];then
			curlVer="7.64.1"
			wget ${download_Url}/src/curl-${curlVer}.tar.gz
			tar -xvf curl-${curlVer}.tar.gz
			cd curl-${curlVer}
			./configure --prefix=/usr/local/curl2 --enable-ares --without-nss --with-ssl=/usr/local/openssl
			make -j${cpuCore}
			make install
			cd ..
			rm -rf curl*
		fi
	fi
}
Install_Icu4c(){
	cd ${run_path}
	if [ -f "/usr/bin/icu-config" ];then
		icu4cVer=$(/usr/bin/icu-config --version 2>/dev/null|cut -d '.' -f 1|tr -cd '0-9')
	fi
	icu4cVer=${icu4cVer:-0}
	if [ ! -f "/usr/bin/icu-config" ] || [ "${icu4cVer}" -gt "60" ];then
		wget -O icu4c-60_3-src.tgz ${download_Url}/src/icu4c-60_3-src.tgz
		tar -xvf icu4c-60_3-src.tgz
		cd icu/source
		./configure --prefix=/usr/local/icu
		make -j${cpuCore}
		make install
		[ -f "/usr/bin/icu-config" ] && mv /usr/bin/icu-config /usr/bin/icu-config.bak 
		ln -sf /usr/local/icu/bin/icu-config /usr/bin/icu-config
		echo "/usr/local/icu/lib" > /etc/ld.so.conf.d/zicu.conf
		ldconfig
		cd ../../
		rm -rf icu
		rm -f icu4c-60_3-src.tgz 
	fi
}
Install_Libzip(){
	if [ "${PM}" == "yum" ];then
		el=$(cat /etc/redhat-release|grep -iE 'CentOS|Red Hat'|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '^[0-9]')
		if [ "${el}" == "7" ];then
		    yum install cmake3 -y
			rpm -q libzip5-devel > /dev/null
			if [ "$?" -ne "0" ];then
				mkdir libzip
				cd libzip
				wget -O libzip5-1.5.2.rpm ${download_Url}/rpm/remi/${el}/libzip5-1.5.2.rpm
				wget -O libzip5-devel-1.5.2.rpm ${download_Url}/rpm/remi/${el}/libzip5-devel-1.5.2.rpm
				wget -O libzip5-tools-1.5.2.rpm ${download_Url}/rpm/remi/${el}/libzip5-tools-1.5.2.rpm
				yum install * -y
				cd ..
				rm -rf libzip
			fi
		else
			libzipVerCheck=$(yum list libzip|grep libzip|awk 'NR==1 {printf("%d",$2)}')
			if [ "${libzipVerCheck}" -ge "1" ];then
				yum install -y libzip-devel
			fi
		fi
	elif [ "${PM}" == "apt-get" ];then
		apt-get install libzip-dev -y
	fi
	
	LIBZIP_CHECK=$(pkg-config --list-all|grep libzip)
	if [ -z "${LIBZIP_CHECK}" ] ;then
		wget -O libzip-1.10.1.tar.gz ${download_Url}/src/libzip-1.10.1.tar.gz
		tar -xvf libzip-1.10.1.tar.gz
		cd libzip-1.10.1
		if [ -f "/usr/bin/cmake3" ];then
			cmake3 -DCMAKE_INSTALL_PREFIX=/usr/local/libzip
		else
			cmake -DCMAKE_INSTALL_PREFIX=/usr/local/libzip
		fi
		make
		make install
		cd ..
		rm -rf libzip-1.10.1
		rm -f libzip-1.10.1.tar.gz
	fi
	
	autoconfVer=$(autoconf -V|grep 'GNU Autoconf'|awk '{print $4}'|grep -oE .[0-9]+|grep -oE [0-9]+)
	if [ "${autoconfVer}" -lt "69" ]; then
		wget ${download_Url}/src/autoconf-2.69.tar.gz
		tar -xvf autoconf-2.69.tar.gz
		cd autoconf-2.69
		./configure --prefix=/usr
		make && make install
		cd ..
		rm -rf autoconf*
	fi

}
Install_Onig(){
	onigCheck=$(pkg-config --list-all|grep onig)
	if [ -z "${onigCheck}" ];then
		cd ${run_path}
		onigVer="6.9.6"
		wget -O onig-${onigVer}.tar.gz ${download_Url}/src/onig-${onigVer}.tar.gz
		tar  -xvf onig-${onigVer}.tar.gz
		cd onig-${onigVer}
		./configure --prefix=/usr/local/onig
		make -j${cpuCore}
		make install
		cd ..
		rm -rf onig-${onigVer}*
	fi
}
Install_Libsodium(){
	sodiumCheck=$(pkg-config --list-all|grep libsodium)
	if [ ! -f "/usr/local/libsodium/lib/libsodium.so" ];then
		cd ${run_path}
		libsodiumVer="1.0.18"
		wget ${download_Url}/src/libsodium-${libsodiumVer}-stable.tar.gz
		tar -xvf libsodium-${libsodiumVer}-stable.tar.gz
		rm -f libsodium-${libsodiumVer}-stable.tar.gz
		cd libsodium-stable
		./configure --prefix=/usr/local/libsodium
		make -j${cpuCore}
		make install
		cd ..
		rm -f libsodium-${libsodiumVer}-stable.tar.gz
		rm -rf libsodium-stable
	fi
	if [ "${php_version}" == "73" ];then
		if [ "${PM}" == "apt-get" ]; then
			GET_LIBSODIUM_VER=$(dpkg -l |grep libsodium-dev|awk '{print $3}'|cut -d '.' -f3|cut -d '-' -f1)
			if [ "${GET_LIBSODIUM_VER}" -lt "15" ];then
				apt-get remove -y libsodium-dev
			fi
		fi
	fi
}
Create_Fpm(){
	PHP_PM_TYPE="dynamic"
	MemTotal=`free -m | grep Mem | awk '{print  $2}'`
	if [ "${MemTotal}" ];then
		if [ "${MemTotal}" -le 2200 ];then
			PHP_PM_TYPE="ondemand"
		fi
	fi
	cat >${php_setup_path}/etc/php-fpm.conf<<EOF
[global]
pid = ${php_setup_path}/var/run/php-fpm.pid
error_log = ${php_setup_path}/var/log/php-fpm.log
log_level = notice

[www]
listen = /tmp/php-cgi-${php_version}.sock
listen.backlog = -1
listen.allowed_clients = 127.0.0.1
listen.owner = www
listen.group = www
listen.mode = 0600
user = www
group = www
pm = ${PHP_PM_TYPE}
pm.status_path = /phpfpm_${php_version}_status
pm.max_children = 30
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
request_terminate_timeout = 100
request_slowlog_timeout = 30
slowlog = var/log/slow.log
EOF
}
Set_PHP_FPM_Opt(){
	MemTotal=`free -m | grep Mem | awk '{print  $2}'`
	if [[ ${MemTotal} -gt 1024 && ${MemTotal} -le 2048 ]]; then
		sed -i "s#pm.max_children.*#pm.max_children = 30#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.start_servers.*#pm.start_servers = 5#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.min_spare_servers.*#pm.min_spare_servers = 5#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.max_spare_servers.*#pm.max_spare_servers = 10#" ${php_setup_path}/etc/php-fpm.conf
	elif [[ ${MemTotal} -gt 2048 && ${MemTotal} -le 4096 ]]; then
		sed -i "s#pm.max_children.*#pm.max_children = 50#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.start_servers.*#pm.start_servers = 5#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.min_spare_servers.*#pm.min_spare_servers = 5#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.max_spare_servers.*#pm.max_spare_servers = 20#" ${php_setup_path}/etc/php-fpm.conf
	elif [[ ${MemTotal} -gt 4096 && ${MemTotal} -le 8192 ]]; then
		sed -i "s#pm.max_children.*#pm.max_children = 100#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.start_servers.*#pm.start_servers = 10#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.min_spare_servers.*#pm.min_spare_servers = 10#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.max_spare_servers.*#pm.max_spare_servers = 30#" ${php_setup_path}/etc/php-fpm.conf
	elif [[ ${MemTotal} -gt 8192 && ${MemTotal} -le 16384 ]]; then
		sed -i "s#pm.max_children.*#pm.max_children = 150#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.start_servers.*#pm.start_servers = 15#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.min_spare_servers.*#pm.min_spare_servers = 15#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.max_spare_servers.*#pm.max_spare_servers = 30#" ${php_setup_path}/etc/php-fpm.conf
	elif [[ ${MemTotal} -gt 16384 ]]; then
		sed -i "s#pm.max_children.*#pm.max_children = 300#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.start_servers.*#pm.start_servers = 20#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.min_spare_servers.*#pm.min_spare_servers = 20#" ${php_setup_path}/etc/php-fpm.conf
		sed -i "s#pm.max_spare_servers.*#pm.max_spare_servers = 50#" ${php_setup_path}/etc/php-fpm.conf
	fi
	sed -i "s#listen.backlog.*#listen.backlog = 8192#" ${php_setup_path}/etc/php-fpm.conf
}
Set_Phpini(){

	sed -i 's/post_max_size =.*/post_max_size = 50M/g' ${php_setup_path}/etc/php.ini
	sed -i 's/upload_max_filesize =.*/upload_max_filesize = 50M/g' ${php_setup_path}/etc/php.ini
	sed -i 's/;date.timezone =.*/date.timezone = PRC/g' ${php_setup_path}/etc/php.ini
	sed -i 's/short_open_tag =.*/short_open_tag = On/g' ${php_setup_path}/etc/php.ini
	sed -i 's/;cgi.fix_pathinfo=.*/cgi.fix_pathinfo=1/g' ${php_setup_path}/etc/php.ini
	sed -i 's/max_execution_time =.*/max_execution_time = 300/g' ${php_setup_path}/etc/php.ini
	sed -i 's/;sendmail_path =.*/sendmail_path = \/usr\/sbin\/sendmail -t -i/g' ${php_setup_path}/etc/php.ini
	sed -i 's/disable_functions =.*/disable_functions = passthru,exec,system,putenv,chroot,chgrp,chown,shell_exec,popen,proc_open,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv/g' ${php_setup_path}/etc/php.ini
	sed -i 's/display_errors = Off/display_errors = On/g' ${php_setup_path}/etc/php.ini
	sed -i 's/error_reporting =.*/error_reporting = E_ALL \& \~E_NOTICE/g' ${php_setup_path}/etc/php.ini

	if [ "${php_version}" = "52" ]; then
		sed -i "s#extension_dir = \"./\"#extension_dir = \"${php_setup_path}/lib/php/extensions/no-debug-non-zts-20060613/\"\n#" ${php_setup_path}/etc/php.ini
		sed -i 's#output_buffering =.*#output_buffering = On#' ${php_setup_path}/etc/php.ini
		sed -i 's/; cgi.force_redirect = 1/cgi.force_redirect = 0;/g' ${php_setup_path}/etc/php.ini
		sed -i 's/; cgi.redirect_status_env = ;/cgi.redirect_status_env = "yes";/g' ${php_setup_path}/etc/php.ini
	fi

	if [ "${php_version}" -ge "56" ]; then
		if [ -f "/etc/pki/tls/certs/ca-bundle.crt" ];then
			crtPath="/etc/pki/tls/certs/ca-bundle.crt"
		elif [ -f "/etc/ssl/certs/ca-certificates.crt" ]; then
			crtPath="/etc/ssl/certs/ca-certificates.crt"
		fi
		sed -i "s#;openssl.cafile=#openssl.cafile=${crtPath}#" ${php_setup_path}/etc/php.ini
		sed -i "s#;curl.cainfo =#curl.cainfo = ${crtPath}#" ${php_setup_path}/etc/php.ini
	fi

	sed -i 's/expose_php = On/expose_php = Off/g' ${php_setup_path}/etc/php.ini
	
}
Ln_PHP_Bin(){
	rm -f /usr/bin/php*
	rm -f /usr/bin/pear
	rm -f /usr/bin/pecl

    ln -sf ${php_setup_path}/bin/php /usr/bin/php
    ln -sf ${php_setup_path}/bin/phpize /usr/bin/phpize
    ln -sf ${php_setup_path}/bin/pear /usr/bin/pear
    ln -sf ${php_setup_path}/bin/pecl /usr/bin/pecl
    ln -sf ${php_setup_path}/sbin/php-fpm /usr/bin/php-fpm
}
Pear_Pecl_Set(){
 	if [ "${php_version}" -le "73" ];then
		pear config-set php_ini ${php_setup_path}/etc/php.ini
		pecl config-set php_ini ${php_setup_path}/etc/php.ini
	fi
}
Install_Composer(){
	if [ ! -f "/usr/bin/composer" ];then
		wget -O /usr/bin/composer ${download_Url}/install/src/composer.phar -T 20;
		chmod +x /usr/bin/composer
	fi
}
Download_Src(){
	php_setup_path="/www/server/php/${php_version}"
	mkdir -p ${php_setup_path}
	if [ "${actionType}" == "install" ];then
		/etc/init.d/php-fpm-$php_version stop
		rm -rf ${php_setup_path}/*
	fi
	
	cd ${php_setup_path}
	rm -rf ${php_setup_path}/src

	wget -O src.tar.gz ${download_Url}/src/php-${phpVersion}.tar.gz
	tar -xvf src.tar.gz
	mv php-${phpVersion} src
	chown -R root:root src

	if [ "${php_version}" == "53" ];then
		rm -rf /patch
		mkdir -p /patch
		cd src
		wget -O /patch/php-5.3-multipart-form-data.patch ${download_Url}/src/patch/php-5.3-multipart-form-data.patch -T20
		patch -p1 < /patch/php-5.3-multipart-form-data.patch
	fi
}
Fix_CentOS_Stream_10(){
    if [ "${CentOS_Stream_10_Check}" ] && [ "${php_version}" -ge "70" ] && [ "${php_version}" -le "80" ]; then
        libxmlFile="/www/server/php/${php_version}/src/ext/libxml/libxml.c"
        if [ -f "${libxmlFile}" ]; then
            sed -i "s/\<xmlErrorPtr\>/const xmlError */g" "${libxmlFile}"
        fi

        domIterFile="/www/server/php/${php_version}/src/ext/dom/dom_iterators.c"
        if [ -f "${domIterFile}" ]; then
            sed -i '45s/xmlChar \*name/const xmlChar *name/' "${domIterFile}"
        fi
    fi
    
    if [ "${CentOS_Stream_10_Check}" ] && [ "${php_version}" -ge "70" ] && [ "${php_version}" -le "73" ]; then
        reentrancyFile="/www/server/php/${php_version}/src/main/reentrancy.c"
        if [ -f "${reentrancyFile}" ]; then
            sed -i 's/readdir_r(dirp, entry);/readdir_r(dirp, entry, result);/' "${reentrancyFile}"
        fi
        
        zipMkstempFile="/www/server/php/${php_version}/src/ext/zip/lib/mkstemp.c"
        if [ -f "${zipMkstempFile}" ]; then
            grep -q '^#include <unistd.h>' "${zipMkstempFile}" || sed -i '1i #include <unistd.h>' "${zipMkstempFile}"
        fi

        castFile="/www/server/php/${php_version}/src/main/streams/cast.c"
        if [ -f "${castFile}" ]; then
            perl -0pi -e 's@static int stream_cookie_seeker\(void \*cookie, [^,]+ position, int whence\)@static int stream_cookie_seeker(void *cookie, off64_t *position, int whence)@' "${castFile}"
            perl -0pi -e 's@return php_stream_seek\(\(php_stream \*\)cookie, position, whence\);@*position = php_stream_seek((php_stream *)cookie, (off_t)*position, whence);

	if (*position == -1)
		return -1;
	return 0;@' "${castFile}"
        fi
    fi
}
Install_Configure(){
	aarch64Check=$(uname -a|grep aarch64)
	if [ "${aarch64Check}" ];then
		CONFIGURE_BUILD_TYPE="--build=arm-linux"
		if [ "${php_version}"  == "55" ];then 
			wget -O /www/server/php/55/src/Zend/zend_multiply.h ${download_Url}/patch/php/php_55_zend_multiply.h
		elif [ "${php_version}"  == "56" ];then
			wget -O /www/server/php/56/src/Zend/zend_multiply.h ${download_Url}/patch/php/php_56_zend_multiply.h
		fi
	fi

	Fix_CentOS_Stream_10


	if [ "${php_version}" == "71" ] || [ "${php_version}" == "72" ] || [ "${php_version}" == "73" ];then
		export CXX="g++ -DTRUE=1 -DFALSE=0"
		export CC="gcc -DTRUE=1 -DFALSE=0"
	
        if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ] ; then
            icu_v=$(rpm -q icu |cut -f 2 -d "-" |cut -d '.' -f1)
        elif [ "${PM}" == "apt-get" ]; then
            icu_v=$(dpkg -l|grep -oE libicu[0-9][0-9]|grep -oE [0-9][0-9])
        fi
        
	    UBUNTU_24=$(cat /etc/issue|grep Ubuntu|grep 24)
		DEBIAN_12_C=$(cat /etc/issue|grep Debian|grep 12)
		OC9=$(cat /etc/os-release |grep "OpenCloudOS 9")
        if { [ "${icu_v}" -gt "70" ] && [ -z "${USE_GCC_13}" ]; } || [ "${DEBIAN_12_C}" ] || [ "${UBUNTU_24}" ] ||  [ "${OC9}" ];then
            wget -O /www/server/php/${php_version}/src/ext/intl/breakiterator/codepointiterator_internal.cpp https://download.bt.cn//patch/php/debian-12-php-71-codepointiterator_internal.cpp
            wget -O /www/server/php/${php_version}/src/ext/intl/breakiterator/codepointiterator_internal.h https://download.bt.cn//patch/php/debian-12-php-71-codepointiterator_internal.h
        fi
	fi 

	if [ "${USE_GCC_13}" ] && [ "${php_version}" -ge "71" ];then
		export PKG_CONFIG_PATH=/usr/local/icu/lib/pkgconfig:$PKG_CONFIG_PATH
		export CC="/usr/bin/gcc-13"
		export CXX="/usr/bin/g++-13"
	fi

	if [ "${php_version}" -ge "73" ];then
		Install_Libzip
		Install_Onig
		Install_Libsodium
		Install_Curl2
		if [ -f "/usr/local/curl2/bin/curl" ]; then
			withCurl="/usr/local/curl2"
		else
			withCurl="/usr/local/curl"
		fi

		if [ -f "/usr/local/openssl111/bin/openssl" ];then
			 curlOpensslLIB=$(${withCurl}/bin/curl -V 2>/dev/null|grep -oE 'OpenSSL/[^ ]+'|cut -d '/' -f 2)
			 openssl111Ver=$(/usr/local/openssl111/bin/openssl version 2>/dev/null|awk '{print $2}')
			 if [ -n "${curlOpensslLIB}" ] && [ "${curlOpensslLIB}" == "${openssl111Ver}" ];then
			 	withOpenssl="/usr/local/openssl111"
			 else
			 	withOpenssl="/usr/local/openssl"
			 fi
		else
			withOpenssl="/usr/local/openssl"
		fi

		# PHP 7.4 的 ext/openssl 不兼容 OpenSSL 3.x（EC_KEY_*/RSA_*/DSA_*/DH_* 等接口在 3.0 已废弃，
		# 直接编译失败），因此与 8.5 一致：7.4 固定使用 openssl111 + 与之配套的 curl_2 编译
		if [ "${php_version}" == "74" ];then
			if [ ! -f "/usr/local/openssl111/bin/openssl" ];then
				if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ] ; then
					yum install lksctp-tools-devel brotli-devel libssh2-devel -y
				elif [ "${PM}" == "apt-get" ]; then
					apt-get install libsctp-dev libbrotli-dev libssh2-1-dev -y
				fi
				Install_Openssl_1_1_1
			fi
			if [ -f "/usr/local/openssl111/bin/openssl" ];then
				if ! grep -qs "/usr/local/openssl111/lib" /etc/ld.so.conf.d/zopenssl111.conf 2>/dev/null; then
					echo "/usr/local/openssl111/lib" >> /etc/ld.so.conf.d/zopenssl111.conf
					ldconfig
				fi
				withOpenssl="/usr/local/openssl111"
				Install_Curl_New
				if [ -f "/usr/local/curl_2/bin/curl" ];then
					withCurl="/usr/local/curl_2"
				fi
			fi
		fi

		if [ "${php_version}" -ge "80" ];then
			opensslCheck=$(openssl version |grep 1.1.1)
			if [ -z "${opensslCheck}" ]; then
				if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ] ; then
					yum install lksctp-tools-devel brotli-devel libssh2-devel -y
				elif [ "${PM}" == "apt-get" ]; then
					apt-get install libsctp-dev libbrotli-dev libssh2-1-dev -y
				fi
				Install_Openssl_1_1_1
				Install_Curl_New
				withOpenssl="/usr/local/openssl111"
				withCurl="/usr/local/curl_2"
			else
				withOpenssl=""
				withCurl=""
			fi
		fi
	fi

	[ "${UBUNTU_22}" ] && WITH_ICU_DIR="--with-icu-dir=/usr/local/icu"
	
	if [ "${DEVTOOLSET8_OK}" ];then
		cmakeV="cmake3"
		export CC=/opt/rh/devtoolset-8/root/usr/bin/gcc
		export CXX=/opt/rh/devtoolset-8/root/usr/bin/g++
	fi

	cd ${php_setup_path}/src
	if [ "${php_version}" == "81" ] || [ "${php_version}" == "80" ] || [ "${php_version}" == "74" ] || [ "${php_version}" == "73" ] || [ "${php_version}" == "72" ] || [ "${php_version}" == "71" ] || [ "${php_version}" == "70" ]; then
		./buildconf --force
	fi
	if [ "${php_version}" == "53" ]; then
		./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype-dir=/usr/local/freetype --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-magic-quotes --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl=/usr/local/curl --enable-mbregex --enable-mbstring --with-mcrypt --enable-ftp --with-gd --enable-gd-native-ttf --with-openssl=/usr/local/openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-gettext --disable-fileinfo ${CONFIGURE_BUILD_TYPE} ${i_make_args} 2>&1|tee /tmp/php_config.pl
	elif [ "${php_version}" -le "56" ];then
		[ "${php_version}" -gt "54" ] && ENABLE_OPCACHE="--enable-opcache" ENABLE_WEBP="--with-vpx-dir"
		./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype-dir=/usr/local/freetype --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl=/usr/local/curl --enable-mbregex --enable-mbstring --with-mcrypt --enable-ftp --with-gd --enable-gd-native-ttf --with-openssl=/usr/local/openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-gettext --disable-fileinfo --enable-intl ${ENABLE_WEBP} ${ENABLE_OPCACHE} ${CONFIGURE_BUILD_TYPE} ${i_make_args} 2>&1|tee /tmp/php_config.pl
	elif [ "${php_version}" -le "72" ]; then
		[ "${php_version}" -lt "72" ] && ENABLE_MCRYPT="--with-mcrypt"
		./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype-dir=/usr/local/freetype --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl=/usr/local/curl --enable-mbregex --enable-mbstring --enable-intl --enable-pcntl --enable-ftp --with-gd --enable-gd-native-ttf --with-openssl=/usr/local/openssl --with-mhash --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-gettext --disable-fileinfo --enable-opcache --with-webp-dir=/usr ${ENABLE_MCRYPT} ${WITH_ICU_DIR} ${i_make_args} 2>&1|tee /tmp/php_config.pl
	elif [ "${php_version}" == "73" ]; then
		./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype-dir=/usr/local/freetype --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl=${withCurl} --enable-mbregex --enable-mbstring --enable-intl --enable-pcntl --enable-ftp --with-gd --with-openssl=${withOpenssl} --with-mhash --enable-sockets --with-xmlrpc  --enable-soap --with-gettext --disable-fileinfo --enable-opcache --with-sodium=/usr/local/libsodium --with-webp-dir=/usr ${WITH_ICU_DIR} ${i_make_args} 2>&1|tee /tmp/php_config.pl
	elif [ "${php_version}" == "74" ] || [ "${php_version}" -ge "80" ]; then
		ALI_OS=$(cat /etc/redhat-release |grep "Alibaba Cloud Linux release 3")
		onigCheck=$(pkg-config --list-all 2>/dev/null|grep onig)
		sodiumCheck=$(pkg-config --list-all 2>/dev/null|grep libsodium)
		if [ -z "${onigCheck}" ] || [ -z "${sodiumCheck}" ] || [ "${ALI_OS}" ];then
			export PKG_CONFIG_PATH="/usr/local/onig/lib/pkgconfig:/usr/local/libsodium/lib/pkgconfig:$PKG_CONFIG_PATH"
		fi

		if [  "${withOpenssl}" ] && [ "${php_version}" -le "82" ];then
			export PKG_CONFIG_PATH="${withCurl}/lib/pkgconfig:${withOpenssl}/lib/pkgconfig:$PKG_CONFIG_PATH"

		fi

		if [ "${aarch64Check}" ];then
			if [ "${Centos7Check}" ];then
				sed -i "s/ZEND_USE_ASM_ARITHMETIC 1/ZEND_USE_ASM_ARITHMETIC 0/" Zend/zend_operators.h
			fi
		fi
        if [ "${php_version}" == "83" ] || [ "${php_version}" == "84" ] || [ "${php_version}" == "85" ];then
			PHP_OPENSSL_CONFIG="--with-openssl"
			if [ "${Centos7Check}" ] && [ "${php_version}" == "83" ] && [ "${withOpenssl}" ];then
				PHP_OPENSSL_CONFIG="--with-openssl=${withOpenssl}"
				export CPPFLAGS="-I${withOpenssl}/include ${CPPFLAGS}"
				export LDFLAGS="-L${withOpenssl}/lib ${LDFLAGS}"
			fi			
			ENABLE_MBSTRING_CONFIG=""
			binutils_minor_ver=$(ld --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -n1|cut -f 2 -d '.')
			if [ -z "${binutils_minor_ver}" ] || [ "${binutils_minor_ver}" -lt "31" ];then
				ENABLE_MBSTRING_CONFIG="--enable-mbstring=shared"
				MBSTRING_SHARED="True"
			else
				ENABLE_MBSTRING_CONFIG="--enable-mbstring"
			fi
		    ./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype --with-jpeg --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex ${ENABLE_MBSTRING_CONFIG} --enable-intl --enable-pcntl --enable-ftp --enable-gd ${PHP_OPENSSL_CONFIG} --with-mhash --enable-sockets --with-xmlrpc  --enable-soap --with-gettext --disable-fileinfo --enable-opcache --with-sodium=/usr/local/libsodium --with-webp ${i_make_args} 2>&1|tee /tmp/php_config.pl
		else
			PHP_OPENSSL_CONFIG="--with-openssl"
			PHP_CURL_CONFIG="--with-curl"
			if [ "${php_version}" == "74" ] && [ -f "/usr/local/openssl111/bin/openssl" ];then
				PHP_OPENSSL_CONFIG="--with-openssl=/usr/local/openssl111"
				export CPPFLAGS="-I/usr/local/openssl111/include ${CPPFLAGS}"
				export LDFLAGS="-L/usr/local/openssl111/lib ${LDFLAGS}"
				if [ -f "/usr/local/curl_2/bin/curl" ];then
					PHP_CURL_CONFIG="--with-curl=/usr/local/curl_2"
				fi
			fi
		    ./configure --prefix=${php_setup_path} --with-config-file-path=${php_setup_path}/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-iconv-dir --with-freetype --with-jpeg --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization ${PHP_CURL_CONFIG} --enable-mbregex --enable-mbstring --enable-intl --enable-pcntl --enable-ftp --enable-gd ${PHP_OPENSSL_CONFIG} --with-mhash --enable-sockets --with-xmlrpc  --enable-soap --with-gettext --disable-fileinfo --enable-opcache --with-sodium=/usr/local/libsodium --with-webp ${i_make_args} 2>&1|tee /tmp/php_config.pl
		fi
	fi

	if [ "${php_version}" == "70" ] || [ "${php_version}" == "71" ];then
		phpConfigFile="/www/server/php/${php_version}/src/main/php_config.h"
		if [ -f "${phpConfigFile}" ];then
			perl -0pi -e 's@^int zend_sprintf\(char \*buffer, const char \*format, \.\.\.\);\s*$@#ifdef __cplusplus
extern "C" {
#endif
int zend_sprintf(char *buffer, const char *format, ...);
#ifdef __cplusplus
}
#endif@m' "${phpConfigFile}"
		fi
	fi

	if [ "${is64bit}" = "32" ];then
		sed -i 's/lcrypt$/lcrypt -lresolv/' Makefile
	fi

	make ZEND_EXTRA_LIBS='-liconv' -j${cpuCore} 2>&1|tee /tmp/php_make.pl
}
Install_PHP(){
	if [ "${actionType}" == "update" ]; then
		/etc/init.d/php-fpm-${php_version} stop
		sleep 2
		make install
		if [ $? -ne 0 ]; then
			/etc/init.d/php-fpm-${php_version} start >/dev/null 2>&1
			Error_Msg
		fi
		sleep 1
		/etc/init.d/php-fpm-${php_version} start
		echo "${phpVersion}" > ${php_setup_path}/version.pl
		rm -f ${php_setup_path}/version_check.pl
		rm -f ${php_setup_path}/src.tar.gz
		rm -rf ${php_setup_path}/src/Zend
		MD5_check
		echo '|-Successify --- 命令已执行! ---'
		exit 0;
	fi
	make install 2>&1|tee /tmp/php_install.pl

	[ ! -f "${php_setup_path}/bin/php" ] && Error_Msg
	
	mkdir -p ${php_setup_path}/etc
	\cp php.ini-production ${php_setup_path}/etc/php.ini
	MD5_check
}
Install_Zip_ext(){
	if [ -f "/usr/local/libzip/lib64/libzip.so" ];then
		export PKG_CONFIG_PATH="/usr/local/libzip/lib64/pkgconfig:$PKG_CONFIG_PATH"
	fi
	cd ${php_setup_path}/src/ext/zip
	${php_setup_path}/bin/phpize
	./configure --with-php-config=${php_setup_path}/bin/php-config
	make && make install
	cd ../../

	if [ "${php_version}" == "73" ];then
		extFile="/www/server/php/73/lib/php/extensions/no-debug-non-zts-20180731/zip.so"
	elif [ "${php_version}" == "74" ]; then
		extFile="/www/server/php/74/lib/php/extensions/no-debug-non-zts-20190902/zip.so"
	elif [ "${php_version}" == "80" ]; then
		extFile="/www/server/php/80/lib/php/extensions/no-debug-non-zts-20200930/zip.so"
	elif [ "${php_version}" == "81" ]; then
		extFile="/www/server/php/81/lib/php/extensions/no-debug-non-zts-20210902/zip.so"
	elif [ "${php_version}" == "82" ]; then
		extFile="/www/server/php/82/lib/php/extensions/no-debug-non-zts-20220829/zip.so"
	elif [ "${php_version}" == "83" ];then
		extFile="/www/server/php/83/lib/php/extensions/no-debug-non-zts-20230831/zip.so"
	elif [ "${php_version}" == "84" ];then
		extFile="/www/server/php/84/lib/php/extensions/no-debug-non-zts-20240924/zip.so"
	elif [ "${php_version}" == "85" ];then
		extFile="/www/server/php/85/lib/php/extensions/no-debug-non-zts-20250925/zip.so"
	fi

	if [ -f "${extFile}" ];then
		echo "extension = zip.so" >> ${php_setup_path}/etc/php.ini
	fi

	if [ ${MBSTRING_SHARED} ];then
		extFile=$(echo "${extFile/zip.so/mbstring.so}")
		if [ -f "${extFile}" ];then
			echo "extension = mbstring.so" >> ${php_setup_path}/etc/php.ini
		fi
	fi
}
Install_Zend(){
	mkdir -p /usr/local/zend/php${php_version}
	if [ "${php_version}" -lt "70" ];then
		echo "Install ZendGuardLoader for PHP ${version}"
		echo "unavailable now."
		echo "Write ZendGuardLoader to php.ini..."
		wget -O php-ZendGuardLoader.tar.gz ${download_Url}/src/php-ZendGuardLoader.tar.gz
		tar -xvf php-ZendGuardLoader.tar.gz > /dev/null
		mv zend/ZendGuardLoader-${php_version}-${is64bit}.so /usr/local/zend/php${php_version}/ZendGuardLoader.so
		rm -f php-ZendGuardLoader.tar.gz
		rm -rf zend
			cat >>${php_setup_path}/etc/php.ini<<EOF
;eaccelerator

;ionCube

;opcache

[Zend ZendGuard Loader]
zend_extension=/usr/local/zend/php${php_version}/ZendGuardLoader.so
zend_loader.enable=1
zend_loader.disable_licensing=0
zend_loader.obfuscation_level_support=3
zend_loader.license_path=

;xcache
EOF
	else
		echo ";ionCube" >> ${php_setup_path}/etc/php.ini
		echo ";opcache" >> ${php_setup_path}/etc/php.ini
	fi
}
Download_Conf(){
	if [ ! -f "/www/server/nginx/conf/enable-php-${php_version}.conf" ];then
		wget -O /www/server/nginx/conf/enable-php-${php_version}.conf ${download_Url}/conf/enable-php-${php_version}.conf
	fi
    for phpV in 52 53 54 55 56 70 71 72 73 74 80 81 82 83 84 85; do
    if [ ! -f "/www/server/nginx/conf/enable-php-${phpV}.conf" ];then
        cat >/www/server/nginx/conf/enable-php-${phpV}.conf <<EOF
    location ~ [^/]\.php(/|$)
    {
        try_files \$uri =404;
        fastcgi_pass  unix:/tmp/php-cgi-${phpV}.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
        include pathinfo.conf;
    }
EOF
    fi
    done
}
SetPHPMyAdmin(){
	if [ -f "/www/server/nginx/sbin/nginx" ]; then
		webserver="nginx"
	fi
	PHPVersion=""
	for phpV in 52 53 54 55 56 70 71 72 73 74 80 81 82 83 84 85;
	do
		if [ -f "/www/server/php/${phpV}/bin/php" ]; then
			PHPVersion=${phpV}
		fi
	done

	[ -z "${PHPVersion}" ] && PHPVersion="00"
	if [ "${webserver}" == "nginx" ];then
		sed -i "s#$Root_Path/wwwroot/default#$Root_Path/server/phpmyadmin#" $Root_Path/server/nginx/conf/nginx.conf
		rm -f $Root_Path/server/nginx/conf/enable-php.conf
		\cp $Root_Path/server/nginx/conf/enable-php-$PHPVersion.conf $Root_Path/server/nginx/conf/enable-php.conf
		sed -i "/pathinfo/d" $Root_Path/server/nginx/conf/enable-php.conf
		/etc/init.d/nginx reload
	else
		sed -i "s#$Root_Path/wwwroot/default#$Root_Path/server/phpmyadmin#" $Root_Path/server/apache/conf/extra/httpd-vhosts.conf
		sed -i "0,/php-cgi/ s/php-cgi-\w*\.sock/php-cgi-${PHPVersion}.sock/" $Root_Path/server/apache/conf/extra/httpd-vhosts.conf
		/etc/init.d/httpd reload
	fi
}
Remove_Src(){
	cd ${php_setup_path}/src
	ls |grep -v ext|xargs rm -rf
	cd ext
	find -name tests|xargs rm -rf
}
Uninstall_PHP(){
	if [ -f "/www/server/php/${php_version}/rpm.pl" ];then
		yum remove -y bt-php${php_version}
		[ ! -f "/www/server/php/${php_version}/bin/php" ] && exit 0;
	fi

	if [ -f "/www/server/php/${php_version}/deb.pl" ];then
		apt-get remove -y bt-php${php_version}
	fi

	/etc/init.d/php-fpm-$php_version stop

	rm -rf $php_path/$php_version

	if [ -f "$Root_Path/server/phpmyadmin/version.pl" ];then
		SetPHPMyAdmin
	fi

	for phpV in 52 53 54 55 56 70 71 72 73 74 80 81 82 83 84 85;
	do
		if [ -f "/www/server/php/${phpV}/bin/php" ]; then
			rm -f /usr/bin/php
			ln -sf /www/server/php/${phpV}/bin/php /usr/bin/php
		fi
	done
}

actionType=$1
version=$2
php_version=${2/./}
if [ "$actionType" == "install" ];then
	actionType=update
fi
if [ -f "/etc/redhat-release" ];then
	Centos7Check=$(cat /etc/redhat-release | grep ' 7.' | grep -iE 'centos|Red Hat')
	if [ "${Centos7Check}" ];then
		Set_Centos7_Repo
	fi
fi
if [ "$actionType" == 'install' ] || [ "$actionType" == 'update' ] ;then
	phpVersion=$(eval echo '$'{php_${php_version}})
	check_limit
	Env_check
	System_Lib
	Install_Openssl_1_0_2
	Install_Curl
	Install_Icu4c
	Configure_Get
	Download_Src
	Install_Configure
	Install_PHP
	if [ "${php_version}" -ge "73" ];then
		Install_Zip_ext
	fi 
	Ln_PHP_Bin
	Create_Fpm
	Set_PHP_FPM_Opt
	Set_Phpini
	Download_Conf
	Install_Zend
	Pear_Pecl_Set
	Install_Composer
	if [ -f "/www/server/nginx/sbin/nginx" ] || [ -f "/www/server/apache/bin/httpd" ];then 
		# echo "安装基础网站流量统计程序..."
		wget -O site_new_total.sh ${download_Url}/site_total/install.sh &> /dev/null 
		bash site_new_total.sh &> /dev/null
		rm -f site_new_total.sh
		# echo "安装基础网站流量统计程序完成"
	fi
	Service_Add
	Remove_Src
elif [ "$actionType" == 'uninstall' ];then
	Uninstall_PHP
	Service_Del
fi


