-
-
Save manmohanmirkar123/8a5743581b17fd2230a1a479c233b3de to your computer and use it in GitHub Desktop.
Wordpress auto installer script PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function($){ | |
/* | |
Script Name: WP Auto Installer | |
Author: Mohan Dere | |
Version: 1.0 | |
Description : This script install new wordpress setup, create database with tables with content & run search replace database for new urls. | |
Last Update: 13 Mar 15 | |
*/ | |
$(window).load(function() { | |
if( $('#stagging-installer__wrap').length ){ | |
console.log('Importer script ready'); | |
var $response = $('#response'); | |
var $error = $('#error'); | |
var $installer__wrap = $('#stagging-installer__wrap'); | |
var reqParm = { | |
'action' : 'begin_stagging_creation', | |
'wp_project_id' : $installer__wrap.attr('data-wp_project_id'), | |
'installer_process' : 'create_db' | |
}; | |
$.post( ajaxurl, reqParm, function(data) { | |
data = $.parseJSON(data); | |
if ( data.db == "error etablishing connection" ) { | |
$errors.show().append('<p style="margin-bottom:0px;">• Error Establishing a Database Connection.</p>'); | |
} else{ | |
$('.progress-bar').animate({width: "16.5%"}); | |
// Fire Step | |
// We dowload WordPress | |
$response.html("<p>WordPress Download in Progress ...</p>"); | |
reqParm.installer_process = 'download_wp'; | |
$.post(ajaxurl, reqParm, function() { | |
unzip_wp(); | |
}); | |
} | |
}); | |
} | |
// Let's unzip WordPress | |
function unzip_wp() { | |
$response.html("<p>Decompressing Files...</p>" ); | |
$('.progress-bar').animate({width: "33%"}); | |
reqParm.installer_process = 'unzip_wp'; | |
$.post(ajaxurl, reqParm, function(data) { | |
wp_config(); | |
}); | |
} | |
// Let's create the wp-config.php file | |
function wp_config() { | |
$response.html("<p>File Creation for wp-config...</p>"); | |
$('.progress-bar').animate({width: "49.5%"}); | |
reqParm.installer_process = 'wp_config'; | |
$.post(ajaxurl, reqParm, function(data) { | |
update_wp(); | |
}); | |
} | |
// CDatabase | |
function update_wp() { | |
$response.html("<p>Database Updatation in Progress...</p>"); | |
$('.progress-bar').animate({width: "66%"}); | |
reqParm.installer_process = 'update_wp'; | |
$.post(ajaxurl, reqParm, function(data) { | |
srdb_db(); | |
}); | |
} | |
// Plugin | |
function srdb_db() { | |
$response.html("<p>Replacing Database in Progress...</p>"); | |
$('.progress-bar').animate({width: "82.5%"}); | |
reqParm.installer_process = 'srdb_db'; | |
$.post(ajaxurl, reqParm, function(data) { | |
install_success(); | |
}); | |
} | |
// Remove the archive | |
function install_success() { | |
$('.progress-bar').animate({width: "100%"}); | |
reqParm.installer_process = 'install_success'; | |
$.post(ajaxurl, reqParm, function(data) { | |
var data = $.parseJSON(data); | |
$('#please-wait-loader').html("<p>Successful installation completed</p>"); | |
$response.html('<p><a href="'+data.stagging_url+'" target="_blank">Visit Staggig Site</a></p>'); | |
$('.progress').fadeOut(); | |
}); | |
} | |
}); | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Script Name: WP Auto Installer | |
Author: Mohan Dere | |
Version: 1.0 | |
Description : This script install new wordpress setup, create database with tables with content & run search replace database for new urls. | |
Last Update: 13 Mar 15 | |
*/ | |
add_action( 'wp_enqueue_scripts', 'importer_load_scripts' ); | |
function importer_load_scripts() { | |
wp_enqueue_script( 'importer_script', CPM_PLUGIN_URI . '/wp-auto-installer/script.js', array('jquery') ); | |
} | |
if ( ! function_exists( '_' ) ) { | |
function _( $str ) { | |
echo $str; | |
} | |
} | |
function sanit( $str ) { | |
return addcslashes( str_replace( array( ';', "\n" ), '', $str ), '\\' ); | |
} | |
/** | |
* Get all details requird | |
**/ | |
function wpqi_get_required_imp( $wp_project_id = 0 ){ | |
global $project; | |
$project = get_post( $wp_project_id ); | |
$project_name_key = $project->post_title; | |
$imp = array(); | |
$imp[ 'DB_NAME' ] = str_replace('-', '_', $project_name_key ); | |
$imp[ 'DB_USER' ] = 'root'; | |
$imp[ 'DB_PASSWORD' ] = ''; | |
$imp[ 'DB_HOST' ] = 'localhost'; | |
$imp[ 'DB_CHARSET' ] = 'utf-8'; | |
$imp[ 'TABLE_PREFIX' ] = 'wp_'; | |
$imp[ 'DELETE_DEFAULT_CONTENT' ] = 1; | |
$imp[ 'INSTALLATION_LANGUAGE' ] = 'en_US'; | |
$imp[ 'INSTALLATION_FOLDER' ] = str_replace('-', '.', $project_name_key ); | |
$imp[ 'SITE_TITLE' ] = $project_name_key; | |
$imp[ 'WP_USER' ] = 'admin'; | |
$imp[ 'WP_PASS' ] = str_replace('-', '.', $project_name_key ); | |
$imp[ 'USER_EMAIL' ] = get_the_author_meta( 'user_email', $project->post_author ); | |
return $imp; | |
} | |
function wpqi_get_source_directory_path( $source_directory = '' ){ | |
$server_root_dir = $_SERVER['DOCUMENT_ROOT']; | |
$directory_path = $server_root_dir . '/' . $source_directory; | |
if( file_exists( $directory_path ) ){ | |
return $directory_path; | |
}else{ | |
return ''; | |
} | |
//$wpDir = ABSPATH; | |
//print_r($wpDir); | |
} | |
function wpqi_get_destination_directory_path( $destination_directory = '' ){ | |
$server_root_dir = $_SERVER['DOCUMENT_ROOT']; | |
$directory_path = $server_root_dir . '/' . $destination_directory; | |
if( file_exists( $directory_path ) ){ | |
return $directory_path; | |
}else{ | |
mkdir( $directory_path ); | |
} | |
// We set the good writing rights | |
chmod( $directory_path , 0755 ); | |
//$wpDir = ABSPATH; | |
//print_r($wpDir); | |
return $directory_path; | |
} | |
/** | |
* Take a serialised array and unserialise it replacing elements as needed and | |
* unserialising any subordinate arrays and performing the replace on those too. | |
* | |
* @param string $from String we're looking to replace. | |
* @param string $to What we want it to be replaced with | |
* @param array $data Used to pass any subordinate arrays back to in. | |
* @param bool $serialised Does the array passed via $data need serialising. | |
* | |
* @return array The original array with all elements replaced as needed. | |
*/ | |
function recursive_unserialize_replace( $from = '', $to = '', $data = '', $serialised = false ) { | |
// some unseriliased data cannot be re-serialised eg. SimpleXMLElements | |
try { | |
if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) { | |
$data = recursive_unserialize_replace( $from, $to, $unserialized, true ); | |
} | |
elseif ( is_array( $data ) ) { | |
$_tmp = array( ); | |
foreach ( $data as $key => $value ) { | |
$_tmp[ $key ] = recursive_unserialize_replace( $from, $to, $value, false ); | |
} | |
$data = $_tmp; | |
unset( $_tmp ); | |
} | |
else { | |
if ( is_string( $data ) ) | |
$data = str_replace( $from, $to, $data ); | |
} | |
if ( $serialised ) | |
return serialize( $data ); | |
} catch( Exception $error ) { | |
} | |
return $data; | |
} | |
/** | |
* The main loop triggered in step 5. Up here to keep it out of the way of the | |
* HTML. This walks every table in the db that was selected in step 3 and then | |
* walks every row and column replacing all occurences of a string with another. | |
* We split large tables into 50,000 row blocks when dealing with them to save | |
* on memmory consumption. | |
* | |
* @param mysql $connection The db connection object | |
* @param string $search What we want to replace | |
* @param string $replace What we want to replace it with. | |
* @param array $tables The tables we want to look at. | |
* | |
* @return array Collection of information gathered during the run. | |
*/ | |
function icit_srdb_replacer( $connection, $search = '', $replace = '', $tables = array( ) ) { | |
$report = array( 'tables' => 0, | |
'rows' => 0, | |
'change' => 0, | |
'updates' => 0, | |
'start' => microtime( ), | |
'end' => microtime( ), | |
'errors' => array( ), | |
); | |
if ( is_array( $tables ) && ! empty( $tables ) ) { | |
foreach( $tables as $table ) { | |
$report[ 'tables' ]++; | |
$columns = array( ); | |
// Get a list of columns in this table | |
$fields = mysql_query( 'DESCRIBE ' . $table, $connection ); | |
while( $column = mysql_fetch_array( $fields ) ) | |
$columns[ $column[ 'Field' ] ] = $column[ 'Key' ] == 'PRI' ? true : false; | |
// Count the number of rows we have in the table if large we'll split into blocks, This is a mod from Simon Wheatley | |
$row_count = mysql_query( 'SELECT COUNT(*) FROM ' . $table, $connection ); | |
$rows_result = mysql_fetch_array( $row_count ); | |
$row_count = $rows_result[ 0 ]; | |
if ( $row_count == 0 ) | |
continue; | |
$page_size = 50000; | |
$pages = ceil( $row_count / $page_size ); | |
for( $page = 0; $page < $pages; $page++ ) { | |
$current_row = 0; | |
$start = $page * $page_size; | |
$end = $start + $page_size; | |
// Grab the content of the table | |
$data = mysql_query( sprintf( 'SELECT * FROM %s LIMIT %d, %d', $table, $start, $end ), $connection ); | |
if ( ! $data ) | |
$report[ 'errors' ][] = mysql_error( ); | |
while ( $row = mysql_fetch_array( $data ) ) { | |
$report[ 'rows' ]++; // Increment the row counter | |
$current_row++; | |
$update_sql = array( ); | |
$where_sql = array( ); | |
$upd = false; | |
foreach( $columns as $column => $primary_key ) { | |
$edited_data = $data_to_fix = $row[ $column ]; | |
// Run a search replace on the data that'll respect the serialisation. | |
$edited_data = recursive_unserialize_replace( $search, $replace, $data_to_fix ); | |
// Something was changed | |
if ( $edited_data != $data_to_fix ) { | |
$report[ 'change' ]++; | |
$update_sql[] = $column . ' = "' . mysql_real_escape_string( $edited_data ) . '"'; | |
$upd = true; | |
} | |
if ( $primary_key ) | |
$where_sql[] = $column . ' = "' . mysql_real_escape_string( $data_to_fix ) . '"'; | |
} | |
if ( $upd && ! empty( $where_sql ) ) { | |
$sql = 'UPDATE ' . $table . ' SET ' . implode( ', ', $update_sql ) . ' WHERE ' . implode( ' AND ', array_filter( $where_sql ) ); | |
$result = mysql_query( $sql, $connection ); | |
if ( ! $result ) | |
$report[ 'errors' ][] = mysql_error( ); | |
else | |
$report[ 'updates' ]++; | |
} elseif ( $upd ) { | |
$report[ 'errors' ][] = sprintf( '"%s" has no primary key, manual change needed on row %s.', $table, $current_row ); | |
} | |
} | |
} | |
} | |
} | |
$report[ 'end' ] = microtime( ); | |
return $report; | |
} | |
function get_replacewith_url( $installation_folder = '') { | |
$replacement_url = 'http'; | |
if( @$_SERVER["HTTPS"] == "on" ){ | |
$replacement_url .= "s"; | |
} | |
$replacement_url .= "://"; | |
if( $_SERVER["SERVER_PORT"] != "80" ){ | |
$replacement_url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"] .'/'. $installation_folder; | |
} else { | |
$replacement_url .= $_SERVER["SERVER_NAME"] .'/'. $installation_folder; | |
} | |
return $replacement_url; | |
} | |
function get_siteurl_option_from_db( $host,$u,$p,$n ){ | |
$connection = @mysql_connect( $host, $u, $p ); | |
@mysql_select_db( $n, $connection ); | |
$result = mysql_query( 'SELECT option_value FROM wp_options WHERE `option_id` =1', $connection ); | |
$row = mysql_fetch_array($result); | |
return $row['option_value']; | |
} | |
add_action( 'wp_ajax_begin_stagging_creation', 'begin_stagging_creation_callback' ); | |
function begin_stagging_creation_callback() { | |
$req_imp = wpqi_get_required_imp( $_POST['wp_project_id'] ); | |
$source_dir_path = wpqi_get_source_directory_path( '43654-wp-installer.zip' ); | |
$destination_dir_path = wpqi_get_destination_directory_path( $req_imp['INSTALLATION_FOLDER'] ); | |
switch( $_POST['installer_process'] ) { | |
case "create_db" : | |
$data = array(); | |
try { | |
$dsn = "mysql:host=".$req_imp['DB_HOST']; | |
$pdo = new PDO( $dsn, $req_imp['DB_USER'], $req_imp['DB_PASSWORD'] ); | |
//Creation of user "user_name" | |
$sql = "CREATE DATABASE IF NOT EXISTS ". $req_imp['DB_NAME'] ."; | |
CREATE USER '".$req_imp['DB_USER']."'@'" .$req_imp['DB_HOST']. "' IDENTIFIED BY '". $req_imp['DB_PASSWORD'] ."'; | |
GRANT ALL ON '" .$req_imp['DB_NAME']. "'.* TO '". $req_imp['DB_USER'] ."'@'" .$req_imp['DB_HOST']. "'; | |
FLUSH PRIVILEGES;"; | |
$pdo->exec($sql) | |
or die( print_r($pdo->errorInfo(), true) ); | |
} catch (PDOException $e) { | |
$data['db'] = "error etablishing connection"; | |
} | |
// We send the response | |
echo json_encode( $data ); | |
break; | |
case "download_wp" : | |
$data = array(); | |
// Get WordPress language | |
//$language = substr( $req_imp['language'], 0, 6 ); | |
//define( 'WP_API_CORE' , 'http://api.wordpress.org/core/version-check/1.7/?locale=' ); | |
// Get WordPress data | |
//$wp = json_decode( file_get_contents( WP_API_CORE . $language ) )->offers[0]; | |
/*--------------------------*/ | |
/* We download the latest version of WordPress | |
/*--------------------------*/ | |
/*if ( ! file_exists( WPQI_CACHE_CORE_PATH . 'wordpress-' . $wp->version . '-' . $language . '.zip' ) ) { | |
file_put_contents( WPQI_CACHE_CORE_PATH . 'wordpress-' . $wp->version . '-' . $language . '.zip', file_get_contents( $wp->download ) ); | |
}*/ | |
if( $source_dir_path ){ | |
//chmod( $source_dir_path , 0777 ); | |
file_put_contents( $destination_dir_path . '/wordpress-cached.zip', file_get_contents( $source_dir_path ) ); | |
} | |
break; | |
case "unzip_wp" : | |
$data = array(); | |
$zip = new ZipArchive; | |
// We verify if we can use the archive | |
if ( $zip->open( $destination_dir_path . '/wordpress-cached.zip' ) === true ) { | |
// Let's unzip | |
$zip->extractTo( $destination_dir_path ); | |
$zip->close(); | |
chmod( $destination_dir_path , 0777 ); | |
chmod( $destination_dir_path . '/wordpress-cached.zip' , 0777 ); | |
unlink( $destination_dir_path . '/wordpress-cached.zip' ); // We remove WordPress folder | |
} | |
break; | |
case "wp_config" : | |
$data = array(); | |
/*--------------------------*/ | |
/* Let's create the wp-config file | |
/*--------------------------*/ | |
// We retrieve each line as an array | |
$config_file = file( $destination_dir_path . '/wp-config-sample.php' ); | |
// We change the data | |
$key = 0; | |
foreach ( $config_file as &$line ) { | |
if ( '$table_prefix =' == substr( $line, 0, 16 ) ) { | |
$line = '$table_prefix = \'' . sanit( $req_imp[ 'TABLE_PREFIX' ] ) . "';\r\n"; | |
continue; | |
} | |
if ( ! preg_match( '/^define\(\'([A-Z_]+)\',([ ]+)/', $line, $match ) ) { | |
continue; | |
} | |
$constant = $match[1]; | |
switch ( $constant ) { | |
case 'DB_NAME' : | |
$line = "define('DB_NAME', '" . sanit( $req_imp[ 'DB_NAME' ] ) . "');\r\n"; | |
break; | |
case 'DB_USER' : | |
$line = "define('DB_USER', '" . sanit( $req_imp['DB_USER'] ) . "');\r\n"; | |
break; | |
case 'DB_PASSWORD' : | |
$line = "define('DB_PASSWORD', '" . sanit( $req_imp['DB_PASSWORD'] ) . "');\r\n"; | |
break; | |
case 'DB_HOST' : | |
$line = "define('DB_HOST', '" . sanit( $req_imp['DB_HOST'] ) . "');\r\n"; | |
break; | |
case 'WPLANG' : | |
$line = "define('WPLANG', '" . sanit( $req_imp['INSTALLATION_LANGUAGE'] ) . "');\r\n"; | |
break; | |
} | |
} | |
unset( $line ); | |
$handle = fopen( $destination_dir_path . '/wp-config.php', 'w' ); | |
foreach ( $config_file as $line ) { | |
fwrite( $handle, $line ); | |
} | |
fclose( $handle ); | |
// We set the good rights to the wp-config file | |
chmod( $destination_dir_path . '/wp-config.php', 0666 ); | |
break; | |
case "update_wp" : | |
$data = array(); | |
$connection = mysql_connect($req_imp['DB_HOST'], $req_imp['DB_USER'], $req_imp['DB_PASSWORD'] ) or $data['connection_error'] = mysql_error(); | |
mysql_query("DROP DATABASE IF EXISTS ".$req_imp[ 'DB_NAME' ] ) or $data['drop_db_error'] = mysql_error(); | |
mysql_query("CREATE DATABASE ".$req_imp[ 'DB_NAME' ] ) or $data['create_table_error'] = mysql_error(); | |
mysql_select_db( $req_imp[ 'DB_NAME' ] ) or $data['select_db'] = mysql_error(); | |
//check for sql file and use that name. | |
$sql_files = glob( $destination_dir_path . '/*.sql' ); | |
if( !empty( $sql_files ) ){ | |
$sql_file = $sql_files[0]; | |
SplitSQL( $sql_file, $delimiter = ';'); | |
} | |
echo json_encode( $data ); | |
echo json_encode( $sql_files ); | |
break; | |
case "srdb_db" : | |
$data = array(); | |
$connection = mysql_connect( $req_imp['DB_HOST'], $req_imp['DB_USER'], $req_imp['DB_PASSWORD'] ) or $data['connection_error'] = mysql_error(); | |
mysql_select_db( $req_imp[ 'DB_NAME' ] ) or $data['select_db'] = mysql_error(); | |
//loop to show all the tables and fields | |
$loop = mysql_query("SHOW tables FROM ".$req_imp['DB_NAME'] ) or $data['show_tables'] = mysql_error(); | |
$tables = array( ); | |
while( $table = mysql_fetch_array( $loop ) ){ | |
array_push( $tables, $table[0] ); | |
} | |
$search = get_siteurl_option_from_db( $req_imp['DB_HOST'], $req_imp['DB_USER'], $req_imp['DB_PASSWORD'], $req_imp['DB_NAME'] ); | |
$replace = get_replacewith_url( $req_imp['INSTALLATION_FOLDER'] ); | |
icit_srdb_replacer( $connection, $search, $replace, $tables ); | |
echo json_encode( $data ); | |
break; | |
case "install_success" : | |
$data = array(); | |
$stagging_url = get_siteurl_option_from_db( $req_imp['DB_HOST'], $req_imp['DB_USER'], $req_imp['DB_PASSWORD'], $req_imp['DB_NAME'] ); | |
$data['stagging_url'] = $stagging_url; | |
echo json_encode($data); | |
break; | |
} | |
wp_die(); // this is required to terminate immediately and return a proper response | |
} | |
function SplitSQL($file, $delimiter = ';') | |
{ | |
set_time_limit(0); | |
if (is_file($file) === true) | |
{ | |
$file = fopen($file, 'r'); | |
if (is_resource($file) === true) | |
{ | |
$query = array(); | |
while (feof($file) === false) | |
{ | |
$query[] = fgets($file); | |
if (preg_match('~' . preg_quote($delimiter, '~') . '\s*$~iS', end($query)) === 1) | |
{ | |
$query = trim(implode('', $query)); | |
if (mysql_query($query) === false) | |
{ | |
echo '<p>ERROR: <blockquote> ' . $query . '</blockquote></p>' . "\n"; | |
} | |
else | |
{ | |
} | |
while (ob_get_level() > 0) | |
{ | |
ob_end_flush(); | |
} | |
flush(); | |
} | |
if (is_string($query) === true) | |
{ | |
$query = array(); | |
} | |
} | |
return fclose($file); | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment