File: index.php

Recommend this page to a friend!
  Classes of Alessandro Quintiliani  >  PHP Multi MySQLDump  >  index.php  >  Download  
File: index.php
Role: Example script
Content type: text/plain
Description: Main php script to dump MySQL databases through AJAX requests to php script asynchronously called
Class: PHP Multi MySQLDump
Dump MySQL database tables for file download
Author: By
Last change: changed page title to MULTIDUMP
Date: 4 years ago
Size: 18,408 bytes
 

Contents

Class file image Download
<?php
/*
* ***************************************************************************************************
*
* File name: index.php
*
* Copyright  2017 Alessandro Quintiliani
*
* This file is part of MultiDump package.
*
* MultiDump is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MultiDump is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MultiDump package.  If not, see <http://www.gnu.org/licenses/>.
*
* ***************************************************************************************************
*/

/*

USAGE:
*
* suppose you have several mysql databases to dump, such as:
*
* dbone, dbtwo, dbthree, dbfour
*
* and all of these databases are installed on the same server (or also different servers), having the same credentials:
* hostname: my.hostdb.com   (or, as the same, its IP address, i.e. 10.20.30.40)
* port: 3307 (not the mysql default port)
* login: mylogin2db
* password: mypasswd2db
*
*
*
*
* 1) set in the file dbConnSettings.php the connection parameters to each database to dump.
*    The order you set the parameters is not relevant, except for the call to setTypeDbToDump,
*    which must always be the first call on a set database connection parameters
*    IMPORTANT NOTICE: the object reference variable name $odmp must be the same as the instance name of MultiDump()
*                      in index.php (see $odmp = new MultiDump(); defined in index.php); so if you would like to use another object reference variable name
*					   such as $myDmpObjRef, you must replace in index.php the variable $odmp with $myDmpObjRef
*
* # set connection parameters to dbone mysql database
* $odmp->setTypeDbToDump('dbone','mysql');			### THE TYPE OF DATABASE MUST ALWAYS BE THE FIRST PARAMETER TO SET
* $odmp->setHostDbToDump('dbone','my.hostdb.com');  ( or, similarly, $odmp ->setHostDbToDump('dbone','10.20.30.40'); )
* $odmp->setPortDbToDump('dbone', 3307);  		  ( this method call is not necessary if the db connection refers to the default port )
* $odmp->setLoginDbToDump('dbone', 'mylogin2db');
* $odmp->setPasswordDbToDump('dbone', 'mypasswd2db');
*
* # set connection parameters to dbtwo mysql database
* $odmp->setTypeDbToDump('dbtwo','mysql');			### THE TYPE OF DATABASE MUST ALWAYS BE THE FIRST PARAMETER TO SET
* $odmp->setHostDbToDump('dbtwo','my.hostdb.com');  ( or, similarly, $odmp->setHostDbToDump('dbtwo','10.20.30.40'); )
* $odmp->setPortDbToDump('dbtwo', 3307);  		  ( this method call is not necessary if the db connection refers to the default port )
* $odmp->setLoginDbToDump('dbtwo', 'mylogin2db');
* $odmp->setPasswordDbToDump('dbtwo', 'mypasswd2db');
*
* # set connection parameters to dbthree mysql database
* $odmp->setTypeDbToDump('dbthree','mysql');		  ### THE TYPE OF DATABASE MUST ALWAYS BE THE FIRST PARAMETER TO SET
* $odmp->setHostDbToDump('dbthree','my.hostdb.com');  ( or, similarly, $odmp->setHostDbToDump('dbthree','10.20.30.40'); )
* $odmp->setPortDbToDump('dbthree', 3307);  			( the call on this method is not necessary if the db connection refers to the default port )
* $odmp->setLoginDbToDump('dbthree', 'mylogin2db');
* $odmp->setPasswordDbToDump('dbthree', 'mypasswd2db');
*
* # set connection parameters to dbfour mysql database
* $odmp->setTypeDbToDump('dbfour','mysql');			 ### THE TYPE OF DATABASE MUST ALWAYS BE THE FIRST PARAMETER TO SET
* $odmp->setHostDbToDump('dbfour','my.hostdb.com');  ( or, similarly, $odmp->setHostDbToDump('dbfour','10.20.30.40'); )
* $odmp->setPortDbToDump('dbfour', 3307);  		   ( the call on this method is not necessary if the db connection refers to the default port )
* $odmp->setLoginDbToDump('dbfour', 'mylogin2db');
* $odmp->setPasswordDbToDump('dbfour', 'mypasswd2db');
*
*
* 2) (optional) if you want to exclude some tables from dump, i.e.:
*    - alpha, beta from dbtwo database
*    - gamma, delta, epsilon from dbfour database
*
*    you must call the method
*
*    	setListExcludedTables(<dbname>, <array tables to exclude from dump>)
*
*    where:
*    - <dbname> is a string with the database name whose tables you want to exclude from dump are referring to
*    - <array tables to exclude from dump> is an array containing the table names you want to exclude from dump
*      (the order you list the tables in the array is not relevant)
*
*    thus:
*
*    $odmp->setListExcludedTables('dbtwo', array('alpha','beta'));
*    $odmp->setListExcludedTables('dbfour', array('gamma','delta','epsilon'));
*
*    (you can change the order of the calls to setListExcludedTables for each database)
*
*
* 3) (optional) if you want to dump some tables, i.e.:
*    - zeta, eta, theta from dbone database
*    - iota, kappa from dbfour database
*
*    at each run and not only when their content/structure have changed, you must call the method
*
*    	setListForcedDumpTables(<dbname>, <array forced dump tables>|-1)
*
*    where:
*    - <dbname> is a string with the database name referring to the tables you want to dump at each run
*    - <array forced dump tables>) is an array containing the tablenames you want to dump at each run
*      (the order you list the tables in the array is not relevant)
*    - value -1 forces the dump to all the tables of a database
*
*    $odmp->setListForcedDumpTables('dbone', array('zeta','eta','theta'));
*    $odmp->setListForcedDumpTables('dbfour', array('iota','kappa'));
*
*    (you can change the order of the calls to setListForcedDumpTables for each database)
*
*    if you want to dump at each run all the tables from a database, the second argument must be -1.
*    So if you want to dump all the tables from i.e. dbthree database, you must call
*
*    $odmp->setListForcedDumpTables('dbthree', -1);
*
*
*    IMPORTANT NOTICE ON CALLS 2) AND 3):
*
*      the excluded tables always have priority on the forced dump tables, independently whether you first call
*      setListExcludedTables() or setListForcedDumpTables().
*      So, if you want to force the dump of a table (i.e. my_important_table) at each run from mydb database, you call
*
*      $odmp->setListForcedDumpTables('mydb', array('my_important_table'));
*
*      but if you accidentally place my_important_table also in the array of the excluded tables, that is
*
*      $odmp->setListExcludedTables('mydb', array('no_important_table','my_important_table'));
*
*      my_important_table will be excluded from dumping instead of being dumped from mydb database
*      at each run of the script
*
*
* 4) launch index.php
*/
##################################################################

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_STRICT);

include_once("Class.MultiDump.php");

$odmp                       = new MultiDump();
$odmp->setLog("log", "logmaindump.txt", 1);
$odmp->wlog("START PROCEDURE MultiDump");

#################### INCLUDE AT THIS POINT OF THE MAIN PHP SCRIPT THE DATABASE CONNECTION PARAMETERS SCRIPT #####################


include_once("dbConnSettings.php");


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


$LIST_DB_DUMPED             = $odmp->getListDbToDump();
$PAGE_GENERATING_DUMP_TABLE = $odmp->getPhpPageTableToDump();


$LIST_ALL_TABLES_DUMPED     = array();
$LIST_TYPE_DB_DUMPED = array();
$LIST_POST_PARAMETERS = array();
$LIST_OUTPUT_FILES = array();
$LIST_EXCLUDED_DUMP_TABLES = array();


# POST variable names
$POST_VAR_DB_NAME                = $odmp->getDbVarName();
$POST_VAR_TABLE_NAME             = $odmp->getTableVarName();
$POST_VAR_DB_CONN_NAME           = $odmp->getReferenceDbConnName();
$POST_VAR_FORCED_DUMP_TABLE_NAME = $odmp->getReferenceForcedDumpTableName();


# querystring variables to URL download archived database dump
$phpFileDownload                 = $odmp->getDownloadDumpPage();
$qsVarCompressionType            = $odmp->getPostVarCompressionType();
$qsVarDbArchived                 = $odmp->getPostVarDbArchived();
$qsTypeDb                        = $odmp->getPostVarTypeDb();
$qsVarAllTablesToArchive         = $odmp->getPostVarAllTablesToArchive();

foreach($LIST_DB_DUMPED as $db_dumped){
	$odmp->wlog("database to dump: $db_dumped");
	$odmp->setListTablesToDump($db_dumped);

	$LIST_TYPE_DB_DUMPED[] = $odmp->getTypeDbToDump($db_dumped);
	$LIST_TABLES_DUMP_FORCED = $odmp->getListForcedDumpTables($db_dumped);
	$LIST_EXCLUDED_DUMP_TABLES[$db_dumped] = $odmp->getListExcludedTables($db_dumped);
	$LIST_TABLES_DUMPED              = $odmp->getListTablesToDump($db_dumped);

	$POST_SERIALIZED_DB_CONN_INFO    = serialize($odmp->getInfoDbConn($db_dumped));
	$POST_SERIALIZED_EXCLUDED_TABLES = serialize($LIST_EXCLUDED_DUMP_TABLES[$db_dumped]);

	foreach($LIST_TABLES_DUMPED as $table_dumped){

		$array_post_vars = array();
		$array_post_vars[] = $POST_VAR_DB_NAME.'='.urlencode($db_dumped);
		$array_post_vars[] = $POST_VAR_TABLE_NAME.'='.urlencode($table_dumped);
		$array_post_vars[] = $POST_VAR_DB_CONN_NAME.'='.urlencode($POST_SERIALIZED_DB_CONN_INFO);

		if( (is_array($LIST_TABLES_DUMP_FORCED) && in_array($table_dumped, $LIST_TABLES_DUMP_FORCED)) || ($LIST_TABLES_DUMP_FORCED == - 1) )
		{
			$flagForcedDumpTable = 1;
		}
		else
		{
			$flagForcedDumpTable = 0;
		}

		$array_post_vars[] = $POST_VAR_FORCED_DUMP_TABLE_NAME.'='.$flagForcedDumpTable;

		$stringPostVars = implode("&", $array_post_vars);
		if(!in_array($table_dumped, $LIST_EXCLUDED_DUMP_TABLES[$db_dumped]))
		{
			$LIST_ALL_TABLES_DUMPED[] = $db_dumped . "." . $table_dumped;
			$LIST_POST_PARAMETERS[$db_dumped . "." . $table_dumped] = $stringPostVars;
		}
	}
}


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>

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

			table.tablelinksdld tr
			{
				line-height: 10px;
			}

			td
			{
				padding-right: 10px;
			}

			ul.listdld
			{
				margin: 0;
				padding: 0;
				list-style: none;
			}

			li.lidld
			{
				margin: 24;
				padding: 0;
			}

			div.pre
			{
				display: block;
				unicode-bidi: embed;
				font-family: monospace;
				white-space: nowrap;
			}

			div.divcallsdump
			{
				font-weight: bold;
				left: 30px;
			}

			div.divdashed
			{
				left: 0px;
			}


		</style>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
		</script>
		<script type="text/javascript">

			var db_dumped = <?php echo json_encode($LIST_DB_DUMPED, JSON_PRETTY_PRINT); ?>;
			var type_db_dumped = <?php echo json_encode($LIST_TYPE_DB_DUMPED, JSON_PRETTY_PRINT); ?>;
			var totalNumberTablesToDump = <?php echo count($LIST_ALL_TABLES_DUMPED); ?>;
			var all_tables_to_archive = '<?php echo urlencode(json_encode(serialize($LIST_ALL_TABLES_DUMPED), JSON_PRETTY_PRINT)); ?>';
			var numberJQueryCallsDone = 0;
			var errorsDump = 0;
			var strPostParamsArchiveZip = "";
			var strPostParamsArchiveTgz = "";

			<?php
			$array_ajax_requests = array();

			$ajaxRequestsHead = "var ajaxRequests = [";

			foreach($LIST_ALL_TABLES_DUMPED as $it=>$full_qualified_table_dumped)
			{

				$post_vars_string = $LIST_POST_PARAMETERS[$full_qualified_table_dumped];

				$id_div_response_dump = $it + 1;

				$strJqueryPost = "jQuery.post('".$odmp->getPhpPageTableToDump()."','".$post_vars_string."',";
				$strJqueryPost .= "function(responseDump,status,xhr) {\n";
				$strJqueryPost .= "  numberJQueryCallsDone++;\n";
				$strJqueryPost .= "  var errorsDumpRegExp = /div_dump_error_id_/;\n";
				$strJqueryPost .= "  var matchedErrorDumpResponse = responseDump.match(errorsDumpRegExp);\n";
				$strJqueryPost .= "  if (matchedErrorDumpResponse === true) {errorsDump++;};\n";
				$strJqueryPost .= "  document.getElementById('ajaxcallsdumptables').style.color = \"#0600ff\"\n";
				$strJqueryPost .= "  document.getElementById('ajaxcallsdumptables').innerHTML = 'Dumped ' + numberJQueryCallsDone + ' tables on ' + totalNumberTablesToDump + '...';\n";
				$strJqueryPost .= "  document.getElementById('dumpresult' + " . $id_div_response_dump . ").innerHTML = responseDump;\n";
				$strJqueryPost .= "},";
				$strJqueryPost .= "\"html\")";

				$array_ajax_requests[] = $strJqueryPost;
			}

			$strAjaxRequests = implode(",\n",$array_ajax_requests);

			$ajaxRequestsTail = "];\n";

			$ajaxRequests = $ajaxRequestsHead . $strAjaxRequests . $ajaxRequestsTail;

			echo $ajaxRequests;
			?>

			function createListHiddenInput(qstring)
			{
				var hiddenFields = "";
				var ahf = qstring.split('&');
				for (var i = 0; i < ahf.length; i++)
				{
					var cp = ahf[i].split('=');
					var keyPost = encodeURIComponent(cp[0]);
					var valuePost = cp[1] || '';
					if (valuePost.charAt(0)=='"' && valuePost.charAt(valuePost.length - 1)=='"')
					{
						hiddenFields+='<input type="hidden" name="'+keyPost+'" value='+valuePost+' />\n';
					} else
					{
						hiddenFields+='<input type="hidden" name="'+keyPost+'" value="'+valuePost+'" />\n';
					}
				}
				return hiddenFields;
			}


			$(document).ready(function()
				{

					jQuery.when.apply(jQuery, ajaxRequests).done(function ()
						{

							var urlToDownloadDbArchived = '<?php echo $phpFileDownload; ?>';
							var qsVarDbArchived = '<?php echo $qsVarDbArchived; ?>';
							var qsTypeDb = '<?php echo $qsTypeDb; ?>';
							var qsVarCompressionType = '<?php echo $qsVarCompressionType; ?>';
							var qsVarAllTablesToArchive = '<?php echo $qsVarAllTablesToArchive; ?>';
							var msgdump = "";

							if (errorsDump == 0)
							{
								document.getElementById("ajaxcallsdumptables").style.color = "#0600ff";
								msgdump = 'Dumped ' + numberJQueryCallsDone + ' tables on ' + totalNumberTablesToDump;
							} else
							{
								document.getElementById("ajaxcallsdumptables").style.color = "red";
								msgdump = "Dump accomplished with " + errorsDump + " errors!!!";
							}

							var links_dld = "<br>";

							links_dld += '<ul class="listdld">';
							links_dld += '<li class="lidld"><table class="tablelinksdld" cellpadding="0" cellspacing="0" border="0">';


							for (var id=0; id<db_dumped.length; id++)
							{

								var db_name_dld = db_dumped[id];
								var type_db = type_db_dumped[id];

								strPostParamsArchiveZip = qsVarDbArchived+'='+db_name_dld+'&'+qsTypeDb+'='+type_db+'&'+qsVarAllTablesToArchive+'='+all_tables_to_archive+'&'+qsVarCompressionType+'=zip';
								strPostParamsArchiveTgz = qsVarDbArchived+'='+db_name_dld+'&'+qsTypeDb+'='+type_db+'&'+qsVarAllTablesToArchive+'='+all_tables_to_archive+'&'+qsVarCompressionType+'=tgz';

								var hiddenFieldsToZip = createListHiddenInput(strPostParamsArchiveZip);
								var hiddenFieldsToTgz = createListHiddenInput(strPostParamsArchiveTgz);
								var titleziparchive = 'If the database '+db_name_dld+' contains extremely large tables, the creation of the zip archive may take several minutes before downloading';
								var titletgzarchive = 'If the database '+db_name_dld+' contains extremely large tables, the creation of the tgz archive may take several minutes before downloading';

								links_dld += '<tr><td>Download db <i>'+db_name_dld+'</i></td><td>&nbsp;<form action="'+urlToDownloadDbArchived+'" method="post" id="formdldzip'+id+'" name="formdldzip'+id+'">'+hiddenFieldsToZip+'<a href="javascript:void(0);" id="linkdldzip'+id+'" title="'+titleziparchive+'" onClick="document.formdldzip'+id+'.submit()">zip</a></form></td><td>&nbsp;&nbsp;&nbsp;<form action="'+urlToDownloadDbArchived+'" method="post" id="formdldtgz'+id+'" name="formdldtgz'+id+'">'+hiddenFieldsToTgz+'<a href="javascript:void(0);" id="linkdldtgz'+id+'" title="'+titletgzarchive+'" onClick="document.formdldtgz'+id+'.submit()">tgz</a></form></td></tr>';
							}

							links_dld += '</table>';
							links_dld += '</li>';
							links_dld += '</ul>';

							setTimeout(function()
								{
									document.getElementById("divbreak").innerHTML="";
									document.getElementById("ajaxcallsdumptables").style.color = "green";
									msgdump = "Dump successfully accomplished!!!";
									document.getElementById("ajaxcallsdumptables").innerHTML = msgdump + links_dld;
								}, 500);


						}).fail(function (jqXhr, textStatus, error)
						{
							document.getElementById("ajaxcallsdumptables").style.color = "red";
							document.getElementById("ajaxcallsdumptables").innerHTML = "Dump accomplished with errors!!! (error: " + error + ")";
						})
				});

		</script>

	</head>
	<body>
		<div class="pre">

			<?php
			$odmp->printInfoDump();
			?>
			<br>
			<div id="ajaxcallsdumptables" class="divcallsdump">
				<span>
				</span>
			</div>

			<?php
			$dbCurrentName = "";
			foreach($LIST_ALL_TABLES_DUMPED as $i=>$fullyQualifiedTableDumped){

				$j = $i + 1;

				list($dbnameDumped,$nameTableDumped) = explode(".",$fullyQualifiedTableDumped,2);

				if($dbnameDumped != $dbCurrentName){
					$dbCurrentName = $dbnameDumped;

					if($i == 0) echo '<div id="divbreak"><br></div>';

					echo '<div class="divdashed">--------------------------------------------------------------------------</div>';

					echo "<h3>Report tables dumped from database <i>".$dbnameDumped."</i></h3>";
				}

				echo '<div id="dumpresult'.$j.'">-------------------<br>Dumping table '.$fullyQualifiedTableDumped.'...</div>';

			}

			echo '<div class="divdashed">--------------------------------------------------------------------------</div>';
			?>

		</div>

	</body>
</html>
<?php
$odmp->wlog("END PROCEDURE MultiDump");
$odmp->end();
unset($odmp);
?>
For more information send a message to info at phpclasses dot org.