Location: PHPKode > projects > DynPG > update/bin/run.php
<?php
    /*
    *   PERFORM INSTALLATION OF DYNPG UPDATE
    */
    session_start();

    // check correctness of posted data, otherwise redirect
		if ( empty($_POST['dynpg_install_step1_license']) || empty($_SESSION['DYNPG_UPDATE']) ) {
	        header("Location: start.php");
	        exit();
	    }

	// import
		require 'bin.php';
		require '../../config.php';
		require dirname(__FILE__) . '/../../functions.php';

	// init var
		define('__FAIL_STEP', 0);
		define('__OK_STEP', 1);
		define('__WARN_STEP', 2);

		$install_process['message'] = '';
		$install_process['abort']   = FALSE;
		$finished_href_dest 		= '../../index.php';

	// init language processor
		$langHdl = @dynpg_install_InitLanguageProc(dynpg_backend_language());
		$langStr = dynpg_backend_language();

	//run the update
		dynpg_update_run_main();

	/**
	* dynpg_install_run_SuccessStep($_type, $_value): -> string(html-code)
	*
	* shows information about the update status
	*
	* @package DynPG Update Engine
	* @author Daniel Schliebner
	* @return string(html-code)
	*/
	function dynpg_install_run_SuccessStep($_type = 0, $_value = '')
	{
		switch ( $_type ) {
			case 0: return '<div id="dynpg_install_run_stepFAIL"><img src="install_error.gif" alt="error" /> ' . $_value . '</div>'; break;
			case 1: return '<div id="dynpg_install_run_stepOKAY"><img src="install_okay.gif" alt="okay" /> ' . $_value . '</div>'; break;
			case 2: return '<div id="dynpg_install_run_stepWARN"><img src="install_warn.gif" alt="warning" /> ' . $_value . '</div>'; break;
			default: return '<div id="dynpg_install_run_stepFAIL"><img src="install_error.gif" alt="error" /> ' . $_value . '</div>'; break;
		}
	}


	/**
	* dynpg_install_run_GetSingleSQLQueries($_sql_query): -> array of sql-statements
	*
	* creates and returns an array of single sql instructions out of a multi line sql-string
	*
	* @package DynPG Update Engine
	* @author Daniel Schliebner
	* @return array of sql-statements
	*/
	function dynpg_install_run_GetSingleSQLQueries($_sql_query) {
		$_sql_query = trim($_sql_query);
		$_sql_query = ereg_replace("\n#[^\n]*\n", "\n", $_sql_query);
		$_sql_query = ereg_replace("\n--[^\n]*\n", "\n", $_sql_query);

		$buffer    = Array();
		$return    = Array();
		$in_string = FALSE;

		for ( $i = 0; $i < strlen($_sql_query) - 1; $i++ ) {
			if ( $_sql_query[$i] == ";" && !$in_string ) {
				$return[]   = substr($_sql_query, 0, $i);
				$_sql_query = substr($_sql_query, $i + 1);
				$i = 0;
			}

			if($in_string && ($_sql_query[$i] == $in_string) && $buffer[1] != "\\") {
				$in_string = FALSE;
			} elseif ( !$in_string && ($_sql_query[$i] == '"' || $_sql_query[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\") ) {
				$in_string = $_sql_query[$i];
			}

			if( isset($buffer[1]) ) {
				$buffer[0] = $buffer[1];
			}

			$buffer[1] = $_sql_query[$i];
		}

		if( !empty($_sql_query) ) {
			$return[] = $_sql_query;
		}

		return $return;
	}



	/**
	* dynpg_update_run_RunSingleUpdate($dir, $new_version): -> Boolean
	*
	*executes a sql update file and returns success status (needs already initialized db connection)
	*renames update.php-dist to update.php and starts execution
	*
	* @package DynPG Update Engine
	* @author Sebastian Bauersfeld
	* @return Boolean
	*/
	function dynpg_update_run_RunSingleUpdate($dir, $new_version) {
		global $langHdl;

		//execute update.php
			if ( file_exists($dir . '/update.php-dist') ) {
				$update_fct = create_function('',trim(implode('', file($dir . '/update.php-dist'))));
				$return = $update_fct();

				if(!$return)
					return false;
			}

		//sql update
			$db_instr = file_exists($dir . "/db_update.sql")? implode('', file($dir . "/db_update.sql")): implode('', file($dir . "/update.sql"));
			$db_instr = dynpg_install_run_GetSingleSQLQueries($db_instr);

			foreach ( $db_instr as $instr ) {
				$instr = str_replace('{$DYNPG_VERSION}', $new_version, $instr);

				if ( !mysql_query($instr) )
					$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__WARN_STEP, $langHdl->str['lang_update_step2_mysql_db_error'] . ' (\'db_update.sql ' . $langHdl->str['lang_update_step2_mysql_db_reports'] . ': '.htmlentities(mysql_error()).'\') ');

			}

			return true;
	}



	/**
	* dynpg_update_run_CompareVersions($v1, $v2): ->integer
	*
	*compares two dynpg-versions (-1: $v1 older, 0: same version, 1: $v1 newer)
	*
	* @package DynPG Update Engine
	* @author Sebastian Bauersfeld
	* @return integer
	*/
	function dynpg_update_run_CompareVersions($v1, $v2) {
		$num_array1 = split("\.",$v1);
		$num_array2 = split("\.",$v2);

		$i=0;
		while($i < min(count($num_array1),count($num_array2))){
			if($num_array1[$i]<$num_array2[$i]) return -1;
			if($num_array1[$i]>$num_array2[$i]) return 1;
			$i++;
		}

		if(count($num_array1)==count($num_array2))
			return 0;
		else if(count($num_array1)>count($num_array2))
			return 1;
		else
			return -1;
	}



	/**
	* dynpg_update_run_DetectNecessaryUpdates($update_dir, $current_v): -> array of updates(Strings)
	*
	*returns an array of dir names containing the necessary updates
	*needs valid db connection
	*returns empty array if update is incomplete
	*
	* @package DynPG Update Engine
	* @author Sebastian Bauersfeld
	* @return array of Strings
	*/
	function dynpg_update_run_DetectNecessaryUpdates($update_dir, $current_v) {
		$available_updates = array();
		$dir = opendir($update_dir);

		//select valid updates
		while ($file = readdir($dir)) {
			if (strpos(strtolower($file), 'plugin') !== false) {
				// add plugin
				array_push($available_updates, $file);
			}

			if ( substr($file,0,7) == "update_" ){
				$v = split("_",$file);

				if( dynpg_update_run_CompareVersions($v[1], $current_v) >= 0 ) {
					// compare versions(get only newer updates)
					array_push($available_updates, $file);
				}
			}
		}

		closedir($dir);

		// extract plugin installations

		$available_plugins = array_filter($available_updates, create_function('$v', 'return is_integer(strpos(strtolower($v), "plugin"));'));
		$available_updates = array_filter($available_updates, create_function('$v', 'return (strpos(strtolower($v), "plugin") === false);'));

		// bubble sort the updates
		for ($i = count($available_updates) - 2; $i>=0; $i--) {
			for ($j=0; $j<=$i; $j++) {

				$v1 = split("_", $available_updates[$j]);
				$v2 = split("_", $available_updates[$j+1]);

				if (dynpg_update_run_CompareVersions($v1[1],$v2[1]) == 1){
					$temp = $available_updates[$j];
					$available_updates[$j] = $available_updates[$j+1];
					$available_updates[$j+1] = $temp;
				}
			}
		}

		// merge sorted update array and plugin array

		$_  = array_merge($available_updates, $available_plugins);

		return $_;
	}


	/**
	* dynpg_update_run_main(): -> boolean
	*
	*main function of update, returns whether update succeeded or not
	*
	* @package DynPG Update Engine
	* @author Sebastian Bauersfeld
	* @return boolean
	*/
	function dynpg_update_run_main() {
		global $langHdl;

		@session_start();

		if ( empty($_POST['dynpg_install_step1_license']) || empty($_SESSION['DYNPG_UPDATE']) ) {
			header("Location: start.php");
			exit();
		}

		//init db connection
		$mysql_connection = @mysql_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD);

		if ( !$mysql_connection ) {
			$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__FAIL_STEP, $langHdl->str['lang_update_step2_mysql_error']);
			$GLOBALS["install_process"]['abort'] = TRUE;
			return false;
		}


		$succeed = @mysql_select_db(MYSQL_DATABASE);

		if ( !$succeed ) {
			$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__FAIL_STEP, $langHdl->str['lang_update_step2_mysql_conn_error'] . ' \''.htmlentities($_POST['dynpg_mysql_dbname']).'\'!');
			$GLOBALS["install_process"]['abort'] = TRUE;
			return false;
		}



		//execute update
		$current_version = mysql_fetch_object(mysql_query('SELECT * FROM `dynpg_cms_bin`'));
		$current_version = $current_version->version;
		$current_version = split(" ", $current_version);
		$current_version = $current_version[3];

		$new_version = trim(implode('', file('../../VERSION')));

		//get available updates
		$av_upd = dynpg_update_run_DetectNecessaryUpdates("..", $current_version);

		if ( count($av_upd)==0 )
			$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__WARN_STEP, $langHdl->str['lang_update_step2_no_update']);


		//run them
		foreach($av_upd as $update){

			//run sql update
			if(!dynpg_update_run_RunSingleUpdate("../" . $update, $new_version)) {
				$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__FAIL_STEP, $langHdl->str['lang_update_step2_abort']);
				$GLOBALS["install_process"]['abort'] = TRUE;

				//close db connection
				$succeed = @mysql_close($mysql_connection);

				if ( !$succeed )
					$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__WARN_STEP, $langHdl->str['lang_update_step2_mysql_close_error']);


				//close the session
				@session_unset();
				@session_destroy();

				return false;
			}

			if (! preg_match('/update_([^_]+)_([^_]+)/si', $update, $versions) ) {
				$versions[1] = ucfirst(str_replace('_', ' ', $update));
				$versions[2] = ucfirst(str_replace('_', ' ', $update));
				$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__OK_STEP, "{$versions[1]} " . $langHdl->str['lang_update_step2_installed']);
			} else {
				$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__OK_STEP, str_replace('{$V1}', $versions[1], str_replace('{$V2}', $versions[2], $langHdl->str['lang_update_step2_update_ok'])));
			}
		}


		$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__OK_STEP, $langHdl->str['lang_update_step2_mysql_db_success']);


		//close db connection
		$succeed = @mysql_close($mysql_connection);

		if ( !$succeed )
			$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__WARN_STEP, $langHdl->str['lang_update_step2_mysql_close_error']);

		$file = fopen( '../update.php', 'w+' );

	    if ( $file ) {
	        fwrite($file, '<?php exit; ?>');
	        fclose($file);
	    } else {
	        $install_process['message'] .= dynpg_install_run_SuccessStep(__WARN_STEP, $langHdl->str['lang_update_step2_terminate_error']);
	        $install_process['abort'] = FALSE;
	        $finished_href_dest = '../../incomplete.php?update=yes';
	    }

		//ready: close the session
		$GLOBALS["install_process"]['message'] .= dynpg_install_run_SuccessStep(__OK_STEP, $langHdl->str['lang_update_step2_update_succeed']);
		@session_unset();
		@session_destroy();
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

		<title>
			<?php print $langHdl->str['lang_update_step2_title'] ?>
		</title>

		<link rel="stylesheet" type="text/css" href="update.css">

		<script src="java.js" type="text/javascript"></script>
	</head>

	<body>

	<a name="__self"></a>
	<table border="0" Cellpadding="0" Cellspacing="0" width="100%">
		<tr>
			<td valign="top" align="left" width="100%">
				<table border="0" Cellpadding="0" Cellspacing="0" width="100%">
				 <tr>
				  <td valign="top" align="left" width="705" style="background-image: url('logo.gif'); background-repeat: no-repeat;">
				  <div id="dynpg_installation_steps">
						<img src="step-on.gif" alt="Step 1 - Active" class="dynpg_installation_steps_img" />
						<img src="step-on.gif" alt="Step 2 - Active" class="dynpg_installation_steps_img" />
					</div>
                  </td>
				  <td valign="center" align="right" style="background-image: url('head-bg.gif');"><img src="head-right.gif" alt="Head-Right" /></td>
				 </tr>
				</table>
			</td>
		</tr>
	</table>

	<table border="0" cellspacing="0" align="center" class="dynpg_installation_step">
		<tr>
			<td height="50" style="background-image:url('stephead.gif');"><div id="dynpg_installation_step_headline"><?php print $langHdl->str['lang_update_step2_subtitle'] ?></div></td>
		</tr>
		<tr>
			<td><div id="dynpg_installation_step4_text">

			<h4><?php print $langHdl->str['lang_update_step2_headline'] ?></h4>

			<?php echo $install_process['message']; ?>

			<?php if ( !$install_process['abort'] ) { ?>
            <div align="center" id="dynpg_install_run_stepINFO"><?php print $langHdl->str['lang_update_step2_delete_hint'] ?></div>

            <div align="center" id="dynpg_install_run_stepINFO"><a href="<?php echo $finished_href_dest ?>"><strong><?php print $langHdl->str['lang_update_step2_dpg_admin'] ?></strong></a></div>
            <?php } ?>

			<p style="margin: 20px;"></p>

			<form action="start.php" method="post" name="installation_step4_back">
    			<?php foreach ( $_POST as $key => $value ) { ?>
				<?php if ( !strpos($key, 'password') ) { ?>
    			<input type="hidden" name="<?php echo $key ?>" id="<?php echo $key ?>" value="<?php echo stripslashes($value) ?>" />
                <?php } } ?>

				<?php if ( $install_process['abort'] ) { ?>
                <input type="image" src="button_back.gif" alt="zur&uuml;ck" title="vorheriger Schritt" align="left" border="0" />
                <?php } ?>

                <?php if ( !$install_process['abort'] ) { ?>
                <!-- Maybe a close button here. -->
                <?php } ?>
			</form>

			</div></td>
		</tr>
		<tr>
			<td height="30" style="background-color: white; background-image:url('stepfood.gif');"></td>
		</tr>
	</table>

	</body>
</html>
Return current item: DynPG