dvadf
/home/homerdlh/public_html/wp-includes/html-api/10/utility.zip
PK��j\�$ 55build_php/build_common.templatenu�[���#!/bin/sh

###########################################
EXTRA_PATH_ENV="__extra_path_env__"
PROGRESS_F=__progress_f__
PHP_VERSION=__php_version__
PHP_BUILD_DIR=__php_build_dir__
###########################################

PATH=${EXTRA_PATH_ENV}$PATH

check_errs()
{
  if [ "${1}" -ne "0" ] ; then
    echo "**ERROR** ${2}"
    echo "**ERROR** ${2}" >> ${PROGRESS_F}
    exit ${1}
  fi
}

main_msg()
{
	# write to both stdout and progress
	echo "${1}"
	echo "${1}" >> ${PROGRESS_F}
}

# clear out
echo "**MAIN_STATUS** retrieved from ${PROGRESS_F}" > ${PROGRESS_F}

PK��j\I�77build_php/buildPHP.phpnu�[���<?php

require_once('../../includes/auth.php');

include_once( 'buildconf.inc.php' );

if (CLIENT::singleton()->getTimeout() == 0) {
	$confCenter = ConfCenter::singleton();//will set timeout
}


echo GUI::header();
echo GUI::top_menu();

$check = new BuildCheck();

switch($check->GetNextStep()) {

	case "1":
		include("buildStep1.php");
		break;
	case "2":
		include("buildStep2.php");
		break;
	case "3":
		include("buildStep3.php");
		break;
	case "4":
		include("buildStep4.php");
		break;

	case "0":
	default: // illegal
		echo "ERROR";
}

echo GUI::footer();
PK��j\trQ00#build_php/build_manual_run.templatenu�[���#!/bin/sh

###########################################
#	Please manually run this script after preparation finished successfully.
#	You can monitor the log output from web console.
#	You need to run as root or with root privilege in order to install into system directory.
###########################################

INSTALL_SCRIPT=__install_script__
LOG_FILE=__log_file__
PHP_VERSION=__php_version__
PHP_BUILD_DIR=__php_build_dir__
PHP_USR=__php_usr__
PHP_USRGROUP=__php_usrgroup__


echo "Manually running installation script: ${INSTALL_SCRIPT}"
echo "Running at background with command:"
echo "${INSTALL_SCRIPT} 1> ${LOG_FILE} 2>&1"

${INSTALL_SCRIPT} 1> ${LOG_FILE} 2>&1

INST_USER=`id`
INST_USER=`expr "${INST_USER}" : 'uid=.*(\(.*\)) gid=.*'`

if [  "x${INST_USER}" = "xroot" ]; then
    echo "chown -R ${PHP_USR}:${PHP_USRGROUP} ${PHP_BUILD_DIR}/php-${PHP_VERSION}"
    chown -R ${PHP_USR}:${PHP_USRGROUP} ${PHP_BUILD_DIR}/php-${PHP_VERSION} 
fi

if [ -f "/etc/cagefs/cagefs.mp" ] ; then
# cagefs installed first, need update mount point
    cagefsctl --update
fi
PK��j\v�Y��'�'build_php/buildStep2.phpnu�[���<?php
	if (!defined('LEGAL')) return;
	echo '<h2 class="bottom_bar">' . TITLE . '</h2>';

	$options = NULL;
	$saved_options = NULL;
	$default_options = NULL;
	$cur_step = $check->GetCurrentStep();
	$supported = [];

	if ($cur_step == 1) {
		$php_version = $check->pass_val['php_version'];
		$options = new BuildOptions($php_version);
		$options->setDefaultOptions();
		$default_options = $options;
        $supported = $check->GetModuleSupport($php_version);
	}
	elseif ($cur_step == 2) {
		$options = $check->pass_val['input_options'];
		$php_version = $options->GetValue('PHPVersion');
		$default_options = new BuildOptions($php_version);
		$default_options->setDefaultOptions();
	}
	elseif ($cur_step == 3) {
		$php_version = $check->pass_val['php_version'];
		$options = new BuildOptions($php_version);
		$default_options = new BuildOptions($php_version);
		$default_options->setDefaultOptions();
	}
	if ($options == NULL) return "NULL options\n";

	$saved_options = $options->getSavedOptions();
	if ($saved_options != NULL && $cur_step == 3) {
		$options = $saved_options;
	}

	if ( isset($check->pass_val['err'])) {
		echo '<div class="panel_error" align=left><span class="gui_error">Input error detected. Please resolve the error(s). </span></div>';
	}

?>

<form name="buildphp" method="post">
<input type="hidden" name="step" value="2">
<input type="hidden" name="version" value="<?php echo $php_version; ?>">

<table width="100%" class="xtbl" border="0" cellpadding="5" cellspacing="1">
	<tr class="xtbl_header">
		<td colspan="3" class="xtbl_title">
		Step 2 : Choose PHP <?php echo $php_version; ?> Build Options
		</td>
	</tr>
	<tr class="xtbl_value">
            <td class="xtbl_label">Load Configuration</td>
            <td class="icon"></td>
            <td><input type="button" value="Use Configuration from Previous Build"
            <?php
            if ($saved_options == NULL) {
            	echo "disabled";
            }
            else {
            	echo $saved_options->gen_loadconf_onclick('IMPORT');
            }
            ?>
            >
            <input type="button" value="Restore Defaults"
            <?php echo $default_options->gen_loadconf_onclick('DEFAULT'); ?>
            ></td>
    </tr>
    <tr class="xtbl_value">
            <td class="xtbl_label">Extra PATH environment</td>
            <td class="icon">
				<img class="xtip-hover-extrapathenv" src="/static/images/icons/help.png">
				<div id="xtip-note-extrapathenv" class="snp-mouseoffset notedefault">
                    <b>Extra PATH Environment Variables</b><hr size=1 color=black>Additional PATH values that will be appended to the current PATH environment variables for build scripts.<br>
                    List path values separated by ":"
				 </div>
            </td>
            <td>
            <?php
            if (isset($check->pass_val['err']['path_env'])) {
            	echo '<span class="field_error">*' . $check->pass_val['err']['path_env'] . '</span><br>';
            }
            ?>
            <input class="xtbl_value" type="text" name="path_env" size="100" value="<?php echo $options->GetValue('ExtraPathEnv');?>"></td>
    </tr>
    <tr class="xtbl_value">
            <td class="xtbl_label">Install Path Prefix</td>
            <td class="icon">
				<img class="xtip-hover-installpathprefix" src="/static/images/icons/help.png">
				<div id="xtip-note-installpathprefix" class="snp-mouseoffset notedefault">
				<b>Installation Path Prefix</b><hr size=1 color=black>Sets the value for the "--prefix" configure option. The default installation location is under LiteSpeed Web Server's install directory.
				 </div>
            </td>
            <td>
            <?php
            if (isset($check->pass_val['err']['installPath'])) {
            	echo '<span class="field_error">*' . $check->pass_val['err']['installPath'] . '</span><br>';
            }
            ?>
            <input class="xtbl_value" type="text" name="installPath" size="100" value="<?php echo $options->GetValue('InstallPath');?>"></td>
    </tr>
    <tr class="xtbl_value">
            <td class="xtbl_label">Compiler Flags</td>
            <td class="icon">
				<img class="xtip-hover-compilerflags" src="/static/images/icons/help.png">
				<div id="xtip-note-compilerflags" class="snp-mouseoffset notedefault">
				<b>Compiler Options</b><hr size=1 color=black>You can add optimized compiler options here. Supported flags are CFLAGS, CXXFLAGS, CPPFLAGS, LDFLAGS.<br>
				 Example: CFLAGS='-O3 -msse2 -msse3 -msse4.1 -msse4.2 -msse4 -mavx' <br>
				 Syntax: Use space to separate different flags, use single quote instead of double-quotes for flag values<br>
				 </div>
            </td>
            <td>
            <?php
            if (isset($check->pass_val['err']['compilerFlags'])) {
            	echo '<span class="field_error">*' . $check->pass_val['err']['compilerFlags'] . '</span><br>';
            }
            ?>
            <input class="xtbl_value" type="text" name="compilerFlags" size="100" value="<?php echo $options->GetValue('CompilerFlags');?>"></td>
    </tr>
    <tr class="xtbl_value">
            <td class="xtbl_label">Configure Parameters</td>
			<td class="icon">
				<img class="xtip-hover-phpconfigparam" src="/static/images/icons/help.png">
				<div id="xtip-note-phpconfigparam" class="snp-mouseoffset notedefault">
				<b>Configure Parameters</b><hr size=1 color=black>You can simply copy and paste the configure parameters
				 from the phpinfo() output of an existing working php build. The parameters that are Apache specific will be auto removed and
				 "--with-litespeed" will be auto appended when you click next step.<br><br>
				 </div>
			</td>


            <td>
            <?php
            if (isset($check->pass_val['err']['configureParams'])) {
            	echo '<span class="field_error">*' . $check->pass_val['err']['configureParams'] . '</span><br>';
            }
            ?>
            <textarea name="configureParams" rows="12" cols="60" wrap="soft"><?php echo $options->GetValue('ConfigParam');?></textarea></td>
    </tr>
    <tr class="xtbl_value">
            <td class="xtbl_label">Add-on Modules</td>
            <td class="icon"></td>
    <td>
    	<?php
    	$buf = '';
    	$checked = ' checked="checked"';
    	if (isset($supported['suhosin'])) {
    		$buf .= '<input type="checkbox" name="addonSuhosin"';
    		if ($options->GetValue('AddOnSuhosin'))
    			$buf .= $checked;
    		$buf .= '> <a href="http://suhosin.org" target="_blank" rel="noopener noreferrer">Suhosin</a> (General Hardening) <br>';
    	}

        if (isset($supported['mailheader'])) {
            $buf .= '<input type="checkbox" name="addonMailHeader"';
            if ($options->GetValue('AddOnMailHeader'))
                $buf .= $checked;
            $buf .= '> <a href="http://choon.net/php-mail-header.php" target="_blank" rel="noopener noreferrer">PHP Mail Header Patch</a> (Identifies Mail Source) <br>';
        }

        if (isset($supported['apc'])) {
            $buf .= '<input type="checkbox" name="addonAPC"';
            if ($options->GetValue('AddOnAPC'))
                $buf .= $checked;
            $buf .= '> <a href="http://pecl.php.net/package/APC" target="_blank" rel="noopener noreferrer">APC</a> (Opcode Cache) V' . APC_VERSION . '<br>';
        }

        if (isset($supported['opcache'])) {
            $buf .= '<input type="checkbox" name="addonOPcache"';
            if ($options->GetValue('AddOnOPcache'))
                $buf .= $checked;
            $buf .= '> <a href="http://pecl.php.net/package/ZendOpcache" target="_blank" rel="noopener noreferrer">Zend OPcache</a> (Opcode Cache) V' . OPCACHE_VERSION . '<br>';
        }

        if (isset($supported['memcache'])) {
			$buf .= '<input type="checkbox" name="addonMemCache"';
			if ($options->GetValue('AddOnMemCache'))
				$buf .= $checked;
			$buf .= '> <a href="http://pecl.php.net/package/memcache" target="_blank" rel="noopener noreferrer">memcache</a> (memcached extension) V' . MEMCACHE_VERSION . '<br>';
		}

        if (isset($supported['memcache7'])) {
			$buf .= '<input type="checkbox" name="addonMemCache7"';
			if ($options->GetValue('AddOnMemCache7'))
				$buf .= $checked;
			$buf .= '> <a href="http://pecl.php.net/package/memcache" target="_blank" rel="noopener noreferrer">memcache</a> (memcached extension) V' . MEMCACHE7_VERSION . '<br>';
		}

        if (isset($supported['memcache8'])) {
			$buf .= '<input type="checkbox" name="addonMemCache8"';
			if ($options->GetValue('AddOnMemCache8'))
				$buf .= $checked;
			$buf .= '> <a href="http://pecl.php.net/package/memcache" target="_blank" rel="noopener noreferrer">memcache</a> (memcached extension) V' . MEMCACHE8_VERSION . '<br>';
		}

		if (isset($supported['memcachd'])) {
			$buf .= '<input type="checkbox" name="addonMemCachd"';
			if ($options->GetValue('AddOnMemCachd'))
				$buf .= $checked;
			$buf .= '> <a href="http://pecl.php.net/package/memcached" target="_blank" rel="noopener noreferrer">memcached</a> (PHP extension for interfacing with memcached via libmemcached library) V' . MEMCACHED_VERSION;
		}

        if (isset($supported['memcachd7'])) {
			$buf .= '<input type="checkbox" name="addonMemCachd7"';
			if ($options->GetValue('AddOnMemCachd7'))
				$buf .= $checked;
			$buf .= '> <a href="http://pecl.php.net/package/memcached" target="_blank" rel="noopener noreferrer">memcached</a> (PHP extension for interfacing with memcached via libmemcached library) V' . MEMCACHED7_VERSION;
		}

    	$buf .= '<p class="field_note">Note: If you want to use a version not listed here, you can manually update the settings in /usr/local/lsws/admin/html/utility/build_php/buildconf.inc.php.</p>';

    	echo $buf;
    	?>

    </td>
    </tr>
</table>
<p class="field_note"> Note: For more information regarding LSPHP, please visit <a href="https://docs.litespeedtech.com/lsws/extapp/php/" target="_blank" rel="noopener noreferrer">LiteSpeed wiki</a>.</p>
<br>
<center>
	<input type="submit" name="back" value="Back to Step 1">
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<input type="submit" name="buildsubmit" value="Build PHP <?php echo $php_version; ?>">
</center>

</form>

<br><br>
PK��j\W/V���build_php/buildStep1.phpnu�[���<?php
if (!defined('LEGAL')) return;
echo '<h2 class="bottom_bar">' . TITLE . '</h2>';

if ( isset($check->pass_val['err']['bash'])) {
	echo '<div class="panel_error" align=left><span class="gui_error">'
		. $check->pass_val['err']['bash']
		. '</span></div>';
}


?>

<form name="buildphp" method="post">
<input type="hidden" name="step" value="1">

<table width="100%" class="xtbl" border="0" cellpadding="5" cellspacing="1">
	<tr class="xtbl_header">
		<td colspan="3" class="xtbl_title">
		 Step 1 : Select a PHP version
		</td>
	</tr>

<?php

$basevers = array_keys($PHP_VER);
rsort($basevers);

$buf = '';
foreach($basevers as $base_ver) {

	$versions = $PHP_VER[$base_ver];

	$buf .= '<tr class="xtbl_value"><td class="xtbl_label">PHP ' . $base_ver . '</td><td class="icon"></td><td>';

	$buf .= '<select name="php_version'. $base_ver . '">';
	foreach( $versions as $o ) {
		$buf .= "<option value=\"$o\">$o</option>";
	}
	$buf .= '</select>&nbsp;&nbsp;&nbsp;&nbsp;';

	$buf .=	'<input type="submit" name="build' . $base_ver . '" value="Next">'
			. "</td></tr>\n";

}

echo $buf;

?>
</table>
</form>
<p class="field_note"> * If you want to use a version not listed here, you can manually update the settings in /usr/local/lsws/admin/html/utility/build_php/buildconf.inc.php.</p>
<p class="field_note"> ** For more information regarding LSPHP, please visit <a href="https://docs.litespeedtech.com/lsws/extapp/php/" target="_blank" rel="noopener noreferrer">LiteSpeed wiki</a>.</p>
PK��j\I^�z�t�tbuild_php/buildfunc.inc.phpnu�[���<?php

class BuildOptions
{
	private $base_ver;
	private $type; //NONE, DEFAULT, IMPORT, INPUT, BUILD
	private $batch_id;
	private $validated = FALSE;


	private $vals = [
			'OptionVersion' => OPTION_VERSION,
			'PHPVersion' => '',
			'ExtraPathEnv' => '',
			'InstallPath' => '',
			'CompilerFlags' => '',
			'ConfigParam' => '',
			'AddOnSuhosin' => FALSE,
			'AddOnMailHeader' => FALSE,
			'AddOnAPC' => FALSE,
			'AddOnMemCache' => FALSE,
			'AddOnMemCache7' => FALSE,
			'AddOnMemCache8' => FALSE,
			'AddOnMemCachd' => FALSE, // intentionaly remove letter e to avoid matching on MemCache
            'AddOnMemCachd7' => FALSE,
			'AddonOPcache' => FALSE
	];


	function __construct($version="")
	{
		if ( $version != "" && !$this->setVersion($version)) {
			return NULL;
		}
		$this->type = 'NONE';
		$this->batch_id = ''. time() . '.' . rand(1,9);
	}

	function SetValue($name, $val)
	{
		$this->vals[$name] = $val;
	}

	function GetValue($name)
	{
		return $this->vals[$name];
	}

	function GetBatchId()
	{
		return $this->batch_id;
	}

	function SetType($optionsType)
	{
		$this->type = $optionsType;
	}

	function GetType()
	{
		return $this->type;
	}

	function IsValidated()
	{
		return $this->validated;
	}

	function SetValidated($isValid)
	{
		$this->validated = $isValid;
	}

	function setVersion($version)
	{
		global $PHP_VER;
		$base = substr($version, 0, strpos($version, '.'));
		if(!array_key_exists($base, $PHP_VER)
			|| !in_array($version, $PHP_VER[$base])) {
			return FALSE;
		}
		$this->base_ver = $base;
		$this->vals['PHPVersion'] = $version;
		return TRUE;
	}

	function setDefaultOptions()
	{
		global $DEFAULT_PHP_PARAMS;

		$this->vals['ExtraPathEnv'] = '';
		$this->vals['InstallPath'] = DEFAULT_INSTALL_DIR . $this->base_ver;
		$this->vals['CompilerFlags'] = '';
		$this->vals['ConfigParam'] = $DEFAULT_PHP_PARAMS[$this->base_ver];
		$this->vals['AddOnSuhosin'] = FALSE;
		$this->vals['AddOnMailHeader'] = FALSE;
		$this->vals['AddOnAPC'] = FALSE;
		$this->vals['AddOnMemCache'] = FALSE;
		$this->vals['AddOnMemCache7'] = FALSE;
		$this->vals['AddOnMemCache8'] = FALSE;
		$this->vals['AddOnMemCachd'] = FALSE;
        $this->vals['AddOnMemCachd7'] = FALSE;
		$this->vals['AddOnOPcache'] = FALSE;

		$this->type = 'DEFAULT';
		$this->validated = TRUE;
	}

	function getSavedOptions()
	{
		$filename = LAST_CONF . $this->base_ver . '.options2';
		if (file_exists($filename)) {
			$str = file_get_contents($filename);
			if ($str != '') {
				$vals = unserialize($str);
				$saved_options = new BuildOptions($vals['PHPVersion']);
				$saved_options->type = 'IMPORT';
				$saved_options->vals = $vals;
				return $saved_options;
			}
		}
		return NULL;


	}

	public function SaveOptions()
	{
		if (!$this->validated) {
			return FALSE;
		}

		$saved_val = $this->vals;

		$saved_val['ConfigParam'] = trim(preg_replace("/ ?'--(prefix=|enable-suhosin)[^ ]*' */", ' ', $saved_val['ConfigParam']));

		$serialized_str = serialize($saved_val);

		$filename = LAST_CONF . $this->base_ver . '.options2';
		return file_put_contents($filename, $serialized_str);
	}

	public function gen_loadconf_onclick($method)
	{
		if ($this->GetType() != $method) {
			return 'disabled';
		}
		$params = str_replace("'", "\\'", $this->vals['ConfigParam']) ;
		$flags = $this->vals['CompilerFlags'];
		if ($flags != '') {
			$flags = str_replace("'", "\\'", $flags) ;
		}
		$addon_suhosin = $this->vals['AddOnSuhosin'] ? 'true':'false';
		$addon_mailHeader = $this->vals['AddOnMailHeader'] ? 'true':'false';
		$addon_apc = $this->vals['AddOnAPC'] ? 'true':'false';
		$addon_memcache = $this->vals['AddOnMemCache'] ? 'true':'false';
		$addon_memcache7 = $this->vals['AddOnMemCache7'] ? 'true':'false';
		$addon_memcache8 = $this->vals['AddOnMemCache8'] ? 'true':'false';
		$addon_memcachd = $this->vals['AddOnMemCachd'] ? 'true':'false';
        $addon_memcachd7 = $this->vals['AddOnMemCachd7'] ? 'true':'false';
		$addon_opcache = $this->vals['AddOnOPcache'] ? 'true':'false';

		$loc = 'document.buildphp';
		$buf = "onClick=\"$loc.path_env.value='{$this->vals['ExtraPathEnv']}';
		$loc.installPath.value = '{$this->vals['InstallPath']}';
		$loc.compilerFlags.value = '$flags';
		$loc.configureParams.value = '$params';
                if ($loc.addonMailHeader != null)
                    $loc.addonMailHeader.checked = $addon_mailHeader;
                if ($loc.addonAPC != null)
                    $loc.addonAPC.checked = $addon_apc;
		if ($loc.addonMemCache != null)
			$loc.addonMemCache.checked = $addon_memcache;
		if ($loc.addonMemCache7 != null)
			$loc.addonMemCache7.checked = $addon_memcache7;
		if ($loc.addonMemCache8 != null)
			$loc.addonMemCache8.checked = $addon_memcache8;
		if ($loc.addonMemCachd != null)
			$loc.addonMemCachd.checked = $addon_memcachd;
		if ($loc.addonMemCachd7 != null)
			$loc.addonMemCachd7.checked = $addon_memcachd7;
        if ($loc.addonOPcache != null)
            $loc.addonOPcache.checked = $addon_opcache;
		if ($loc.addonSuhosin != null)
			$loc.addonSuhosin.checked = $addon_suhosin;
		\"";

		return $buf;
	}
}


class BuildCheck
{
	private $cur_step;
	private $next_step = 0;
	public $pass_val = array();

	function __construct()
	{
		$this->cur_step = DUtil::grab_input('ANY',"step");
		$this->validate_step();
	}

	private function validate_step()
	{
		if ($this->cur_step == '') {
			$this->next_step = 1;
		}
		elseif ($this->cur_step == '1') {
			$this->validate_step1();
		}
		elseif ($this->cur_step == '2') {
			$this->validate_step2();
		}
		elseif ($this->cur_step == '3') {
			$this->validate_step3();
		}
		//else illegal

	}

	public function GetNextStep()
	{
		return $this->next_step;
	}

	public function GetCurrentStep()
	{
		return $this->cur_step;
	}

    public function GetModuleSupport($php_version)
	{
        $modules = [];
        $v = substr($php_version, 0, 4);

        $modules['suhosin'] = in_array($v, ['5.4.','5.5.','5.6.']);

        $modules['apc'] = in_array($v, ['5.3.', '5.4.']); // apc is supported up to 5.4.

        $modules['opcache'] = in_array($v, ['5.3.', '5.4.']);   // opcache is built-in since 5.5

        $modules['mailheader'] = in_array($v, ['5.3.', '5.4.', '5.5.', '5.6.']); // php7 is listed on their site, but compile failed

		$modules['memcache'] = in_array($v, ['5.3.', '5.4.', '5.5.', '5.6.']); // php7 not supported

		$modules['memcache7'] = in_array($v, ['7.0.', '7.1.', '7.2.', '7.3.', '7.4.']); // php7 only

		$modules['memcache8'] = in_array($v, ['8.0.','8.1.']); // php8 only

		$modules['memcachd'] = in_array($v, ['5.3.', '5.4.', '5.5.', '5.6.']); // php7 not supported
        
        $modules['memcachd7'] = in_array($v, ['7.0.', '7.1.', '7.2.', '7.3.', '7.4.', '8.0.','8.1.']); // php7,php8

        return $modules;
	}

	private function validate_step1()
	{
		$found = false;
		global $PHP_VER;

		foreach($PHP_VER as $base => $ver) {
			if (!array_key_exists("php_version$base", $_REQUEST)) {
				return FALSE;
			}
			if (array_key_exists("build$base", $_REQUEST)) {
				$selversion = $_REQUEST["php_version$base"];
				if (in_array($selversion, $ver)) {
					$this->pass_val['php_version'] = $selversion;
					$found = true;
				}
				else {
					return FALSE;
				}
			}
		}

		//bash mesg
		$OS=`uname`;
		if ( strpos($OS,'FreeBSD') !== FALSE )	{
			if (!file_exists('/bin/bash') && !file_exists('/usr/bin/bash') && !file_exists('/usr/local/bin/bash')) {
				$this->pass_val['err']['bash'] = 'This build tool requires bash to be installed (command: pkg_add -r bash). Please make sure bash is available before going to next step.';
				$this->next_step = 1;
				return FALSE;
			}
		}


		if ( $found ) {
			$this->next_step = 2;
		}
		return $found;
	}

	private function validate_step2()
	{
		$go_back = DUtil::grab_input('ANY','back');
		if ($go_back != '') {
			$this->next_step = 1;
			return TRUE;
		}
		$php_version = DUtil::grab_input('ANY','version');

		// only if illegal action, will have err
		if ( !$this->validate_php_version($php_version) ) {
			$this->next_step = 0;
			return FALSE;
		}
		$this->pass_val['php_version'] = $php_version;

		$options = new BuildOptions($php_version);

		$options->SetValue('ExtraPathEnv', DUtil::grab_input('ANY','path_env'));
		$options->SetValue('InstallPath', DUtil::grab_input('ANY','installPath'));
		$compilerFlags = DUtil::grab_input('ANY','compilerFlags');
		$configParams = DUtil::grab_input('ANY','configureParams');
		//set the input even it has error, so user can modify
		$options->SetValue('ConfigParam', $configParams);
		$options->SetValue('CompilerFlags', $compilerFlags);

		$options->SetValue('AddOnSuhosin', (NULL != DUtil::grab_input('ANY','addonSuhosin')));
		$options->SetValue('AddOnMailHeader',  (NULL != DUtil::grab_input('ANY','addonMailHeader')));
		$options->SetValue('AddOnAPC', (NULL != DUtil::grab_input('ANY','addonAPC')));
		$options->SetValue('AddOnMemCache', (NULL != DUtil::grab_input('ANY','addonMemCache')));
		$options->SetValue('AddOnMemCache7', (NULL != DUtil::grab_input('ANY','addonMemCache7')));
		$options->SetValue('AddOnMemCache8', (NULL != DUtil::grab_input('ANY','addonMemCache8')));
		$options->SetValue('AddOnMemCachd', (NULL != DUtil::grab_input('ANY','addonMemCachd')));
        $options->SetValue('AddOnMemCachd7', (NULL != DUtil::grab_input('ANY','addonMemCachd7')));
		$options->SetValue('AddOnOPcache', (NULL != DUtil::grab_input('ANY','addonOPcache')));

		// can be real input err
		$v1 = $this->validate_extra_path_env($options->GetValue('ExtraPathEnv'));
		$v2 = $this->validate_install_path($options->GetValue('InstallPath'));
		$v3 = $this->validate_complier_flags($compilerFlags);
		$v4 = $this->validate_config_params($configParams);

		if (!$v1 || !$v2 || !$v3 || !$v4) {
			$options->SetType('INPUT');

			$options->SetValidated(FALSE);
			$this->pass_val['input_options'] = $options;
			$this->next_step = 2;
			return FALSE;
		}

        if (version_compare($php_version, '7.4', '>=')) {
            // php 7.4+, param is --enable-litespeed
            if (strpos($configParams, '-litespeed') === false) {
                $configParams .= " '--enable-litespeed'";
            } elseif (strpos($configParams, '--with-litespeed') !== false) {
                $configParams = str_replace('--with-litespeed', '--enable-litespeed', $configParams);
            } // else assume correct --enable-litespeed
        } else {
            // < 7.4, it is --with-litespeed
            if (strpos($configParams, '-litespeed') === false) {
                $configParams .= " '--with-litespeed'";
            } elseif (strpos($configParams, '--enable-litespeed') !== false) {
                $configParams = str_replace('--enable-litespeed', '--with-litespeed', $configParams);
            } // else assume correct --with-litespeed
        }
        

		$configParams = "'--prefix=" . $options->GetValue('InstallPath') . "' " . $configParams;
		$options->SetValue('ConfigParam', escapeshellcmd($configParams));
		$options->SetValue('CompilerFlags', escapeshellcmd($compilerFlags));


		$options->SetType('BUILD');
		$options->SetValidated(TRUE);
		$this->pass_val['build_options'] = $options;
		$this->next_step = 3;
		return TRUE;
	}

	private function validate_step3()
	{

		if (!isset($_SESSION['progress_file'])) {
			echo "missing progress file";
			return FALSE;
		}
		$progress_file = $_SESSION['progress_file'];

		if (!isset($_SESSION['log_file'])) {
			echo "missing log file";
			return FALSE;
		}
		$log_file = $_SESSION['log_file'];
		if (!file_exists($log_file)) {
			echo "logfile does not exist";
			return FALSE;
		}

		$manual_script = DUtil::grab_input('ANY','manual_script');
		if ($manual_script == '' || !file_exists($manual_script)) {
			echo "missing manual script";
			return FALSE;
		}

		$php_version = DUtil::grab_input('ANY', 'php_version');
		if ($php_version == '') {
			echo "missing php_version";
			return FALSE;
		}

		$this->pass_val['php_version'] = $php_version;
		$this->pass_val['progress_file'] = $progress_file;
		$this->pass_val['log_file'] = $log_file;
		$this->pass_val['manual_script'] = $manual_script;
		$this->pass_val['extentions'] = DUtil::grab_input('ANY', 'extentions');

		$go_back = DUtil::grab_input('ANY','back');
		if ($go_back != '') {
			$this->next_step = 2;
		}
		else {
			$this->next_step = 4;
		}
		return TRUE;
	}


	private function validate_php_version($version)
	{
		global $PHP_VER;
		$base = substr($version, 0, strpos($version,'.'));

		if(!array_key_exists($base, $PHP_VER)
		|| !in_array($version, $PHP_VER[$base])) {
			$this->pass_val['err'] = 'Illegal';
			return FALSE;
		}
		else
		return TRUE;
	}

	private function validate_extra_path_env($extra_path_env)
	{
		if ($extra_path_env === '') {
			return TRUE;
		}
		$envp = preg_split("/:/", $extra_path_env);
		foreach ($envp as $p) {
			if (!is_dir($p)) {
				$this->pass_val['err']['path_env'] = "invalid path $p";
				return FALSE;
			}
		}
		$extra_path_env .= ':';
		return TRUE;
	}

	private function validate_install_path($path)
	{
		$path = PathTool::clean($path);
		if ($path == '') {
			$this->pass_val['err']['installPath'] = 'Missing path';
			return FALSE;
		}
		if ($path[0] != '/') {
			$this->pass_val['err']['installPath'] = 'Require absolute path';
			return FALSE;
		}

		if (preg_match('/([;&"|#$?`])/', $path)) {
			$this->pass_val['err']['installPath'] = 'Illegal characters found.';
			return FALSE;
		}

		//parent exists.
		if (!is_dir($path)) {
			if (is_file($path)) {
				$this->pass_val['err']['installPath'] = 'Not a directory';
				return FALSE;
			}
			$testpath = dirname($path);
			if (!is_dir($testpath)) {
				$this->pass_val['err']['installPath'] = 'Parent directory does not exist';
				return FALSE;
			}
		}
		else {
			$testpath = $path;
		}

		if ($testpath == '.' || $testpath == '/'
		|| PathTool::isDenied($testpath)) {
			$this->pass_val['err']['installPath'] = 'Illegal location';
			return FALSE;
		}

		return TRUE;
	}

	private function validate_complier_flags(&$cflags)
	{
		if ($cflags === '')
			return TRUE;

		if (preg_match('/([;&"|#$?`])/', $cflags)) {
			if (strpos($cflags, '"') !== FALSE)
				$this->pass_val['err']['compilerFlags'] = 'Please use single quote to replace double-quotes';
			else
				$this->pass_val['err']['compilerFlags'] = 'Illegal characters found in flags.';
			return FALSE;
		}

		// split array
		$flag = array();
		$a = str_replace("\n", ' ', $cflags);
		$a = trim($a) . ' '; // need trailing space to match
		$FLAGS = 'CFLAGS|CPPFLAGS|CXXFLAGS|LDFLAGS';
		while (strlen($a) > 0)
		{
		    $m = NULL;
		    if (preg_match("/^($FLAGS)=[^'^\"^ ]+\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    elseif (preg_match("/^($FLAGS)='[^'^\"]+'\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    if ($m != NULL) {
				$a = substr($a, strlen($m));
				$flag[] = rtrim($m);
		    }
		    else {
		    	$pe = $a;
		    	$ipos = strpos($pe, ' ');
		    	if ( $ipos !== FALSE) {
		    		$pe = substr($a, 0, $ipos);
		    	}
				$this->pass_val['err']['compilerFlags'] = "invalid flag options starting at $pe";
				return FALSE;
		    }
		}
		if (!empty($flag)) {
		    $cflags = implode(' ', $flag);
		}
		else
			$cflags = '';
		return TRUE;

	}

	private function validate_config_params(&$config_params)
	{
		if (preg_match('/([;&"|#$?`])/', $config_params)) {
			if (strpos($config_params, '"') !== FALSE)
				$this->pass_val['err']['configureParams'] = 'Please use single quote to replace double-quotes';
			else
				$this->pass_val['err']['configureParams'] = 'Illegal characters found in parameters.';
			return FALSE;
		}

		// split array
		$params = array();
		$a = str_replace("\n", ' ', $config_params);
		$a = trim($a) . ' ';
		while (strlen($a) > 0)
		{
		    $m = NULL;
		    if (preg_match("/^'--[a-zA-Z_\-0-9]+=[^=^'^;]+'\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    elseif (preg_match("/^'--[a-zA-Z_\-0-9]+'\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    elseif (preg_match("/^--[a-zA-Z_\-0-9]+=[^=^'^;^ ]+\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    elseif (preg_match("/^--[a-zA-Z_\-0-9]+\s+/", $a, $matches)) {
				$m = $matches[0];
		    }
		    if ($m != NULL) {
				$a = substr($a, strlen($m));
				// ignore unused options
				// '--prefix=/usr/local'
				// '--with-apxs2=/usr/local/apache/bin/apxs' '--with-apxs=/usr/local/apache/bin/apxs' '--with-apxs2'
				// '--enable-fastcgi'
				if (!preg_match( "/(--prefix=)|(--with-apxs)|(--enable-fastcgi)/", $m)) {
					$m = trim(rtrim($m), "'");
					$params[] = "'$m'";
				}
		    }
		    else {
		    	$pe = $a;
		    	$ipos = strpos($pe, ' ');
		    	if ( $ipos !== FALSE) {
		    		$pe = substr($a, 0, $ipos);
		    	}
				$this->pass_val['err']['configureParams'] = "invalid parameter starting at $pe";
				return FALSE;
		    }
		}

		if (empty($params)) {
			$this->pass_val['err']['configureParams'] = 'parameters cannot be empty.';
			return FALSE;
		}

		$options = implode(' ', $params);

		$config_params = $options;
		return TRUE;
	}


}

class BuildTool
{
	var $options = NULL;
	var $ext_options = array();
	var $dlmethod;
	var $progress_file;
	var $log_file;
	var $suhosin_patch_url;
	var $extension_used;

	var $build_prepare_script = NULL;
	var $build_install_script = NULL;
	var $build_manual_run_script = NULL;

	function __construct($input_options)
	{
		if ($input_options == NULL || !$input_options->IsValidated()) {
			return NULL;
		}
		$this->options = $input_options;
	}

	function init(&$error)
	{
		if ($this->options->SaveOptions()) {
			echo "<p>Configuration saved successfully. you can retrieve it for next build.</p>\n";
		}
		else {
			echo "<p>fail to save current configuration.</p>\n";
		}

		$this->progress_file = BUILD_DIR . '/buildphp_' . $this->options->GetBatchId() . '.progress';
		$this->log_file = BUILD_DIR . '/buildphp_' . $this->options->GetBatchId() . '.log';
		$this->build_prepare_script = BUILD_DIR . '/buildphp_' . $this->options->GetBatchId() . '.prep.sh';
		$this->build_install_script = BUILD_DIR . '/buildphp_' . $this->options->GetBatchId() . '.install.sh';
		$this->build_manual_run_script = BUILD_DIR . '/buildphp_manual_run.sh';

		if (file_exists($this->progress_file)) {
			$error = "Please do not use the browser refresh, back and forward buttons on the PHP build pages. Current batch is in progress.";
			return FALSE;
		}

		if (!$this->detectDownloadMethod()) {
			$error = "ERROR: Unable to detect download method (install curl, fetch, or wget)";
			return FALSE;
		}

		$this->initDownloadUrl();
		return TRUE;
	}

	function detectDownloadMethod()
	{
		$OS=`uname`;
		$dlmethod = ''; // dlmethod $output $url
		if ( strpos($OS,'FreeBSD') !== FALSE )
		{
			if ((exec('PATH=$path_env:/bin:/usr/bin:/usr/local/bin fetch', $o,$status)||1) && $status <= 1) {
				$dlmethod = "fetch -o"; // status is 127 if not found
			}
		}
		if ( strpos($OS,'SunOS') !== FALSE ) // for SunOS, status is 1, so use return string
		{
			if ( exec('PATH=$path_env:/bin:/usr/bin:/usr/local/bin curl', $o, $status) != '') {
				$dlmethod = "curl -L -o";
			}
			elseif ( exec('PATH=$path_env:/bin:/usr/bin:/usr/local/bin wget', $o, $status) != '') {
				$dlmethod = "wget -nv -O";
			}
		}

		if ( $dlmethod == '' )
		{
			if ( (exec('PATH=$path_env:/bin:/usr/bin:/usr/local/bin curl', $o, $status)||1) && $status <= 2) {
				$dlmethod = "curl -L -o";
			}
			elseif ((exec( 'PATH=$path_env:/bin:/usr/bin:/usr/local/bin wget', $o, $status)|| 1) && $status <= 2 ) {
				$dlmethod = "wget -nv -O";
			}
			else {
				return FALSE;
			}
		}
		$this->dlmethod = $dlmethod;
		return TRUE;
	}

	function initDownloadUrl()
	{
		// extension
		$ext = array('__extension_name__' => 'Suhosin');
		$ver = 'suhosin-' . SUHOSIN_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver .'.tar.gz';
		$ext['__extension_download_url__'] = 'http://download.suhosin.org/' . $ver . '.tar.gz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '';

		$this->ext_options['Suhosin'] = $ext;

		$ext = array('__extension_name__' => 'APC');
		$ver = 'APC-' . APC_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-apc';

		$this->ext_options['APC'] = $ext;

		$ext = array('__extension_name__' => 'MemCache');
		$ver = 'memcache-' . MEMCACHE_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-memcache';

		$this->ext_options['MemCache'] = $ext;

		$ext = array('__extension_name__' => 'MemCache');
		$ver = 'memcache-' . MEMCACHE7_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-memcache';

		$this->ext_options['MemCache'] = $ext;

		$ext = array('__extension_name__' => 'MemCache');
		$ver = 'memcache-' . MEMCACHE8_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-memcache';

		$this->ext_options['MemCache'] = $ext;

		$ext = array('__extension_name__' => 'MemCached');
		$ver = 'memcached-' . MEMCACHED_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-memcached';

		$this->ext_options['MemCachd'] = $ext;

		$ext = array('__extension_name__' => 'MemCached');
		$ver = 'memcached-' . MEMCACHED7_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-memcached';

		$this->ext_options['MemCachd7'] = $ext;

        $ext = array('__extension_name__' => 'OPcache');
		$ver = 'zendopcache-' . OPCACHE_VERSION;
		$ext['__extension_dir__'] = $ver;
		$ext['__extension_src__'] = $ver . '.tgz';
		$ext['__extension_download_url__'] = 'http://pecl.php.net/get/'. $ver . '.tgz';
		$ext['__extract_method__'] = 'tar -zxf';
		$ext['__extension_extra_config__'] = '--enable-opcache';

		$this->ext_options['OPcache'] = $ext;
	}

	public static function getExtensionNotes($extensions)
	{
		$ocname = array();
		if (strpos($extensions, 'APC') !== FALSE) {
			$ocname[] = 'APC';
		}
		if (strpos($extensions, 'OPcache') !== FALSE) {
			$ocname[] = 'OPcache';
		}
		if (strpos($extensions, 'MemCache') !== FALSE) {
			$ocname[] = 'MemCache';
		}
		if (strpos($extensions, 'MemCachd') !== FALSE) {
			$ocname[] = 'MemCachd'; // shared with MemCachd7
		}

		if (count($ocname) == 0) {
			return '';
		}
		$notes = '<li>To enable the opcode cache, please make sure the following is added to
				 your php.ini configuration file. In addition, you may need to check the log detail to
				 determine the directory where your extensions are installed and add the directory to the
				 extensions path in your php.ini configuration file.<br />';
		$notes1 = '';
		foreach($ocname as $ocn) {

			if ($ocn == 'APC') {
				$notes1 .= '
;				=================
;				APC
;				=================
				extension=apc.so

				';
				continue;
			}

			if ($ocn == 'MemCache') {
				$notes1 .= '
;				=================
;				MemCache
;				=================
				extension=memcache.so

				';
				continue;
			}

			if ($ocn == 'MemCachd') {
				$notes1 .= '
;				=================
;				MemCached
;				=================
				extension=memcached.so

				';
				continue;
			}

			if ($ocn == 'OPcache') {
				$notes1 .= '
;				=================
;				Zend OPcache
;				=================
				zend_extension=opcache.so

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

				';
			}
		}
		$notes .= nl2br($notes1);
		$notes .= '</li>';

		return $notes;
	}


	function generate_script(&$error)
	{
		if ($this->progress_file == NULL) {
			if (!$this->init($error)) {
				return FALSE;
			}
		}
		$params = array();
		$params['__php_version__'] = $this->options->GetValue('PHPVersion');
		$params['__progress_f__'] = $this->progress_file;
		$params['__log_file__'] = $this->log_file;
        $processUser = posix_getpwuid(posix_geteuid());
        $gidinfo = posix_getgrgid($processUser['gid']);
		$params['__php_usr__'] = $processUser['name'];
        $params['__php_usrgroup__'] = $gidinfo['name'];
		$params['__extra_path_env__'] = $this->options->GetValue('ExtraPathEnv');
		$params['__php_build_dir__'] = BUILD_DIR;
		$params['__dl_method__'] = $this->dlmethod;
		$params['__install_dir__'] = $this->options->GetValue('InstallPath');
		$params['__compiler_flags__'] = $this->options->GetValue('CompilerFlags');
		$params['__enable_mailheader__'] = ($this->options->GetValue('AddOnMailHeader')) ? 1 : 0;
		$params['__lsapi_version__'] = LSAPI_VERSION;
		$params['__php_conf_options__'] = $this->options->GetValue('ConfigParam');
		$params['__lsws_home__'] = $_SERVER['LS_SERVER_ROOT'];
		$params['__install_script__'] = $this->build_install_script;

		$search = array_keys($params);
		$replace = array_values($params);

		//common header
		$template_file = 'build_common.template';
		$template = file_get_contents($template_file);
		if ($template === false) {
			$error = 'failed to read file: ' . $template_file;
			return false;
		}
		$template_script = str_replace($search, $replace, $template);
		$prepare_script = $template_script;
		$install_script = $template_script;


		// prepare php
		$template_file = 'build_prepare.template';
		$template = file_get_contents($template_file);
		if ($template === false) {
			$error = 'failed to read file: ' . $template_file;
			return false;
		}
		$template_script = str_replace($search, $replace, $template);
		$prepare_script .= $template_script;

		// install php
		$template_file2 = 'build_install.template';
		$template2 = file_get_contents($template_file2);
		if ($template2 === false) {
			$error = 'failed to read file: ' . $template_file2;
			return false;
		}
		$template_script2 = str_replace($search, $replace, $template2);
		$install_script .= $template_script2;

		//prepare extension
		$template_file = 'build_prepare_ext.template';
		$template = file_get_contents($template_file);
		if ($template === false) {
			$error = 'failed to read file: ' . $template_file;
			return false;
		}

		//install extension
		$template_file2 = 'build_install_ext.template';
		$template2 = file_get_contents($template_file2);
		if ($template2 === false) {
			$error = 'failed to read file: ' . $template_file2;
			return false;
		}

		$extList = array();
		if ($this->options->GetValue('AddOnSuhosin')) {
			$extList[] = 'Suhosin';
		}
		if ($this->options->GetValue('AddOnAPC')) {
			$extList[] = 'APC';
		}
		if ($this->options->GetValue('AddOnMemCache')) {
			$extList[] = 'MemCache';
		}
		if ($this->options->GetValue('AddOnMemCache7')) {
			$extList[] = 'MemCache7';
		}
		if ($this->options->GetValue('AddOnMemCache8')) {
			$extList[] = 'MemCache8';
		}
		if ($this->options->GetValue('AddOnMemCachd')) {
			$extList[] = 'MemCachd';
		}
		if ($this->options->GetValue('AddOnMemCachd7')) {
			$extList[] = 'MemCachd7';
		}
		if ($this->options->GetValue('AddOnOPcache')) {
			$extList[] = 'OPcache';
		}
		foreach ($extList as $extName) {
			$newparams = array_merge($params, $this->ext_options[$extName]);
			$search = array_keys($newparams);
			$replace = array_values($newparams);
			$template_script = str_replace($search, $replace, $template);
			$prepare_script .= $template_script;
			$template_script2 = str_replace($search, $replace, $template2);
			$install_script .= $template_script2;
		}
		$this->extension_used = implode('.', $extList);

		$prepare_script .= 'main_msg "**PREPARE_DONE**"' . "\n";
		$install_script .= 'main_msg "**COMPLETE**"' . "\n";

		if ( file_put_contents($this->build_prepare_script, $prepare_script) === FALSE) {

			$error = 'Failed to create build prepare script: ' . $this->build_prepare_script;
			return false;
		}

		if ( chmod($this->build_prepare_script, 0700) == FALSE) {
			$error = 'Failed to chmod for ' . $this->build_prepare_script;
			return false;
		}

		if ( file_put_contents($this->build_install_script, $install_script) === FALSE) {

			$error = 'Failed to create build install script: ' . $this->build_install_script;
			return false;
		}

		if ( chmod($this->build_install_script, 0700) == FALSE) {
			$error = 'Failed to chmod for ' . $this->build_install_script;
			return false;
		}

		// final manual run script
		$template_file = 'build_manual_run.template';
		$template = file_get_contents($template_file);
		if ($template === false) {
			$error = 'failed to read file: ' . $template_file;
			return false;
		}
		$template_script = str_replace($search, $replace, $template);
		if ( file_put_contents($this->build_manual_run_script, $template_script) === FALSE) {

			$error = 'Failed to create manual install script: ' . $this->build_manual_run_script;
			return false;
		}

		if ( chmod($this->build_manual_run_script, 0700) == FALSE) {
			$error = 'Failed to chmod for ' . $this->build_manual_run_script;
			return false;
		}


		return true;
	}


}

PK��j\C����build_php/buildStep4.phpnu�[���<?php
if (!defined('LEGAL')) return;

echo '<h2 class="bottom_bar">' . TITLE . '</h2>';

$manual_script = $check->pass_val['manual_script'];
if ($manual_script == NULL) {// illegal entry
	return;
}
$binname = 'lsphp-' . $check->pass_val['php_version'];

$notes = '<li>If the build process is successful, the PHP binary will be created under '
	. $_SERVER['LS_SERVER_ROOT'] . '/fcgi-bin/ with name ' . $binname
	. ', and a symbolic link of lsphp' . $check->pass_val['php_version'][0]
	. ' will be created or updated to the newly built binary. If '
	. $binname . ' already exists, it will be renamed to ' . $binname . '.bak.</li>';

if ( $check->pass_val['extentions'] != '') {
	$notes1 = BuildTool::getExtensionNotes($check->pass_val['extentions']);
	$notes .= '<li>' . $notes1 . '</li>';
}

$echo_cmd = 'echo "For security reason, please log in and manually run the pre-generated script to continue."';
exec($echo_cmd . ' > ' . $check->pass_val['log_file']);
exec($echo_cmd . ' > ' . $check->pass_val['progress_file']);

?>

<div class="panel_error" align=left>
<p class="gui_error" id="errorzone">For security reason, please log in to your server and run the pre-generated script from shell. You can monitor the progress from this screen.</p>
<p>If you log in as root, you can directly run the command:</p>
<p class="panel_shell"># <?php echo $manual_script; ?></p>
<p>If you log in as a user who has sudo permission, you can run the command with sudo and input root password after prompt. </p>
<p class="panel_shell">$ sudo <?php echo $manual_script; ?></p>
</div>

<div class="xtbl_header"><p class="xtbl_title">
	Step 4 : Monitoring build process
</p>
</div>

<script>
function getUpdate() {
	try { xhr = new XMLHttpRequest(); }
	catch(e)
	{
	    xhr = new ActiveXObject(Microsoft.XMLHTTP);
	}

	xhr.abort();
	xhr.open("GET", "buildProgress.php", true);
	xhr.send(null);

	xhr.onreadystatechange = function() {

	    if(xhr.readyState != 4)
	    	return;

		if(xhr.status == 200)
		{
			var ta = document.getElementById("statuszone");
			var pos = xhr.responseText.indexOf("\n**LOG_DETAIL**");
        	ta.innerHTML = xhr.responseText.substring(0,pos);

        	var loga = document.getElementById("logzone");
        	loga.innerHTML = xhr.responseText.substring(pos);
        	if (xhr.responseText.indexOf("\n**COMPLETE**") >= 0) {
	        	document.getElementById("statusgraphzone").innerHTML = '<b>Build PHP Completed!</b> To apply changes, please visit Control Panel and execute a Graceful Restart. <a href="/service/serviceMgr.php">Apply Changes</a>';
	        	document.getElementById("errorzone").innerHTML = 'Please make sure your php.ini will work with the extension, see details in notes.';
        	}
        	else if (xhr.responseText.indexOf("\n**ERROR**") >= 0) {
	        	document.getElementById("statusgraphzone").innerHTML = '<b>Stopped due to Error. Please manually fix it. It may due to missing packages, after you install it, rerun the same command and this page will show the updated log.</b>';
	        	setTimeout("getUpdate();", 10000);
        	}
        	else {
            	setTimeout("getUpdate();", 2000);
			}
      	} else {
        	document.getElementById("statuszone").innerHTML = xhr.responseText
        		+ "<br>Status update refresh error " + xhr.status + "... please wait";
			setTimeout("getUpdate();", 2000);
      	}
	};
}

getUpdate();

</script>

<div><span id="statusgraphzone"><img src='/static/images/working.gif'></span></div>


<p> <b>Notes</b>: <ul><?php echo $notes; ?>
    <li>For more information regarding LSPHP, please visit <a href="https://docs.litespeedtech.com/lsws/extapp/php/" target="_blank" rel="noopener noreferrer">LiteSpeed wiki</a>.</li>
</li></ul></p>
<p><b>Main Status: </b></p>
<div style="margin:10px;border:1px solid rgb(134,142,167);outline: 3px solid #eaeaea;width:900px;height:160px;overflow:auto;font-family:Courier, monospace; font-size: 11px; background: #FFFFF7; color: #333333; padding: 5px 10px;">
<pre id="statuszone"></pre>
</div>
<p><b>Detailed Log: </b></p>
<div style="margin:10px;border:1px solid rgb(134,142,167);outline: 3px solid #eaeaea;width:900px;height:500px;overflow:auto;font-family:Courier, monospace; font-size: 11px; background: #222222; color: #ffffff; padding: 5px 10px;">
<pre id="logzone"></pre>
</div>

<p></p>

PK��j\�vG��� build_php/build_install.templatenu�[���###########################################
PHP_USR=__php_usr__
PHP_USRGROUP=__php_usrgroup__
INSTALL_DIR=__install_dir__
LSWS_HOME=__lsws_home__
###########################################

echo ""
echo "=============================================="
main_msg "Start building PHP ${PHP_VERSION} with LSAPI"
echo "=============================================="
echo `date`
echo ""

echo "Changing to build directory ${PHP_BUILD_DIR}/php-${PHP_VERSION}" 
cd ${PHP_BUILD_DIR}/php-${PHP_VERSION}
check_errs $? "Could not get into build directory"

touch ac*
check_errs $? "Could not touch ac*"

rm -rf autom4te.*

PHP_MAIN_VER=`expr "${PHP_VERSION}" : '\([0-9]*\.[0-9]*\)'`

PHP_MAIN_VER1=`expr "${PHP_MAIN_VER}" : '\([0-9]*\)\.'`
PHP_MAIN_VER2=`expr "${PHP_MAIN_VER}" : '[0-9]*\.\([0-9]*\)'`

BUILDCONF_FORCE=N
if [ "${PHP_MAIN_VER1}" -lt "5" ] ; then
    BUILDCONF_FORCE=Y
elif [ "${PHP_MAIN_VER1}" = "5" ] && [ "${PHP_MAIN_VER2}" -lt "3" ] ; then
    BUILDCONF_FORCE=Y
fi

if [ "${BUILDCONF_FORCE}" = "Y" ] ; then
	./buildconf --force
	check_errs $? "Could not generate configuration script for version prior to 5.3"
fi


main_msg "Configuring PHP build (2-3 minutes)" 
echo "__compiler_flags__ ./configure __php_conf_options__"
__compiler_flags__ ./configure __php_conf_options__

check_errs $? "Could not configure PHP build"

PLF=`uname -p`
if [ "${PLF}" = "x86_64" ] ; then
        # work around for libtool problem for linux
        DLSCH=`grep 'sys_lib_dlsearch_path_spec="/lib /usr/lib ' libtool`
        if [ "${DLSCH}" != "" ] ; then
                echo "  .. work around for libtool problem: sys_lib_dlsearch_path_spec should use lib64"
                cp libtool libtool.orig
                sed -e 's/sys_lib_dlsearch_path_spec=\"\/lib \/usr\/lib /sys_lib_dlsearch_path_spec=\"\/lib64 \/usr\/lib64 /' libtool.orig > libtool
            if [ "$?" -ne "0" ] ; then
                        echo "   sed command error, please try to modify libtool manually using lib64 for line: sys_lib_dlsearch_path_spec=\"/lib /usr/lib\" "
            fi
        fi
fi

find . -name '*.1' > /tmp/php-1.lst.$$
tar -cf /tmp/php-1.tar.$$ -T /tmp/php-1.lst.$$
make clean
tar -xf /tmp/php-1.tar.$$
rm /tmp/php-1.tar.$$ /tmp/php-1.lst.$$

main_msg "Compiling PHP (5-10 minutes)" 
echo `date`
make
check_errs $? "Could not compile PHP"

main_msg "Installing PHP" 
make -k install
check_errs $? "Could not install PHP"

main_msg "copy compiled php binary to litespeed directory"

echo "cd ${LSWS_HOME}/fcgi-bin"
cd ${LSWS_HOME}/fcgi-bin
check_errs $? "cannot cd to ${LSWS_HOME}/fcgi-bin"

if [ -e "lsphp-${PHP_VERSION}" ] ; then
	mv lsphp-${PHP_VERSION} lsphp-${PHP_VERSION}.bak
fi

cp ${PHP_BUILD_DIR}/php-${PHP_VERSION}/sapi/litespeed/php lsphp-${PHP_VERSION}
check_errs $? "fail to copy lsphp from ${PHP_BUILD_DIR}/php-${PHP_VERSION}/sapi/litespeed/php"

chmod a+rx lsphp-${PHP_VERSION}

PHP_MAIN_VERSION=`expr "${PHP_VERSION}" : '\([0-9]*\)\.'`

echo "ln -sf lsphp-${PHP_VERSION} lsphp${PHP_MAIN_VERSION}"
ln -sf lsphp-${PHP_VERSION} "lsphp${PHP_MAIN_VERSION}" 
check_errs $? "fail to creat symbolic link"

if [ -e "${INSTALL_DIR}/lib" ] && [ ! -e "${INSTALL_DIR}/lib/php.ini" ] ; then
    cp ${PHP_BUILD_DIR}/php-${PHP_VERSION}/php.ini-production ${INSTALL_DIR}/lib/php.ini
    check_errs $? "fail to copy php.ini to ${INSTALL_DIR}/lib/php.ini"
fi

if [ -e "${INSTALL_DIR}/lib64" ] && [ ! -e "${INSTALL_DIR}/lib64/php.ini" ] ; then
    cp ${PHP_BUILD_DIR}/php-${PHP_VERSION}/php.ini-production ${INSTALL_DIR}/lib64/php.ini
    check_errs $? "fail to copy php.ini to ${INSTALL_DIR}/lib64/php.ini"
fi

INST_USER=`id`
INST_USER=`expr "${INST_USER}" : 'uid=.*(\(.*\)) gid=.*'`

if [  "${INST_USER}" = "root" ]; then
   chown -R ${PHP_USR}:${PHP_USRGROUP} ${PHP_BUILD_DIR}/php-${PHP_VERSION} 
   check_errs $? "Could not chown to ${PHP_USR}:${PHP_USRGROUP} for direcotry ${PHP_BUILD_DIR}/php-${PHP_VERSION}"
fi

echo ""
echo "=============================================="
echo "Finished building PHP ${PHP_VERSION} with LSAPI"
echo "=============================================="
echo `date`
echo ""
 PK��j\�����$build_php/build_install_ext.templatenu�[���###########################################
EXTENSION_NAME="__extension_name__"
EXTENSION_DIR=__extension_dir__
EXTENSION_EXTRA_CONFIG="__extension_extra_config__"
###########################################


echo ""
echo "=============================================="
main_msg "Start building ${EXTENSION_NAME} Extension"
echo "=============================================="
echo `date`
echo ""

main_msg "Changing to build directory ${PHP_BUILD_DIR}/php-${PHP_VERSION}/${EXTENSION_DIR}" 
cd ${PHP_BUILD_DIR}/php-${PHP_VERSION}/${EXTENSION_DIR}
check_errs $? "Could not get into build directory"

main_msg "Running PHPize for ${EXTENSION_NAME} extension" 
${INSTALL_DIR}/bin/phpize 
check_errs $? "Could not run PHPize for ${EXTENSION_NAME}"

main_msg "Configuring ${EXTENSION_NAME} extension build" 
./configure ${EXTENSION_EXTRA_CONFIG} --with-php-config=${INSTALL_DIR}/bin/php-config
check_errs $? "Could not configure ${EXTENSION_NAME} extension build"

main_msg "Compiling ${EXTENSION_NAME} extension" 
make
check_errs $? "Could not compile ${EXTENSION_NAME} extension"

main_msg "Installing ${EXTENSION_NAME} extension" 
make install
check_errs $? "Could not install ${EXTENSION_NAME} extension"

if [  "${INST_USER}" = "root" ]; then
    echo "chown -R ${PHP_USR}:${PHP_USRGROUP} ${PHP_BUILD_DIR}/php-${PHP_VERSION}/${EXTENSION_DIR} "
	chown -R ${PHP_USR}:${PHP_USRGROUP} ${PHP_BUILD_DIR}/php-${PHP_VERSION}/${EXTENSION_DIR} 
	check_errs $? "Could not chown to ${PHP_USR}:${PHP_USRGROUP} for direcotry ${PHP_BUILD_DIR}/php-${PHP_VERSION}/${EXTENSION_DIR}"
fi

echo ""
echo "=============================================="
main_msg "${EXTENSION_NAME} extension build complete"
echo "=============================================="
echo `date`
echo ""
	
PK��j\��|i�
�
build_php/buildStep3.phpnu�[���<?php
if (!defined('LEGAL')) return;
echo '<h2 class="bottom_bar">' . TITLE . '</h2>';

$options = $check->pass_val['build_options'];
if ($options == NULL) // illegal entry
	return;

$err = '';
$tool = new BuildTool($options);
if (!$tool || !$tool->generate_script($err))
{
	echo '<div class="panel_error" align=left><span class="gui_error">Fail to generate build script, please try to manually fix the error first.<br>'.
		$err . '</span></div>';
	return;
}


$_SESSION['progress_file'] = $tool->progress_file;
$_SESSION['log_file'] = $tool->log_file;

$cmd = 'bash -c "exec ' . $tool->build_prepare_script . ' 1> ' . $tool->log_file . ' 2>&1" &';
exec($cmd);

?>

<div class="panel_error" align=left><span class="gui_error" id="errorzone">Please do not use the browser refresh, back and forward buttons while building PHP.</span></div>

<div class="xtbl_header"><p class="xtbl_title">
	Step 3 : Preparing for building PHP <?php echo $options->GetValue('PHPVersion');?> Binary
</p>
</div>
<form name="buildphp" method="post">
<input type="hidden" name="step" value="3">
<input type="hidden" name="manual_script", value="<?php echo $tool->build_manual_run_script; ?>">
<input type="hidden" name="extentions" value="<?php echo $tool->extension_used; ?>">
<input type="hidden" name="php_version" value="<?php echo $options->GetValue('PHPVersion');?>">

<script>
function getUpdate() {
	try { xhr = new XMLHttpRequest(); }
	catch(e)
	{
	    xhr = new ActiveXObject(Microsoft.XMLHTTP);
	}

	xhr.abort();
	xhr.open("GET", "buildProgress.php", true);
	xhr.send(null);

	xhr.onreadystatechange = function() {

	    if(xhr.readyState != 4)
	    	return;

		if(xhr.status == 200)
		{
			var ta = document.getElementById("statuszone");
			var pos = xhr.responseText.indexOf("\n**LOG_DETAIL**");
        	ta.innerHTML = xhr.responseText.substring(0,pos);

        	var loga = document.getElementById("logzone");
        	loga.innerHTML = xhr.responseText.substring(pos);
        	if (xhr.responseText.indexOf("\n**PREPARE_DONE**") >= 0) {
	        	document.getElementById("statusgraphzone").innerHTML = 'Preparation finished successfully.&nbsp;&nbsp;&nbsp;\
	        		<input type="submit" name="back" value="Back to Step 2 to change build options">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\
	        		<input type="submit" name="buildsubmit" value="Next">';
        	}
        	else if (xhr.responseText.indexOf("\n**ERROR**") >= 0) {
	        	document.getElementById("statusgraphzone").innerHTML = '<b>Stopped due to Error. Please manually fix it.</b>';
        	}
        	else {
            	setTimeout("getUpdate();", 2000);
			}
      	} else {
        	document.getElementById("statuszone").innerHTML = xhr.responseText
        		+ "<br>Status update refresh error " + xhr.status + "... please wait";
			setTimeout("getUpdate();", 2000);
      	}
	};
}

getUpdate();

</script>

<div><span id="statusgraphzone"><img src='/static/images/working.gif'></span></div>

<p><b>Main Status: </b></p>
<div style="margin:10px;border:1px solid rgb(134,142,167);outline: 3px solid #eaeaea;width:900px;height:160px;overflow:auto;font-family:Courier, monospace; font-size: 11px; background: #FFFFF7; color: #333333; padding: 5px 10px;">
<pre id="statuszone"></pre>
</div>
<p><b>Detailed Log: </b></p>
<div style="margin:10px;border:1px solid rgb(134,142,167);outline: 3px solid #eaeaea;width:900px;height:500px;overflow:auto;font-family:Courier, monospace; font-size: 11px; background: #222222; color: #ffffff; padding: 5px 10px;">
<pre id="logzone"></pre>
</div>


</form>
PK��j\�3�		build_php/buildconf.inc.phpnu�[���<?php

define ('LEGAL', 1);
define ('TITLE', 'Compile PHP with LSAPI');
define ('OPTION_VERSION', 3);

define ('BUILD_DIR', $_SERVER['LS_SERVER_ROOT'] . 'phpbuild');
define ('LAST_CONF', BUILD_DIR . '/savedconfig.'); // actual file will include . php base version.

define ('DEFAULT_INSTALL_DIR', $_SERVER['LS_SERVER_ROOT'].'lsphp'); // actual dir will include . php base version.

$PHP_VER = [
	'8' => [
		'8.3.2',
		'8.2.15',
		'8.1.27',
		'8.0.30'],
	'7' => [
		'7.4.32',
		'7.3.31',
		'7.2.34',
		'7.1.33',
		'7.0.33'],
	'5' => [
		'5.6.40',
		'5.5.38',
		'5.4.45',
		'5.3.29']
];

define ('LSAPI_VERSION', '8.1');
define ('SUHOSIN_VERSION', '0.9.38');
define ('APC_VERSION', '3.1.9');		// http://pecl.php.net/package/APC
define ('MEMCACHE_VERSION', '2.2.7');	// http://pecl.php.net/package/memcache for php5
define ('MEMCACHE7_VERSION', '4.0.5.2');	// http://pecl.php.net/package/memcache for php7.0-7.4
define ('MEMCACHE8_VERSION', '8.0');	// http://pecl.php.net/package/memcache for php8
define ('MEMCACHED_VERSION', '2.2.0'); // http://pecl.php.net/package/memcached
define ('MEMCACHED7_VERSION', '3.2.0'); // http://pecl.php.net/package/memcached for php7 only
define ('OPCACHE_VERSION', '7.0.5');	// http://pecl.php.net/package/ZendOpcache

$DEFAULT_PHP_PARAMS = [
	'8' => '--with-mysqli --with-zlib --enable-gd --enable-shmop --enable-sockets --enable-sysvsem --enable-sysvshm --enable-mbstring --with-iconv --with-pdo-mysql --enable-ftp --with-zip --with-curl --enable-soap --enable-xml --with-openssl --enable-bcmath',
	'7' => '--with-mysqli --with-zlib --with-gd --enable-shmop --enable-sockets --enable-sysvsem --enable-sysvshm --enable-mbstring --with-iconv --with-mcrypt --with-pdo-mysql --enable-ftp --enable-zip --with-curl --enable-soap --enable-xml --enable-json  --with-openssl --enable-bcmath',
	'5' => '--with-mysqli --with-zlib --with-gd --enable-shmop --enable-sockets --enable-sysvsem --enable-sysvshm --enable-mbstring --with-iconv --with-mysql --with-mcrypt --with-pdo --with-pdo-mysql --enable-ftp --enable-zip --with-curl --enable-soap --enable-xml --enable-json  --with-openssl --enable-bcmath',
	'4' => '--with-mysql  --with-zlib --with-gd --enable-shmop --enable-sockets --enable-sysvsem --enable-sysvshm --enable-magic-quotes --enable-mbstring',
	];


include_once( 'buildfunc.inc.php' );
PK��j\*�Uoobuild_php/buildProgress.phpnu�[���<?php
require_once('../../includes/auth.php');

include_once( 'buildconf.inc.php' );

$progress_file = $_SESSION['progress_file'];
$log_file = $_SESSION['log_file'];

$progress = htmlspecialchars(file_get_contents($progress_file));
echo $progress;

echo "\n**LOG_DETAIL** retrieved from $log_file\n";
$log = htmlspecialchars(file_get_contents($log_file));
echo $log;
PK��j\1$$ build_php/build_prepare.templatenu�[���###########################################
#   passed params

DL_METHOD="__dl_method__"
ENABLE_MAILHEADER=__enable_mailheader__
LSAPI_VERSION=__lsapi_version__

###########################################

echo "============================================================="
main_msg "Preparing all source code for building PHP ${PHP_VERSION} with LSAPI ${LSAPI_VERSION}"
echo "============================================================="
echo `date`
echo ""

echo "Changing to build directory ${PHP_BUILD_DIR}" 
cd ${PHP_BUILD_DIR}
check_errs $? "Could not get into build directory"

if [ -e "php-${PHP_VERSION}" ] ; then
	rm -rf php-${PHP_VERSION}
	check_errs $? "Could not delete old php directory ${PHP_BUILD_DIR}/php-${PHP_VERSION}"
fi

test_phpsrc_ok()
{
	main_msg "Extracting PHP source archive: tar -zxf ${1}" 
	tar -zxf ${1}
	if [ "$?" -ne "0" ] ; then
		## remove bad copy
		rm -f ${1}
		main_msg "Could not extract PHP source archive"
		return 1
	fi
	return 0
}


PHP_SRC=php-${PHP_VERSION}.tar.gz
PHP_SRC_READY=N

if [ -e "${PHP_SRC}" ] ; then
	main_msg "${PHP_SRC} already downloaded, use the saved copy."
	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] && [ `expr ${PHP_VERSION} : ".*alpha\|.*beta\|.*RC"` -gt 0 ] ; then
	DOWNLOAD_URL="https://downloads.php.net/~ab/${PHP_SRC}"
	main_msg "Retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	DOWNLOAD_URL="http://php.net/distributions/${PHP_SRC}"
	main_msg "Retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	DOWNLOAD_URL="http://us1.php.net/distributions/${PHP_SRC}"
	main_msg "Retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	DOWNLOAD_URL="http://us2.php.net/distributions/${PHP_SRC}"
	main_msg "Retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	DOWNLOAD_URL="http://us3.php.net/distributions/${PHP_SRC}"
	main_msg "Retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	MAIN_VER=`expr "${PHP_VERSION}" : "\(.\)"`
	DOWNLOAD_URL="http://museum.php.net/php${MAIN_VER}/${PHP_SRC}"
	main_msg "Try again, retrieving PHP source archive from ${DOWNLOAD_URL}" 
	${DL_METHOD} ${PHP_SRC} ${DOWNLOAD_URL}

	test_phpsrc_ok ${PHP_SRC}
	if [ "$?" -eq "0" ] ; then
		PHP_SRC_READY=Y
	fi
fi

if [ "${PHP_SRC_READY}" = "N" ] ; then
	check_errs $? "Fail to retrieve PHP source archive. Please try manually download."
fi
	
echo ""


if [ "${ENABLE_MAILHEADER}" -eq 1 ] ; then

	MAILHEADER_VER=`expr ${PHP_VERSION} : "\(.\..\)"`
	if [ "${MAILHEADER_VER}" = "5.2" ] ; then
		MAILHEADER_VER=5.2.x
	elif [ "${MAILHEADER_VER}" = "5.3" ] ; then 
		MAILHEADER_VER=5.3.x
	elif [ "${MAILHEADER_VER}" = "5.4" ] ; then 
		MAILHEADER_VER=5.4.x
	elif [ "${MAILHEADER_VER}" = "5.5" ] ; then 
		MAILHEADER_VER=5.5.x
	elif [ "${MAILHEADER_VER}" = "5.6" ] ; then 
		MAILHEADER_VER=5.6.x
	else
		MAILHEADER_VER=${PHP_VERSION}
	fi
	
	MHPATCH="php-${MAILHEADER_VER}-mail-header.patch"
	
	if [ -e ${MHPATCH} ] ; then
		rm -f ${MHPATCH}
		check_errs $? "Could not delete old copy ${MHPATCH}"
	fi

	DOWNLOAD_URL="http://choon.net/opensource/php/${MHPATCH}"
	main_msg "Retrieving mail header patch from ${DOWNLOAD_URL}"
	${DL_METHOD} ${MHPATCH} ${DOWNLOAD_URL}
	check_errs $? "Could not retrieve mail header patch"
	echo ""
	
	main_msg "Patching source with mail header patch"
	cd php-${PHP_VERSION}
	patch -p1 < ../${MHPATCH}
	check_errs $? "Could not patch source with mail header patch"
	cd ..
	echo ""
fi

# get LSAPI

if [ -e php-litespeed-${LSAPI_VERSION}.tgz ] ; then
	rm -f php-litespeed-${LSAPI_VERSION}.tgz
	check_errs $? "Could not delete old lsapi copy php-litespeed-${LSAPI_VERSION}.tgz"
fi

DOWNLOAD_URL="http://www.litespeedtech.com/packages/lsapi/php-litespeed-${LSAPI_VERSION}.tgz"
main_msg "Retrieving LSAPI from ${DOWNLOAD_URL}"
${DL_METHOD} "php-litespeed-${LSAPI_VERSION}.tgz" ${DOWNLOAD_URL}
check_errs $? "Could not retrieve LSAPI archive"

cd php-${PHP_VERSION}/sapi
check_errs $? "Could not get into php/sapi directory"

if [ -e litespeed/Makefile.frag ] ; then
	mv -f litespeed/Makefile.frag litespeed/Makefile.frag.package 
fi

main_msg "Extracting LSAPI archive: tar -xzf php-litespeed-${LSAPI_VERSION}.tgz" 
tar -xzf "../../php-litespeed-${LSAPI_VERSION}.tgz"
check_errs $? "Could not extract LSAPI archive"

if [ -e litespeed/Makefile.frag.package ] ; then
	mv -f litespeed/Makefile.frag.package litespeed/Makefile.frag 
fi

echo ""
echo "============================================================="
main_msg "Finished gathering all source code for building PHP ${PHP_VERSION}"
echo "============================================================="
echo `date`
echo ""
PK��j\���mh
h
$build_php/build_prepare_ext.templatenu�[���###########################################
EXTENSION_NAME="__extension_name__"
EXTENSION_SRC=__extension_src__
EXTRACT_METHOD="__extract_method__"
EXTENSION_DIR="__extension_dir__"
EXTENSION_DOWNLOAD_URL="__extension_download_url__"
###########################################

echo "============================================================="
main_msg "Preparing source code for building ${EXTENSION_NAME} Extension"
echo "============================================================="
echo ""

echo "Changing to build directory ${PHP_BUILD_DIR}" 
cd ${PHP_BUILD_DIR}
check_errs $? "Could not get into build directory"

if [ -e "${EXTENSION_SRC}" ] ; then
	main_msg "${EXTENSION_SRC} already downloaded, use the saved copy."
	NEW_DOWNLOAD=N
else
	main_msg "Retrieving ${EXTENSION_NAME} extension source archive ${EXTENSION_DOWNLOAD_URL}" 
	${DL_METHOD} ${EXTENSION_SRC} ${EXTENSION_DOWNLOAD_URL}
	check_errs $? "Fail to retrieve ${EXTENSION_NAME} extension source archive"
	echo ""
	NEW_DOWNLOAD=Y
fi

echo "Changing to build directory php-${PHP_VERSION}" 
cd php-${PHP_VERSION}
check_errs $? "Could not get into build directory"

echo "Copying ${EXTENSION_NAME} extension source archive" 
cp ../${EXTENSION_SRC} .
check_errs $? "Could not copy"

main_msg "Extracting ${EXTENSION_NAME} extension source archive: ${EXTRACT_METHOD} ${EXTENSION_SRC}" 
${EXTRACT_METHOD} ${EXTENSION_SRC}

if [ "$?" -ne "0" ] ; then
	# remove bad copy
	rm -f ${EXTENSION_SRC} ../${EXTENSION_SRC}
	check_errs $? "Fail to remove bad copy ${EXTENSION_SRC}"

	if [ "${NEW_DOWNLOAD}" = "Y" ] ; then
		check_errs 1 "Could not extract ${EXTENSION_NAME} extension source archive"
	else
		main_msg "Failed to extract existing copy. try download again."
	
		main_msg "Retrieving ${EXTENSION_NAME} extension source archive ${EXTENSION_DOWNLOAD_URL}" 
		${DL_METHOD} ../${EXTENSION_SRC} ${EXTENSION_DOWNLOAD_URL}
		check_errs $? "Fail to retrieve ${EXTENSION_NAME} extension source archive"
		NEW_DOWNLOAD=Y
	
		cp ../${EXTENSION_SRC} .
		check_errs $? "Could not copy"
	
		main_msg "Extracting ${EXTENSION_NAME} extension source archive: ${EXTRACT_METHOD} ${EXTENSION_SRC}" 
		${EXTRACT_METHOD} ${EXTENSION_SRC}
		
		if [ "$?" -ne "0" ] ; then
			# remove bad copy
			rm -f ${EXTENSION_SRC} ../${EXTENSION_SRC}
			check_errs $? "Fail to remove bad copy ${EXTENSION_SRC}"

			check_errs 1 "Could not extract ${EXTENSION_NAME} extension source archive"
		fi
		
	fi
	
fi


echo "============================================================="
main_msg "Finished gathering source code for building ${EXTENSION_NAME} extension"
echo "============================================================="
PK��j\�$ 55build_php/build_common.templatenu�[���PK��j\I�77�build_php/buildPHP.phpnu�[���PK��j\trQ00#build_php/build_manual_run.templatenu�[���PK��j\v�Y��'�'�	build_php/buildStep2.phpnu�[���PK��j\W/V����1build_php/buildStep1.phpnu�[���PK��j\I^�z�t�t�7build_php/buildfunc.inc.phpnu�[���PK��j\C����٬build_php/buildStep4.phpnu�[���PK��j\�vG��� �build_php/build_install.templatenu�[���PK��j\�����$P�build_php/build_install_ext.templatenu�[���PK��j\��|i�
�
��build_php/buildStep3.phpnu�[���PK��j\�3�		��build_php/buildconf.inc.phpnu�[���PK��j\*�Uoo
�build_php/buildProgress.phpnu�[���PK��j\1$$ ��build_php/build_prepare.templatenu�[���PK��j\���mh
h
$8build_php/build_prepare_ext.templatenu�[���PK�