1
0
Fork 0

Struggeling with relocating

Dieser Commit ist enthalten in:
DSB 2011-06-10 21:28:27 +00:00
Commit 89ea01c429
301 geänderte Dateien mit 59926 neuen und 0 gelöschten Zeilen

195
inc/classes/Log.php Normale Datei
Datei anzeigen

@ -0,0 +1,195 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $Rev$
* @author $Author$
* @lastmodified $Date$
*/
/**
* Log Class
*/
class Log
{
// Define constants
const PHP = 1;
const PERL = 2;
const PERL_COMPLETE = 3;
const ERROR = 4;
const PHP_FILE = 'work/log/mysqldump.log';
const PERL_FILE = 'work/log/mysqldump_perl.log';
const PERL_COMPLETE_FILE = 'work/log/mysqldump_perl.complete.log';
const ERROR_FILE = 'work/log/error.log';
/**
* Init file handles
*
* @return void
*/
public function __construct()
{
$this->handle = array();
$this->handle[self::PHP] = false;
$this->handle[self::PERL] = false;
$this->handle[self::PERL_COMPLETE] = false;
$this->handle[self::ERROR] = false;
}
/**
* Close all open file handles on destruct
*
* @return void
*/
public function __destruct()
{
if ($this->handle[self::PHP]) {
$this->_close(self::PHP);
}
if (is_resource($this->handle[self::PERL])) {
$this->_close(self::PERL);
}
if (is_resource($this->handle[self::PERL_COMPLETE])) {
$this->_close(self::PERL_COMPLETE);
}
if (is_resource($this->handle[self::ERROR])) {
$this->_close(self::ERROR);
}
}
/**
* Open file and store file handle
*
* @param string $file
*
* @return bool
*/
private function _getFileHandle($file)
{
$filename=$this->getLogfile($file);
if ($_SESSION['config']['logcompression'] == 1) {
$fileHandle = @gzopen($filename, 'a');
} else {
$fileHandle = @fopen($filename, 'ab');
}
if ($fileHandle) {
$this->handle[$file] = $fileHandle;
return $this->handle[$file];
} else {
return false;
}
}
/**
* Close a filehandle
*
* @param Loge $file The file to close
*/
private function _close($file)
{
$filename=$this->getLogfile($file);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($extension == 'gz') {
gzclose($this->handle[$file]);
} else {
fclose($this->handle[$file]);
}
}
/**
* Write to log file
*
* @param string $file
* @param string $message
*
* @return bool
*/
public function write($file, $message)
{
// TODO get $config-values from a config class and delete global
global $config;
if (!$this->handle[$file]) {
$this->handle[$file] = $this->_getFileHandle($file);
}
$message = strip_tags($message);
// we don't need linebreaks in the log
$search = array("\n","\r");
$replace = array ('','');
$message = str_replace($search, $replace, $message);
$logMessage = date('d.m.Y H:i:s') . ' '. $message . "\n";
$_SESSION['log']['actions'][] = $logMessage;
$filename = $this->getLogfile($file);
if (@filesize($filename) > $config['log_maxsize']) {
Log::delete($file);
}
//save to log file
if ($_SESSION['config']['logcompression'] == 1) {
$res = @gzwrite($this->handle[$file], $logMessage);
} else {
$res = @fwrite($this->handle[$file], $logMessage);
}
return $res;
}
/**
* Get log file name
*
* @param const $file
*
* @return string Filename of logfile
*/
public function getLogfile($file)
{
switch ($file)
{
case Log::PHP:
$filename = self::PHP_FILE;
break;
case Log::PERL:
$filename = self::PERL_FILE;
break;
case Log::PERL_COMPLETE:
$filename = self::PERL_COMPLETE_FILE;
break;
case Log::ERROR:
$filename = self::ERROR_FILE;
break;
default:
echo "Unknown $file: ".$file;
return;
}
if ($_SESSION['config']['logcompression'] == 1) {
$filename .= '.gz';
}
return $filename;
}
/**
* Delete log file and recreates it.
*
* @param string $file Filename
*
* @return void
*/
public function delete($file)
{
$filename=Log::getLogfile($file);
@unlink($filename);
if ($file == Log::PHP) {
// re-create main log
if (substr($filename, -3) == '.gz') {
$log = date('d.m.Y H:i:s') . " Log created.\n";
if ($_SESSION['config']['logcompression'] == 1) {
$fp = @gzopen($filename, "wb");
@gzwrite($fp, $log);
@chmod($file . '.gz', 0777);
$this->handle[$file]=$fp;
} else {
$fp = @fopen($filename, "wb");
@fwrite($fp, $log);
@chmod($file, 0777);
$this->handle[$file]=$fp;
}
}
}
}
}

Datei anzeigen

@ -0,0 +1,249 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1212 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* DB-Factory
*
* @abstract
*/
abstract class MsdDbFactory
{
const FORCE_MYSQL = false; // for debugging
// define result set types
const ARRAY_NUMERIC = 0; // return resultset as numeric array
const ARRAY_ASSOC = 1; // return resultset as associative array
const ARRAY_OBJECT = 2; // return resultset as array of object
const SIMPLE = 3; // return result as boolean
/**
* Init database object
*
* @param string $server SQL-Server
* @param string $user SQL-User used to authenticate at server
* @param string $password SQL-User-Password usued to authenticate
* @param string $port [optional] Port to use
* @param string $socket [optional] Socket to use (only for *nix)
*
* @return void
*/
function __construct($server, $user, $password, $port = 3306, $socket ='')
{
$this->server = $server;
$this->user = $user;
$this->password = $password;
$this->port = $port;
$this->socket = $socket;
$this->connectionCharset = 'utf8';
$this->connectionHandle = false;
$this->dbSelected = '';
$this->tables = array();
$this->metaTables = array();
}
/**
* Create database adapter
*
* @param string $server
* @param string $user
* @param string $password
* @param string $port
* @param string $socket
*
* @return MsdDbFactory
*/
static function getAdapter($server, $user, $password, $port = 3306, $socket = '')
{
if (function_exists('mysqli_connect') && !self::FORCE_MYSQL) {
include_once ('./inc/classes/db/mysqli/MsdDbMysqli.php');
$db = new MsdDbMysqli($server, $user, $password, $port, $socket);
} else {
include_once ('./inc/classes/db/mysql/MsdDbMysql.php');
$db = new MsdDbMysql($server, $user, $password, $port, $socket);
}
return $db;
}
/**
* Establish a connection to SQL-Server.
*
* Doesn't need to be called directly because of lazy loading.
* Will be called automatically if any other method is called that
* needs a connection.
* Creates a connection to the database and stores the connection handle
* in $this->connection_handle.
* If $select_database is set, the database is selected for next queries.
* Returns true on success or false if connection couldn't be established.
*
* @param string $select_database
* @param string $connection_charset
*
* @return bool
* */
abstract public function dbConnect($selectDatabase = false);
/**
* Get selected database
*
* @return string
*/
abstract public function getSelectedDb();
/**
* Get version nr of sql server
*
* @return string
*/
abstract public function getServerInfo();
/**
* Get version nr of sql client
*
* @return string
*/
abstract public function getClientInfo();
/**
* Get all known character sets of this SQL-Server.
*
* @return array
*/
abstract public function getCharsets();
/**
* Set character set of the MySQL-connection.
*
* Trys to set the connection charset and returns it.
* Throw Exception on failure.
*
* @param string $charset
* @throws Exception
*
* @return string
*/
abstract public function setConnectionCharset($charset = 'utf8');
/**
* Get list of databases
*
* Gets list of all databases that the actual SQL-Server-User has access to
* and saves it in $this->databases.
* Returns true on success or false on error.
*
* @return bool
*/
abstract public function getDatabases();
/**
* Select the given database to use it as the target for following queries.
*
* Returns true if selection was succesfull otherwise false.
*
* @throws Exception
* @param string $database
*
* @return bool
*/
abstract public function selectDb($database);
/**
* Execute a SQL-Server-Query
*
* @param $query The query to execute
* @param $kind Type of result set
*
* @return array
*/
abstract public function query($query, $kind = self::ARRAY_OBJECT);
/**
* Get table list of given database(s)
*
* Stores them in $this->tables[database]
* When no database is given, all databases are scanned for tables.
* Returns table list for selected or for all databases.
*
* @param string|array $database
*
* @return array
*/
abstract public function getTables($database = false);
/**
* Gets extended table information for one or all tables
*
* @param string $table
* @param string $database
*
* @return array
*/
abstract public function getTableStatus($table = false, $database = false);
/**
* Returns the CREATE Statement of a table.
*
* @throws Exception
* @param string $table Get CREATE-Statement for this table
* @param string $database Database holding the table
*
* @return string Create statement
*/
abstract public function getTableCreate($table, $database = false);
/**
* Gets the full description of all columns of a table
*
* Saves list to $this->metaTables[$database][$table].
*
* @param string $table Table to read meta info from
* @param string $database Database holding the table
*
* @return array
*/
abstract public function getTableColumns($table, $database = false);
/**
* Gets the number of affected rows of the last query
*
* @return int
*/
abstract function getAffectedRows();
/**
* Escape a value for inserting it in query
*
* @param string $val
*
* @return string
*/
abstract function escape($val);
/**
* Optimize a table. Returns true on success or MySQL-Error.
*
* @param $table string Name of table
*
* @return string|bool Returned optimize message or false on error
*/
abstract function optimizeTable($table);
/**
* Handles a SQL-Error
*
* @param string $errmsg
* @param int $errno
* @throws MsdEception
*
* @return void
*/
public function sqlError($errmsg, $errno)
{
throw new Exception($errmsg, $errno);
}
}

Datei anzeigen

@ -0,0 +1,439 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage MsdDbFactory
* @version SVN: $rev: 1205 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* Capsules all database related actions.
* Uses some magic getters to allow lazy connecting.
*
*/
class MsdDbMysql extends MsdDbFactory
{
/**
* Get all known character sets of this SQL-Server.
*
* @return array
*/
public function getCharsets()
{
if (isset($this->charsets)) return $this->charsets;
if (false === $this->connectionHandle) $this->dbConnect();
$result = $this->query('SHOW CHARACTER SET', self::ARRAY_ASSOC);
$this->charsets = array();
foreach ($result as $r) {
$this->charsets[$r['Charset']] = $r;
}
@ksort($this->charsets);
return $this->charsets;
}
/**
* Establish a connection to MySQL.
*
* Creates a connection to the database and stores the connection handle in
* $this->connectionHandle.
* If $select_database is set, the database is selected for further queries.
* Returns true on success or false if connection couldn't be established.
*
* @param string $select_database
* @param string $connectionCharset
*
* @return bool
**/
public function dbConnect($selectDatabase = false)
{
if (is_resource($this->connectionHandle)) return true;
$connectionString = $this->server . ':' . $this->port;
if ($this->socket > '') $connectionString .= ':' . $this->socket;
if (false === $this->connectionHandle) {
$this->connectionHandle = @mysql_connect(
$connectionString,
$this->user, $this->password
);
if (false === $this->connectionHandle) {
return '(' . mysql_errno() . ') ' . mysql_error();
}
}
$this->setConnectionCharset($this->connectionCharset);
if (false === $selectDatabase && $this->dbSelected > '') {
$selectDatabase = $this->dbSelected;
}
if ($selectDatabase) {
try
{
$this->selectDb($selectDatabase, $this->connectionHandle);
$this->dbSelected = $selectDatabase;
return true;
} catch (Exception $e) {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
return false;
}
}
return true;
}
/**
* Get version nr of sql server
*
* @return string
*/
public function getServerInfo()
{
if (false === $this->connectionHandle) {
$this->dbConnect();
}
$version = mysql_get_server_info($this->connectionHandle);
return $version;
}
/**
* Get version nr of sql client
*
* @return string
*/
public function getClientInfo()
{
if (false === $this->connectionHandle) $this->dbConnect();
$version = mysql_get_client_info();
return $version;
}
/**
* Set character set of the MySQL-connection.
*
* Trys to set the connection charset and returns it.
* Throw Exception on failure.
*
* @param string $charset
* @throws Exception
*
* @return string
*/
public function setConnectionCharset($charset = 'utf8')
{
if (false === $this->connectionHandle) $this->dbConnect();
if (function_exists('mysql_set_charset')
&& @mysql_set_charset($charset, $this->connectionHandle)) {
$this->connectionCharset = $charset;
return $this->connectionCharset;
} else {
$this->query('SET NAMES \'' . $charset . '\'', self::SIMPLE);
$this->connectionCharset = $charset;
return $charset;
}
}
/**
* Get list of databases
*
* Gets list of all databases that the actual MySQL-User has access to
* and saves it in $this->databases.
* Returns true on success or false on error.
*
* @return array List of found database names
*/
public function getDatabases()
{
if (false === $this->connectionHandle) $this->dbConnect();
$this->databases = array();
$databases = @mysql_list_dbs($this->connectionHandle);
if (is_resource($databases)) {
WHILE ($row = mysql_fetch_array($databases, MYSQL_ASSOC)) {
$this->databases[] = $row['Database'];
}
} else {
//mysql_list_dbs seems not to be allowed for this user
// try to get list via "SHOW DATABASES"
$res = $this->query('SHOW DATABASES', self::ARRAY_ASSOC);
foreach ($res as $r) {
$this->databases[] = $r['Database'];
}
}
sort($this->databases);
return $this->databases;
}
/**
* Select the given database to use it as the target for following queries
*
* Returns true if selection was succesfull otherwise false.
*
* @throws Exception
* @param string $database
*
* @return bool
*/
public function selectDb($database)
{
if (!is_resource($this->connectionHandle)) {
$this->dbConnect();
}
$res=@mysql_select_db($database, $this->connectionHandle);
if ($res===false) {
return mysql_error();
} else {
$this->dbSelected = $database;
return true;
}
}
/**
* Get selected database
*
* @see inc/classes/db/MsdDbFactory#getSelectedDb()
*
* @return string
*/
public function getSelectedDb()
{
return $this->dbSelected;
}
/**
* Execute a query
*
* @param $query The query to execute
* @param $kind Type of result set
*
* @return array
*/
public function query($query, $kind = self::ARRAY_OBJECT)
{
if (false === $this->connectionHandle) {
$this->dbConnect();
}
$res = @mysql_query($query, $this->connectionHandle);
if (false === $res) {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
}
if ($kind === self::SIMPLE || is_bool($res)) {
return $res;
}
$ret = array();
if ($kind === self::ARRAY_OBJECT) {
WHILE ($row = mysql_fetch_object($res)) {
$ret[] = $row;
}
} elseif ($kind === self::ARRAY_NUMERIC) {
WHILE ($row = mysql_fetch_array($res, MYSQL_NUM)) {
$ret[] = $row;
}
} elseif ($kind === self::ARRAY_ASSOC) {
WHILE ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$ret[] = $row;
}
}
return $ret;
}
/**
* Get table list of given database(s)
*
* Stores them in $this->tables[database]
* When no database is given, all databases are scanned for tables.
* Returns table list for selected or for all databases.
*
* @param string|array $database
*
* @return array
*/
public function getTables($database = false)
{
if (false === $this->connectionHandle) $this->dbConnect();
if (!isset($this->tables)) $this->tables = array();
if ($database !== false) {
//list tables of selected database
if (is_array($database)) {
$databases = $database;
} else {
$databases = array();
$databases[0] = $database;
}
} else {
//list tables for all databases
$this->getDatabases();
$databases = $this->databases;
}
// get tablenames inside each database
foreach ($databases as $db) {
$this->tables[$db] = array();
$sql = 'SHOW TABLES FROM `' . $db . '`';
$res = $this->query($sql, self::ARRAY_NUMERIC);
foreach ($res as $val) {
$this->tables[$db][] = $val[0];
}
}
return is_string($database) ? $this->tables[$database] : $this->tables;
}
/**
* Gets extended table information for one or all tables
*
* @param string $table
* @param string $database
*
* @return array
*/
public function getTableStatus($table = false, $database = false)
{
if ($database !== false && $database != $this->dbSelected) {
$this->selectDb($database);
} elseif (!$this->_mysqli instanceof mysqli) {
$this->selectDb($this->dbSelected);
}
if (!isset($this->tableinfo)) {
$this->tableinfo = array();
}
if (!isset($this->tableinfo[$this->dbSelected])) {
$this->tableinfo[$this->dbSelected] = array();
}
$sql = 'SHOW TABLE STATUS';
if ($table !== false) {
$sql .= ' LIKE \'' . $table . '\'';
}
$res = $this->query($sql, self::ARRAY_ASSOC);
if (is_array($res)) {
foreach ($res as $r) {
$tablename = $r['Name'];
unset($r['Name']);
$this->tableinfo[$this->dbSelected][$tablename] = $r;
}
} elseif ($res === false) {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
}
if ($table !== false) {
if (isset($this->tableinfo[$this->dbSelected][$table])) {
return $this->tableinfo[$this->dbSelected][$table];
}
}
return $this->tableinfo[$this->dbSelected];
}
/**
* Returns the CREATE-Statement for the given table or false on error.
*
* @throws Exception
* @param string $table
* @param string $database
*
* @return string
*/
public function getTableCreate($table, $database = false)
{
if (false === $database) $database = $this->dbSelected;
if ($database != $this->dbSelected) {
if (false === $this->selectDB($database)) {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
}
}
if (!is_resource($this->connectionHandle)) {
$this->dbConnect($this->dbSelected);
}
$sql = 'SHOW CREATE TABLE `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
if (isset($res[0]['Create Table'])) {
return $res[0]['Create Table'];
} else {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
}
}
/**
* Gets the full description of all columns of a table
*
* Saves it to $this->metaTables[$database][$table].
*
* @param string $table
* @param string $database
* @return array
*/
public function getTableColumns($table, $database = false)
{
if (false === $database) $database = $this->dbSelected;
if ($database != $this->dbSelected) {
if (false === $this->selectDB($database)) {
$this->sqlError(
mysql_error($this->connectionHandle),
mysql_errno($this->connectionHandle)
);
}
}
if (!is_resource($this->connectionHandle)) {
$this->dbConnect($this->dbSelected);
}
$sql = 'SHOW FULL COLUMNS FROM `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
if (!isset($this->metaTables[$database])) {
$this->metaTables[$database] = array();
}
if ($res) {
$this->metaTables[$database][$table] = array();
foreach ($res as $r) {
$this->metaTables[$database][$table][$r['Field']] = $r;
}
}
return $this->metaTables[$database][$table];
}
/**
* Gets the number of affected rows for the last query
*
* @see inc/classes/db/MsdDbFactory#affectedRows()
*
* @return int
*/
public function getAffectedRows()
{
return mysql_affected_rows($this->connectionHandle);
}
/**
* Escape a value to use it in a query
*
* @see inc/classes/db/MsdDbFactory#escape($val)
* @param mixed $val The value to escape
* @return mixed
*/
public function escape($val)
{
return mysql_real_escape_string($val, $this->connectionHandle);
}
/**
* Optimize a table. Returns true on success or MySQL-Error.
*
* @param string $table Name of table
*
* @return string|bool Returned optimize message or false on error
*/
function optimizeTable($table)
{
$sql = 'OPTIMIZE TABLE `' . $this->dbSelected . '`.`' . $table . '`';
$res = $this->query($sql, MsdDbFactory::ARRAY_ASSOC);
if (isset($res[0]['Msg_text'])) {
return $res[0];
} else {
return false;
}
}
}

Datei anzeigen

@ -0,0 +1,413 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage MsdDbFactory
* @version SVN: $rev: 1208 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* Capsules all database related actions.
* Uses some magic getters to allow lazy connecting.
*
*/
class MsdDbMysqli extends MsdDbFactory
{
/**
* @var resource
*/
private $_mysqli = null;
/**
* Get known charsets of MySQL-Server
*
* @return array
*/
public function getCharsets()
{
if (isset($this->charsets)) return $this->charsets;
if (!$this->_mysqli instanceof mysqli) $this->dbConnect();
$result = $this->query('SHOW CHARACTER SET', self::ARRAY_ASSOC);
$this->charsets = array();
foreach ($result as $r) {
$this->charsets[$r['Charset']] = $r;
}
@ksort($this->charsets);
return $this->charsets;
}
/**
* Establish a connection to MySQL.
*
* Create a connection to MySQL and store the connection handle in
* $this->connectionHandle.
* If $select_database is set, the database is selected for further queries.
* Returns true on success or false if connection couldn't be established.
*
* @param string $select_database
* @param string $connectionCharset
* @return boolean
**/
public function dbConnect($selectDatabase = false)
{
if ($this->_mysqli instanceof mysqli) {
return true;
}
$this->_mysqli = @new mysqli(
$this->server,
$this->user,
$this->password,
$this->dbSelected,
$this->port,
$this->socket
);
if ($this->_mysqli->connect_errno) {
$error = $this->_mysqli->connect_error;
$errno = $this->_mysqli->connect_errno;
$this->_mysqli = null;
return '(' . $errno . ') ' . $error;
}
$this->setConnectionCharset($this->connectionCharset);
if (false === $selectDatabase && $this->dbSelected > '') {
$selectDatabase = $this->dbSelected;
}
if ($selectDatabase) {
if ($this->selectDb($selectDatabase)) {
$this->dbSelected = $selectDatabase;
return true;
} else {
$this->sqlError(mysqli_error(mysqli_error(), mysqli_errno()));
}
}
return true;
}
/**
* Get version nr of sql server
*
* @return string
*/
public function getServerInfo()
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect();
}
return $this->_mysqli->server_info;
}
/**
* Get version nr of sql client
*
* @return string
*/
public function getClientInfo()
{
if (!$this->_mysqli instanceof mysqli) $this->dbConnect();
return $this->_mysqli->client_info;
}
/**
* Set character set of the MySQL-connection.
*
* Trys to set the connection charset and returns it.
* Throw Exception on failure.
*
* @param string $charset
* @throws Exception
*
* @return string
*/
public function setConnectionCharset($charset = 'utf8')
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect();
}
if (!@$this->_mysqli->set_charset($charset)) {
$this->sqlError(
$charset . ' ' . $this->_mysqli->error,
$this->_mysqli->errno
);
}
$this->connectionCharset = $this->_mysqli->character_set_name();
return $this->connectionCharset;
}
/**
* Get list of databases
*
* Gets list of all databases that the actual MySQL-User has access to
* and saves it in $this->databases.
* Returns true on success or false on error.
*
* @return boolean
*/
public function getDatabases()
{
if (!$this->_mysqli instanceof mysqli) $this->dbConnect();
$res = $this->query('SHOW DATABASES', self::ARRAY_ASSOC);
$this->databases = array();
foreach ($res as $r) {
$this->databases[] = $r['Database'];
}
sort($this->databases);
return $this->databases;
}
/**
* Select the given database to use it as the target for following queries.
*
* Returns true if selection was succesfull otherwise false.
*
* @throws Exception
* @param string $database Database to select
*
* @return boolean
*/
public function selectDb($database)
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect();
}
$res=@$this->_mysqli->select_db($database);
if ($res===false) {
return $this->_mysqli->error;
} else {
$this->dbSelected = $database;
return true;
}
}
/**
* Get selected database
*
* @see inc/classes/db/MsdDbFactory#getSelectedDb()
* @return string
*/
public function getSelectedDb()
{
return $this->dbSelected;
}
/**
* Execute a MySQL-Query
*
* @throws Exception
* @param string $query The query to execute
* @param const $kind Type of result set
*
* @return array
*/
public function query($query, $kind = self::ARRAY_OBJECT)
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect($this->dbSelected);
}
//echo "<br>Mysqli: executing query: " . $query;
$result = $this->_mysqli->query($query);
if (false === $result) {
$this->sqlError($this->_mysqli->error, $this->_mysqli->errno);
}
if (!$result instanceof mysqli_result || $kind === self::SIMPLE) {
return $result;
}
$ret = array();
if ($kind === self::ARRAY_OBJECT) {
WHILE ($row = $result->fetch_object()) {
$ret[] = $row;
}
} elseif ($kind === self::ARRAY_NUMERIC) {
WHILE ($row = $result->fetch_array(MYSQLI_NUM)) {
$ret[] = $row;
}
} elseif ($kind === self::ARRAY_ASSOC) {
WHILE ($row = $result->fetch_assoc()) {
$ret[] = $row;
}
}
if ($result instanceof mysqli) {
$result->close();
}
return $ret;
}
/**
* Get table list of given database(s)
*
* Stores them in $this->tables[database]
* When no database is given, all databases are scanned for tables.
* Returns table list for selected or for all databases.
*
* @param string|array $database
* @return array
*/
public function getTables($database = false)
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect($this->dbSelected);
}
if (!isset($this->tables)) {
$this->tables = array();
}
if ($database !== false) {
//only list tables of selected database
if (is_array($database)) {
$databases = $database;
} else {
$databases = array();
$databases[0] = $database;
}
} else {
//list tables for all databases
$databases = $this->databases;
}
// get tablenames for each database
foreach ($databases as $db) {
$this->tables[$db] = array();
$sql = 'SHOW TABLES FROM `' . $db . '`';
$res = $this->query($sql, self::ARRAY_NUMERIC);
foreach ($res as $val) {
$this->tables[$db][] = $val[0];
}
}
return is_string($database) ? $this->tables[$database] : $this->tables;
}
/**
* Gets extended table information for one or all tables
*
* @param string $table
* @param string $database
* @return array
*/
public function getTableStatus($table = false, $database = false)
{
if ($database !== false && $database != $this->dbSelected) {
$this->selectDb($database);
}
if (!$this->_mysqli instanceof mysqli) {
$this->selectDb($this->dbSelected);
}
if (!isset($this->tableinfo)) {
$this->tableinfo = array();
}
if (!isset($this->tableinfo[$this->dbSelected])) {
$this->tableinfo[$this->dbSelected] = array();
}
$sql = 'SHOW TABLE STATUS';
if ($table !== false) {
$sql .= ' LIKE \'' . $table . '\'';
}
$res = $this->query($sql, self::ARRAY_ASSOC);
if (is_array($res)) {
foreach ($res as $r) {
$tablename = $r['Name'];
unset($r['Name']);
$this->tableinfo[$this->dbSelected][$tablename] = $r;
}
} elseif ($res === false) {
$this->sqlError($this->_mysqli->error, $this->_mysqli->errno);
}
if ($table !== false) {
if (isset($this->tableinfo[$this->dbSelected][$table])) {
return $this->tableinfo[$this->dbSelected][$table];
}
}
return $this->tableinfo[$this->dbSelected];
}
/**
* Returns the CREATE Statement of a table.
*
* @throws Exception
* @param string $table
* @param string $database
*
* @return string
*/
public function getTableCreate($table, $database = false)
{
if (false === $database) {
$database = $this->dbSelected;
}
if ($database != $this->dbSelected) {
if (false === $this->selectDB($database)) {
$this->sqlError($this->_mysqli->error, $this->_mysqli->errno);
}
}
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect($this->dbSelected);
}
$sql = 'SHOW CREATE TABLE `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
if (isset($res[0]['Create Table'])) {
return $res[0]['Create Table'];
} else {
$this->sqlError($this->_mysqli->error, $this->_mysqli->errno);
}
}
/**
* Gets the full description of all columns of a table
*
* Saves it to $this->metaTables[$database][$table].
*
* @param string $table
* @param string $database
*
* @return array
*/
public function getTableColumns($table, $database = false)
{
if (!$this->_mysqli instanceof mysqli) {
$this->dbConnect($this->dbSelected);
}
if (false === $database) {
$database = $this->dbSelected;
}
if ($database != $this->dbSelected) {
if (false === $this->selectDB($database)) {
$this->sqlError($this->_mysqli->error, $this->_mysqli->errno);
}
}
$sql = 'SHOW FULL FIELDS FROM `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
if (!isset($this->metaTables[$database])) $this->metaTables[$database] = array();
if (is_array($res)) {
$this->metaTables[$database][$table] = array();
foreach ($res as $r) {
$this->metaTables[$database][$table][$r['Field']] = $r;
}
}
return $this->metaTables[$database][$table];
}
/**
* Gets the number of affected rows for the last query
*
* @see inc/classes/db/MsdDbFactory#affectedRows()
* @return integer
*/
public function getAffectedRows()
{
return $this->_mysqli->affected_rows;
}
/**
* Escape a value to use it in a query
*
* @see inc/classes/db/MsdDbFactory#escape($val)
* @param mixed $val The value to escape
*
* @return mixed
*/
public function escape($val)
{
return $this->_mysqli->real_escape_string($val);
}
/**
* Optimize a table. Returns true on success or MySQL-Error.
*
* @param string $table Name of table
*
* @return boolean or string true on success or mysql_error() on failure
*/
function optimizeTable($table)
{
$sql = 'OPTIMIZE TABLE `' . $this->dbSelected . '`.`' . $table . '`';
$res = $this->query($sql, MsdDbFactory::ARRAY_ASSOC);
if (isset($res[0]['Msg_text'])) {
return $res[0];
} else {
return false;
}
}
}

51
inc/classes/helper/File.php Normale Datei
Datei anzeigen

@ -0,0 +1,51 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Helper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* File-Helper Class
*
* Class offers some methods for file handling
*/
class File
{
/**
* Get CHMOD of a file
*
* @param string $file The file to get chmod for
*
* @return int
*/
public static function getChmod($file)
{
clearstatcache();
return @substr(decoct(fileperms($file)), -3);
}
/**
* Detects if file or directory is writable and trys to chmod it.
*
* Returns if file or directory is writable after chmodding.
*
* @param string $path
* @param string $chmod
*
* @return bool
*/
public static function isWritable($path, $chmod)
{
if (!is_writable($path)) {
@chmod($path, $chmod);
}
return is_writable($path);
}
}

218
inc/classes/helper/Html.php Normale Datei
Datei anzeigen

@ -0,0 +1,218 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* HTML-Helper Class
*
* Class has some static methods for building HTML-output
*/
class Html
{
/**
* Build HTML option list from array.
*
* @param array $arr Array $array[key]=value
* @param string $selected Selected key
* @param string $valuePattern Pattern to format value output
*
* @return string HTML option list
*/
public static function getOptionlist($arr, $selected, $valuePattern = false)
{
$r = '';
foreach ($arr as $key => $val) {
$r .= '<option value="' . $key . '"';
$r .= Html::getSelected($key, $selected) . '>';
if ($valuePattern) $r .= sprintf($valuePattern, $val);
else $r .= $val;
$r .= '</option>' . "\n";
}
return $r;
}
/**
* Get HTML output for attribute "checked"
*
* @param string $val The current value
* @param string $checked The value for the element if it should be checked
* @return string Html attribute "checked" or empty string
*/
public static function getChecked($val, $checked)
{
return $val == $checked ? ' checked="checked"' : '';
}
/**
* Get HTML output for attribute "disable"
*
* @param string $val The current value
* @param string $disabled The value for the element if disabled
*
* @return string Html attribute "disabled" or empty string
*/
public static function getDisabled($val, $disabled)
{
return $val == $disabled ? ' disabled="disabled"' : '';
}
/**
* Get HTML output for attribute "selected"
*
* @param string $val The current value
* @param string $selected The value for the element if selected
*
* @return string Html attribute "selected" or empty string
*/
public static function getSelected($val, $selected)
{
return $val == $selected ? ' selected="selected"' : '';
}
/**
* Convert HTML br's to new lines.
*
* @param string $str The string to convert
* @return string Converted string
*/
public static function br2nl($str)
{
$search = array('<br>', '<br />', '<br/>');
$replace = array("\n", "\n", "\n");
return str_replace($search, $replace, $str);
}
/**
* Escape quotes and/or slashes and double quotes.
*
* Used for escaping strings in JS-alerts and config-files.
*
* @param string $string String to escape
* @param boolean $escapeSlashes Escape slashes and double quotes
*
* @return string Escaped string
*/
public static function getJsQuote($string, $escapeSlashes = false)
{
if ($escapeSlashes) {
$string = str_replace('/', '\/', $string);
$string = str_replace('"', '\"', $string);
}
$string = str_replace("\n", '\n', $string);
return str_replace("'", '\\\'', $string);
}
/**
* Replace quotes with their Html entity.
*
* Used for outputing values in HTML attributes without breaking HTML
*
* @param string $string String with quotes
*
* @return string String with replaced quotes
*/
public static function replaceQuotes($string)
{
$string = str_replace("\n", '\n', $string);
return str_replace('"', '&quot;', $string);
}
/**
* Escape special chars according to Perl syntax.
*
* @param string $text The string to escape
*
* @return string Escaped string
*/
public static function escapeSpecialchars($string)
{
$search = array('@', '$', '\\\\', '"');
$replace = array('\@', '\$', '\\', '\"');
return str_replace($search, $replace, $string);
}
/**
* Remove added slashes recursively.
*
* @param mixed $values Array or string to remove added slashes from
*
* @return mixed Array or String with recursively removed slashes
*/
public static function stripslashesDeep($values)
{
if (is_array($values)) {
$values = array_map('Html::stripslashesDeep', $values);
} else {
$values = stripslashes($values);
}
return $values;
}
/**
* Remove whitespaces before and after string or array.
*
* @param mixed $values Array or string to remove whitespaces from
*
* @return mixed Recursively trimmed array or string
*/
public static function trimDeep($values)
{
if (is_array($values)) {
$values = array_map('Html::trimDeep', $values);
} else {
$values = trim($values);
}
return $values;
}
/**
* Build HTML-Message-String for success messages
*
* @param string $text Message to print
*
* @return string Message surrounded by HTML-Container
*/
public static function getOkMsg($text)
{
$html= sprintf('<span class="ok">%s</span>', $text);
$html .= '<span style="float:right">';
$html .= '<img src="./css/msd/icons/ok.gif" title="" alt="">';
$html .= '</span><br />';
return $html;
}
/**
* Build HTML-Message-String for error messages
*
* @param string $text Message to print
*
* @return string Message surrounded by HTML-Container
*/
public static function getErrorMsg($text)
{
$html= sprintf('<span class="error">%s</span>', $text);
$html .= '<span style="float:right">';
$html .= '<img src="./css/msd/icons/notok.gif" title="" alt="">';
$html .= '</span><br />';
return $html;
}
/**
* Create IMG-Tag
*
* @param string $pic Filename of picture
* @param string $title Title for the picture (will alsobe used for alt-tag)
*
* @return string Built img-tag
*/
public static function getIcon($pic, $title = '')
{
//TODO get value from a config class and get rid of global
global $config;
$img = '<img src="%s%s" alt="%s" title="%s" />';
return sprintf($img, $config['files']['iconpath'], $pic, $title, $title);
}
}

87
inc/classes/helper/Sql.php Normale Datei
Datei anzeigen

@ -0,0 +1,87 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Helper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* Sql-Helper Class
*
* Class offers some methods to wrap some common Sql-commands
*/
class Sql
{
/**
* Optimize a table and write returned message to log file.
*
* Returns true on success or MySQL-Error.
*
* @param MsdDbFactory $dbo Database object
* @param string $table Name of table
*
* @return bool
*/
public static function optimizeTable(MsdDbFactory $dbo, $table)
{
global $lang, $log;
$res = $dbo->optimizeTable($table);
if (false !== $res) {
$success=array('status', 'info','warning','note');
if (in_array($res['Msg_type'], $success)) {
$logMsg = $lang['L_OPTIMIZE'].' `'.$dbo->dbSelected. '`.`';
$logMsg .= $table.'`: '.$res['Msg_text'];
$log->write(Log::PHP, $logMsg);
return true;
} else {
$logMsg = sprintf($lang['L_OPTIMIZE_TABLE_ERR'], $table);
writeToErrorLog($dbo->dbSelected, $logMsg, $res['msg_text'], 0);
return false;
}
} else {
$logMsg = sprintf($lang['L_OPTIMIZE_TABLE_ERR'], $table);
writeToErrorLog($dbo->dbSelecte, $logMsg, $res['msg_text'], 0);
return false;
}
}
/**
* Creates a INSERT INTO-string
*
* "INSERT INTO (`field1`,`field2`,..)"-Command for the given table
* by looking up the meta-information. Table must exists.
* Note: Only used when restoring a backup not from MySQLDumper containing
* extended inserts.
*
* @param MsdDbFactory Database object
* @param string $table Name of table to analyze
*
* @return string $insert The name of the table extracted from the Query
**/
public static function getInsertSyntax(MsdDbFactory $dbo, $table)
{
$insert = '';
$columns=$dbo->getTableColumns($table);
$fields=array_keys($columns);
$insert = 'INSERT INTO `' . $table . '` (`';
$insert .=implode('`,`', $fields) . '`)';
return $insert;
}
/**
* Disables keys for given table
*
* @param MsdDbFactory $dbo Database object
* @param string $table Name of table
*
* @return bool
*/
public static function disableKeys(MsdDbFactory $dbo, $table)
{
$query = '/*!40000 ALTER TABLE `' . $table . '` DISABLE KEYS */';
return $dbo->query($query, MsdDbFactory::SIMPLE);
}
}

Datei anzeigen

@ -0,0 +1,37 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: $
* @author $Author$
* @lastmodified $Date$
*/
/**
* String-Helper Class
*
* Class has some static methods to modify String-output
*/
class String
{
/**
* Format the given number to better readable number
*
* @param float|int $number Number to format
* @param int $precision Selected format precision
*
* @return string Formatted number
*/
public static function formatNumber($number, $precision = 0)
{
$formattedNumber = number_format(
(float) $number,
(int) $precision,
',',
'.'
);
return $formattedNumber;
}
}

94
inc/configuration.php Normale Datei
Datei anzeigen

@ -0,0 +1,94 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
// language changed?
if (isset($_POST['save']) && isset($_POST['lang_old'])
&& $_POST['language'] != $_POST['lang_old']) {
$config['language'] = $_POST['language'];
$_SESSION['config']['language'] = $_POST['language'];
include ('./language/' . $config['language'] . '/lang.php');
}
include ('./inc/functions/functions_sql.php');
include ('./inc/functions/functions_dump.php');
include ('./language/lang_list.php');
include ('./inc/define_icons.php');
if (!isset($msg)) {
$msg = '';
}
$saveConfig = false;
$blendInConnectionParams = false;
$oldTheme = $config['theme'];
if (isset($_POST['save'])) {
// $saveConfig will be set to false if fatal errors occur while validating
$saveConfig = true;
}
include ('./inc/configuration/databases.php');
include ('./inc/configuration/general.php');
include ('./inc/configuration/interface.php');
include ('./inc/configuration/autodelete.php');
include ('./inc/configuration/email.php');
include ('./inc/configuration/ftp.php');
include ('./inc/configuration/cronscript.php');
// should a new configuration file be created?
if (isset($_GET['create_new_configfile'])) {
$saveConfig = false;
if ($_POST['new_configurationfile'] > '') {
$tmpConfigfilename = utf8_decode(trim($_POST['new_configurationfile']));
if (!preg_match("/^[a-z.-_]+$/i", $tmpConfigfilename, $matches)) {
$msg = sprintf(
$lang['L_ERROR_CONFIGFILE_NAME'],
$_POST['new_configurationfile']
);
$msg = Html::getErrorMsg($msg);
} else {
$config['config_file'] = $_POST['new_configurationfile'];
$config['cron_configurationfile'] = $_POST['new_configurationfile']
. ".conf.php";
$saveConfig = true;
}
if ($saveConfig) {
if (saveConfig() == true) {
$saveConfig = false;
$msg = sprintf(
$lang['L_SUCCESS_CONFIGFILE_CREATED'],
$_POST['new_configurationfile']
);
$msg = Html::getOkMsg($msg);
} else {
$msg = Html::getErrorMsg($lang['L_SAVE_ERROR']);
$saveConfig = false;
}
}
} else {
$msg = Html::getErrorMsg($lang['L_NO_NAME_GIVEN']);
}
}
if ($saveConfig) {
// validation was fine, we can write the values to the actual config file
if (saveConfig() == true) {
getConfig($config['config_file']);
if ($config['logcompression'] != $oldlogcompression) {
deleteLog();
}
$msg = sprintf($lang['L_SAVE_SUCCESS'], $config['config_file']);
$msg = Html::getOkMsg($msg);
} else {
$msg = Html::getErrorMsg($lang['L_SAVE_ERROR']);
}
}
include ('./inc/configuration/config_files.php');
include ('./inc/configuration/config_menu.php');
include ('./inc/configuration/footer.php');

Datei anzeigen

@ -0,0 +1,46 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
if (isset($_POST['save'])) {
if (!is_array($config['auto_delete'])) {
$config['auto_delete'] = array();
$config['auto_delete']['activated'] = 0;
$config['auto_delete']['max_backup_files'] = 3;
}
if (isset($_POST['auto_delete'])) {
$config['auto_delete']['activated'] = (int) $_POST['auto_delete'];
}
if (isset($_POST['max_backup_files'])) {
$config['auto_delete']['max_backup_files'] =
(int) $_POST['max_backup_files'];
}
}
$tplConfigurationAutodelete = new MSDTemplate();
$tplConfigurationAutodelete->set_filenames(
array(
'tplConfigurationAutodelete' => 'tpl/configuration/autodelete.tpl')
);
$tplConfigurationAutodelete->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'AUTODELETE_ENABLED_SELECTED' =>
Html::getChecked($config['auto_delete']['activated'], 1),
'AUTODELETE_DISABLED_SELECTED' =>
Html::getChecked($config['auto_delete']['activated'], 0),
'MAX_BACKUP_FILES' =>
(int) $config['auto_delete']['max_backup_files'],
'MAX_BACKUP_FILES_DISABLED' =>
Html::getDisabled($config['auto_delete']['activated'], 0))
);

Datei anzeigen

@ -0,0 +1,206 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$oldConfig = $config['config_file'];
if (isset($_GET['config'])) {
$oldDatabases = $databases;
$databases = array();
if (isset($_POST['save'])) {
unset($_POST['save']);
}
if (getConfig($_GET['config'])) {
$config['config_file'] = $_GET['config'];
$_SESSION['config_file'] = $_GET['config'];
$oldConfig = $_GET['config'];
$msg = '<p class="success">'
. sprintf($lang['L_CONFIG_LOADED'], $config['config_file'])
. '</p>';
} else {
getConfig($oldConfig);
$databases = $oldDatabases;
$msg = '<p class="error">'
. sprintf(
$lang['L_ERROR_LOADING_CONFIGFILE'],
$config['config_file']
) . '</p>';
}
}
if (isset($_GET['config_delete'])) {
$deleteConfig = urldecode($_GET['config_delete']);
if ($deleteConfig == $config['config_file']) {
//actaul configuration was deleted, fall back to mysqldumper-conf
$config['config_file'] = 'mysqldumper';
$_SESSION['config_file'] = $config['config_file'];
getConfig($config['config_file']);
}
$del = @unlink('./' . $config['paths']['config'] . $deleteConfig . '.php');
if ($del) {
// delete Perl config file
$delFile = $config['paths']['config'] . $deleteConfig . '.conf.php';
$del = @unlink('./' . $delFile);
}
if ($del === false) {
$msg = '<p class="error">'
. sprintf($lang['L_ERROR_DELETING_CONFIGFILE'], $deleteConfig)
. '</p>';
} else {
$msg = '<p class="success">'
. sprintf($lang['L_SUCCESS_DELETING_CONFIGFILE'], $deleteConfig)
. '</p>';
}
$sel = 'configs';
}
$tplConfigurationConfigFiles = new MSDTemplate();
$tplConfigurationConfigFiles->set_filenames(
array(
'tplConfigurationConfigFiles' => 'tpl/configuration/configFiles.tpl'
)
);
$tplConfigurationConfigFiles->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'ICON_SEARCH' => $icon['search'],
'ICON_EDIT' => $icon['edit'],
'ICON_DELETE' => $icon['delete']
)
);
$i = 0;
$configs = getConfigFilenames();
// iterate config files and print settings to screen
foreach ($configs as $c) {
$i++;
unset($databases);
$databases = array();
getConfig($c);
$rowclass = ($i % 2) ? 'dbrow' : 'dbrow1';
if ($oldConfig == $c) {
$rowclass = 'dbrowsel'; // highlight active configuration
}
// Generate configuration output
$outputstringMultisettings = '';
$dbsToBackup = array();
// look up which databases are set to be dumped
prepareDumpProcess();
$dbs = array_keys($dump['databases']);
$dbsToBackup = implode(', ', $dbs);
$tplConfigurationConfigFiles->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $rowclass,
'NR' => $i,
'CONFIG_ID' => sprintf("%03d", $i),
'CONFIG_NAME' => $c,
'CONFIG_NAME_URLENCODED' => urlencode($c),
'DB_HOST' => $config['dbhost'],
'DB_USER' => $config['dbuser'],
'NR_OF_DATABASES' => sizeof($databases),
'DBS_TO_BACKUP' => $dbsToBackup . '&nbsp;',
'ATTACH_BACKUP' =>
$config['email']['attach_backup'] == 1 ?
$lang['L_YES'] : $lang['L_NO']
)
);
if (count($databases) > 0) {
$a = 1;
foreach ($databases as $dbName => $val) {
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.LIST_DBS',
array(
'ROWCLASS' => $a % 2 ? 'dbrow' : 'dbrow1',
'NR' => $a,
'DB_NAME_URLENCODED' => base64_encode($dbName),
'DB_NAME' => $dbName
)
);
$a++;
}
}
// is Multipart used?
if ($config['multi_part'] == 1) {
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.USE_MULTIPART',
array(
'MULTIPART_FILESIZE' =>
byteOutput($config['multipart_groesse'])
)
);
}
// send mail after backup?
if ($config['send_mail'] == 1) {
$recipientsCc = implodeSubarray(
$config['email']['recipient_cc'],
'address'
);
if ($config['email']['recipient_name'] > '') {
$recipient = $config['email']['recipient_name'];
} else {
$recipient = $config['email']['recipient_address'];
}
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.SEND_EMAIL',
array(
'RECIPIENT' => $recipient,
'RECIPIENT_CC' =>
$recipientsCc > '' ? $recipientsCc : $lang['L_NO']
)
);
$bytes = $config['email_maxsize1'] * 1024;
if ($config['email_maxsize2'] == 2) $bytes = $bytes * 1024;
if ($config['email']['attach_backup'] == 1) {
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.SEND_EMAIL.EMAIL_MAX_SIZE',
array(
'SIZE' => byteOutput($bytes)
)
);
}
}
// FTP settings
foreach ($config['ftp'] as $ftp) {
if ($ftp['transfer'] > 0) {
$ftpSettings = sprintf(
$lang['L_FTP_SEND_TO'], $ftp['server'], $ftp['dir']
);
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.SEND_FTP',
array(
'FTP_SETTINGS' => Html::replaceQuotes($ftpSettings)
)
);
}
}
// Show delete-button if it is not the standard config file
if ($c != 'mysqldumper') {
$confirmDelete = sprintf($lang['L_CONFIRM_CONFIGFILE_DELETE'], $c);
$tplConfigurationConfigFiles->assign_block_vars(
'ROW.DELETE_CONFIG',
array(
'CONFIRM_DELETE' => Html::getJsQuote($confirmDelete)
)
);
}
}
unset($databases);
$databases = array();
$_SESSION['config_file'] = $oldConfig;
$config['config_file'] = $oldConfig;
// reload actual configuration
getConfig($oldConfig);

Datei anzeigen

@ -0,0 +1,31 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$tplConfigurationConfigMenu = new MSDTemplate();
$tplConfigurationConfigMenu->set_filenames(
array(
'tplConfigurationConfigMenu' => 'tpl/configuration/config_menu.tpl'
)
);
$msdMode = $lang['L_MODE_EXPERT'];
if ($config['msd_mode'] == 0) {
$msdMode = $lang['L_MODE_EASY'];
}
$tplConfigurationConfigMenu->assign_vars(
array(
'CONFIGURATION_NAME' => $config['config_file'],
'ICON_SAVE' => $icon['small']['save'],
'ICON_OPEN_FILE' => $icon['small']['open_file'],
'MSD_MODE' => $msdMode
)
);

Datei anzeigen

@ -0,0 +1,69 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
if (isset($_POST['save'])) {
$config['cron_comment'] = $_POST['cron_comment'];
if (isset($_POST['cron_extender'])) {
$config['cron_extender'] = (int) $_POST['cron_extender'];
}
// cron_select_savepath/
if (!isset($_POST['cron_select_savepath'])) {
$_POST['cron_select_savepath'] = $config['config_file'];
}
$config['cron_execution_path'] = $_POST['cron_execution_path'];
if ($config['cron_execution_path'] == '') {
$config['cron_execution_path'] = 'msd_cron/';
}
if (strlen($config['cron_execution_path']) > 1
&& substr($config['cron_execution_path'], -1) != '/') {
$config['cron_execution_path'] .= '/';
}
if (isset($_POST['cron_printout'])) {
$config['cron_printout'] = (int) $_POST['cron_printout'];
}
if (isset($_POST['cron_completelog'])) {
$config['cron_completelog'] = (int) $_POST['cron_completelog'];
}
if (isset($_POST['compression'])) {
$config['cron_compression'] = (int) $_POST['compression'];
}
if (isset($_POST['cron_completelog'])) {
$config['cron_completelog'] = (int) $_POST['cron_completelog'];
}
}
$tplConfigurationCronscript = new MSDTemplate();
$tplConfigurationCronscript->set_filenames(
array('tplConfigurationCronscript' => 'tpl/configuration/cronscript.tpl')
);
$tplConfigurationCronscript->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'EXTENSION_PL_SELECTED' =>
Html::getChecked($config['cron_extender'], 0),
'EXTENSION_CGI_SELECTED' =>
Html::getChecked($config['cron_extender'], 1),
'EXEC_PATH' => $config['cron_execution_path'],
'CRON_PRINTOUT_ENABLED_SELECTED' =>
Html::getChecked($config['cron_printout'], 1),
'CRON_PRINTOUT_DISABLED_SELECTED' =>
Html::getChecked($config['cron_printout'], 0),
'CRON_COMPLETELOG_ENABLED_SELECTED' =>
Html::getChecked($config['cron_completelog'], 1),
'CRON_COMPLETELOG_DISABLED_SELECTED' =>
Html::getChecked($config['cron_completelog'], 0),
'CRON_COMMENT' =>
htmlspecialchars($config['cron_comment'], ENT_COMPAT, 'UTF-8')
)
);

Datei anzeigen

@ -0,0 +1,174 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) {
die('No direct access.');
}
getSqlLibrary();
if (isset($_POST['save'])) {
if (count($databases) > 0) {
$i = 0;
foreach ($databases as $dbName => $val) {
$databases[$dbName]['prefix'] = '';
if (isset($_POST['dbpraefix_' . $i])) {
$databases[$dbName]['prefix'] = $_POST['dbpraefix_' . $i];
}
$databases[$dbName]['command_before_dump'] = '';
if (!empty($_POST['command_before_' . $i])) {
$databases[$dbName]['command_before_dump'] =
getQueryFromSqlLibrary($_POST['command_before_' . $i]);
}
$databases[$dbName]['command_after_dump'] = '';
if (!empty($_POST['command_after_' . $i])) {
$databases[$dbName]['command_after_dump'] =
getQueryFromSqlLibrary($_POST['command_after_' . $i]);
}
if (isset($_POST['db_multidump_' . $i])
&& $_POST['db_multidump_' . $i] == "db_multidump_$i") {
$databases[$dbName]['dump'] = 1;
} else {
$databases[$dbName]['dump'] = 0;
}
$i++;
}
}
if ($config['dbhost'] != $_POST['dbhost']
|| $config['dbuser'] != $_POST['dbuser']
|| $config['dbpass'] != $_POST['dbpass']
|| $config['dbport'] != $_POST['dbport']
|| $config['dbsocket'] != $_POST['dbsocket']) {
//neue Verbindungsparameter
$blendInConnectionParams = true;
//alte Parameter sichern
$old['dbhost'] = $config['dbhost'];
$old['dbuser'] = $config['dbuser'];
$old['dbpass'] = $config['dbpass'];
$old['dbport'] = $config['dbport'];
$old['dbsocket'] = $config['dbsocket'];
//neu setzen
$config['dbhost'] = $_POST['dbhost'];
$config['dbuser'] = $_POST['dbuser'];
$config['dbpass'] = $_POST['dbpass'];
$config['dbport'] = $_POST['dbport'];
$config['dbsocket'] = $_POST['dbsocket'];
$dbo = MsdDbFactory::getAdapter(
$config['dbhost'],
$config['dbuser'],
$config['dbpass'],
$config['dbport'],
$config['dbsocket']
);
// try to connect with new params
$res = $dbo->dbConnect();
if ($res === true) {
// ok - get list of databases
$dbo->getDatabases();
setDefaultConfig();
} else {
//something went wrong - resume old values
$config['dbhost'] = $old['dbhost'];
$config['dbuser'] = $old['dbuser'];
$config['dbpass'] = $old['dbpass'];
$config['dbport'] = $old['dbport'];
$config['dbsocket'] = $old['dbsocket'];
$msg .= '<p class="error">' . $lang['L_WRONG_CONNECTIONPARS'] . ': ' . $res . '</p>';
$saveConfig = false;
$dbo = MsdDbFactory::getAdapter(
$config['dbhost'],
$config['dbuser'],
$config['dbpass'],
$config['dbport'],
$config['dbsocket']
);
}
}
// manual adding of a database
if ($_POST['add_db_manual'] > '') {
$saveConfig = false;
$blendInConnectionParams = true;
$dbToAdd = trim($_POST['add_db_manual']);
$found = false;
// Check if we already have this one in our db list
if (isset($databases[$dbToAdd])) {
$addDbMessage = sprintf($lang['L_DB_IN_LIST'], $dbToAdd);
} else {
$dbo = MsdDbFactory::getAdapter(
$config['dbhost'],
$config['dbuser'],
$config['dbpass'],
$config['dbport'],
$config['dbsocket']
);
try {
$dbo->selectDb($dbToAdd, true);
addDatabaseToConfig($dbToAdd);
$saveConfig = true;
} catch (Exception $e){
$addDbMessage = $lang['L_ERROR'] . ': (' . $e->getCode() . ') ';
$addDbMessage .= $e->getMessage();
}
}
}
}
$tplConfigurationDatabases = new MSDTemplate();
$tplConfigurationDatabases->set_filenames(
array('tplConfigurationDatabases' => 'tpl/configuration/databases.tpl')
);
$tplConfigurationDatabases->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'DB_HOST' => $config['dbhost'],
'DB_USER' => $config['dbuser'],
'DB_PASS' => $config['dbpass'],
'DB_PORT' => $config['dbport'],
'DB_SOCKET' => $config['dbsocket'],
'ICON_EDIT' => $icon['edit'],
'ICON_DOWN' => $icon['arrow_down'],
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'])
);
if (isset($addDbMessage) && $addDbMessage > '')
$tplConfigurationDatabases->assign_block_vars(
'MANUAL_DB_ADD', array('MESSAGE' => $addDbMessage)
);
//Wenn Datenbanken vorhanden sind
if (count($databases) > 0) {
$dbCount = count($databases);
$tplConfigurationDatabases->assign_block_vars(
'DBS', array('DB_COUNT' => $dbCount)
);
$i = 0;
foreach ($databases as $dbName => $val) {
if (!isset($val['dump'])) {
$val['dump'] = 0;
}
if (!isset($val['prefix'])) {
$val['prefix'] = '';
}
$rowclass = $i % 2 ? 'dbrow' : 'dbrow1';
if ($dbName == $config['db_actual']) {
$rowclass = 'dbrowsel';
}
$tplConfigurationDatabases->assign_block_vars(
'DBS.ROW', array(
'ROWCLASS' => $rowclass,
'ID' => $i,
'NR' => $i + 1,
'DB_NAME' => $dbName,
'DB_MULTIDUMP_ENABLED' => Html::getChecked($val['dump'], 1),
'DB_PREFIX' => $val['prefix'],
'COMMAND_BEFORE_BACKUP_COMBO' => getCommandDumpComboBox(0, $i, $dbName),
'COMMAND_AFTER_BACKUP_COMBO' => getCommandDumpComboBox(1, $i, $dbName))
);
$i++;
}
} else {
$tplConfigurationDatabases->assign_block_vars('NO_DB', array());
}

184
inc/configuration/email.php Normale Datei
Datei anzeigen

@ -0,0 +1,184 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//add new cc-recipient
if ($action == 'add_recipient_cc') {
$index = 0;
if (isset($_POST['email_recipient_cc'])) {
$index = count($_POST['email_recipient_cc']);
}
$_POST['email_recipient_cc'][$index]['name'] = '';
$_POST['email_recipient_cc'][$index]['address'] = '';
$_POST['save'] = true;
}
// delete cc-recipient
if ($action == 'delete_recipient_cc') {
$index = (int) $_GET['cc'];
unset($_POST['email_recipient_cc'][$index]);
if (isset($config['email']['recipient_cc'][$index])) {
unset($config['email']['recipient_cc'][$index]);
}
$_POST['save'] = true;
}
if (isset($_POST['save'])) {
if (isset($_POST['send_mail'])) {
$config['send_mail'] = (int) $_POST['send_mail'];
}
if (!is_array($config['email'])) {
$config['email'] = array();
}
if (isset($_POST['email_recipient_address'])) {
$config['email']['recipient_address'] =
$_POST['email_recipient_address'];
}
if (isset($_POST['email_recipient_name'])) {
$config['email']['recipient_name'] = $_POST['email_recipient_name'];
}
$config['email']['recipient_cc'] = array();
if (isset($_POST['email_recipient_cc'])) {
$i = 0;
foreach ($_POST['email_recipient_cc'] as $key => $val) {
$config['email']['recipient_cc'][$i] = array();
$config['email']['recipient_cc'][$i]['name'] = $val['name'];
$config['email']['recipient_cc'][$i]['address'] = $val['address'];
$i++;
}
}
if (isset($_POST['email_sender_name'])) {
$config['email']['sender_name'] = $_POST['email_sender_name'];
}
if (isset($_POST['email_sender_address'])) {
$config['email']['sender_address'] = $_POST['email_sender_address'];
}
if (isset($_POST['attach_backup'])) {
$config['email']['sender_address'] = $_POST['attach_backup'];
}
if (isset($_POST['email_maxsize1'])) {
$config['email_maxsize1'] = floatval($_POST['email_maxsize1']);
}
if (isset($_POST['email_maxsize2'])) {
$config['email_maxsize2'] = $_POST['email_maxsize2'];
}
$config['email_maxsize'] = $config['email_maxsize1']
* (($config['email_maxsize2'] == 1) ? 1024 : 1024 * 1024);
if (isset($_POST['use_mailer'])) {
$config['use_mailer'] = $_POST['use_mailer'];
}
if (isset($_POST['sendmail_call'])) {
$config['sendmail_call'] = $_POST['sendmail_call'];
}
if (isset($_POST['smtp_server'])) {
$config['smtp_server'] = $_POST['smtp_server'];
}
if (isset($_POST['smtp_user'])) {
$config['smtp_user'] = $_POST['smtp_user'];
}
if (isset($_POST['smtp_pass'])) {
$config['smtp_pass'] = $_POST['smtp_pass'];
}
if (isset($_POST['smtp_useauth'])) {
$config['smtp_useauth'] = $_POST['smtp_useauth'];
}
if (isset($_POST['smtp_usessl'])) {
$config['smtp_usessl'] = $_POST['smtp_usessl'];
}
if (isset($_POST['smtp_port'])) {
$config['smtp_port'] = (int) $_POST['smtp_port'];
}
if (isset($_POST['smtp_pop3_server'])) {
$config['smtp_pop3_server'] = (string) $_POST['smtp_pop3_server'];
}
if (isset($_POST['smtp_pop3_port'])) {
$config['smtp_pop3_port'] = (int) $_POST['smtp_pop3_port'];
}
}
// backwards compatibilty with older configurations
if (!isset($config['email_maxsize1'])) {
$config['email_maxsize1'] = 0;
}
if (!isset($config['email_maxsize2'])) {
$config['email_maxsize2'] = 1;
}
$tplConfigurationEmail = new MSDTemplate();
$tplConfigurationEmail->set_filenames(
array('tplConfigurationEmail' => 'tpl/configuration/email.tpl')
);
$tplConfigurationEmail->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'ICON_PLUS' => $icon['plus'],
'ICON_DELETE' => $icon['delete'],
'SEND_MAIL_ENABLED_SELECTED' => Html::getChecked($config['send_mail'], 1),
'EMAIL_DISABLED' => Html::getDisabled($config['send_mail'], 0),
'SEND_MAIL_DISABLED_SELECTED' => Html::getChecked($config['send_mail'], 0),
'EMAIL_RECIPIENT_NAME' =>
Html::replaceQuotes($config['email']['recipient_name']),
'EMAIL_RECIPIENT_ADDRESS' =>
Html::replaceQuotes($config['email']['recipient_address']),
'EMAIL_SENDER_NAME' => Html::replaceQuotes($config['email']['sender_name']),
'EMAIL_SENDER_ADDRESS' =>
Html::replaceQuotes($config['email']['sender_address']),
'ATTACH_BACKUP_ENABLED_SELECTED' =>
Html::getChecked($config['email']['attach_backup'], 1),
'ATTACH_BACKUP_DISABLED_SELECTED' =>
Html::getChecked($config['email']['attach_backup'], 0),
'MAXSIZE_DISABLED' =>
Html::getDisabled($config['email']['attach_backup'], 0),
'EMAIL_MAXSIZE' => $config['email_maxsize1'],
'EMAIL_UNIT_SIZE_KB_SELECTED' =>
Html::getSelected($config['email_maxsize2'], 1),
'EMAIL_UNIT_SIZE_MB_SELECTED' =>
Html::getSelected($config['email_maxsize2'], 2),
'EMAIL_USE_PHPMAIL_SELECTED' => Html::getChecked($config['use_mailer'], 0),
'EMAIL_USE_SENDMAIL_SELECTED' => Html::getChecked($config['use_mailer'], 1),
'EMAIL_USE_SMTP_SELECTED' => Html::getChecked($config['use_mailer'], 2),
'SENDMAIL_CALL' => Html::replaceQuotes($config['sendmail_call']),
'SMTP_SERVER' => $config['smtp_server'],
'SMTP_USER' => $config['smtp_user'],
'SMTP_PASS' => $config['smtp_pass'],
'SMTP_AUTH_DISABLED' => Html::getDisabled($config['smtp_useauth'], 0),
'SMTP_AUTH_SELECTED' => Html::getChecked($config['smtp_useauth'], 1),
'SMTP_AUTH_NOT_SELECTED' => Html::getChecked($config['smtp_useauth'], 0),
'SMTP_SSL_SELECTED' => Html::getChecked($config['smtp_usessl'], 1),
'SMTP_SSL_NOT_SELECTED' => Html::getChecked($config['smtp_usessl'], 0),
'SMTP_PORT' => $config['smtp_port'],
'SMTP_POP3_SERVER' => $config['smtp_pop3_server'],
'SMTP_POP3_PORT' => $config['smtp_pop3_port'])
);
if ($config['smtp_useauth'] == 0) {
$tplConfigurationEmail->assign_block_vars('HIDE_SMTP_AUTH_FIELDS', array());
}
if (is_array($config['email']['recipient_cc'])
&& sizeof($config['email']['recipient_cc']) > 0) {
foreach ($config['email']['recipient_cc'] as $key => $val) {
$confirmRecDelete = sprintf(
$lang['L_CONFIRM_RECIPIENT_DELETE'],
$val['name'] . ' ' . $val['address']
);
$confirmRecDelete = Html::replaceQuotes($confirmRecDelete);
$tplConfigurationEmail->assign_block_vars(
'EMAIL_RECIPIENT_CC',
array(
'NR' => $key,
'CONFIRM_RECIPIENT_DELETE' => $confirmRecDelete,
'EMAIL_RECIPIENT_CC_NAME' => Html::replaceQuotes($val['name']),
'EMAIL_RECIPIENT_CC_ADDRESS' =>
Html::replaceQuotes($val['address'])
)
);
}
}

44
inc/configuration/footer.php Normale Datei
Datei anzeigen

@ -0,0 +1,44 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
// special div selected? DIV with this id will be shown e.g after pressing
// the save button
$sel = (isset($_POST['sel'])) ? $_POST['sel'] : 'db';
if (isset($_GET['sel'])) $sel = $_GET['sel'];
$tplConfigurationFooter = new MSDTemplate();
$tplConfigurationFooter->set_filenames(
array('tplConfigurationFooter' => 'tpl/configuration/footer.tpl')
);
$tplConfigurationFooter->assign_vars(
array(
'SELECTED_DIV' => $sel,
'NOTIFICATION_POSITION' => $config['notification_position']
)
);
//output notification message if we have one
if ($msg > '') {
$tplConfigurationFooter->assign_block_vars(
'MESSAGE', array('TEXT' => Html::getJsQuote($msg, true))
);
}
// if something went wrong with the change of a user or no database was found
// -> blend in connection params and let the user correct it
if ( (isset($blendInConnectionParams) && $blendInConnectionParams)
|| count($databases) == 0) {
$tplConfigurationFooter->assign_block_vars(
'SWITCH_TO_CONNECTION_PARAMETER', array()
);
}

156
inc/configuration/ftp.php Normale Datei
Datei anzeigen

@ -0,0 +1,156 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) {
die('No direct access.');
}
// will hold connection result if ftp connection should be checked
$ftpConnectionCheck = array();
if (isset($_POST['save'])) {
if (!is_array($config['ftp'])) {
$config['ftp'] = array();
}
// add ftp connection
if (!isset($_POST['ftp'])) {
$_POST['ftp'] = array();
}
if (isset($_POST['ftp_add_new_connection'])) {
$_POST['ftp'][count($_POST['ftp'])] = array();
}
foreach ($_POST['ftp'] as $key => $val) {
// set default values if this connection is a new one
if (!isset($config['ftp'][$key]) || !is_array($config['ftp'][$key])) {
$config['ftp'][$key] = array();
}
if (!isset($config['ftp'][$key]['server'])) {
$config['ftp'][$key]['server'] = '';
}
if (!isset($config['ftp'][$key]['transfer'])) {
$config['ftp'][$key]['transfer'] = 0;
}
if (!isset($config['ftp'][$key]['timeout'])) {
$config['ftp'][$key]['timeout'] = 10;
}
if (!isset($config['ftp'][$key]['ssl'])) {
$config['ftp'][$key]['ssl'] = 0;
}
if (!isset($config['ftp'][$key]['mode'])) {
$config['ftp'][$key]['mode'] = 0;
}
if (!isset($config['ftp'][$key]['port'])) {
$config['ftp'][$key]['port'] = 21;
}
if (!isset($config['ftp'][$key]['user'])) {
$config['ftp'][$key]['user'] = '';
}
if (!isset($config['ftp'][$key]['pass'])) {
$config['ftp'][$key]['pass'] = '';
}
if (!isset($config['ftp'][$key]['dir'])) {
$config['ftp'][$key]['dir'] = '/';
}
if (isset($val['transfer'])) {
$config['ftp'][$key]['transfer'] = (int) $val['transfer'];
}
if (isset($val['server'])) {
$config['ftp'][$key]['server'] = (string) $val['server'];
}
if (isset($val['timeout'])) {
$config['ftp'][$key]['timeout'] = (int) $val['timeout'];
}
if (isset($val['ssl'])) {
$config['ftp'][$key]['ssl'] = (int) $val['ssl'];
}
if (isset($val['mode'])) {
$config['ftp'][$key]['mode'] = (int) $val['mode'];
}
if (isset($val['port'])) {
$config['ftp'][$key]['port'] = (int) $val['port'];
}
if (isset($val['user'])) {
$config['ftp'][$key]['user'] = (string) $val['user'];
}
if (isset($val['pass'])) {
$config['ftp'][$key]['pass'] = (string) $val['pass'];
}
if (isset($val['dir'])) {
$config['ftp'][$key]['dir'] = (string) $val['dir'];
}
if ($config['ftp'][$key]['dir'] == ''
|| (strlen($config['ftp'][$key]['dir']) > 1
&& substr($config['ftp'][$key]['dir'], -1) != '/')) {
$config['ftp'][$key]['dir'] .= '/';
}
if (isset($_POST['ftp'][$key]['test'])) {
$ftpConnectionCheck[$key] = testFTP($key);
// don't save values - we just want to test the ftp connection data
$saveConfig = false;
}
}
}
if (isset($_GET['del_ftp'])) {
$index = intval($_GET['del_ftp']);
if (isset($config['ftp'][$index])) {
unset($config['ftp'][$index]);
}
sort($config['ftp']);
}
$tplConfigurationFtp = new MSDTemplate();
$tplConfigurationFtp->set_filenames(
array('tplConfigurationFtp' => 'tpl/configuration/ftp.tpl')
);
$tplConfigurationFtp->assign_vars(
array(
'ICON_ADD' => $icon['plus'],
'ICON_DELETE' => $icon['delete'],
'ICON_SAVE' => $icon['small']['save']
)
);
foreach ($config['ftp'] as $key => $val) {
// if ftp extension is not loaded -> disable ftp transfer
if (!extension_loaded('ftp')) {
$config['ftp'][$key]['transfer'] = 0;
}
$tplConfigurationFtp->assign_block_vars(
'FTP',
array(
'NR' => $key + 1,
'ID' => $key,
'FTP_DISABLED' => Html::getDisabled(!extension_loaded("ftp"), true),
'FTP_ENABLED_SELECTED' => Html::getChecked($val['transfer'], 1),
'FTP_DISABLED_SELECTED' => Html::getChecked($val['transfer'], 0),
'FTP_FIELDS_DISABLED' => Html::getDisabled($val['transfer'], 0),
'FTP_TIMEOUT' => $val['timeout'],
'FTP_PASSIVE_MODE_SELECTED' => Html::getChecked($val['mode'], 1),
'FTP_SSL_DISABLED' =>
Html::getDisabled(extension_loaded('openssl'), false),
'FTP_SSL_ENABLED_SELECTED' => Html::getChecked($val['ssl'], 1),
'FTP_SERVER' => $config['ftp'][$key]['server'],
'FTP_PORT' => $val['port'],
'FTP_USER' => Html::replaceQuotes($val['user']),
'FTP_PASSWORD' => Html::replaceQuotes($val['pass']),
'FTP_DIRECTORY' => $val['dir'],
'FTP_CONFIRM_DELETE' =>
Html::replaceQuotes($lang['L_FTP_CONFIRM_DELETE'])
)
);
if (isset($ftpConnectionCheck[$key])) {
$tplConfigurationFtp->assign_block_vars(
'FTP.CHECK', array('RESULT' => $ftpConnectionCheck[$key])
);
}
}

146
inc/configuration/general.php Normale Datei
Datei anzeigen

@ -0,0 +1,146 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
if (isset($_POST['save'])) {
if (isset($_POST['msd_mode'])) {
$config['msd_mode'] = (int) $_POST['msd_mode'];
}
if (isset($_POST['compression'])) {
$config['compression'] = (int) $_POST['compression'];
}
if (isset($_POST['minspeed'])) {
$config['minspeed'] = (int) $_POST['minspeed'];
}
if ($config['minspeed'] < 50) $config['minspeed'] = 50;
if (isset($_POST['maxspeed'])) {
$config['maxspeed'] = (int) $_POST['maxspeed'];
}
if ($config['maxspeed'] < $config['minspeed']) {
$config['maxspeed'] = $config['minspeed'] * 2;
}
if (isset($_POST['stop_with_error'])) {
$config['stop_with_error'] = (int) $_POST['stop_with_error'];
}
if (isset($_POST['multi_part'])) {
$config['multi_part'] = (int) $_POST['multi_part'];
}
if (isset($_POST['multipartgroesse1'])) {
$config['multipartgroesse1'] =
floatval(str_replace(',', '.', $_POST['multipartgroesse1']));
}
if (isset($_POST['multipartgroesse2'])) {
$config['multipartgroesse2'] = (int) $_POST['multipartgroesse2'];
}
if ($config['multipartgroesse1'] < 100
&& $config['multipartgroesse2'] == 1) {
$config['multipartgroesse1'] = 100;
}
if ($config['multipartgroesse1'] < 1 && $config['multipartgroesse2'] == 2) {
$config['multipartgroesse1'] = 1;
}
// if compression changes -> delete old log file
$oldlogcompression = $config['logcompression'];
if (isset($_POST['logcompression'])) {
$config['logcompression'] = $_POST['logcompression'];
} else {
$config['logcompression'] = 0;
}
// if zlib-extension is not installed de-activate compression
// for log and dump file automatically
if (!$config['zlib']) {
$config['logcompression'] = 0;
$config['compression'] = 0;
}
// max size of logfiles
if (isset($_POST['log_maxsize1'])) {
$config['log_maxsize1'] = (int) $_POST['log_maxsize1'];
}
if (isset($_POST['log_maxsize2'])) {
$config['log_maxsize2'] = (int) $_POST['log_maxsize2'];
}
if ($config['log_maxsize1'] < 1) {
$config['log_maxsize1'] = 1;
}
if ($config['log_maxsize1'] < 100 && $config['log_maxsize2'] == 1) {
$config['log_maxsize1'] = 100;
}
if ($config['log_maxsize2'] == 1) {
$config['log_maxsize'] = 1024 * $config['log_maxsize1']; // kB
} else {
$config['log_maxsize'] = 1024 * 1024 * $config['log_maxsize1']; // MB
}
if (isset($_POST['empty_db_before_restore'])) {
$config['empty_db_before_restore'] =
(int) $_POST['empty_db_before_restore'];
}
if (isset($_POST['optimize_tables'])) {
$config['optimize_tables_beforedump'] = (int) $_POST['optimize_tables'];
}
//if we are not in mode expert -> reset hidden settings to safe defaults
if ($config['msd_mode'] == 0) {
$config['empty_db_before_restore'] = 0;
}
}
$tplConfigurationGeneral = new MSDTemplate();
$tplConfigurationGeneral->set_filenames(
array('tplConfigurationGeneral' => 'tpl/configuration/general.tpl')
);
if ($config['msd_mode'] > 0) {
$tplConfigurationGeneral->assign_block_vars('MODE_EXPERT', array());
}
$logGz = !$config['zlib'] ? '' : Html::getChecked($config['logcompression'], 1);
$tplConfigurationGeneral->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'MSD_MODE_EASY_SELECTED' => Html::getChecked($config['msd_mode'], 0),
'MSD_MODE_EXPERT_SELECTED' => Html::getChecked($config['msd_mode'], 1),
'GZ_DISABLED' => Html::getDisabled($config['zlib'], 0),
'LOG_GZ_SELECTED' => $logGz,
'LOG_MAXSIZE1' => $config['log_maxsize1'],
'LOG_UNIT_KB_SELECTED' => Html::getSelected($config['log_maxsize2'], 1),
'LOG_UNIT_MB_SELECTED' => Html::getSelected($config['log_maxsize2'], 2),
'PHP_MEMORY_LIMIT' => $config['memory_limit'],
'MIN_SPEED' => $config['minspeed'],
'MAX_SPEED' => $config['maxspeed'],
'DUMP_GZ_ENABLED_SELECTED' =>
Html::getChecked($config['compression'], 1),
'DUMP_GZ_DISABLED_SELECTED' =>
Html::getChecked($config['compression'], 0),
'MULTIPART_ENABLED_SELECTED' =>
Html::getChecked($config['multi_part'], 1),
'MULTIPART_DISABLED_SELECTED' =>
Html::getChecked($config['multi_part'], 0),
'MULTIPART_FILE_SIZE' => $config['multipartgroesse1'],
'MULTIPART_DISABLED' => Html::getDisabled($config['multi_part'], 0),
'MULTIPART_FILE_SIZE_DISABLED' =>
Html::getDisabled($config['multi_part'], 0),
'MULTIPART_FILE_UNIT_KB_SELECTED' =>
Html::getSelected($config['multipartgroesse2'], 1),
'MULTIPART_FILE_UNIT_MB_SELECTED' =>
Html::getSelected($config['multipartgroesse2'], 2),
'OPTIMIZE_TABLES_ENABLED_SELECTED' =>
Html::getChecked($config['optimize_tables_beforedump'], 1),
'OPTIMIZE_TABLES_DISABLED_SELECTED' =>
Html::getChecked($config['optimize_tables_beforedump'], 0),
'TRUNCATE_DB_ENABLED_SELECTED' =>
Html::getChecked($config['empty_db_before_restore'], 1),
'TRUNCATE_DB_DISABLED_SELECTED' =>
Html::getChecked($config['empty_db_before_restore'], 0),
'STOP_ON_ERROR_ENABLED_SELECTED' =>
Html::getChecked($config['stop_with_error'], 1),
'STOP_ON_ERROR_DISABLED_SELECTED' =>
Html::getChecked($config['stop_with_error'], 0)
)
);

Datei anzeigen

@ -0,0 +1,100 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//define position-array for notification window
$positions = array(
'tl' => $lang['L_POSITION_TL'],
'tc' => $lang['L_POSITION_TC'],
'tr' => $lang['L_POSITION_TR'],
'ml' => $lang['L_POSITION_ML'],
'mc' => $lang['L_POSITION_MC'],
'mr' => $lang['L_POSITION_MR'],
'bl' => $lang['L_POSITION_BL'],
'bc' => $lang['L_POSITION_BC'],
'br' => $lang['L_POSITION_BR']
);
if (isset($_POST['save'])) {
if (isset($_POST['interface_server_caption'])) {
$config['interface_server_caption'] = 1;
} else {
$config['interface_server_caption'] = 0;
}
if (isset($_POST['interface_server_caption_position_1'])) {
$config['interface_server_caption_position'] = 1;
} else {
$config['interface_server_caption_position'] = 0;
}
if (isset($_POST['sqlboxsize'])) {
$config['interface_sqlboxsize'] = (int) $_POST['sqlboxsize'];
}
if (isset($_POST['theme'])) {
$config['theme'] =(string) $_POST['theme'];
}
// make sure that the theme exists! If not fall back to standard theme
if (!is_dir('./css/' . $config['theme'])
|| !is_readable('./css/' . $config['theme'])) {
$config['theme'] = 'msd';
}
if (isset($_POST['notification_position'])) {
$config['notification_position'] = $_POST['notification_position'];
}
if (isset($_POST['interface_table_compact'])) {
$config['interface_table_compact']
= (int) $_POST['interface_table_compact'];
};
if (isset($_POST['resultsPerPage'])) {
$config['resultsPerPage'] = (int) $_POST['resultsPerPage'];
}
if (isset($_POST['refresh_processlist'])) {
$config['refresh_processlist'] = (int) $_POST['refresh_processlist'];
}
if ($config['refresh_processlist'] < 2) {
$config['refresh_processlist'] = 2;
}
}
$tplConfigurationInterface = new MSDTemplate();
$tplConfigurationInterface->set_filenames(
array('tplConfigurationInterface' => 'tpl/configuration/interface.tpl')
);
$tplConfigurationInterface->assign_vars(
array(
'ICON_SAVE' => $icon['small']['save'],
'SEL_LANGUAGES' => getLanguageCombo(),
'LINK_DOWNLOAD_LANGUAGE_PACKS' =>
'http://forum.mysqldumper.de/downloads.php?cat=9',
'LANGUAGE' => $config['language'],
'SERVER_CAPTION' => $config['interface_server_caption'],
'INTERFACE_SERVER_CAPTION_ACTIVATED' =>
Html::getChecked($config['interface_server_caption'], 1),
'INTERFACE_SERVER_CAPTION_DISABLED' =>
Html::getDisabled($config['interface_server_caption'], 0),
'SERVER_CAPTION_POS_MAINFRAME_SELECTED' =>
Html::getChecked($config['interface_server_caption_position'], 1),
'SERVER_CAPTION_POS_MENUE_SELECTED' =>
Html::getChecked($config['interface_server_caption_position'], 0),
'SEL_THEME' => getThemes(),
'LINK_DOWNLOAD_THEMES' =>
'http://forum.mysqldumper.de/downloads.php?cat=3',
'SQLBOX_HEIGHT' => intval($config['interface_sqlboxsize']),
'RESULTS_PER_PAGE' => intval($config['resultsPerPage']),
'SEL_NOTIFICATION_POSITION' =>
Html::getOptionlist($positions, $config['notification_position']),
'REFRESH_PROCESSLIST' => (int) $config['refresh_processlist'],
'SQL_GRID_TYPE_COMPACT_SELECTED' =>
$config['interface_table_compact'] == 1 ? ' checked="checked"' : '',
'SQL_GRID_TYPE_NORMAL_SELECTED' =>
$config['interface_table_compact'] == 0 ? ' checked="checked"' : ''
)
);

69
inc/define_icons.php Normale Datei
Datei anzeigen

@ -0,0 +1,69 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//define icons
$icon['arrow_up'] = Html::getIcon('arrow_up.gif');
$icon['arrow_down'] = Html::getIcon('arrow_down.gif');
$icon['arrow_left'] = Html::getIcon(
'arrowleft.gif', $lang['L_SQL_BACKDBOVERVIEW']
);
$icon['browse'] = Html::getIcon('browse.gif', $lang['L_TITLE_SHOW_DATA']);
$icon['cancel'] = Html::getIcon('delete.gif', $lang['L_CANCEL']);
$icon['edit'] = Html::getIcon('edit.gif', $lang['L_EDIT']);
$icon['delete'] = Html::getIcon('delete.gif', $lang['L_DELETE']);
$icon['db'] = Html::getIcon('db.gif', $lang['L_DBS']);
$icon['download'] = Html::getIcon('download.png');
$icon['close'] = Html::getIcon('close.gif', $lang['L_CLOSE']);
$icon['gz'] = Html::getIcon('gz.gif', $lang['L_COMPRESSED']);
$icon['index'] = Html::getIcon('index.gif', $lang['L_TITLE_INDEX']);
$icon['key_primary'] = Html::getIcon(
'key_primary.gif', $lang['L_TITLE_KEY_PRIMARY']
);
$icon['key_fulltext'] = Html::getIcon(
'key_fulltext.gif', $lang['L_TITLE_KEY_FULLTEXT']
);
$icon['key_unique'] = Html::getIcon(
'key_unique.gif', $lang['L_TITLE_KEY_UNIQUE']
);
$icon['key_nokey'] = Html::getIcon('key_nokey.gif', $lang['L_TITLE_NOKEY']);
$icon['kill_process'] = Html::getIcon('delete.gif', $lang['L_KILL_PROCESS']);
$icon['minus'] = Html::getIcon('minus.gif');
$icon['mysql_help'] = Html::getIcon(
'mysql_help.gif', $lang['L_TITLE_MYSQL_HELP']
);
$icon['not_ok'] = Html::getIcon('notok.gif');
$icon['ok'] = Html::getIcon('ok.gif');
$icon['open_file'] = Html::getIcon('openfile.gif', $lang['L_LOAD_FILE']);
$icon['plus'] = Html::getIcon('plus.gif');
$icon['restore'] = Html::getIcon('key_nokey.gif');
$icon['save'] = Html::getIcon('save.png', $lang['L_SAVE']);
$icon['search'] = Html::getIcon('search.gif', $lang['L_TITLE_SEARCH']);
$icon['table_truncate'] = Html::getIcon(
'table_truncate.gif', $lang['L_EMPTY']
);
$icon['table_truncate_reset'] = Html::getIcon(
'table_truncate_reset.gif', $lang['L_EMPTYKEYS']
);
$icon['truncate'] = Html::getIcon('truncate.gif', $lang['L_EMPTY']);
$icon['upload'] = Html::getIcon('openfile.gif', $lang['L_TITLE_UPLOAD']);
$icon['view'] = Html::getIcon('search.gif', $lang['L_VIEW']);
//other pics
$icon['logo'] = $config['theme'] . 'pics/h1_logo.gif';
// build smaller icons for ConfigButtons
$icon['small'] = array();
$icon['small']['edit'] = Html::getIcon('edit.gif', $lang['L_EDIT']);
$icon['small']['open_file'] = Html::getIcon('openfile.gif', $lang['L_LOAD_FILE']);
$icon['small']['save'] = Html::getIcon('save.png', $lang['L_SAVE']);
$icon['small']['view'] = Html::getIcon('search.gif', $lang['L_VIEW']);

31
inc/dump.php Normale Datei
Datei anzeigen

@ -0,0 +1,31 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/functions/functions_dump.php');
include ('./inc/functions/functions_sql.php');
include ('./inc/define_icons.php');
if ($action == '') {
//first call -> clear arrays with values from last run
$_SESSION['dump'] = array();
$_SESSION['log'] = array();
$_SESSION['log']['actions'] = array();
$_SESSION['log']['errors'] = array();
$_SESSION['log']['files_created'] = array();
$dump['comment'] = '';
$action = 'prepare_dump';
}
if ($action == 'prepare_dump') include ('./inc/dump/dump_prepare.php');
if ($action == 'select_tables') include ('./inc/dump/select_tables.php');
if ($action == 'do_dump') include ('./inc/dump/do_dump.php');
if ($action == 'done') include ('./inc/dump/dump_finished.php');
$_SESSION['dump'] = $dump;

70
inc/dump/do_dump.php Normale Datei
Datei anzeigen

@ -0,0 +1,70 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
// first call of a new backup progress -> set start values
$dump = $_SESSION['dump'];
$dump['tables_total'] = 0;
$dump['records_total'] = 0;
$dump['tables_optimized'] = 0;
$dump['part'] = 1;
$dump['part_offset'] = 0;
$dump['errors'] = 0;
//-1 instead of 0 is needed for the execution of command before backup
$dump['table_offset'] = -1;
$dump['table_record_offset'] = 0;
$dump['filename_stamp'] = '';
$dump['speed'] = $config['minspeed'] > 0 ? $config['minspeed'] : 50;
$dump['max_zeit'] =
(int) $config['max_execution_time'] * $config['time_buffer'];
$dump['dump_start_time'] = time();
$dump['countdata'] = 0;
$dump['table_offset_total'] = 0;
$dump['page_refreshs'] = 0;
// used as overall flag including e-mail and ftp-actions
$dump['backup_in_progress'] = 1;
// used to determine id databases still need to be dumped
$dump['backup_done'] = 0;
$dump['selected_tables'] = FALSE;
if (isset($_POST['sel_tbl'])) {
$dump['selected_tables'] = $_POST['sel_tbl'];
}
// function was called in dump_prepare
// -- maybe get rid of this second call later on
prepareDumpProcess();
// last_db_actual is used to detect if db changed in multidump-mode
// -> set to first db
$dump['last_db_actual'] = $dump['db_actual'];
$_SESSION['config_file'] = $config['config_file'];
$_SESSION['dump'] = $dump;
$tplDoDump = new MSDTemplate();
$tplDoDump->set_filenames(array('tplDoDump' => 'tpl/dump/dump.tpl'));
$gzip = $config['compression'] == 1 ? $icon['gz'] : $lang['L_NOT_ACTIVATED'];
$tplDoDump->assign_vars(
array(
'ICONPATH' => $config['files']['iconpath'],
'GZIP' => $gzip,
'SESSION_ID' => session_id(),
'NOTIFICATION_POSITION' => $config['notification_position']
)
);
$sizeUnits = array(1, 1024, 1024 * 1024, 1024 * 10242 * 1024);
$size = $config['multipartgroesse1'] * $sizeUnits[$config['multipartgroesse2']];
if ($config['multi_part'] > 0) {
$tplDoDump->assign_block_vars(
'MULTIPART', array('SIZE' => byteOutput($size))
);
}
$tplDoDump->assign_var('TABLES_TO_DUMP', $dump['tables_total']);

88
inc/dump/dump_finished.php Normale Datei
Datei anzeigen

@ -0,0 +1,88 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/define_icons.php');
$dump = $_SESSION['dump'];
$tplDumpFinished = new MSDTemplate();
$tplDumpFinished->set_filenames(
array('tplDumpFinished' => 'tpl/dump/dump_finished.tpl')
);
$recordsTotal = String::formatNumber((int)$dump['records_total']);
$tablesTotal = $dump['tables_total'];
$msg = sprintf($lang['L_DUMP_ENDERGEBNIS'], $tablesTotal, $recordsTotal);
$tplDumpFinished->assign_vars(
array(
'ICON_OPEN_FILE' => $icon['small']['open_file'],
'ICON_EDIT' => $icon['small']['edit'],
'ICON_VIEW' => $icon['small']['view'],
'SESSION_ID' => session_id(),
'BACKUPPATH' => $config['paths']['backup'],
'PAGE_REFRESHS' => $dump['page_refreshs'],
'TIME_ELAPSED' => getTimeFormat(time() - $dump['dump_start_time']),
'MSG' => $msg
)
);
if (count($dump['databases']) > 1) {
$msg = sprintf($lang['L_MULTIDUMP_FINISHED'], count($dump['databases']));
$tplDumpFinished->assign_block_vars('MULTIDUMP', array('MSG' => $msg));
}
$i = 1;
foreach ($_SESSION['log']['files_created'] as $file) {
$fileSize = @filesize($config['paths']['backup'] . $file);
$tplDumpFinished->assign_block_vars(
'FILE',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'FILENAME' => $file,
'FILENAME_URLENCODED' => urlencode($file),
'FILESIZE' => byteOutput($fileSize)
)
);
$i++;
}
$i = 1;
foreach ($_SESSION['log']['actions'] as $message) {
$timestamp = substr($message, 0, 19);
$message = substr($message, 20);
$tplDumpFinished->assign_block_vars(
'ACTION',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'TIMESTAMP' => $timestamp,
'ACTION' => $message
)
);
$i++;
}
if (sizeof($_SESSION['log']['errors']) > 0) {
$tplDumpFinished->assign_block_vars('ERROR', array());
$i = 1;
foreach ($_SESSION['log']['errors'] as $error) {
$timestamp = substr($error, 0, 19);
$error = substr($error, 20);
$tplDumpFinished->assign_block_vars(
'ERROR.ERRORMSG',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'TIMESTAMP' => $timestamp,
'MSG' => $error
)
);
$i++;
}
}

158
inc/dump/dump_prepare.php Normale Datei
Datei anzeigen

@ -0,0 +1,158 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
// remove table selection from previous runs
if (isset($dump['sel_tbl'])) {
unset($dump['sel_tbl']);
}
if (isset($_SESSION['dump']['sel_tbl'])) {
unset($_SESSION['dump']['sel_tbl']);
}
//if we are not in mode expert -> reset hidden settings to safe defaults
if ($config['msd_mode'] == 0) {
$config['replace_command'] = 0;
}
$tplDumpPrepare = new MSDTemplate();
$tplDumpPrepare->set_filenames(
array('tplDumpPrepare' => 'tpl/dump/dump_prepare.tpl')
);
if ($config['msd_mode'] > 0) {
$tplDumpPrepare->assign_block_vars('MODE_EXPERT', array());
}
// set charset-selectbox to standard-encoding of MySQL-Server as initial value
$dump['sel_dump_encoding'] = 'utf8';
$dump['dump_encoding'] = 'utf8';
$charsets=$dbo->getCharsets();
foreach ($charsets as $name=>$val) {
$charsetsDescription[$name]=$name.' - '.$val['Description'];
}
// tables will be selected on next page, but we need a dummy val
// for prepareDumpProcess()
$dump['selected_tables'] = false;
$dbsToBackup = array();
// look up which databases need to be dumped
prepareDumpProcess();
$dbs = array_keys($dump['databases']);
$dbsToBackup = implode(', ', $dbs);
$cext = ($config['cron_extender'] == 0) ? 'pl' : 'cgi';
$scriptName = $_SERVER['SCRIPT_NAME'];
$serverName = $_SERVER['SERVER_NAME'];
$url = substr($scriptName, 0, strrpos($scriptName, '/') + 1);
if (substr($url, -1) != '/') $url .= '/';
if (substr($url, 0, 1) != '/') $url = '/' . $url;
$refdir = (substr($config['cron_execution_path'], 0, 1) == '/') ? '' : $url;
$scriptdir = $config['cron_execution_path'] . 'crondump.' . $cext;
$perlModultest = $config['cron_execution_path'] . "perltest.$cext";
$perlSimpletest = $config['cron_execution_path'] . "simpletest.$cext";
$scriptentry = myRealpath('./') . $config['paths']['config'];
$cronabsolute = myRealpath('./') . $scriptdir;
if (substr($config['cron_execution_path'], 0, 1) == '/') {
$cronabsolute = $_SERVER['DOCUMENT_ROOT'] . $scriptdir;
}
$confabsolute = $config['config_file'];
$perlHttpCall = getServerProtocol() . $serverName . $refdir;
$perlHttpCall .= $config['cron_execution_path'] . 'crondump.' . $cext;
$perlHttpCall .= '?config=' . $confabsolute;
$perlCrontabCall = 'perl ' . $cronabsolute . ' -config=' . $confabsolute;
$perlCrontabCall .= ' -html_output=0';
$tplDumpPrepare->assign_vars(
array(
'SESSION_ID' => session_id(),
'CONFIG_FILE' => $config['config_file'],
'POSSIBLE_DUMP_ENCODINGS' =>
Html::getOptionlist($charsetsDescription, 'utf8'),
'DBS_TO_BACKUP' => $dbsToBackup,
'TABLES_TOTAL' => $dump['tables_total'],
'RECORDS_TOTAL' => String::formatNumber(intval($dump['records_total'])),
'DATASIZE_TOTAL' => byteOutput($dump['datasize_total']),
'NR_OF_DBS' => count($dump['databases']),
'DUMP_COMMENT' => Html::replaceQuotes($dump['comment']),
'PERL_TEST' => $perlSimpletest,
'PERL_MODULTEST' => $perlModultest,
'PERL_HTTP_CALL' => $perlHttpCall,
'PERL_CRONTAB_CALL' => $perlCrontabCall,
'PERL_ABSOLUTE_PATH_OF_CONFIGDIR' => $scriptentry,
'TIMESTAMP' => time()
)
);
if (count($dump['databases']) == 1 && $config['db_actual'] == $dbsToBackup) {
$tplDumpPrepare->assign_block_vars('TABLESELECT', array());
}
if ($config['compression'] == 1) {
$tplDumpPrepare->assign_block_vars('GZIP_ACTIVATED', array());
} else {
$tplDumpPrepare->assign_block_vars('GZIP_NOT_ACTIVATED', array());
}
if ($config['multi_part'] == 1) {
$tplDumpPrepare->assign_block_vars(
'MULTIPART',
array('SIZE' => byteOutput($config['multipart_groesse']))
);
} else {
$tplDumpPrepare->assign_block_vars('NO_MULTIPART', array());
}
if ($config['send_mail'] == 1) {
$tplDumpPrepare->assign_block_vars(
'SEND_MAIL',
array('RECIPIENT' => $config['email']['recipient_address'])
);
$recipients = $config['email']['recipient_cc'];
$recipientsCc = implodeSubarray($recipients, 'address');
if ($recipientsCc > '') {
$tplDumpPrepare->assign_block_vars(
'SEND_MAIL.CC', array('EMAIL_ADRESS' => $recipientsCc)
);
}
if ($config['email']['attach_backup'] == 1) {
$bytes = $config['email_maxsize1'] * 1024;
if ($config['email_maxsize2'] == 2) {
$bytes = $bytes * 1024;
}
$tplDumpPrepare->assign_block_vars(
'SEND_MAIL.ATTACH_BACKUP', array('SIZE' => byteOutput($bytes))
);
} else {
$tplDumpPrepare->assign_block_vars(
'SEND_MAIL.DONT_ATTACH_BACKUP', array()
);
}
} else {
$tplDumpPrepare->assign_block_vars('NO_SEND_MAIL', array());
}
$i = 1;
foreach ($config['ftp'] as $ftp) {
if ($ftp['transfer'] == 1) {
$tplDumpPrepare->assign_block_vars(
'FTP',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow1' : 'dbrow'
)
);
$tplDumpPrepare->assign_block_vars(
'FTP.CONNECTION',
array(
'SERVER' => $ftp['server'],
'PORT' => $ftp['port'],
'DIR' => $ftp['dir']
)
);
$i++;
}
}

76
inc/dump/select_tables.php Normale Datei
Datei anzeigen

@ -0,0 +1,76 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) {
die('No direct access.');
}
// action is called, even if the checkbox "select tables" was not checked
// save selected values from the last site
$dump['comment'] = $_POST['comment'];
$dump['sel_dump_encoding'] = $_POST['sel_dump_encoding'];
$dump['dump_encoding'] = $dump['sel_dump_encoding'];
// we need to save this before the Ajax-Requests starts, so we are doing it here
// although it is done in dump.php
$_SESSION['dump'] = $dump;
// checks after first dump-prepare if we need to head over to table selection
// or if we can start the backup process
if (!isset($_POST['tableselect'])) {
// nothing to select - start dump action
$action = 'do_dump';
} else {
// yes, we need to show the table-selection, but first save commetn and
// encoding that was set before
$tplDumpSelectTables = new MSDTemplate();
$tplDumpSelectTables->set_filenames(
array('tplDumpSelectTables' => 'tpl/dump/selectTables.tpl')
);
$dbo->selectDb($dump['db_actual']);
$tables=$dbo->getTableStatus();
$i=0;
foreach ($tables as $tableName => $row) {
$klasse = ($i % 2) ? 1 : '';
$tableSize = byteOutput($row['Data_length'] + $row['Index_length']);
$tableType = $row['Engine'];
$nrOfRecords = String::formatNumber($row['Rows']);
if (substr($row['Comment'], 0, 4) == 'VIEW' && $row['Engine'] == '') {
$tableType = 'View';
$tableSize = '-';
$nrOfRecords = '-';
}
$tplDumpSelectTables->assign_block_vars(
'ROW',
array(
'CLASS' => 'dbrow' . $klasse,
'ID' => $i,
'NR' => $i + 1,
'TABLENAME' => $tableName,
'TABLETYPE' => $tableType,
'RECORDS' => $nrOfRecords,
'SIZE' => $tableSize,
'LAST_UPDATE' => $row['Update_time']
)
);
$i++;
}
$tplDumpSelectTables->assign_vars(
array(
'PAGETITLE' => $lang['L_TABLESELECTION'],
'SESSION_ID' => session_id(),
'DATABASE' => $config['db_actual'],
'ICON_OK' => $icon['ok'],
'ICON_DELETE' => $icon['delete'],
'ICON_DB' => $icon['db'],
'L_NO_MSD_BACKUP' => $lang['L_NOT_SUPPORTED']
)
);
}

Datei anzeigen

@ -0,0 +1,77 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
@ini_set('max_execution_time', 0);
// first output menu to show it while converting.
// Otherwise it would only be shwon after the conversion is finished
include ('./inc/menu.php');
$tplGlobalHeader->pparse('tplGlobalHeader');
$tplMenu->pparse('tplMenu');
// Konverter
$selectfile = (isset($_POST['selectfile'])) ? $_POST['selectfile'] : '';
$destfile = (isset($_POST['destfile'])) ? $_POST['destfile'] : '';
$compressed = (isset($_POST['compressed'])) ? $_POST['compressed'] : '';
include ('./inc/define_icons.php');
$doConversion = false;
if ($selectfile != '' & file_exists($config['paths']['backup'] . $selectfile)
&& strlen($destfile) > 2) {
$doConversion = true;
}
$tpl = new MSDTemplate();
$tpl->set_filenames(array('show' => 'tpl/filemanagement/converter.tpl'));
$tpl->assign_vars(
array(
'SELECTBOX_FILE_LIST' => getFilelisteCombo($selectfile),
'NEW_FILE' => Html::replaceQuotes($destfile),
'NEW_FILE_COMPRESED' => $compressed == 1 ? ' checked="checked"' : '',
'ICON_GZ' => $icon['gz']
)
);
if ($doConversion) {
$tpl->assign_block_vars('AUTOSCROLL', array());
}
$tpl->pparse('show');
flush();
if (isset($_POST['startconvert'])) {
echo $lang['L_CONVERTING'] . ' ' . $selectfile
. ' ==&gt; ' . $destfile . '.sql';
if ($compressed == 1) {
echo '.gz';
}
if ($doConversion) {
convert($selectfile, $destfile, $compressed);
} else {
echo '<br /><p class="error">' . $lang['L_CONVERT_WRONG_PARAMETERS']
. '</p>';
}
}
if ($doConversion) {
?>
<script type="text/javascript">
/*<![CDATA[*/
setTimeout('clearTimeout(scrolldelay)',2000);
/*]]>*/
</script>
<?php
}
?>
</div>
</body>
</html>
<?php
die(); // menu is shown - nothing more to do;

Datei anzeigen

@ -0,0 +1,68 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$del = array();
if (isset($_POST['delete'])) {
if (isset($_POST['file'])) {
$delfiles = Array();
for ($i = 0; $i < count($_POST['file']); $i++) {
if (!strpos($_POST['file'][$i], '_part_') === false) {
$pos = strpos($_POST['file'][$i], '_part_');
$delfiles[] = substr($_POST['file'][$i], 0, $pos + 6);
} else {
$delfiles[] = $_POST['file'][$i];
}
}
for ($i = 0; $i < count($delfiles); $i++) {
$del = array_merge(
$del,
deleteMultipartFiles($config['paths']['backup'], $delfiles[$i])
);
}
} else {
$msg .= Html::getErrorMsg($lang['L_FM_NOFILE']);
}
}
if (isset($_POST['deleteauto'])) {
$deleteResult = doAutoDelete();
if ($deleteResult > '') {
$msg .= $deleteResult;
}
}
if (isset($_POST['deleteall']) || isset($_POST['deleteallfilter'])) {
if (isset($_POST['deleteall'])) {
$del = deleteMultipartFiles($config['paths']['backup'], '', '.sql');
$del = array_merge(
$del, deleteMultipartFiles($config['paths']['backup'], '', '.gz')
);
} else {
$del = deleteMultipartFiles($config['paths']['backup'], $dbactive);
}
}
// print file-delete-messages
if (is_array($del) && sizeof($del) > 0) {
foreach ($del as $file => $success) {
if ($success) {
$msg .= $lang['L_FM_DELETE1'] . ' \'' . $file . '\' ';
$msg .= $lang['L_FM_DELETE2'];
$msg = Html::getOkMsg($msg);
$log->write(Log::PHP, "Deleted '$file'.");
} else {
$msg .= $lang['L_FM_DELETE1'] . ' \'' . $file . '\' ';
$msg .= $lang['L_FM_DELETE3'];
$msg = Html::getErrorMsg($msg);
$log->write(Log::PHP, "Deleted '$file'.");
}
}
}

Datei anzeigen

@ -0,0 +1,41 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
// Download of a backup file wanted
$file = urldecode($_GET['f']);
// check for injected chars by removing allowed chars and check if the rest
// only contains alphanumerical chars
$search = array('-','.', '_');
$replace = array('', '', '');
$check = str_replace($search, $replace, $file);
if (ctype_alnum($check) && is_readable($config['paths']['backup'] . $file)) {
$file = './' . $config['paths']['backup'] . $file;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . (string) filesize($file));
flush();
$file = fopen($file, "rb");
while (!feof($file)) {
print fread($file, round(100 * 1024));
flush();
}
fclose($file);
} else {
die('Error: Couldn\'t open file: ' . $file);
}
die();

Datei anzeigen

@ -0,0 +1,49 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) {
die('No direct access.');
}
if (!isset($_FILES['upfile']['name'])
|| trim($_FILES['upfile']['name']) == '') {
$msg .= Html::getErrorMsg(
$lang['L_FM_UPLOADFILEREQUEST'] . '<br />' . $lang['L_FM_UPLOADFAILED']
);
} else {
if (!file_exists($config['paths']['backup'] . $_FILES['upfile']['name'])) {
$extension = strrchr($_FILES['upfile']['name'], '.');
$allowedExtensions = array('.gz', '.sql', 'txt');
if (!in_array($extension, $allowedExtensions)) {
$msg .= Html::getErrorMsg(
$lang['L_FM_UPLOADNOTALLOWED1'] . '<br />'
. $lang['L_FM_UPLOADNOTALLOWED2']
);
$msg .= Html::getErrorMsg($lang['L_FM_UPLOADFAILED']);
} else {
$upfile = $config['paths']['backup'] . $_FILES['upfile']['name'];
if (@move_uploaded_file($_FILES['upfile']['tmp_name'], $upfile)) {
@chmod($upfile, 0777);
$msg = Html::getOkMsg(
sprintf(
$lang['L_FILE_UPLOAD_SUCCESSFULL'],
$_FILES['upfile']['name']
)
);
} else {
$msg .= Html::getErrorMsg($lang['L_FM_UPLOADMOVEERROR']);
$msg .= Html::getErrorMsg($lang['L_FM_UPLOADFAILED']);
}
}
} else {
$msg .= Html::getErrorMsg($lang['L_FM_UPLOADFILEEXISTS']);
$msg .= Html::getErrorMsg($lang['L_FM_UPLOADFAILED']);
}
}

237
inc/filemanagement/files.php Normale Datei
Datei anzeigen

@ -0,0 +1,237 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/define_icons.php');
$expand = (isset($_GET['expand'])) ? $_GET['expand'] : -1;
// execute delete action if clicked
if (isset($_POST['delete']) || isset($_POST['deleteauto'])
|| isset($_POST['deleteall']) || isset($_POST['deleteallfilter'])) {
include ('./inc/filemanagement/file_delete.php');
}
$tplFiles = new MSDTemplate();
$tplFiles->set_filenames(array('tplFiles' => 'tpl/filemanagement/files.tpl'));
$dbactualOutput = $dbactive;
// replace internal keys for backups of other programs and converted files
// with human readable output
if ($dbactive == '~unknown') {
$dbactualOutput = '<i>' . $lang['L_UNKNOWN'] . '</i>';
}
if ($dbactive == '~converted') {
$dbactualOutput = '<i>' . $lang['L_CONVERTED_FILES'] . '</i>';
}
$autoDelete = $lang['L_NOT_ACTIVATED'];
if ($config['auto_delete']['activated'] > 0) {
$autoDelete = $lang['L_ACTIVATED'] . ' ('
. $config['auto_delete']['max_backup_files'] . ' '
. $lang['L_MAX_BACKUP_FILES_EACH2'] . ')';
}
$tplFiles->assign_vars(
array(
'BACKUP_PATH' => $config['paths']['backup'],
'ICON_DOWNLOAD' => $icon['open_file'],
'ICON_VIEW' => $icon['view'],
'ICON_DELETE' => $icon['delete'],
'DB_ACTUAL' => $dbactive,
'DB_ACTUAL_OUTPUT' => $dbactualOutput,
'UPLOAD_MAX_SIZE' => $config['upload_max_filesize'],
'AUTODELETE_ENABLED' => $autoDelete,
'NOTIFICATION_POSITION' => $config['notification_position']
)
);
if ($msg > '') {
$tplFiles->assign_block_vars(
'MESSAGE', array('TEXT' => Html::getJsQuote($msg, true))
);
}
$backups = getBackupfileInfo();
$i = 0;
if (!isset($backups['databases'][$dbactive])) {
$tplFiles->assign_block_vars('NO_FILE_FOUND', array());
}
if ($dbactive != '~unknown' && $dbactive != '~converted') {
$tplFiles->assign_block_vars('DELETE_FILTER', array());
}
// show detailed file info of the selected database at top
foreach ($backups['files'] as $backup) {
if ($backup['db'] == $dbactive) {
// get MySQL Version from which the backup was taken
$mysqlVersion = '';
if (isset($backup['mysqlversion'])) {
$mysqlVersion = $backup['mysqlversion'];
}
// get grouping name of database
$dbName = $backup['name'];
if (!in_array($backup['db'], array('~unknown', '~converted'))) {
$dbName = $backup['db'];
}
// with which MSD-Version was the backup made?
$scriptVersion = $lang['L_UNKNOWN'];
if ($backup['script'] > '') {
$scriptVersion = $backup['script'];
}
// show Gzip-Icon?
$compressed = substr($backup['name'], -3) == '.gz' ? $icon['gz'] : '-';
// is a commetn given?
$comment = '';
if ($backup['comment'] > '') {
$comment = nl2br(wordwrap($backup['comment'], 50));
}
// number of tables
$nrOfTables = $lang['L_UNKNOWN'];
if ($backup['tables'] > -1) {
$nrOfTables = String::formatNumber($backup['tables']);
}
// number of records
$nrOfRecords = $lang['L_UNKNOWN'];
if ($backup['records'] > -1) {
$nrOfRecords = String::formatNumber($backup['records']);
}
// charset of bakup file
$charset = $lang['L_UNKNOWN'];
if ($backup['charset'] != '?') {
$charset = $backup['charset'];
}
$tplFiles->assign_block_vars(
'FILE',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'FILE_INDEX' => $i,
// expand or unexpand multipart list on next click
'FILE_EXPAND_INDEX' => $expand == $i ? -1 : $i,
'FILE_NAME' => $backup['name'],
'FILE_NAME_URLENCODED' => urlencode($backup['name']),
'DB_NAME' => $dbName,
'ICON_COMPRESSED' => $compressed,
'SCRIPT_VERSION' => $scriptVersion,
'COMMENT' => $comment,
'FILE_CREATION_DATE' => $backup['date'],
'NR_OF_TABLES' => $nrOfTables,
'NR_OF_RECORDS' => $nrOfRecords,
'FILESIZE' => byteOutput($backup['size']),
'FILE_CHARSET' => $charset,
'NR_OF_MULTIPARTS' => $backup['multipart'],
'MYSQL_VERSION' => $mysqlVersion
)
);
if ($backup['multipart'] > 0) {
$mpFileHeadline = $lang['L_FILES'];
if ($backup['multipart'] == 1) {
$mpFileHeadline = $lang['L_FILE'];
}
$tplFiles->assign_block_vars(
'FILE.IS_MULTIPART', array('FILES' => $mpFileHeadline)
);
} else {
$tplFiles->assign_block_vars('FILE.NO_MULTIPART', array());
}
if ($backup['multipart'] > 0) {
// show all files of a Multipart-backup
$tplFiles->assign_block_vars(
'FILE.EXPAND_MULTIPART',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow1' : 'dbrow'
)
);
// expand multipartlist if click came from restore screen
if ($expand == $i) {
$tplFiles->assign_block_vars(
'EXPAND_MP_FILE', array('FILEINDEX' => $i)
);
}
$partPosition = strrpos($backup['name'], 'part_');
$fileBase = substr($backup['name'], 0, $partPosition) . 'part_';
$fileExtension = '.sql';
if (substr($backup['name'], -2) == 'gz') {
$fileExtension = '.sql.gz';
}
for ($x = 0; $x < $backup['multipart']; $x++) {
$fileName = $fileBase . ($x + 1) . $fileExtension;
$fileSize = $lang['L_UNKNOWN'];
$file = $config['paths']['backup'] . $fileName;
if (!is_readable($file)) {
$fileName = $backup['name'];
$fileSize = byteOutput(@filesize($file));
}
$tplFiles->assign_block_vars(
'FILE.EXPAND_MULTIPART.MP_FILE',
array(
'ROWCLASS' => $x % 2 ? 'dbrow' : 'dbrow1',
'NR' => $x + 1,
'FILE_NAME' => $fileName,
'FILE_NAME_URLENCODED' => urlencode($fileName),
'FILE_SIZE' => $fileSize
)
);
}
}
$i++;
}
}
//sort databases according to the databasenames ascending
ksort($backups['databases']);
// list summary of other backup files grouped by databases
if (count($backups['databases']) > 0) {
$i = 0;
foreach ($backups['databases'] as $db => $info) {
$rowclass = $i % 2 ? 'dbrow' : 'dbrow1';
if ($db == $dbactive) {
$rowclass = 'dbrowsel';
}
$dbNameOutput = $db;
if ($db == '~unknown') {
$dbNameOutput = '<i>' . $lang['L_NO_MSD_BACKUPFILE'] . '</i>';
}
if ($db == '~converted') {
$dbNameOutput = '<i>' . $lang['L_CONVERTED_FILES'] . '</i>';
}
$nrOfBackups = isset($info['backup_count']) ? $info['backup_count'] : 0;
$latestBackup = '-';
if (isset($info['latest_backup_timestamp'])) {
$latestBackup = $info['latest_backup_timestamp'];
}
$fileSizeTotal = 0;
if (isset($info['backup_size_total'])) {
$fileSizeTotal = byteOutput($info['backup_size_total']);
}
$tplFiles->assign_block_vars(
'DB',
array(
'ROWCLASS' => $rowclass,
'DB_NAME_LINK' => $db,
'DB_NAME' => $dbNameOutput,
'NR_OF_BACKUPS' => $nrOfBackups,
'LATEST_BACKUP' => $latestBackup,
'SUM_SIZE' => $fileSizeTotal
)
);
$i++;
}
}
$tplFiles->assign_vars(
array(
'SUM_SIZE' => byteOutput($backups['filesize_total']),
'FREESPACE_ON_SERVER' => getFreeDiskSpace()
)
);

37
inc/files.php Normale Datei
Datei anzeigen

@ -0,0 +1,37 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
include ('./inc/functions/functions_files.php');
if (isset($_GET['action']) && $_GET['action'] == 'dl') {
$download = true;
include ('./inc/filemanagement/file_download.php');
}
include ('./inc/functions/functions_sql.php');
$msg = '';
$dump = array();
$toolboxstring = '';
$dbactive = (isset($_GET['dbactive'])) ? $_GET['dbactive'] : $config['db_actual'];
if (isset($_POST['dbactive'])) {
$dbactive = $_POST['dbactive'];
}
if ($action == 'restore' || isset($_POST['restore_tbl'])
|| isset($_POST['restore'])) {
include ('./inc/restore/restore_prepare.php');
}
if (isset($_POST['upload'])) {
include ('./inc/filemanagement/file_upload.php');
}
if ($action == 'files' || $action == '') {
include ('./inc/filemanagement/files.php');
}
if ($action == 'convert') {
include ('./inc/filemanagement/converter.php');
}

715
inc/functions/functions.php Normale Datei
Datei anzeigen

@ -0,0 +1,715 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
/**
* Output human readable Byte-Values
*
* @param integer $bytes Bytes to convert to human readable format
* @param boolean $useHTML Decides whether explaining span-tags should surround
* the returned string
*
* @return string human readable output
*/
function byteOutput($bytes, $useHTML = true)
{
$precision = 2;
if (!is_numeric($bytes) || $bytes < 0) {
return false;
}
for ($level = 0; $bytes >= 1024; $level++) {
$bytes /= 1024;
}
switch ($level)
{
case 0:
$suffix = '<span class="explain" title="Bytes">B</span>';
break;
case 1:
$suffix = '<span class="explain" title="KiloBytes">KB</span>';
break;
case 2:
$suffix = '<span class="explain" title="MegaBytes">MB</span>';
break;
case 3:
$suffix = '<span class="explain" title="GigaBytes">GB</span>';
break;
case 4:
$suffix = '<span class="explain" title="TeraBytes">TB</span>';
break;
case 5:
$suffix = '<span class="explain" title="PetaBytes">PB</span>';
break;
case 6:
$suffix = '<span class="explain" title="ExaBytes">EB</span>';
break;
case 7:
$suffix = '<span class="explain" title="YottaBytes">ZB</span>';
break;
default:
$suffix = '';
break;
}
if (!$useHTML) {
$suffix = strip_tags($suffix);
}
$ret = sprintf("%01." . $precision . "f", round($bytes, $precision));
return $ret . ' ' . $suffix;
}
/**
* Delete Multipart files
*
* @param string $dir Directory to check
* @param string $prefix Only check files with this prefix
* @param string $suffix Only check files with this suffix
*
* @return array Array $file['filename']=true | false
*/
function deleteMultipartFiles($dir, $prefix = '', $suffix = '')
{
$deleted = array();
if (substr($dir, -1) != '/') {
$dir .= '/';
}
if (is_dir($dir)) {
$d = opendir($dir);
while ($file = readdir($d)) {
if (is_file($dir . $file)) {
$del = false;
if ($prefix > '' && substr($file, 0, strlen($prefix)) == $prefix) $del = true;
if ($suffix > '' && substr($file, strlen($file) - strlen($suffix), strlen($suffix)) == $suffix) $del = true;
if ($del)
{
if (unlink($dir . $file)) $deleted[$file] = true;
else $deleted[$file] = false;
}
}
}
closedir($d);
return $deleted;
}
}
/**
* Add a database to the global $databases-Array and set necessary indexes
*
* @param string $db_name Databaase-Name
* @param string $praefix Table-Prefix
* @param string $cbd Command before Dump
* @param string $cad Command after Dump
*
* @return void
*/
function addDatabaseToConfig($db_name)
{
global $databases;
if (!isset($databases)) $databases = array();
if (!isset($databases[$db_name])) $databases[$db_name] = array();
if (!isset($databases[$db_name]['dump'])) $databases[$db_name]['dump'] = 0;
if (!isset($databases[$db_name]['prefix'])) $databases[$db_name]['prefix'] = '';
if (!isset($databases[$db_name]['command_before_dump'])) $databases[$db_name]['command_before_dump'] = '';
if (!isset($databases[$db_name]['command_after_dump'])) $databases[$db_name]['command_after_dump'] = '';
}
/**
* Check settings of language, config file, reloads list of databases and save result to configuration
*
* @return string String with checked and added databases
*/
function setDefaultConfig()
{
global $config, $databases, $out, $lang, $dbo;
// check language and fallback to englisch if language file is not readable
$lang_file = './language/' . $config['language'] . '/lang.php';
if (!file_exists($lang_file) || !is_readable($lang_file))
{
$config['language'] = 'en';
}
include ('./language/' . $config['language'] . '/lang.php');
getConfig($config['config_file']); // falls back to config mysqldumper if something is wrong
// get list of databases for this user
$dbUser = $dbo->getDatabases();
foreach ($dbUser as $db)
{
// new found db? -> add it
if (!isset($databases[$db])) $databases[$db] = array();
}
ksort($databases);
foreach ($databases as $db_name => $val)
{
if ($dbo->selectDb($db_name, true))
{
addDatabaseToConfig($db_name);
$out .= $lang['L_SAVING_DB_FORM'] . " " . $db_name . " " . $lang['L_ADDED'] . "\n";
}
else
unset($databases[$db_name]);
}
saveConfig();
return $out;
}
/**
* Save actual configuration to file
*
* @return boolean
*/
function saveConfig()
{
global $config, $databases, $configDontsave;
$config['multipart_groesse'] = $config['multipartgroesse1'] * (($config['multipartgroesse2'] == 1) ? 1024 : 1024 * 1024);
if (!isset($config['email_maxsize'])) $config['email_maxsize'] = $config['email_maxsize1'] * (($config['email_maxsize2'] == 1) ? 1024 : 1024 * 1024);
if (!isset($config['cron_execution_path'])) $config['cron_execution_path'] = "msd_cron/";
$config2 = $config;
foreach ($config2 as $var => $val)
{
if (in_array($var, $configDontsave)) unset($config2[$var]);
}
$t = '$config=array_merge($config,unserialize(base64_decode(\'' . base64_encode(serialize($config2)) . "')));\r\n";
if (isset($databases)) $t .= '$databases=array_merge($databases,unserialize(base64_decode(\'' . base64_encode(serialize($databases)) . "')));\r\n";
$pars_all = '<?php' . "\n" . $t . "\n?>";
$ret = true;
$file = './' . $config['paths']['config'] . $config['config_file'] . '.php';
if ($fp = @fopen($file, "wb"))
{
if (!fwrite($fp, $pars_all)) $ret = false;
if (!fclose($fp)) $ret = false;
@chmod($file, 0777);
}
else
$ret = false;
if ($ret)
{
$_SESSION['config'] = $config;
$ret = writeCronScript();
}
return $ret;
}
/**
* Build string of array according to Perl syntax (needed to save Perl configuration file)
*
* @param array $arr Array to build the string from
* @param string $mode 0 for strings, 1 for int values
*
* @return string The converted Perl string
*/
function myImplode($arr, $mode = 0) // 0=String, 1=intval
{
if (!is_array($arr)) return false;
foreach ($arr as $key => $val)
{
if ($mode == 0) $arr[$key] = Html::escapeSpecialchars($val);
else $arr[$key] = intval($val);
}
if ($mode == 0) $ret = '("' . implode('","', $arr) . '")';
else $ret = '(' . implode(',', $arr) . ')';
return $ret;
}
/**
* Build and save the actual configuration file for Perl (used by crondump.pl)
*
* @return boolean true on success or false on failure
*/
function writeCronScript()
{
global $config, $databases, $cron_db_array, $cron_dbpraefix_array, $cron_db_cbd_array, $cron_db_cad_array;
if (!isset($config['email_maxsize'])) $config['email_maxsize'] = $config['email_maxsize1'] * (($config['email_maxsize2'] == 1) ? 1024 : 1024 * 1024);
if (isset($config['db_actual'])) $cron_dbname = $config['db_actual'];
else
{
//get first database name from database-array (this is the case at fresh installing)
$dbs = array_keys($databases);
$cron_dbname = $dbs[0];
}
// -2 = Multidump configuration
// -3 = all databases - nothing to do
// get standard values for all databases
$cron_db_array = ''; //$databases['Name'];
$cron_dbpraefix_array = ''; //$databases['praefix'];
$cron_command_before_dump = ''; //$databases['command_before_dump'];
$cron_command_after_dump = ''; //$databases['command_after_dump'];
$cron_ftp_server = '';
$cron_ftp_port = '';
$cron_ftp_mode = '';
$cron_ftp_user = '';
$cron_ftp_pass = '';
$cron_ftp_dir = '';
$cron_ftp_timeout = '';
$cron_ftp_ssl = '';
$cron_ftp_transfer = '';
//build db-arrays
foreach ($databases as $k => $v)
{
//should we dump this database
if (isset($databases[$k]['dump']) && $databases[$k]['dump'] === 1)
{
$cron_db_array[] .= $k;
$cron_dbpraefix_array[] .= $databases[$k]['prefix'];
$cron_command_before_dump[] .= $databases[$k]['command_before_dump'];
$cron_command_after_dump[] .= $databases[$k]['command_after_dump'];
}
}
//build ftp-arrays
foreach ($config['ftp'] as $k => $v)
{
$cron_ftp_server[] .= $config['ftp'][$k]['server'];
$cron_ftp_port[] .= $config['ftp'][$k]['port'];
$cron_ftp_mode[] .= $config['ftp'][$k]['mode'];
$cron_ftp_user[] .= $config['ftp'][$k]['user'];
$cron_ftp_pass[] .= $config['ftp'][$k]['pass'];
$cron_ftp_dir[] .= $config['ftp'][$k]['dir'];
$cron_ftp_timeout[] .= $config['ftp'][$k]['timeout'];
$cron_ftp_ssl[] .= $config['ftp'][$k]['ssl'];
$cron_ftp_transfer[] .= $config['ftp'][$k]['transfer'];
}
$r = str_replace("\\\\", "/", $config['paths']['root']);
$r = str_replace("@", "\@", $r);
//built recipient_cc-arrays
$recipients_cc = '';
foreach ($config['email']['recipient_cc'] as $k => $v)
{
$recipients_cc .= '"' . $config['email']['recipient_cc'][$k]['name'] . '" <' . $config['email']['recipient_cc'][$k]['address'] . '>, ';
}
$recipients_cc = substr($recipients_cc, 0, -2);
// auf manchen Server wird statt 0 ein leerer String gespeichert -> fuehrt zu einem Syntax-Fehler
// hier die entsprechenden Ja/Nein-Variablen sicherheitshalber in intvalues aendern
$int_array = array(
'dbport',
'cron_compression',
'cron_printout',
'multi_part',
'multipart_groesse',
'email_maxsize',
//'auto_delete][activated',
//'auto_delete][max_backup_files',
'perlspeed',
'optimize_tables_beforedump',
'logcompression',
'log_maxsize',
'cron_completelog',
'use_sendmail',
'smtp_port',
'smtp_useauth',
'smtp_usessl');
foreach ($int_array as $i)
{
if (is_array($i))
{
foreach ($i as $key => $val)
{
$int_array[$key] = intval($val);
}
}
else
{
if (!isset($config[$i])) $config[$i] = 0;
$config[$i] = intval($config[$i]);
}
}
if ($config['dbport'] == 0) $config['dbport'] = 3306;
$cronscript = "<?php\n#Vars - written at " . date("Y-m-d H:i") . "\n";
$cronscript .= '$dbhost="' . $config['dbhost'] . '";' . "\n";
$cronscript .= '$dbname="' . $cron_dbname . '";' . "\n";
$cronscript .= '$dbuser="' . Html::escapeSpecialchars($config['dbuser']) . '";' . "\n";
$cronscript .= '$dbpass="' . Html::escapeSpecialchars($config['dbpass']) . '";' . "\n";
$cronscript .= '$dbport=' . $config['dbport'] . ';' . "\n";
$cronscript .= '$dbsocket="' . Html::escapeSpecialchars($config['dbsocket']) . '";' . "\n";
$cronscript .= '$compression=' . $config['cron_compression'] . ';' . "\n";
$cronscript .= '$sendmail_call="' . Html::escapeSpecialchars($config['sendmail_call']) . '";' . "\n";
$cronscript .= '$backup_path="' . $config['paths']['root'] . $config['paths']['backup'] . '";' . "\n";
$cronscript .= '$cron_printout=' . $config['cron_printout'] . ';' . "\n";
$cronscript .= '$cronmail=' . $config['send_mail'] . ';' . "\n";
$cronscript .= '$cronmail_dump=' . $config['email']['attach_backup'] . ';' . "\n";
$cronscript .= '$cronmailto="' . Html::escapeSpecialchars('"' . $config['email']['recipient_name'] . '" <' . $config['email']['recipient_address'] . '>') . '";' . "\n";
$cronscript .= '$cronmailto_cc="' . Html::escapeSpecialchars($recipients_cc) . '";' . "\n";
$cronscript .= '$cronmailfrom="' . Html::escapeSpecialchars('"' . $config['email']['sender_name'] . '" <' . $config['email']['sender_address'] . '>') . '";' . "\n";
$cronscript .= '$cron_use_sendmail=' . $config['use_sendmail'] . ';' . "\n";
$cronscript .= '$cron_smtp="' . Html::escapeSpecialchars($config['smtp_server']) . '";' . "\n";
$cronscript .= '$smtp_port=' . $config['smtp_port'] . ';' . "\n";
$cronscript .= '$smtp_useauth=' . $config['smtp_useauth'] . ';' . "\n";
$cronscript .= '$smtp_usessl=' . $config['smtp_usessl'] . ';' . "\n";
$cronscript .= '$smtp_user="' . $config['smtp_user'] . '";' . "\n";
$cronscript .= '$smtp_pass="' . $config['smtp_pass'] . '";' . "\n";
$cronscript .= '@cron_db_array=' . myImplode($cron_db_array) . ';' . "\n";
$cronscript .= '@cron_dbpraefix_array=' . myImplode($cron_dbpraefix_array) . ';' . "\n";
$cronscript .= '@cron_command_before_dump=' . myImplode($cron_command_before_dump) . ';' . "\n";
$cronscript .= '@cron_command_after_dump=' . myImplode($cron_command_after_dump) . ';' . "\n";
$cronscript .= '@ftp_server=' . myImplode($cron_ftp_server) . ';' . "\n";
$cronscript .= '@ftp_port=' . myImplode($cron_ftp_port, 1) . ';' . "\n";
$cronscript .= '@ftp_mode=' . myImplode($cron_ftp_mode, 1) . ';' . "\n";
$cronscript .= '@ftp_user=' . myImplode($cron_ftp_user) . ';' . "\n";
$cronscript .= '@ftp_pass=' . myImplode($cron_ftp_pass) . ';' . "\n";
$cronscript .= '@ftp_dir=' . myImplode($cron_ftp_dir) . ';' . "\n";
$cronscript .= '@ftp_timeout=' . myImplode($cron_ftp_timeout, 1) . ';' . "\n";
$cronscript .= '@ftp_useSSL=' . myImplode($cron_ftp_ssl, 1) . ';' . "\n";
$cronscript .= '@ftp_transfer=' . myImplode($cron_ftp_transfer, 1) . ';' . "\n";
$cronscript .= '$mp=' . $config['multi_part'] . ';' . "\n";
$cronscript .= '$multipart_groesse=' . $config['multipart_groesse'] . ';' . "\n";
$cronscript .= '$email_maxsize=' . $config['email_maxsize'] . ';' . "\n";
$cronscript .= '$auto_delete=' . $config['auto_delete']['activated'] . ';' . "\n";
$cronscript .= '$max_backup_files=' . $config['auto_delete']['max_backup_files'] . ';' . "\n";
$cronscript .= '$perlspeed=' . $config['perlspeed'] . ';' . "\n";
$cronscript .= '$optimize_tables_beforedump=' . $config['optimize_tables_beforedump'] . ';' . "\n";
$cronscript .= '$logcompression=' . $config['logcompression'] . ';' . "\n";
//add .gz to logfiles?
if ($config['logcompression'] === 1)
{
$cronscript .= '$logdatei="' . $config['paths']['root'] . $config['files']['perllog'] . '.gz";' . "\n";
$cronscript .= '$completelogdatei="' . $config['paths']['root'] . $config['files']['perllogcomplete'] . '.gz";' . "\n";
}
else
{
$cronscript .= '$logdatei="' . $config['paths']['root'] . $config['files']['perllog'] . '";' . "\n";
$cronscript .= '$completelogdatei="' . $config['paths']['root'] . $config['files']['perllogcomplete'] . '";' . "\n";
}
$cronscript .= '$log_maxsize=' . $config['log_maxsize'] . ';' . "\n";
$cronscript .= '$complete_log=' . $config['cron_completelog'] . ';' . "\n";
$cronscript .= '$cron_comment="' . Html::escapeSpecialchars(stripslashes($config['cron_comment'])) . '";' . "\n";
$cronscript .= "?>";
// Save config
$ret = true;
$sfile = './' . $config['paths']['config'] . $config['config_file'] . '.conf.php';
if (file_exists($sfile)) @unlink($sfile);
if ($fp = @fopen($sfile, "wb"))
{
if (!fwrite($fp, $cronscript)) $ret = false;
if (!fclose($fp)) $ret = false;
@chmod("$sfile", 0777);
}
else
$ret = false;
// if standard config was deleted -> restore it with the actual values
if (!file_exists('./' . $config['paths']['config'] . "mysqldumper.conf.php"))
{
$sfile = './' . $config['paths']['config'] . 'mysqldumper.conf.php';
if ($fp = fopen($sfile, "wb"))
{
if (!fwrite($fp, $cronscript)) $ret = false;
if (!fclose($fp)) $ret = false;
@chmod("$sfile", 0777);
}
else
$ret = false;
}
return $ret;
}
/**
* Collect log file information and return it as assoziative array
*
* @param boolean $logcompression Watch for compressed (true) or uncompressed files
*
* @return array Associative array with information
*/
function getLogFileInfo($logcompression)
{
global $config;
$l = Array();
$sum = $s = $l['log_size'] = $l['perllog_size'] = $l['perllogcomplete_size'] = $l['errorlog_size'] = $l['log_totalsize'] = 0;
if ($logcompression == 1)
{
$l['log'] = $config['files']['log'] . ".gz";
$l['perllog'] = $config['files']['perllog'] . ".gz";
$l['perllogcomplete'] = $config['files']['perllogcomplete'] . ".gz";
$l['errorlog'] = $config['paths']['log'] . "error.log.gz";
}
else
{
$l['log'] = $config['files']['log'];
$l['perllog'] = $config['files']['perllog'];
$l['perllogcomplete'] = $config['files']['perllogcomplete'];
$l['errorlog'] = $config['paths']['log'] . "error.log";
}
$l['log_size'] += @filesize($l['log']);
$sum += $l['log_size'];
$l['perllog_size'] += @filesize($l['perllog']);
$sum += $l['perllog_size'];
$l['perllogcomplete_size'] += @filesize($l['perllogcomplete']);
$sum += $l['perllogcomplete_size'];
$l['errorlog_size'] += @filesize($l['errorlog']);
$sum += $l['errorlog_size'];
$l['log_totalsize'] += $sum;
return $l;
}
/**
* Delete log file and recreates it.
*
* @return void
*/
function deleteLog()
{
global $config;
$log = date('d.m.Y H:i:s') . " Log created.\n";
if (file_exists($config['files']['log'] . '.gz')) @unlink($config['files']['log'] . '.gz');
if (file_exists($config['files']['log'] . '.gz')) @unlink($config['files']['log']);
if ($config['logcompression'] == 1)
{
$fp = @gzopen($config['files']['log'] . '.gz', "wb");
@gzwrite($fp, $log);
@gzclose($fp);
@chmod($config['files']['log'] . '.gz', 0777);
}
else
{
$fp = @fopen($config['files']['log'], "wb");
@fwrite($fp, $log);
@fclose($fp);
@chmod($config['files']['log'], 0777);
}
}
/**
* Detect accessable databases for the current SQL-User in $config-array and returns output-string with all dbs
* Additionally it adds all found databases in the global var $databases
*
* @param boolean $printout Wether to return the output string or not
* @param string $db Optional name of a database to add manually
*
* @return string Output string containing all found dbs
*/
function searchDatabases($printout = 0, $db = '')
{
global $config, $lang, $dbo, $databases;
$databases = array();
$ret = '';
$db_list = $dbo->getDatabases();
// add manual added db to array, but only if it was not detected before
if ($db > '' && !in_array($db, $db_list)) $db_list[] = $db;
// now check if we can select the db - if not, we can't access the database
if (sizeof($db_list) > 0)
{
foreach ($db_list as $db)
{
$res = $dbo->selectDb($db, true);
if ($res === true)
{
addDatabaseToConfig($db);
if ($printout == 1) $ret .= Html::getOkMsg($lang['L_FOUND_DB'] . ' `' . $db);
} elseif ($printout == 1) {
$ret .= Html::getErrorMsg($lang['L_ERROR'].' : '.$res);
}
}
}
return $ret;
}
/**
* realpath implementation working on any server
*
* @return $dir string The application path
*/
function myRealpath()
{
$dir = dirname(__FILE__);
$dir = str_replace('\\', '/', $dir);
$dir = str_replace('//', '/', $dir);
if (substr($dir, -14) == '/inc/functions') $dir = substr($dir, 0, -13);
if (substr($dir, -1) != '/') $dir .= '/';
return $dir;
}
/**
* Remove tags recursivly from array or from string
*
* @param $value string | array Value/s to strip
*
* @return string|array Cleaned values
*/
function myStripTags($value)
{
global $dont_strip;
if (is_array($value))
{
foreach ($value as $key => $val)
{
if (!in_array($key, $dont_strip)) $ret[$key] = myStripTags($val);
else $ret[$key] = $val;
}
}
else
$ret = trim(strip_tags($value));
return $ret;
}
/**
* First start output buffering then start SESSION
* Reads configuration and main-language file lang.php and creates
* Database-Object $dbo
*
* @param string $json Return JSON-Encoded answer
* @param string $send_header If set to false headers are completely skipped
* @return void
*/
function obstart($json = false, $send_header = true)
{
global $dbo, $config, $databases, $dump, $lang;
if ($config['ob_gzhandler'])
{
if (!@ob_start("ob_gzhandler")) @ob_start();
}
// if default config file doesn't exists, it is a new installation -> redirect to installation
if (!$json && !file_exists('./work/config/mysqldumper.php'))
{
header("location: install.php");
die();
exit();
}
session_name('MySQLDumper');
$res = session_start();
if (false === $res) die("Error starting session! Check server.");
if (isset($_SESSION['config_file'])) $config['config_file'] = $_SESSION['config_file'];
else $config['config_file'] = 'mysqldumper';
if ($send_header)
{
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate'); // HTTP/1.1
header('Expires: -1'); // Datum in der Vergangenheit
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
if (!$json) header('Content-Type: text/html; charset=UTF-8');
else header('Content-type: application/x-json');
}
// get config from configuration file if not set
if (!isset($_SESSION['config'])) getConfig($config['config_file']);
else
{
// otherwise get parameters from session
$config = array_merge($config, $_SESSION['config']);
if (isset($_SESSION['databases'])) $databases = $_SESSION['databases'];
if (isset($_SESSION['dump'])) $dump = $_SESSION['dump'];
}
// special case -> configuration is set to a language that was deleted meanwhile
if (!is_readable('./language/' . $config['language'] . '/lang.php')) $config['language'] = 'en';
include ('./language/' . $config['language'] . '/lang.php');
// create database object
$dbo = MsdDbFactory::getAdapter($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbport'], $config['dbsocket']);
if (!isset($_SESSION['databases'])) setDefaultConfig();
//echo $config['db_actual'];
// die();
if (isset($config['db_actual']) && $config['db_actual'] > '') $dbo->selectDb($config['db_actual']);
else
{
if (!isset($databases)) {
// no config loaded -> SetDefault-Values
setDefaultConfig();
}
// get first DB-Name and set as actual db
$dbNames = array_keys($databases);
$config['db_actual'] = $dbNames[0];
$dbo->selectDb($config['db_actual']);
}
//$_SESSION['config'] = $config;
//$_SESSION['databases'] = $databases;
}
/**
* Add end of body/html, end output buffering and output the buffer
*
* @param boolean $ajax
* @return void
*/
function obend($ajax = false)
{
global $config, $databases;
$_SESSION['databases'] = $databases;
$_SESSION['config'] = $config;
if (!$ajax) {
echo '</div>' . "\n\n" . '</body>' . "\n\n" . '</html>';
// close HTML-page
}
@ob_end_flush();
}
/**
* Extract unique prefixes from an array
*
* and return new array containing the different prefixes
*
* @param array $array Array to scan for prefixes
* @param boolean $addNoneOption Wether to add a first entry '---'
*
* @return $prefix_array array The array conatining the unique prefixes
*/
function getPrefixArray($array, $addNoneOption = true)
{
$prefixes = array();
$keys = array_keys($array);
foreach ($keys as $k) {
$pos = strpos($k, '_'); // find '_'
if ($pos !== false) {
$prefix = substr($k, 0, $pos);
if (!in_array($prefix, $prefixes)) {
$prefixes[$prefix] = $prefix;
}
}
}
if ($addNoneOption) {
$prefixes['-1'] = '---';
}
ksort($prefixes);
return $prefixes;
}
/**
* Implode the given keys of multidimensional array using the implode string
*
* @param array $array The array to implode
* @param string $key The values that should be imploded
* @param string $implodeString The string to concatenate the values with
*
* @return string The impoloded valuies as string
*/
function implodeSubarray($array, $key, $implodeString = ', ')
{
$ret = '';
foreach ($array as $k => $v) {
$ret .= $v[$key] . $implodeString;
}
if (strlen($ret) > 1) {
$ret = substr($ret, 0, -(strlen($implodeString)));
}
return $ret;
}

Datei anzeigen

@ -0,0 +1,668 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1209 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
/**
* Creates a new backup file including the header information
*
* @return void
*/
function createNewFile()
{
global $dump, $databases, $config, $lang, $log;
// Dateiname aus Datum und Uhrzeit bilden
if ($dump['part'] - $dump['part_offset'] == 1) {
$dump['filename_stamp'] = date("Y_m_d_H_i", time());
}
if ($config['multi_part'] == 1) {
$dateiname = $dump['db_actual'] . '_' . $dump['filename_stamp']
. '_part_' . ($dump['part'] - $dump['part_offset']);
} else {
$dateiname = $dump['db_actual'] . '_' . date("Y_m_d_H_i", time());
}
$endung = ($config['compression']) ? '.sql.gz' : '.sql';
$dump['backupdatei'] = $dateiname . $endung;
$_SESSION['log']['files_created'][] = $dump['backupdatei'];
if (file_exists($config['paths']['backup'] . $dump['backupdatei'])) {
unlink($config['paths']['backup'] . $dump['backupdatei']);
}
$curTime = date("Y-m-d H:i");
$statuszeile = getStatusLine() . "\n-- Dump by MySQLDumper " . MSD_VERSION
. ' (' . $config['homepage'] . ')' . "\n";
$statuszeile .= '/*!40101 SET NAMES \'' . $dump['dump_encoding']
. '\' */;' . "\n";
$statuszeile .= 'SET FOREIGN_KEY_CHECKS=0;' . "\n";
if ($dump['part'] - $dump['part_offset'] == 1) {
$log->write(
Log::PHP,
sprintf(
$lang['L_SAVING_DATA_TO_FILE'],
$dump['db_actual'],
$dump['backupdatei']
)
);
if ($dump['part'] == 1) {
$dump['table_offset'] = 0;
$dump['countdata'] = 0;
}
// Seitenerstaufruf -> Backupdatei anlegen
$dump['data'] = $statuszeile . '-- Dump created: ' . $curTime;
} else {
if ($config['multi_part'] != 0) {
$log->write(
Log::PHP,
sprintf(
$lang['L_SAVING_DATA_TO_MULTIPART_FILE'],
$dump['backupdatei']
)
);
$dump['data'] = $statuszeile . '-- ' . ' This is part '
. ($dump['part'] - $dump['part_offset']) . ' of the backup.'
. "\n\n" . $dump['data'];
}
}
writeToDumpFile();
$dump['part']++;
}
/**
* Creates the first statusline with information for backup files
*
* @return string
*/
function getStatusLine()
{
// strcuture of status line:
// -- Status:nrOfTables:nrOfRecords:Multipart:database:script:
// scriptversion:comment:MySQL-Version:Backupflags(unused):SQLBefore:
//SQLAfter:Charset:CharsetEXTINFO
global $databases, $config, $dump;
if (!defined('MSD_MYSQL_VERSION')) {
GetMySQLVersion();
}
$tline = "-- \n-- TABLE-INFO\r\n";
foreach ($dump['databases'][$dump['db_actual']]['tables']
as $tableName => $val) {
$tline .= "-- TABLE|" . $tableName . '|' . $val['records']
. '|' . $val['data_length'] . '|' . $val['update_time'] . '|'
. $val['engine'] . "\n";
}
$flags = 1;
$mp = 'MP_0';
if ($config['multi_part'] == 1) {
$mp = "MP_" . ($dump['part'] - $dump['part_offset']);
}
$statusline = "-- Status:"
. $dump['databases'][$dump['db_actual']]['table_count']
. ':' . $dump['databases'][$dump['db_actual']]['records_total']
. ":$mp:" . $dump['db_actual'] . ":PHP:" . MSD_VERSION . ":"
. $dump['comment'] . ":";
$statusline .= MSD_MYSQL_VERSION . ":$flags:::" . $dump['dump_encoding']
. ":EXTINFO\n" . $tline . "-- " . "EOF TABLE-INFO\n-- ";
return $statusline;
}
/**
* Build the DROP and CREATE TABLE string for dump file.
*
* Parameter $withdata decides if we should add the
* "ALTER TABLE DISABLE KEYS"-query.
*
* @param string $db The database
* @param string $table The table
* @param integer $withdata Add DISABLE KEYS
* @return string $def Created Query-string or false on error
*/
function getCreateString($db, $table, $withdata = 1)
{
global $dbo, $config, $dump, $lang, $log;
$def = "\n\n--\n-- Table structure for table `$table`\n--\n";
if ($dump['databases'][$dump['db_actual']]['tables'][$table]['engine']
== 'VIEW') {
$def .= "DROP VIEW IF EXISTS `$table`;\n";
$withdata = 0;
} else {
$def .= "DROP TABLE IF EXISTS `$table`;\n";
}
$createStatement = $dbo->getTableCreate($table, $db);
$def .= $createStatement . ';' . "\n\n";
if ($withdata == 1) {
$def .= "--\n-- Dumping data for table `$table`\n--\n";
$def .= "/*!40000 ALTER TABLE `$table` DISABLE KEYS */;\n";
}
$log->write(Log::PHP, sprintf($lang['L_CREATE_TABLE_SAVED'], $table));
return $def;
}
/**
* Read records from table, build query-strings and write them to dump file
*
* @param string $db The database to read from
* @param string $table The table to read from
* @return void
*/
function getContent($db, $table)
{
global $dbo, $config, $dump, $lang, $log;
$content = '';
$fields = $dbo->getTableColumns($table, $db);
// TODO decide if the type of field needs to be escaped and placed between quotes
// also handle NULL-values very strict for MySQL-servers running with sql-mod=STRICT
$fieldNames = array_keys($fields);
$fieldList = '`' . implode('`,`', $fieldNames) . '`';
// indicator if the actual table is fully dumped in this call
$tableDone = 0;
$sql = 'SELECT * FROM `' . $db . '`.`' . $table . '` LIMIT '
. $dump['table_record_offset'] . ',' . ($dump['restzeilen'] + 1);
$result = $dbo->query($sql, MsdDbFactory::ARRAY_NUMERIC);
$numRows = @count($result);
if ($numRows > 0) {
// we've got records - get fields
$numfields = count($result[0]);
if ($numRows > $dump['restzeilen']) {
// there are more records to get - table is not fully dumped
$dump['table_record_offset'] += $dump['restzeilen']; //set table record offset for next call
$numRows--; // correct counter - we only used the last record to find out if there is more to fetch
unset($result[$numRows]);
} else {
// table is done -> increase table offset
$recordsSaved = $dump['table_record_offset'] + $numRows;
$log->write(
Log::PHP,
sprintf(
$lang['L_BACKUP_TABLE_DONE'],
$table,
String::formatNumber($recordsSaved)
)
);
$dump['table_offset']++;
$dump['table_offset_total']++;
$dump['table_record_offset'] = 0;
$tableDone = 1;
}
foreach ($result as $row) {
//if($config['backup_using_updates']==1){
$insert = 'INSERT INTO `' . $table . '` (' . $fieldList
. ') VALUES (';
//TODO implement REPLACE INTO for expert mode
// }
//else{
//$insert='REPLACE INTO `'.$table.'` '.$complete.' VALUES (';
// }
foreach ($row as $field => $val) {
if ($val != '') $insert .= '\'' . $dbo->escape($val) . '\',';
else $insert .= '\'\',';
}
$insert = substr($insert, 0, -1) . ');' . "\n";
$dump['data'] .= $insert;
$dump['restzeilen']--;
$dump['countdata']++;
if (strlen($dump['data']) > $config['memory_limit']
|| ($config['multi_part'] == 1
&& strlen($dump['data']) + MULTIPART_FILESIZE_BUFFER
> $config['multipart_groesse'])) {
writeToDumpFile();
}
}
if ($tableDone == 1) {
// check if records have been saved and add "enable keys"
$tables = $dump['databases'][$dump['db_actual']]['tables'];
if ($tables[$table]['dump_records'] == 1) {
$dump['data'] .= "/*!40000 ALTER TABLE `$table`"
." ENABLE KEYS */;";
}
}
} else {
// table corrupt -> skip it
$dump['table_offset']++;
$dump['table_offset_total']++;
$dump['table_record_offset'] = 0;
$dump['restzeilen'] = $dump['restzeilen'] - $numRows;
$dump['data'] .= "/*!40000 ALTER TABLE `$table` ENABLE KEYS */;\n";
if (strlen($dump['data']) > $config['memory_limit']
|| ($config['multi_part'] == 1 && strlen($dump['data'])
+ MULTIPART_FILESIZE_BUFFER > $config['multipart_groesse'])) {
writeToDumpFile();
}
}
}
/**
* Saves the created data of global var $dump['data'] to the dump file.
*
* If Multipart is used and the maximum filesize is reached a new file is
* created. Sets global var $dump['filesize'] to new vaule for printing
* on sccreen.
*
* @return void
*/
function writeToDumpFile()
{
global $config, $dump;
$file = $config['paths']['backup'] . $dump['backupdatei'];
if ($config['compression'] == 1) {
if ($dump['data'] != '') {
$fp = gzopen($file, 'ab');
gzwrite($fp, $dump['data']);
gzclose($fp);
}
} else {
if ($dump['data'] != '') {
$fp = fopen($file, 'ab');
fwrite($fp, $dump['data']);
fclose($fp);
}
}
$dump['data'] = '';
clearstatcache();
$dump['filesize'] = intval(@filesize($file));
// if Multipart is used and maximum filesize is reached -> create new file
if ($config['multi_part'] == 1) {
if ($dump['filesize'] + MULTIPART_FILESIZE_BUFFER
> $config['multipart_groesse']) {
@chmod($file, 0777);
createNewFile();
}
}
}
/**
* Checks if there is a next db to be dumped
*
* Sets the global flag $dump['backup_done']
*
* @return void
*/
function checkForNextDB()
{
global $dump;
// a check, if another db should be saved is at the end of the script
// backup of actual db is done -> lets check if there is more to do
$nextDb = getNextKey($dump['databases'], $dump['db_actual']);
if ($nextDb !== false) {
$dump['backup_done'] = 0;
//-1 instead of 0 is needed for the execution of command before backup
$dump['table_offset'] = -1;
$dump['db_actual'] = $nextDb;
$dump['part_offset'] = $dump['part'] - 1;
} else {
$dump['backup_done'] = 1;
$dump['table_offset_total']--;
}
}
/**
* Execute queries before and after the backup process
*
* Queries are saved in the configuration profile
*
* @param string $when Before (b) or after backup process
*
* @return void
*/
function executeCommand($when)
{
// TODO implement execution of command before/after backup
return;
}
/**
* Send e-mail and attach file
*
* @param string $file
* @return boolean
*/
function doEmail($file)
{
global $config, $dump, $lang, $log;
include ('lib/phpmailer/php5/class.phpmailer.php');
include ('inc/classes/helper/Html.php');
// get some status info from actual file
$rootpath = $config['paths']['root'] . $config['paths']['backup'];
$fileInfo = ReadStatusline($file);
$fileInfo['size'] = @filesize($rootpath . $file);
$database = $fileInfo['dbname'];
$tablesSaved = $fileInfo['tables'];
$recordsSaved = $fileInfo['tables'];
if (sizeof($_SESSION['email']['filelist']) == 0) {
// first call after backup -> create file list of all files for each database
$_SESSION['email']['filelist'] = array();
foreach ($_SESSION['log']['email'] as $filename) {
$statusInfo = ReadStatusline($filename);
if (!isset($_SESSION['email']['filelist'][$statusInfo['dbname']])) {
$_SESSION['email']['filelist'][$statusInfo['dbname']] = array();
}
$_SESSION['email']['filelist'][$statusInfo['dbname']][] = $filename;
}
}
// create file list for specific database
$filelist = '';
foreach ($_SESSION['email']['filelist'][$database] as $filename) {
$phpSelf = $_SERVER['PHP_SELF'];
$linkToFile = '<a href="' . getServerProtocol()
. $_SERVER['HTTP_HOST']
. substr($phpSelf, 0, strrpos($phpSelf, '/'))
. '/' . $config['paths']['backup'] . $filename . '">'
. $filename . '</a>';
$filelist .= $linkToFile;
if ($file == $filename && $config['email']['attach_backup']) {
$filelist .= ' (' . $lang['L_ATTACHED_AS_FILE'] . ')';
}
$filelist .= '<br />' . "\n";
}
$mail = new PHPMailer();
$mail->CharSet = 'utf-8';
$mail->PlugInDir = 'lib/phpmailer/php5/';
$mail->From = $config['email']['sender_address'];
$mail->FromName = $config['email']['sender_name'];
$mail->AddAddress($config['email']['recipient_address'], $config['email']['recipient_name']);
// add cc-recipients
foreach ($config['email']['recipient_cc'] as $recipient) {
if ($recipient['address'] > '') {
$mail->AddCC($recipient['address'], $recipient['name']);
}
}
//build subject
$subject = $lang['L_DUMP_FILENAME'] . ': ' . $file;
if ($fileInfo['comment'] > '') {
$subject = $fileInfo['comment'] . ', ' . $subject;
}
$mail->Subject = $subject;
$mail->Timeout = 60;
// set used mail-method
$mail->IsMail(); //defaults to php-mail-function
if ($config['use_mailer'] == 1) {
$mail->IsSendmail();
$mail->Sendmail = $config['sendmail_call'];
} elseif ($config['use_mailer'] == 2) {
$mail->IsSMTP();
//debug
//$mail->SMTPDebug = PHP_INT_MAX;
$mail->Host = $config['smtp_server'];
$mail->Port = $config['smtp_port'];
// auth?
if ($config['smtp_useauth']) {
$mail->SMTPAuth = true;
$mail->Username = $config['smtp_user'];
$mail->Password = $config['smtp_pass'];
}
//use ssl?
if ($config['smtp_usessl']) {
$mail->SMTPSecure = 'tls';
}
}
//build mail body
$body = '';
//add attachement?
if ($config['email']['attach_backup']) {
//check if file is bigger than allowed max size
if ($config['email_maxsize'] > 0
&& $fileInfo['size'] > $config['email_maxsize']) {
// attachement too big -> don't attach and paste message to body
$body .= sprintf(
$lang['L_EMAILBODY_TOOBIG'],
byteOutput($config['email_maxsize']),
$database,
$file . ' (' . byte_output(
filesize($config['paths']['backup'] . $file)
)
. ')<br />'
);
} else {
// add file as attachement
$mail->AddAttachment($rootpath . $file);
$body .= sprintf($lang['L_EMAILBODY_ATTACH'], $database, $filelist);
}
} else {
// don't attach backup file according to configuration
$body .= sprintf(
$lang['L_EMAILBODY_TOOBIG'],
byteOutput($config['email_maxsize']),
$database,
"$file (" . byteOutput(
filesize($config['paths']['backup'] . $file)
)
. ")<br />"
);
}
//set body
$mail->MsgHTML($body);
//build alternative-body without tags for mail-clients blocking HTML
$altBody = strip_tags(Html::br2nl($body));
$mail->AltBody = $altBody;
$mail->Timeout = 30;
$ret = $mail->Send();
if (!$ret) {
writeToErrorLog(
'', '', $lang['L_MAILERROR'] . ' -> ' . $mail->ErrorInfo, 0
);
$log->write(Log::PHP, $lang['L_MAILERROR']);
} else {
$msg = $lang['L_EMAIL_WAS_SEND'] . "`"
. $config['email']['recipient_address'];
$log->write(Log::PHP, $msg);
}
return $ret;
}
/**
* Transfers a file via FTP and logs each action
*
* @param integer $ftpConnectionIndex Index of FTP-Connection in configuration
* @param string $sourceFile File to transfer
* @return void
*/
function sendViaFTP($ftpConnectionIndex, $sourceFile)
{
global $config, $lang, $log;
$upload = false;
$i = $ftpConnectionIndex; // I am lazy ;)
// connect to ftp server
if ($config['ftp'][$i]['ssl'] == 0) {
$connId = @ftp_connect(
$config['ftp'][$i]['server'],
$config['ftp'][$i]['port'],
$config['ftp'][$i]['timeout']
);
} else {
$connId = @ftp_ssl_connect(
$config['ftp'][$i]['server'],
$config['ftp'][$i]['port'],
$config['ftp'][$i]['timeout']
);
}
if (is_resource($connId)) {
$log->write(
Log::PHP,
$lang['L_FTP'] . ': ' .
sprintf(
$lang['L_FTP_CONNECTION_SUCCESS'],
$config['ftp'][$i]['server'],
$config['ftp'][$i]['port']
)
);
} else {
$msg = sprintf(
$lang['L_FTP_CONNECTION_ERROR'],
$config['ftp'][$i]['server'],
$config['ftp'][$i]['port']
);
writeToErrorLog('', '', $lang['L_FTP'] . ': ' . $msg, 0);
}
// login using user and password
$loginResult = @ftp_login(
$connId,
$config['ftp'][$i]['user'],
$config['ftp'][$i]['pass']
);
if (!$loginResult) {
writeToErrorLog(
'',
'',
$lang['L_FTP'] . ': ' . sprintf(
$lang['L_FTP_LOGIN_ERROR'],
$config['ftp'][$i]['user']
),
0
);
} else {
$log->write(
Log::PHP,
$lang['L_FTP'] . ': ' . sprintf(
$lang['L_FTP_LOGIN_SUCCESS'],
$config['ftp'][$i]['user']
)
);
}
if ($config['ftp'][$i]['mode'] == 1) {
if (@ftp_pasv($connId, true)) {
$log->write(
Log::PHP,
$lang['L_FTP'] . ': ' . $lang['L_FTP_PASV_SUCCESS']
);
} else {
writeToErrorLog(
'', '',
$lang['L_FTP'] . ': ' . $lang['L_FTP_PASV_ERROR'], 0
);
}
}
// Upload der Datei
$dest = $config['ftp'][$i]['dir'] . $sourceFile;
$source = $config['paths']['backup'] . $sourceFile;
$upload = @ftp_put($connId, $dest, $source, FTP_BINARY);
// Upload-Status überprüfen
if (!$upload) {
writeToErrorLog(
'', '', sprintf($lang['L_FTP_FILE_TRANSFER_ERROR'], $sourceFile), 0
);
} else {
$log->write(
Log::PHP,
sprintf($lang['L_FTP_FILE_TRANSFER_SUCCESS'], $sourceFile)
);
}
// Schließen des FTP-Streams
@ftp_quit($connId);
$log->write(Log::PHP, $lang['L_FTP_CONNECTION_CLOSED']);
}
/**
* Gets all information about a dump process and stores it in global $dump-Array
*
* @return void
*/
function prepareDumpProcess()
{
global $databases, $dump, $config, $tableInfos;
$dump['databases'] = array();
$dump['records_total'] = 0;
$dump['tables_total'] = 0;
$dump['datasize_total'] = 0;
// make copy of database-array to make changes for value "dump" just here
$dbs = $databases;
// first check if any db is marked to be dumped
$dbToDumpExists = false;
foreach ($dbs as $val) {
if (isset($val['dump']) && $val['dump'] == 1) {
// Db should be saved
$dbToDumpExists = true;
break;
}
}
// no db selected for dump -> set actual db to be dumped
if (!$dbToDumpExists) {
$dbs[$config['db_actual']]['dump'] = 1;
}
// find out which databases and tables should be saved
// dump=0 -> don't dump records
// dump=1 -> dump records using "INSERT INTO"
foreach ($dbs as $dbName => $val) {
if (isset($val['dump']) && $val['dump'] > 0) {
// db should be dumped
// now lets check which tables should be saved
// for now we save all tables -> later check prefixes etc...
$tableInfos = getTableInfo($dbName);
if (isset($tableInfos[$dbName])) {
if (!isset($dump['databases'][$dbName])) {
$dump['databases'][$dbName] = array();
}
// calculate sums
$dump['databases'][$dbName] = $tableInfos[$dbName];
$dump['databases'][$dbName]['prefix'] = '';
if (isset($databases[$dbName]['prefix'])) {
$dump['databases'][$dbName]['prefix'] =
$databases[$dbName]['prefix'];
}
$dump['records_total'] +=
$dump['databases'][$dbName]['records_total'];
$dump['tables_total'] +=
$dump['databases'][$dbName]['table_count'];
$dump['datasize_total'] +=
$dump['databases'][$dbName]['datasize_total'];
// check if tables are selected ->
// then remove all others from array and correct sums
if ($dbName == $_SESSION['config']['db_actual']
&& isset($dump['selected_tables'])
&& is_array($dump['selected_tables'])
&& count($dump['selected_tables']) > 0) {
foreach ($dump['databases'][$dbName]['tables']
as $tablename => $val) {
if (!in_array($tablename, $dump['selected_tables'])) {
$dump['databases'][$dbName]['tables'][$tablename]['dump_structure'] = 0;
$dump['databases'][$dbName]['tables'][$tablename]['dump_records'] = 0;
// remove table from todo-list
unset($dump['databases'][$dbName]['tables'][$tablename]);
// substract values of table from sums
$dump['tables_total']--;
$dump['databases'][$dbName]['table_count']--;
$dump['databases'][$dbName]['records_total'] -= $val['records'];
$dump['databases'][$dbName]['datasize_total'] -= $val['data_length'];
$dump['databases'][$dbName]['size_total'] -= $val['data_length'] + $val['index_length'];
$dump['datasize_total'] -= $val['data_length'];
$dump['records_total'] -= $val['records'];
}
}
}
}
}
}
// set db to be dumped first -> start index is needed
$dbNames=array_keys($dump['databases']);
$dump['db_actual'] = $dbNames[0];
}

Datei anzeigen

@ -0,0 +1,370 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
/**
* Read list of backups in work/backup and create selectbox.
*
* Used in backup converter.
*
* @param string $selected selected file
* @return string String containing HTML-selectbox ready to output
*/
function getFilelisteCombo($selected)
{
global $config;
$files = array();
$dir = new DirectoryIterator($config['paths']['backup']);
foreach ($dir as $fileinfo)
{
$file = $fileinfo->getFilename();
if ($file[0] != '.' && $fileinfo->isFile())
{
$size = byteOutput($fileinfo->getSize());
$files["$file"] = $file . ' (' . $size . ')';
}
}
ksort($files);
$r = Html::getOptionlist($files, $selected);
return $r;
}
/**
* Reformat a date from format dd.mm.yyyy hh:mm to yyyy.mm.dd hh:mm to make it sortable.
*
* @param string $datum Datetime taken from filename
* @return string
*/
function getSortableDate($datum)
{
$p = explode(' ', $datum);
$uhrzeit = $p[1];
$p2 = explode('.', $p[0]);
$day = $p2[0];
$month = $p2[1];
$year = $p2[2];
return $year . '.' . $month . '.' . $day . ' ' . $uhrzeit;
}
/**
* Checks a dump file and converts it.
*
* Places field names in backticks and splitts files into 10 MB-Parts.
*
* @param string $filesource File to convert
* @param string $db_name Database name will be used to create filenames and statusline
* @param string $cp Target copy file
* @return void
*/
function convert($filesource, $db_name, $cp)
{
global $config, $lang;
@ini_set('max_input_time', '0'); // for real big dumps
$filesize = 0;
$max_filesize = 1024 * 1024 * 10; //10 MB splitsize
$part = 1;
$cps = (substr(strtolower($filesource), -2) == "gz") ? 1 : 0;
// we compare the string size with this value (not the real filesie)
//so if file is compressed we need to adjust it
if ($cps == 1) $max_filesize *= 7;
$filedestination = $db_name . '_' . date("Y_m_d_H_i", time());
echo "<h5>" . sprintf($lang['L_CONVERT_FILEREAD'], $filesource) . ".....</h5><span style=\"font-size:10px;\">";
if (file_exists($config['paths']['backup'] . $filedestination)) unlink($config['paths']['backup'] . $filedestination);
$f = ($cps == 1) ? gzopen($config['paths']['backup'] . $filesource, "r") : fopen($config['paths']['backup'] . $filesource, "r");
$z = ($cp == 1) ? gzopen($config['paths']['backup'] . $filedestination . '_part_1.sql.gz', "w") : fopen($config['paths']['backup'] . $filedestination . '_part_1.sql', "w");
$zeile = getPseudoStatusline($part, $db_name) . "\r\n";
($cp == 1) ? gzwrite($z, $zeile) : fwrite($z, $zeile);
$zeile = '';
flush();
$insert = $mode = "";
$n = 0;
$eof = ($cps == 1) ? gzeof($f) : feof($f);
$splitable = false; // can the file be splitted? Try to avoid splitting before a command is completed
WHILE (!$eof)
{
flush();
$eof = ($cps == 1) ? gzeof($f) : feof($f);
$zeile = ($cps == 1) ? gzgets($f, 5144000) : fgets($f, 5144000);
$t = strtolower(substr($zeile, 0, 10));
if ($t > '')
{
switch ($t)
{
case 'insert int':
{
// eine neue Insert Anweisung beginnt
if (strpos($zeile, '(') === false)
{
//Feldnamen stehen in der naechsten Zeile - holen
$zeile .= "\n\r";
$zeile .= ($cps == 1) ? trim(gzgets($f, 8192)) : trim(fgets($f, 8192));
$zeile .= ' ';
}
// get INSERT-Satement
$insert = substr($zeile, 0, strpos($zeile, '('));
if (substr(strtoupper($insert), -7) != 'VALUES ') $insert .= ' VALUES ';
$mode = 'insert';
$splitable = false;
break;
}
case 'create tab':
{
$mode = 'create';
WHILE (substr(rtrim($zeile), -1) != ';')
{
$zeile .= fgets($f, 8192);
}
$zeile = setBackticks($zeile) . "\n\r";
$splitable = true;
break;
}
}
}
if ($mode == 'insert')
{
if (substr(rtrim($zeile), strlen($zeile) - 3, 2) == ');') $splitable = true;
// Komma loeschen
$zeile = str_replace('),(', ");\n\r" . $insert . ' (', $zeile);
}
if ($splitable == true && $filesize > $max_filesize) // start new file?
{
$part++;
if ($mode == 'insert') // Insert -> first complete Insert-Statement, then begin new file
{
if ($cp == 1)
{
gzwrite($z, $zeile);
gzclose($z);
$z = gzopen($config['paths']['backup'] . $filedestination . '_part_' . $part . '.sql.gz', "w");
$zeile = getPseudoStatusline($part, $db_name) . "\r\n";
gzwrite($z, $zeile);
$zeile = '';
}
else
{
fwrite($z, $zeile);
fclose($z);
$z = fopen($config['paths']['backup'] . $filedestination . '_part_' . $part . '.sql', "w");
$zeile = getPseudoStatusline($part, $db_name) . "\r\n";
gzwrite($z, $zeile);
$zeile = '';
}
}
else // first close last file, then begin new one and write new beginning command
{
if ($cp == 1)
{
gzclose($z);
$z = gzopen($config['paths']['backup'] . $filedestination . '_part_' . $part . '.sql.gz', "w");
$zeile = getPseudoStatusline($part, $filedestination) . "\r\n" . $zeile;
gzwrite($z, $zeile);
}
else
{
fclose($z);
$z = fopen($config['paths']['backup'] . $filedestination . '_part_' . $part . '.sql', "w");
$zeile = getPseudoStatusline($part, $filedestination) . "\r\n" . $zeile;
fwrite($z, $zeile);
}
$n = 0;
}
$filesize = 0;
$splitable = false;
}
else // no, append to actual file
{
$filesize += strlen($zeile);
if ($n > 200)
{
$n = 0;
echo '<br />';
}
echo '.';
if ($cps == 1) gzwrite($z, $zeile);
else fwrite($z, $zeile);
flush();
}
$n++;
}
$zeile = "\n-- EOB";
if ($cps == 1)
{
gzwrite($z, $zeile);
gzclose($z);
}
else
{
fwrite($z, $zeile);
fclose($z);
}
if ($cps == 1) gzclose($f);
else fclose($f);
echo '</span><h5>' . sprintf($lang['L_CONVERT_FINISHED'], $filedestination) . '</h5>';
}
/**
* Create a dummy statusline.
*
* Used when converting a file, to create a legal MSD-Multipart-File.
*
* @param integer $part
* @param string $db_name
* @return string
*/
function getPseudoStatusline($part, $db_name)
{
if ($part > 1) echo '<br />Continue with part: ' . $part . '<br />';
$ret = '-- Status:-1:-1:MP_' . ($part) . ':' . $db_name . ":php:converter2:converted:unknown:1:::latin1:EXTINFO\r\n" . "-- TABLE-INFO\r\n" . "-- TABLE|unknown|0|0|2009-01-24 20:39:39\r\n" . "-- EOF TABLE-INFO\r\n";
return $ret;
}
/**
* Read information from all backup files in folder work/backup and return multidimensional array
* containing all info.
*
* @return array
*/
function getBackupfileInfo()
{
global $config;
clearstatcache();
$files = Array();
$dh = opendir($config['paths']['backup']);
while (false !== ($filename = readdir($dh)))
{
if ($filename != '.' && $filename != '..' && !is_dir($config['paths']['backup'] . $filename))
{
$files[]['name'] = $filename;
}
}
$arrayindex = 0;
$total_filesize = 0;
$db_backups = array();
$db_summary_anzahl = array();
$db_summary_last = array();
if (count($files) > 0)
{
for ($i = 0; $i < sizeof($files); $i++)
{
// filesize
$size = filesize($config['paths']['backup'] . $files[$i]['name']);
$file_datum = date("d\.m\.Y H:i", filemtime($config['paths']['backup'] . $files[$i]['name']));
$statusline = ReadStatusline($files[$i]['name']);
$backup_timestamp = GetTimestampFromFilename($files[$i]['name']);
$pathinfo = pathinfo($files[$i]['name']);
$file_extension = $pathinfo['extension'];
if ($backup_timestamp == '') $backup_timestamp = $file_datum;
$database_name = $statusline['dbname'];
// check for some special cases
if ($database_name == 'unknown') $database_name = '~unknown'; // needed for sorting - place unknown files at the end
if ($statusline['comment'] == 'converted') $database_name = '~converted'; // converted fiels
//jetzt alle in ein Array packen
if ($statusline['part'] == 'MP_0' || $statusline['part'] == '')
{
$db_backups[$arrayindex]['name'] = $files[$i]['name'];
$db_backups[$arrayindex]['db'] = $database_name;
$db_backups[$arrayindex]['extension'] = $file_extension;
$db_backups[$arrayindex]['size'] = $size;
$db_backups[$arrayindex]['date'] = $backup_timestamp;
$db_backups[$arrayindex]['sort'] = getSortableDate($backup_timestamp);
$db_backups[$arrayindex]['tables'] = $statusline['tables'];
$db_backups[$arrayindex]['records'] = $statusline['records'];
$db_backups[$arrayindex]['multipart'] = 0;
$db_backups[$arrayindex]['comment'] = $statusline['comment'];
$db_backups[$arrayindex]['script'] = ($statusline['script'] != '') ? $statusline['script'] . '(' . $statusline['scriptversion'] . ')' : '';
$db_backups[$arrayindex]['charset'] = $statusline['charset'];
$db_backups[$arrayindex]['mysqlversion'] = $statusline['mysqlversion'];
if (!isset($db_summary_last[$database_name])) $db_summary_last[$database_name] = $backup_timestamp;
$db_summary_anzahl[$database_name] = (isset($db_summary_anzahl[$database_name])) ? $db_summary_anzahl[$database_name] + 1 : 1;
$db_summary_size[$database_name] = (isset($db_summary_size[$database_name])) ? $db_summary_size[$database_name] + $size : $size;
if (getSortableDate($backup_timestamp) > getSortableDate($db_summary_last[$database_name])) $db_summary_last[$database_name] = $backup_timestamp;
}
else
{
//v($statusline);
//list multipart files only once but keep info how many files belong to this backup
$done = 0;
if (!isset($db_summary_size[$database_name])) {
$db_summary_size[$database_name] = 0;
}
for ($j = 0; $j < $arrayindex; $j++)
{
if (isset($db_backups[$j]))
{
if (($db_backups[$j]['date'] == $backup_timestamp) && $db_backups[$j]['db'] == $database_name && $db_backups[$j]['extension'] == $file_extension)
{
$db_backups[$j]['mysqlversion'] = $statusline['mysqlversion'];
$db_backups[$j]['multipart']++;
$db_backups[$j]['size'] += $size; // calculate size for this multipart backup
$db_summary_size[$database_name] += $size; // calculate total size for this database
$done = 1;
break;
}
}
}
if ($done == 1) $arrayindex--;
if ($done == 0)
{
//new entry for this backup with this timestamp
$db_backups[$arrayindex]['name'] = $files[$i]['name'];
$db_backups[$arrayindex]['db'] = $database_name;
$db_backups[$arrayindex]['extension'] = $file_extension;
$db_backups[$arrayindex]['size'] = $size;
$db_backups[$arrayindex]['date'] = $backup_timestamp;
$db_backups[$arrayindex]['sort'] = getSortableDate($backup_timestamp);
$db_backups[$arrayindex]['tables'] = $statusline['tables'];
$db_backups[$arrayindex]['records'] = $statusline['records'];
$db_backups[$arrayindex]['multipart'] = 1;
$db_backups[$arrayindex]['comment'] = $statusline['comment'];
$db_backups[$arrayindex]['script'] = ($statusline['script'] != "") ? $statusline['script'] . "(" . $statusline['scriptversion'] . ")" : "";
$db_backups[$arrayindex]['charset'] = $statusline['charset'];
if (!isset($db_summary_last[$database_name])) $db_summary_last[$database_name] = $backup_timestamp;
$db_summary_anzahl[$database_name] = (isset($db_summary_anzahl[$database_name])) ? $db_summary_anzahl[$database_name] + 1 : 1;
$db_summary_size[$database_name] = (isset($db_summary_size[$database_name])) ? $db_summary_size[$database_name] + $size : $size;
if (getSortableDate($backup_timestamp) > getSortableDate($db_summary_last[$database_name])) $db_summary_last[$database_name] = $backup_timestamp;
}
}
$arrayindex++;
$total_filesize += $size; // calculate overall file size
}
}
if ((isset($db_backups)) && (is_array($db_backups))) $db_backups = arfsort($db_backups, get_orderarray('sort,d|name,A'));
// merge infos into one array
$info = array();
$info['filesize_total'] = $total_filesize; // total size of all files
$info['files'] = $db_backups; // info per file
unset($db_backups);
$info['databases'] = array();
foreach ($db_summary_anzahl as $db => $count)
{
$info['databases'][$db]['backup_count'] = $count;
$info['databases'][$db]['backup_size_total'] = $db_summary_size[$db];
$info['databases'][$db]['latest_backup_timestamp'] = $db_summary_last[$db];
}
return $info;
}

Datei anzeigen

@ -0,0 +1,915 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1213 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION'))
die('No direct access.');
/**
* Build order array from string
*
* key1,type1|key2,type2| ...
*
* d= sort key as string descending
* D= sort key as float ascending
* a= sort key as string ascending
* A= sort key as floatval ascending
*
* @param string $order
* @return array order-array
*/
/**
* Simple debug output for objects and arrays
* @param mixed
*
* @return void
*/
if (!function_exists('v')) {
function v($t)
{
echo '<br />';
if (is_array($t) || is_object($t)){
echo '<pre style="font-size:12px;">';
print_r($t);
echo '</pre>';
}else
echo $t;
}
}
/**
* Detect server protocol
*
* @return string 'https://' || 'http://'
*/
function getServerProtocol()
{
return (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
}
/**
* Build order array from string 'col1,A|col2,d' for function arfosort
*
* @param string $order Orderstring
*
* @return array
*/
function get_orderarray($order)
{
$order_arr = array();
$orders = explode('|', $order);
foreach ($orders as $o){
$d = explode(',', $o);
if (isset($d[0]) && isset($d[1]))
$order_arr[] = array($d[0], $d[1]);
}
return $order_arr;
}
/**
* Order multidimensial array
*
* @param array $a Array to sort
* @param string $fl Order-string to define what keys should be sortet in what direction
*
* @return array Sorted array
*/
function arfsort($a, $fl)
{
$GLOBALS['__ARFSORT_LIST__'] = $fl;
usort($a, 'arfsort_func');
return $a;
}
/**
* Sort a multidimenional array no matter in which depth the key is
*
* @param array $a Array to sort
* @param string $b Sortstring containing keys and kind of sorting
*
* @return mixed
*/
function arfsort_func($a, $b)
{
foreach ($GLOBALS['__ARFSORT_LIST__'] as $f){
if (isset($b[$f[0]]) && isset($a[$f[0]])){
switch ($f[1]){ // switch on ascending or descending value
case 'd':
$strc = strcmp(strtolower($b[$f[0]]), strtolower($a[$f[0]]));
if ($strc != 0)
return $strc;
break;
case 'a':
$strc = strcmp(strtolower($a[$f[0]]), strtolower($b[$f[0]]));
if ($strc != 0)
return $strc;
break;
case 'D':
$strc = (floatval($b[$f[0]]) < floatval($a[$f[0]])) ? -1 : 1;
if ($b[$f[0]] != $a[$f[0]])
return $strc;
break;
case 'A':
$strc = (floatval($b[$f[0]]) > floatval($a[$f[0]])) ? -1 : 1;
if ($b[$f[0]] != $a[$f[0]])
return $strc;
break;
}
}
}
return 0;
}
/**
* Read table information about nr of records and more for given database name.
* Return array with advsanced information.
*
* @param string $db The database name to read info from
* @param string $table If set, only information for this table is filled
*
* @return array
*/
function getTableInfo($db, $table = '')
{
global $dbo, $config;
$tableInfos=array();
$res = $dbo->selectDb($db);
if ($res){
$query = 'SHOW TABLE STATUS FROM `' . $db . '`';
if ($table > '') {
$query .= ' LIKE \'' . $table . '\'';
}
$res = $dbo->query($query, MsdDbFactory::ARRAY_ASSOC);
// init index if not set
if (!isset($tableInfos[$db]))
$tableInfos[$db] = array();
if (!isset($tableInfos[$db]['tables']))
$tableInfos[$db]['tables'] = array();
$tableInfos[$db]['table_count'] = sizeof($res);
$tableInfos[$db]['records_total'] = 0;
$tableInfos[$db]['datasize_total'] = 0;
$tableInfos[$db]['size_total'] = 0;
if ($tableInfos[$db]['table_count'] > 0){
for ($i = 0, $max = $tableInfos[$db]['table_count']; $i < $max; $i++){
$row = $res[$i];
$n = $row['Name'];
if (!isset($tableInfos[$db]['tables'][$n]))
$tableInfos[$db]['tables'][$row['Name']] = array();
if (isset($row['Type']))
$row['Engine'] = $row['Type'];
$tableInfos[$db]['tables'][$n]['name'] = $row['Name'];
$tableInfos[$db]['tables'][$n]['engine'] = $row['Engine'];
$tableInfos[$db]['tables'][$n]['dump_structure'] = 1;
$tableInfos[$db]['tables'][$n]['dump_records'] = 1;
// if we have a VIEW or a table of Type MEMORY -> don't save records
if (strtoupper($row['Comment']) == 'VIEW' || (isset($row['Engine']) && in_array(strtoupper($row['Engine']), array(
'MEMORY')))){
$tableInfos[$db]['tables'][$n]['dump_records'] = 0;
}
if (!isset($row['Update_time']))
$row['Update_time'] = '';
$tableInfos[$db]['tables'][$n]['update_time'] = $row['Update_time'];
$tableInfos[$db]['tables'][$n]['data_free'] = isset($row['Data_free']) ? $row['Data_free'] : 0;
$tableInfos[$db]['tables'][$n]['collation'] = isset($row['Collation']) ? $row['Collation'] : '';
$tableInfos[$db]['tables'][$n]['comment'] = isset($row['Comment']) ? $row['Comment'] : '';
$tableInfos[$db]['tables'][$n]['auto_increment'] = isset($row['Auto_increment']) ? $row['Auto_increment'] : '';
$tableInfos[$db]['tables'][$n]['records'] = (int) $row['Rows'];
$tableInfos[$db]['tables'][$n]['data_length'] = (float) $row['Data_length'];
$tableInfos[$db]['tables'][$n]['index_length'] = $row['Index_length'];
$tableInfos[$db]['records_total'] += (int) $row['Rows'];
$tableInfos[$db]['datasize_total'] += (float) $row['Data_length'];
$tableInfos[$db]['size_total'] += (float) $row['Data_length'] + (float) $row['Index_length'];
}
}
}
return $tableInfos;
}
/**
* Returns microtime of now as float value
*
* @return float microtime
*/
function getMicrotime()
{
list ($usec, $sec) = explode(' ', microtime());
return ((float) $usec + (float) $sec);
}
/**
* Detect free diskspace
*
* @return string Space in human readable Bytes or message if not available
*/
function getFreeDiskSpace()
{
global $lang;
$dfs = @diskfreespace("../");
return ($dfs) ? byteOutput($dfs) : $lang['L_NOTAVAIL'];
}
/**
* Extract timestamp informations from a filename and return formatted string YYYY.MM.DD HH:MM
*
* @param string $s Filename as input 'dbname_2009_10_18_16_22_part1_sql-gz'
*
* @return string Formated timestamp YYYY.MM.DD HH:MM
*/
function getTimestampFromFilename($s)
{
$i = strpos(strtolower($s), 'part');
if ($i > 0)
$s = substr($s, 0, $i - 1);
$i = strpos(strtolower($s), 'crondump');
if ($i > 0)
$s = substr($s, 0, $i - 1);
$i = strpos(strtolower($s), '.sql');
if ($i > 0)
$s = substr($s, 0, $i);
$sp = explode('_', $s);
$anz = count($sp) - 1;
if (strtolower($sp[$anz]) == 'perl')
$anz--;
if ($anz > 4){
return $sp[$anz - 2] . '.' . $sp[$anz - 3] . '.' . $sp[$anz - 4] . ' ' . $sp[$anz - 1] . ':' . $sp[$anz];
}else{
//no MySQLDumper file
return '';
}
}
/**
* Writes errors or notices to the corresponding error log
*
* @param string $db Affected database
* @param string $sql The executed query
* @param string $error The error message to log
* @param int $art The kind of error (0=error, 1=notice)
*
* @return void
*/
function writeToErrorLog($db = '', $sql = '', $error = '', $art = 1)
{
global $config, $lang, $log;
$sql = str_replace("\r", '', $sql);
$sql = str_replace("\n\n", '<br>', $sql);
$sql = str_replace("\n", '<br>', $sql);
$sql = trim($sql);
$error = str_replace("\r", '', $error);
if ($art == 0) {
$errormsg = $lang['L_ERROR'] . ': ' . $error;
} else {
$errormsg = $lang['L_NOTICE'] . ': ' . $error;
}
// append query if set
if ($sql > '') {
$errormsg .= '<br>SQL: ' . $sql;
}
$time = date('d.m.Y H:i:s') . ' ';
if ($art == 0) {
$_SESSION['log']['errors'][] = $time.$errormsg;
} else {
$_SESSION['log']['notices'][] = $time.$errormsg;
}
$log->write(Log::ERROR, $errormsg);
}
/**
* Checks if the directories work, config, backup and log are writable
* Returns concatenated string with warnings or empty string if every directory is writable
*
* @return string
*/
function checkDirectories()
{
global $config, $lang;
$warn = '';
if (!is_writable($config['paths']['work']))
$warn .= sprintf($lang['L_WRONG_RIGHTS'], $config['paths']['work'], '0777');
if (!is_writable($config['paths']['config']))
$warn .= sprintf($lang['L_WRONG_RIGHTS'], $config['paths']['config'], '0777');
if (!is_writable($config['paths']['backup']))
$warn .= sprintf($lang['L_WRONG_RIGHTS'], $config['paths']['backup'], '0777');
if (!is_writable($config['paths']['log']))
$warn .= sprintf($lang['L_WRONG_RIGHTS'], $config['paths']['log'], '0777');
if ($warn != '')
$warn = '<span class="warnung"><strong>' . $warn . '</strong></span>';
return $warn;
}
/**
* Deletes every table or view in a database
*
* @param string $dbn Databasename
*
* @return void
*/
function truncateDb($dbn)
{
global $dbo;
$t_sql = array();
$dbo->query('SET FOREIGN_KEY_CHECKS=0', MsdDbFactory::SIMPLE);
$res = $dbo->query('SHOW TABLE STATUS FROM `' . $dbn . '`', MsdDbFactory::ARRAY_ASSOC);
foreach ($res as $row){
if (substr(strtoupper($row['Comment']), 0, 4) == 'VIEW'){
$t_sql[] = 'DROP VIEW `' . $dbn . '``' . $row['Name'] . '`';
}else{
$t_sql[] = 'DROP TABLE `' . $dbn . '`.`' . $row['Name'] . '`';
}
}
if (sizeof($t_sql) > 0){
for ($i = 0; $i < count($t_sql); $i++){
try{
$dbo->query($t_sql[$i]);
}catch (Excption $e){
//TODO create clean error handling depending on context
writeToErrorLog($e->getMessage());
die($e->getMessage());
}
}
}
$dbo->query('SET FOREIGN_KEY_CHECKS=1', MsdDbFactory::SIMPLE);
}
/**
* Delete old backups from folder work/backup according to configuration
*
* @return string Outputstring with messages about deleted files
*/
function doAutoDelete()
{
global $config, $lang, $out;
$out = '';
if ($config['auto_delete']['max_backup_files'] > 0){
//Files einlesen
$dh = opendir($config['paths']['backup']);
$files = array();
// Build assoc Array $db=>$timestamp=>$filenames
if (!function_exists('ReadStatusline'))
include ('./inc/functions/functions_files.php');
while (false !== ($filename = readdir($dh))){
if ($filename != '.' && $filename != '..' && !is_dir($config['paths']['backup'] . $filename)){
$statusline = readStatusline($filename);
if ($statusline['dbname'] != 'unknown'){
$dbName = $statusline['dbname'];
$datum = substr($filename, strlen($dbName) + 1);
$timestamp = substr($datum, 0, 16);
if (!isset($files[$dbName]))
$files[$dbName] = array();
if (!isset($files[$dbName][$timestamp]))
$files[$dbName][$timestamp] = array();
$files[$dbName][$timestamp][] = $filename;
}
}
}
$out = ''; // stores output messages
// Backups per DB and Timestamp
foreach ($files as $db => $val){
if (sizeof($val) > $config['auto_delete']['max_backup_files']){
$db_files = $val;
krsort($db_files, SORT_STRING);
//now latest backupfiles are on top -> delete all files with greater index
$i = 0;
foreach ($db_files as $timestamp => $filenames){
if ($i >= $config['auto_delete']['max_backup_files']){
// Backup too old -> delete files
foreach ($filenames as $f){
if ($out == '')
$out .= $lang['L_FM_AUTODEL1'] . '<br />';
if (@unlink('./' . $config['paths']['backup'] . $f)){
$out .= '<span class="success">' . sprintf($lang['L_DELETE_FILE_SUCCESS'], $f) . '</span><br />';
}else{
$out .= $lang['L_ERROR'] . ': <p class="error">' . sprintf($lang['L_DELETE_FILE_ERROR'], $f) . '</p><br />';
}
}
}
$i++;
}
}
}
}
return $out;
}
/**
* Analyzes the first line of a MSD-Backup. Expects it as string parameter.
*
* @param string $line The statusline from the backup to analyze
*
* @return array Extracted information as array
*/
function readStatusline($filename)
{
global $config;
/*AUFBAU der Statuszeile:
-- Status:nr of tables:records:Multipart:Databasename:script:scriptversion:Comment:
MySQL-Version:flags (unused):SQLCommandBeforeBackup:SQLCommandAfterBackup:Charset:EXTINFO
*/
$gz = substr($filename, -3) == '.gz' ? true : false;
$fh = $gz ? gzopen($config['paths']['backup'] . $filename, 'r') : fopen($config['paths']['backup'] . $filename, 'r');
if (!$fh){
v(debug_backtrace());
die();
}
$line = $gz ? gzgets($fh) : fgets($fh);
$gz ? gzclose($fh) : fclose($fh);
$statusline = array();
$line = removeBom($line);
if ((substr($line, 0, 8) != "# Status" && substr($line, 0, 9) != "-- Status") || substr($line, 0, 10) == '-- StatusC'){
//Fremdfile
$statusline['tables'] = -1;
$statusline['records'] = -1;
$statusline['part'] = 'MP_0';
$statusline['dbname'] = 'unknown';
$statusline['script'] = '';
$statusline['scriptversion'] = '';
$statusline['comment'] = '';
$statusline['mysqlversion'] = 'unknown';
$statusline['flags'] = '2222222';
$statusline['sqlbefore'] = '';
$statusline['sqlafter'] = '';
$statusline['charset'] = '?';
}else{
// MySQLDumper-File - Informationen extrahieren
$s = explode(':', $line);
if (count($s) < 12){
//fehlenden Elemente auffüllen
$c = count($s);
array_pop($s);
for ($i = $c - 1; $i < 12; $i++){
$s[] = '';
}
}
$statusline['tables'] = $s[1];
$statusline['records'] = $s[2];
$statusline['part'] = ($s[3] == '' || $s[3] == 'MP_0') ? 'MP_0' : $s[3];
$statusline['dbname'] = $s[4];
$statusline['script'] = $s[5];
$statusline['scriptversion'] = $s[6];
$statusline['comment'] = $s[7];
$statusline['mysqlversion'] = $s[8];
if ((isset($s[12])) && trim($s[12]) != 'EXTINFO'){
$statusline['charset'] = $s[12];
}else{
$statusline['charset'] = '?';
}
}
return $statusline;
}
/**
* Reads Head-Information about tables from MSD-Backup and returns it as array
*
* @param string $filename Filename of MSD-Backup to analyze
*
* @return array Detailed information about tables n MSD-Backup
*/
function getTableHeaderInfoFromBackup($filename)
{
global $config;
// Get Tableinfo from file header
$tabledata = array();
$i = 0;
$gz = substr($filename, -3) == '.gz' ? true : false;
$fh = $gz ? gzopen($config['paths']['backup'] . $filename, 'r') : fopen($config['paths']['backup'] . $filename, 'r');
$eof = false;
WHILE (!$eof){
$line = $gz ? gzgets($fh, 40960) : fgets($fh, 40960);
$line = trim($line);
if (substr($line, 0, 9) == '-- TABLE|'){
$d = explode('|', $line);
$tabledata[$i]['name'] = $d[1];
$tabledata[$i]['records'] = $d[2];
$tabledata[$i]['size'] = $d[3];
$tabledata[$i]['update'] = $d[4];
$tabledata[$i]['engine'] = isset($d[5]) ? $d[5] : '';
$i++;
}elseif (substr($line, 0, 6) == '-- EOF')
$eof = true; // End of Table-Info - >done
elseif (substr(strtolower($line), 0, 6) == 'create')
$eof = true; // we have found the first CREATE-Query -> done
}
$gz ? gzclose($fh) : fclose($fh);
return $tabledata;
}
/**
* Calculate next Multipart-Filename
*
* @param string $filename The filename to calculate the next name from
*
* @return string Filename of next Multipart-File
*/
function getNextPart($filename)
{
$nf = explode('_', $filename);
$i = array_search('part', $nf) + 1;
$part = substr($nf[$i], 0, strpos($nf[$i], '.'));
$ext = substr($nf[$i], strlen($part));
$nf[$i] = ++$part . $ext;
$filename = implode('_', $nf);
return $filename;
}
/**
* Formats seconds to human readable output
*
* @param integer $time Time in seconds
*
* @return string Time as human readable formatted string
*/
function getTimeFormat($time)
{
global $lang;
$d = floor($time / 86400);
$h = floor(($time - $d * 86400) / 3600);
$m = floor(($time - $d * 86400 - $h * 3600) / 60);
$s = $time - $d * 86400 - $h * 3600 - $m * 60;
$ret = sprintf('%02d', $s) . ' ' . ($s == 1 ? $lang['L_SECOND'] : $lang['L_SECONDS']);
if ($m > 0){
$ret = $m . ' ' . ($m == 1 ? $lang['L_MINUTE'] : $lang['L_MINUTES']) . ' ' . $ret;
}
if ($h > 0){
$ret = $h . ' ' . ($h == 1 ? $lang['L_HOUR'] : $lang['L_HOURS']) . ' ' . $ret;
}
if ($d > 0){
$ret = $d . ' ' . ($d == 1 ? $lang['L_DAY'] : $lang['L_DAYS']) . ' ' . $ret;
}
return $ret;
}
/**
* Tests a ftp-connection and returns messages about uccess or failure
*
* @param integer $i The index of the connection profile to test
*
* @return array Array with messages
*/
function testFTP($i)
{
global $lang, $config;
if (!isset($config['ftp'][$i]['timeout']))
$config['ftp'][$i]['timeout'][$i] = 30;
$ret = array();
if ($config['ftp'][$i]['port'] == '' || $config['ftp'][$i]['port'][$i] == 0)
$config['ftp'][$i]['port'] = 21;
$pass = -1;
if (!extension_loaded("ftp")){
$ret[] = '<span class="error">' . $lang['L_NOFTPPOSSIBLE'] . '</span>';
}else
$pass = 0;
if ($pass == 0){
if ($config['ftp'][$i]['server'] == '' || $config['ftp'][$i]['user'] == ''){
$ret[] = '<span class="error">' . $lang['L_WRONGCONNECTIONPARS'] . '</span>';
}else
$pass = 1;
}
if ($pass == 1){
if ($config['ftp'][$i]['ssl'] == 0)
$conn_id = @ftp_connect($config['ftp'][$i]['server'], $config['ftp'][$i]['port'], $config['ftp'][$i]['timeout']);
else
$conn_id = @ftp_ssl_connect($config['ftp'][$i]['server'], $config['ftp'][$i]['port'], $config['ftp'][$i]['timeout']);
if (is_resource($conn_id)){
$ret[] = sprintf($lang['L_FTP_CONNECTION_SUCCESS'], $config['ftp'][$i]['server'], $config['ftp'][$i]['port']);
}else
$ret[] = sprintf($lang['L_FTP_CONNECTION_ERROR'], $config['ftp'][$i]['server'], $config['ftp'][$i]['port']);
if ($conn_id){
$login_result = @ftp_login($conn_id, $config['ftp'][$i]['user'], $config['ftp'][$i]['pass']);
if ($login_result)
$ret[] = sprintf($lang['L_FTP_LOGIN_SUCCESS'], $config['ftp'][$i]['user']);
else
$ret[] = sprintf($lang['L_FTP_LOGIN_ERROR'], $config['ftp'][$i]['user']);
}
if ($conn_id && $login_result){
$pass = 2;
if ($config['ftp'][$i]['mode'] == 1){
if (ftp_pasv($conn_id, true))
$ret[] = $lang['L_FTP_PASV_SUCCESS'];
else
$ret[] = $lang['L_FTP_PASV_ERROR'];
}
}
}
if ($pass == 2){
$dirc = @ftp_chdir($conn_id, $config['ftp'][$i]['dir']);
if (!$dirc){
$ret[] = $lang['L_CHANGEDIR'] . ' \'' . $config['ftp'][$i]['dir'] . '\' -> <span class="error">' . $lang['L_CHANGEDIRERROR'] . '</span>';
}else{
$pass = 3;
$ret[] = $lang['L_CHANGEDIR'] . ' \'' . $config['ftp'][$i]['dir'] . '\' -> <span class="success">' . $lang['L_OK'] . '</span>';
}
@ftp_close($conn_id);
}
if ($pass == 3)
$ret[] = '<span class="success"><strong>' . $lang['L_FTP_OK'] . '</strong></span>';
return implode('<br />', $ret);
}
/**
* Returns list of configuration profiles as HTML-Optionlist
*
* @param string $selected_config The actual configuration to pre-select in option list
*
* @return string HTML-option-string
*/
function getConfigFilelist($selected_config)
{
$configs = getConfigFilenames();
$options = Html::getOptionlist($configs, $selected_config);
return $options;
}
/**
* Returns list of installed themes as HTML-Optionlist
*
* @return string HTML-option-string
*/
function getThemes()
{
global $config;
$themes = array();
$dh = opendir($config['paths']['root'] . "css/");
while (false !== ($filename = readdir($dh))){
if ($filename != '.' && $filename != '..' && is_dir($config['paths']['root'] . 'css/' . $filename) && substr($filename, 0, 1) != '.' && substr($filename, 0, 1) != '_'){
$themes[$filename] = $filename;
}
}
@ksort($themes);
$options = Html::getOptionlist($themes, $config['theme']);
return $options;
}
/**
* Detects all language-directories and builds HTML-Optionlist
*
* @return string HTML-option-string
*/
function getLanguageCombo()
{
global $config, $lang;
$default = $config['language'];
$dh = opendir('./language/');
$r = "";
$lang_files = array();
while (false !== ($filename = readdir($dh))){
if ($filename != '.' && $filename != '.svn' && $filename != '..' && $filename != 'flags' && is_dir('./language/' . $filename)){
if (isset($lang[$filename]))
$lang_files[$lang[$filename]] = $filename;
}
}
@ksort($lang_files);
foreach ($lang_files as $filename){
$style = 'background:url(language/flags/width25/' . $filename . '.gif) 4px;background-repeat:no-repeat;padding:2px 6px 2px 36px !important;';
$r .= '<option value="' . $filename . '" style="' . $style . '"';
$r .= Html::getSelected($filename, $default);
$r .= '>' . $lang[$filename] . '</option>' . "\n";
}
return $r;
}
/**
* Detects language subdirs and adds them to the global definition of $lang
*
* @return void
*/
function getLanguageArray()
{
global $lang;
$dh = opendir('./language/');
if (isset($lang['languages']))
unset($lang['languages']);
$lang['languages'] = array();
while (false !== ($filename = readdir($dh))){
if ($filename != '.' && $filename != '.svn' && $filename != ".." && $filename != "flags" && is_dir('./language/' . $filename)){
$lang['languages'][] = $filename;
}
}
}
/**
* Sets database and tablenames into backticks
*
* @param string $s Querystring
*
* @return string Querystring with backticks
*/
function setBackticks($s)
{
$klammerstart = $lastklammerstart = $end = 0;
$inner_s_start = strpos($s, '(');
$inner_s_end = strrpos($s, ')');
$inner_s = substr($s, $inner_s_start + 1, $inner_s_end - (1 + $inner_s_start));
$pieces = explode(',', $inner_s);
for ($i = 0; $i < count($pieces); $i++){
$r = trim($pieces[$i]);
$klammerstart += substr_count($r, "(") - substr_count($r, ")");
if ($i == count($pieces) - 1)
$klammerstart += 1;
if (substr(strtoupper($r), 0, 4) == "KEY " || substr(strtoupper($r), 0, 7) == "UNIQUE " || substr(strtoupper($r), 0, 12) == "PRIMARY KEY " || substr(strtoupper($r), 0, 13) == "FULLTEXT KEY "){
//nur ein Key
$end = 1;
}else{
if (substr($r, 0, 1) != '`' && substr($r, 0, 1) != '\'' && $klammerstart == 0 && $end == 0 && $lastklammerstart == 0){
$pos = strpos($r, ' ');
$r = '`' . substr($r, 0, $pos) . '`' . substr($r, $pos);
}
}
$pieces[$i] = $r;
$lastklammerstart = $klammerstart;
}
$back = substr($s, 0, $inner_s_start + 1) . implode(',', $pieces) . ');';
return $back;
}
//
/**
* Returns the index of the selected value in an array
*
* @param array $arr The Array to get the index from
* @param string $selected The value to find the index for
*
* @return mixed Found Index or false
*/
function getIndexFromValue($arr, $selected)
{
$ret = false; // return false if not found
foreach ($arr as $key => $val){
if (strtolower(substr($val, 0, strlen($selected))) == strtolower($selected)){
$ret = $key;
break;
}
}
return $ret;
}
/**
* Checks if config is readable and loads it
* Expects only the name of the configuration (not the path or complete filename)
*
* Returns true on success or false on failure
*
* @param string $file Name of configuration without extension
* @param boolean $redirect_to_install Decide if user should be redirected to installation if config doesn't exist
*
* @return boolean
*/
function getConfig($file = '', $redirect_to_install = true)
{
global $config, $databases;
if (!isset($_SESSION['config_file']))
$_SESSION['config_file'] = 'mysqldumper';
if ($file == '')
$file = $_SESSION['config_file'];
$ret = false;
// protect from including external files
$search = array(':', 'http', 'ftp', ' ', '/', '\\');
$replace = array('', '', '', '', '', '');
$file = str_replace($search, $replace, $file);
clearstatcache();
if ($redirect_to_install && !is_readable('./' . $config['paths']['config'] . $file . '.php') && $file == 'mysqldumper'){
header('Location: install.php');
exit();
}
if (!is_readable('./' . $config['paths']['config'] . $file . '.php'))
$file = 'mysqldumper';
if (is_readable('./' . $config['paths']['config'] . $file . '.php')){
$databases = array(); // reset databaselist - will be read from config file
$c = implode('', file('./' . $config['paths']['config'] . $file . '.php'));
$c = str_replace('<?php', '', $c);
eval($c);
$config['config_file'] = $file;
$_SESSION['config_file'] = $file;
$_SESSION['config'] = $config; // $config is defined in read file
$_SESSION['databases'] = $databases; // $databases is defined in read file
$config['files']['iconpath'] = './css/' . $config['theme'] . '/icons/';
$ret = true;
}
return $ret;
}
/**
* Get all names of configuration files located in /work/config directory
*
* @return array
*/
function getConfigFilenames()
{
global $config;
$configs = array();
$dh = opendir('./' . $config['paths']['config']);
while (false !== ($filename = readdir($dh))){
if (substr($filename, -4) == '.php' && substr($filename, -9) != '.conf.php' && $filename != 'dbs_manual.php'){
$index = substr($filename, 0, -4);
$configs[$index] = $index;
}
}
@ksort($configs);
return $configs;
}
/**
* Loads data from an external source via HTTP-socket
*
* Loads data from an external source $url given as URL
* and returns the content as a binary string or false on connection error
*
* @param string $url URL to fetch
*
* @return string file data or false
*/
function getFileDataFromURL($url)
{
$url_parsed = parse_url($url);
$data = false;
$host = $url_parsed['host'];
$port = isset($url_parsed['port']) ? intval($url_parsed['port']) : 80;
if ($port == 0)
$port = 80;
$path = $url_parsed['path'];
if (!isset($url_parsed['scheme']))
$url_parsed['scheme'] = 'http';
if (!isset($url_parsed['path']))
$url_parsed['path'] = '/';
if (isset($url_parsed['query']) && $url_parsed['query'] != '')
$path .= '?' . $url_parsed['query'];
$fp = @fsockopen($host, $port, $errno, $errstr, 10);
if ($fp){
$out = "GET $path HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= 'Referer: ' . $url_parsed['scheme'] . '://' . $_SERVER['SERVER_NAME'] . $path . "\r\n";
$out .= 'User-Agent: MySQLDumper ' . MSD_VERSION . "\r\n";
$out .= "Connection: close\r\n\r\n";
@fwrite($fp, $out);
$body = false;
$data = '';
while (!feof($fp)){
$s = fgets($fp, 1024);
if ($body)
$data .= $s;
if ($s == "\r\n"){
$body = true;
}
}
fclose($fp);
}
return $data;
}
/**
* Recursevely detects differences of multidimensional arrays
* and returns a new array containing all differences. Indexes that exists in both arrays are skipped.
* (e.g. used to detect differences between the complete SESSION['log'] and the built log of a page-call
* in ajax-functions to only return the last changes to the client)
*
* @param array $array1 Array1
* @param array $array2 Array2
*
* @return array Array with differences
*/
function getArrayDiffAssocRecursive($array1, $array2)
{
foreach ($array1 as $key => $value){
if (is_array($value)){
if (!isset($array2[$key]))
$difference[$key] = $value;
elseif (!is_array($array2[$key]))
$difference[$key] = $value;
else{
$new_diff = getArrayDiffAssocRecursive($value, $array2[$key]);
if ($new_diff != FALSE)
$difference[$key] = $new_diff;
}
}elseif (!isset($array2[$key]) || $array2[$key] != $value)
$difference[$key] = $value;
}
return !isset($difference) ? 0 : $difference;
}
/**
* Gets value in associative array by indexnr
*
* @param array $array
* @param mixed $index Index
*
* @return string
*/
function getValueFromIndex($array, $index)
{
$array_keys = array_keys($array);
if (isset($array_keys[$index]))
return $array_keys[$index];
else
return false;
}
/**
* Gets the next key in an associative array and returns it.
* If it was the last key return false
*
* @param array $array Array
* @param string $key current Index
*
* @return mixed
*/
function getNextKey($array, $key)
{
$array_keys = array_keys($array);
$array_flip = array_flip($array_keys);
$index = $array_flip[$key];
$index++;
if ($index < sizeof($array_keys))
return $array_keys[$index];
else
return false;
}
/**
* Detect Byte Order Mark (BOM) and remove it if found
*
* @param string $str String
*
* @return string
*/
function removeBom($str)
{
$bom = pack('CCC', 0xef, 0xbb, 0xbf);
if (0 == strncmp($str, $bom, 3)){
$str = substr($str, 3);
}
return $str;
}

Datei anzeigen

@ -0,0 +1,426 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
/**
* Reads next lines from file and extracts a complete SQL-Command
*
* @return string $sql_command The complete Query
*/
function getQueryFromFile($showErrors = true)
{
global $restore, $config, $databases, $lang, $dbo, $log;
//Init
$complete_sql = '';
$sqlparser_status = 0;
$query_found = false;
//Parse
WHILE (!$query_found && !$restore['fileEOF'] && !$restore['EOB'])
{
//get next line from file
$zeile = ($restore['compressed']) ? gzgets($restore['filehandle']) : fgets($restore['filehandle']);
// if we are at the beginning of a file look for BOM and remove it
if ($restore['offset'] == 0) $zeile = removeBom($zeile);
// what kind of command did we read from the file?
if ($sqlparser_status == 0)
{
// build comparing line in uppercase
$zeile2 = strtoupper(trim(substr($zeile, 0, 9)));
// pre-build compare strings - so we need the CPU power only once :)
$sub9 = substr($zeile2, 0, 9);
$sub7 = substr($sub9, 0, 7);
$sub6 = substr($sub7, 0, 6);
$sub4 = substr($sub6, 0, 4);
$sub3 = substr($sub4, 0, 3);
$sub2 = substr($sub3, 0, 2);
$sub1 = substr($sub2, 0, 1);
if ($sub7 == 'INSERT ')
{
$sqlparser_status = 3;
$restore['actual_table'] = getTablename($zeile, $restore['actual_table']);
}
elseif ($sub7 == 'REPLACE')
{
$sqlparser_status = 8;
$restore['actual_table'] = getTablename($zeile, $restore['actual_table']);
}
// find statements ending with a colon
elseif ($sub7 == 'LOCK TA') $sqlparser_status = 4;
elseif ($sub6 == 'COMMIT') $sqlparser_status = 7;
elseif (substr($sub6, 0, 5) == 'BEGIN') $sqlparser_status = 7;
elseif ($sub9 == 'UNLOCK TA') $sqlparser_status = 4;
elseif ($sub3 == 'SET') $sqlparser_status = 4;
elseif ($sub6 == 'START ') $sqlparser_status = 4;
elseif ($sub3 == '/*!') $sqlparser_status = 5; //MySQL-Condition oder Comment
elseif ($sub9 == 'ALTER TAB') $sqlparser_status = 4; // Alter Table
elseif ($sub9 == 'CREATE TA') $sqlparser_status = 2; //Create Table
elseif ($sub9 == 'CREATE AL') $sqlparser_status = 2; //Create View
elseif ($sub9 == 'CREATE IN') $sqlparser_status = 4; //Indexaction
elseif ($sub7 == 'UPDATE ') $sqlparser_status = 4;
elseif ($sub7 == 'SELECT ') $sqlparser_status = 4;
// divide comment from condition
elseif (($sqlparser_status != 5) && ($sub2 == '/*')) $sqlparser_status = 6;
// delete actions
elseif ($sub9 == 'DROP TABL') $sqlparser_status = 1;
elseif ($sub9 == 'DROP VIEW') $sqlparser_status = 1;
elseif ($sub7 == 'DELETE ') $sqlparser_status = 1;
// commands that mustn't be executed
elseif ($sub9 == 'CREATE DA ') $sqlparser_status = 7;
elseif ($sub9 == 'DROP DATA ') $sqlparser_status = 7;
elseif ($sub3 == 'USE') $sqlparser_status = 7;
// end of a MySQLDumper-Dump reached?
elseif ($sub6 == '-- EOB' || $sub4 == '# EO')
{
$restore['EOB'] = true;
$restore['fileEOF'] = true;
$zeile = '';
$zeile2 = '';
$query_found = true;
}
// Comment?
elseif ($sub2 == '--' || $sub1 == '#')
{
$zeile = '';
$zeile2 = '';
$sqlparser_status = 0;
}
// continue extended Insert?
if ($restore['extended_insert_flag'] == 1) $sqlparser_status = 3;
if (($sqlparser_status == 0) && (trim($complete_sql) > '') && ($restore['extended_insert_flag'] == -1))
{
if ($showErrors)
{
// unknown command -> output debug information
v($restore);
echo "<br />Sql: " . htmlspecialchars($complete_sql);
die('<br />' . $lang['L_UNKNOWN_SQLCOMMAND'] . ': ' . $zeile . '<br /><br />' . $complete_sql);
}
else
return array(
false,
$complete_sql);
}
}
$last_char = substr(rtrim($zeile), -1);
// retain new lines - otherwise keywords are glued together
// e.g. 'null' and on next line 'check' would necome 'nullcheck'
$complete_sql .= $zeile . "\n";
if ($sqlparser_status == 3 || $sqlparser_status == 8)
{
//INSERT or REPLACE
if (isCompleteQuery($complete_sql))
{
$query_found = true;
$complete_sql = trim($complete_sql);
if (substr($complete_sql, -2) == '*/')
{
$complete_sql = deleteInlineComments($complete_sql);
}
// end of extended insert found?
if (substr($complete_sql, -2) == ');')
{
$restore['extended_insert_flag'] = -1;
}
// if there is a ")," at end of line -> extended Insert-Modus -> set flag
else
if (substr($complete_sql, -2) == '),')
{
// letztes Komme gegen Semikolon tauschen
$complete_sql = substr($complete_sql, 0, -1);
$restore['extended_inserts'] = 1;
$restore['extended_insert_flag'] = 1;
}
$compare = substr(strtoupper($complete_sql), 0, 7);
if (($compare != 'INSERT ' && $compare != 'REPLACE'))
{
// we do have extended inserts here -> prepend insert syntax
// if we don't have it because of a page refresh -> get it
if (!isset($restore['insert_syntax'])) {
$restore['insert_syntax'] = Sql::getInsertSyntax(
$dbo, $restore['actual_table']
);
}
$complete_sql = $restore['insert_syntax'] . ' VALUES ' . $complete_sql;
}
else
{
// remember the INSERT syntax
$ipos = strpos(strtoupper($complete_sql), ' VALUES');
if (!$ipos === false) $restore['insert_syntax'] = substr($complete_sql, 0, $ipos);
else
{
if ($sqlparser_status == 3) $restore['insert_syntax'] = 'INSERT INTO `' . $restore['actual_table'] . '`';
else $restore['insert_syntax'] = 'REPLACE INTO `' . $restore['actual_table'] . '`';
}
}
}
}
else
if ($sqlparser_status == 1)
{
// delete action
if ($last_char == ';') $query_found = true;
$restore['actual_table'] = getTablename($complete_sql);
}
else
if ($sqlparser_status == 2)
{
// Create-command is finished if there is a colon at the end of line
if ($last_char == ';')
{
$restore['speed'] = $config['minspeed'];
// Restore this table?
$do_it = true;
if (is_array($restore['tables_to_restore']))
{
$do_it = false;
if (in_array($restore['actual_table'], $restore['tables_to_restore']))
{
$do_it = true;
}
else
{
// if we do a partial restore with selected tables and we already inserted all
// of them and we now have a table we don't need to restore
// -> we did all we need to do! Check and finish the process in that case
// (we don't need to further walk through the file if all needed tables are done)
if ($restore['table_ready'] == $restore['tables_total'])
{
$sqlparser_status = 0;
$restore['EOB'] = true;
}
}
}
$tablename = getTablename($complete_sql);
if ($do_it)
{
$complete_sql = getCorrectedCreateCommand($complete_sql);
$restore['table_ready']++;
}
else
$complete_sql = '';
$restore['actual_table'] = $tablename;
$query_found = true;
$sqlparser_status = 0;
}
}
// Index
else
if ($sqlparser_status == 4)
{
if ($last_char == ';')
{
$restore['speed'] = $config['minspeed'];
$complete_sql = deleteInlineComments($complete_sql);
$query_found = true;
}
}
// Comment or condition
else
if ($sqlparser_status == 5)
{
$t = strrpos($zeile, '*/;');
if (!$t === false)
{
$restore['speed'] = $config['minspeed'];
$query_found = true;
}
}
// multiline-comment
else
if ($sqlparser_status == 6)
{
$t = strrpos($zeile, '*/');
if (!$t === false)
{
$complete_sql = '';
$sqlparser_status = 0;
}
}
// commands that mustn't be executet
else
if ($sqlparser_status == 7)
{
if ($last_char == ';')
{
$restore['speed'] = $config['minspeed'];
$complete_sql = '';
$sqlparser_status = 0;
}
}
if (($restore['compressed']) && (gzeof($restore['filehandle']))) $restore['fileEOF'] = true;
elseif ((!$restore['compressed']) && (feof($restore['filehandle']))) $restore['fileEOF'] = true;
}
// if special tables are selected for restoring, check if this query belongs to them
if (is_array($restore['tables_to_restore']) && !(in_array($restore['actual_table'], $restore['tables_to_restore'])))
{
$complete_sql = '';
}
//detect if a table is finished and write log message
if ($sqlparser_status != 3 && $sqlparser_status != 8 && in_array($restore['last_parser_status'], array(
3,
8)))
{
if (isset($restore['records_inserted_table'][$restore['actual_table']]))
{
$message = sprintf($lang['L_RESTORE_TABLE'], $restore['actual_table']) . ': ';
$message .= sprintf($lang['L_RECORDS_INSERTED'], String::formatNumber($restore['records_inserted_table'][$restore['actual_table']]));
$log->write(Log::PHP, $message);
}
}
$restore['last_parser_status'] = $sqlparser_status;
$complete_sql = trim($complete_sql);
return $complete_sql;
}
/**
* Checks SQL-Create-Query for VIEW-Syntax, substitutes the old DEFINER with the actual sql-user
* and returns the corrected query.
*
* @param string $sql SQL-Create-Command
* @return string
**/
function getCorrectedCreateCommand($sql)
{
global $config;
if (strtoupper(substr($sql, 0, 16)) == 'CREATE ALGORITHM')
{
// It`s a VIEW. We need to substitute the original DEFINER with the actual MySQL-User
$parts = explode(' ', $sql);
for ($i = 0, $count = sizeof($parts); $i < $count; $i++)
{
if (strtoupper(substr($parts[$i], 0, 8)) == 'DEFINER=')
{
global $config;
$parts[$i] = 'DEFINER=`' . $config['dbuser'] . '`@`' . $config['dbhost'] . '`';
$sql = implode(' ', $parts);
break;
}
}
}
return $sql;
}
/**
* Deletes inline-comments from a SQL-String
*
* @param string $sql SQL-Command
*
* @return string $sql The cleaned SQL-String
**/
function deleteInlineComments($sql)
{
$array = array();
preg_match_all("/(\/\*(.+)\*\/)/U", $sql, $array);
if (is_array($array[0]))
{
$sql = trim(str_replace($array[0], '', $sql));
}
//If there is only a colon left, it was a condition -> clear all
if ($sql == ';') $sql = '';
return $sql;
}
/**
* Extract the tablename from a query
*
* @param string $sql SQL-Command
* @param string $actual_table Tablename to look for if it is known
* @return string The name of the table extracted from the Query
**/
function getTablename($sql, $actual_table = '')
{
$t = substr($sql, 0, 150); // shorten string, the tablename will be in the first 150 chars
// if we find the actual table in the string we got it -> return t without any further parsing
if (!false === stripos($t . '` ', $actual_table)) return $t;
if (!false === stripos($t . ' ', $actual_table)) return $t;
// remove all keywords until the tablename is in the front position
$t = str_ireplace('DROP TABLE', '', $t);
$t = str_ireplace('DROP VIEW', '', $t);
$t = str_ireplace('CREATE TABLE', '', $t);
$t = str_ireplace('INSERT INTO', '', $t);
$t = str_ireplace('REPLACE INTO', '', $t);
$t = str_ireplace('IF NOT EXISTS', '', $t);
$t = str_ireplace('IF EXISTS', '', $t);
if (substr(strtoupper($t), 0, 16) == 'CREATE ALGORITHM')
{
$pos = strpos($t, 'DEFINER VIEW ');
$t = substr($t, $pos, strlen($t) - $pos);
}
$t = str_ireplace(';', ' ;', $t); // tricky -> insert space as delimiter
$t = trim($t);
// now we simply can search for the first space or `
$delimiter = substr($t, 0, 1);
if ($delimiter != '`') $delimiter = ' ';
$found = false;
$position = 1;
WHILE (!$found)
{
if (substr($t, $position, 1) == $delimiter) $found = true;
if ($position >= strlen($t)) $found = true;
$position++;
}
$t = substr($t, 0, $position);
$t = trim(str_replace('`', '', $t));
return $t;
}
/**
* Detect if a SQL-Command is complete
*
* @param string $sql String to interpret as sql
* @return boolean
**/
function isCompleteQuery($string)
{
$string = str_replace('\\\\', '', trim($string)); // trim and remove escaped backslashes
$string = trim($string);
$quotes = substr_count($string, '\'');
$escaped_quotes = substr_count($string, '\\\'');
if (($quotes - $escaped_quotes) % 2 == 0)
{
$compare = substr($string, -2);
if ($compare == '*/') $compare = substr(deleteInlineComments($string), -2);
if ($compare == ');') return true;
if ($compare == '),') return true;
}
return false;
}

Datei anzeigen

@ -0,0 +1,403 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//SQL-Library laden
include ('./inc/sqllib.php');
/**
* Get sql-library as array.
*
* @return array
*/
function getSqlLibrary()
{
global $SQL_ARRAY, $config;
$sf = './' . $config['paths']['config'] . 'sql_statements';
if (!is_file($sf)) {
$fp = fopen($sf, "w+");
fclose($fp);
@chmod($sf, 0777);
}
if (count($SQL_ARRAY) == 0 && filesize($sf) > 0) {
$SQL_ARRAY = file($sf);
}
}
/**
* Saves a new query to the Sql-Library
*
* @return void
*/
function saveQueryToSqlLibrary()
{
global $SQL_ARRAY, $config;
$sf = './' . $config['paths']['config'] . 'sql_statements';
$str = "";
for ($i = 0; $i < count($SQL_ARRAY); $i++)
{
$str .= $SQL_ARRAY[$i];
if (substr($str, -1) != "\n" && $i != (count($SQL_ARRAY) - 1)) $str .= "\n";
}
if ($config['magic_quotes_gpc']) $str = stripslashes($str);
$fp = fopen($sf, "wb");
fwrite($fp, $str);
fclose($fp);
}
/**
* Gets the name of query nr $index from the Sql-Library.
*
* @param integer $index
* @return string
*/
function getQueryNameFromSqlLibrary($index)
{
global $SQL_ARRAY;
$s = explode('|', $SQL_ARRAY[$index]);
return $s[0];
}
/**
* Gets the query nr $index from the Sql-Library.
*
* @param integer $index
* @return string
*/
function getQueryFromSqlLibrary($index)
{
global $SQL_ARRAY;
if (!is_array($SQL_ARRAY)) getSqlLibrary();
if (isset($SQL_ARRAY[$index]) && !empty($SQL_ARRAY[$index]))
{
$s = explode('|', $SQL_ARRAY[$index], 2);
return (isset($s[1])) ? $s[1] : '';
}
else
return '';
}
/**
* Creates a html option list from the Sql-Library
*
* @return string
*/
function getSqlLibraryComboBox()
{
global $SQL_ARRAY, $tablename;
$s = '';
if (count($SQL_ARRAY) > 0)
{
$s = "\n\n" . '<select class="SQLCombo" name="sqlcombo" onchange="this.form.sqltextarea.value=this.options[this.selectedIndex].value;">' . "\n";
$s .= '<option value=""';
$s .= Html::getSelected(true, true);
$s .= '>---</option>' . "\n";
for ($i = 0; $i < count($SQL_ARRAY); $i++)
{
$s .= '<option value="' . htmlspecialchars(stripslashes(getQueryFromSqlLibrary($i))) . '">' . getQueryNameFromSqlLibrary($i) . '</option>' . "\n";
}
$s .= '</select>' . "\n\n";
}
return $s;
}
/**
* Detects if a query returns rows as result or just true or false
* Used in SQLBrowser to decide wether a list of records must be shown
*
* @param $sql the query to discover
* return bool
**/
function queryReturnsRecords($sql)
{
global $mysql_SQLhasRecords;
$s = explode(' ', $sql);
if (!is_array($s)) return false;
return in_array(strtoupper($s[0]), $mysql_SQLhasRecords) ? true : false;
}
function splitSQLStatements2Array($sql)
{
$z = 0;
$sqlArr = array();
$tmp = '';
$sql = str_replace("\n", '', $sql);
$l = strlen($sql);
$inQuotes = false;
for ($i = 0; $i < $l; $i++)
{
$tmp .= $sql[$i];
if ($sql[$i] == "'" || $sql[$i] == '"') $inQuotes = !$inQuotes;
if ($sql[$i] == ';' && $inQuotes == false)
{
$z++;
$sqlArr[] = $tmp;
$tmp = '';
}
}
if (trim($tmp) != '') $sqlArr[] = $tmp;
return $sqlArr;
}
/**
* Build HTML-Selectbox from saved SQL-Commands
*
* @param string $when Before backup = 0, After Backup =1
* @param integer $index Index of database
* @return string HTML as string
*/
function getCommandDumpComboBox($when, $index, $db_name)
{
global $SQL_ARRAY, $databases, $lang;
if (count($SQL_ARRAY) == 0)
{
if ($when == 0) $r = '<input type="hidden" name="command_before_' . $index . '" value="" />';
else $r = '<input type="hidden" name="command_after_' . $index . '" value="" />';
}
else
{
if ($when == 0)
{
$r = '<select class="SQLCombo select noleftmargin" name="command_before_' . $index . '" />';
$csql = trim($databases[$db_name]['command_before_dump']);
}
else
{
$r = '<select class="SQLCombo select noleftmargin" name="command_after_' . $index . '" />';
$csql = trim($databases[$db_name]['command_after_dump']);
}
$r .= '<option value=""' . Html::getSelected($csql, '') . ' />&nbsp;&nbsp;</option>' . "\n";
for ($i = 0; $i < count($SQL_ARRAY); $i++)
{
$s = trim(getQueryFromSqlLibrary($i));
$r .= '<option value="' . $i . '"';
$r .= Html::getSelected($s, $csql);
$r .= '>' . getQueryNameFromSqlLibrary($i) . '&nbsp;</option>' . "\n";
}
$r .= '</select>';
}
return $r;
}
/**
* Extracts the target tablename from a query
*
* @param string $q The query
* @return string
*/
function extractTablenameFromSQL($q)
{
global $databases, $db, $dbid;
$tablename = '';
if (strlen($q) > 100) $q = substr($q, 0, 100);
$p = trim($q);
// if we get a list of tables - no current table is selected -> return ''
if (strtoupper(substr($q, 0, 17)) == 'SHOW TABLE STATUS') return '';
// check for SELECT-Statement to extract tablename after FROM
if (strtoupper(substr($p, 0, 7)) == 'SELECT ')
{
$parts = array();
$p = substr($p, strpos(strtoupper($p), 'FROM') + 5);
$parts = explode(' ', $p);
$p = $parts[0];
}
$suchen = array(
'SHOW ',
'SELECT',
'DROP',
'INSERT',
'UPDATE',
'DELETE',
'CREATE',
'TABLE',
'STATUS',
'FROM',
'*');
$ersetzen = array(
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'');
$cleaned = trim(str_ireplace($suchen, $ersetzen, $p));
$tablename = $cleaned;
if (strpos($cleaned, ' ')) $tablename = substr($cleaned, 0, strpos($cleaned, ' '));
$tablename = str_replace('`', '', $tablename); // remove backticks
// take care of db-name.tablename
if (strpos($tablename, '.'))
{
$p = explode('.', $tablename);
$config['db_actual'] = $p[0];
if (isset($_GET['tablename'])) unset($_GET['tablename']);
$tablename = $p[1];
}
return $tablename;
}
/**
* Reads extened MySQL field information
*
* Reads extened field information for each field of a MySQL table
* and fills an array like
* array(
* [Fieldname][attribut]=value,
* ['primary_key']=keys
* )
*
* @param $db Database
* @param $table Table
* @return array Field infos
*/
function getExtendedFieldInfo($db, $table)
{
global $config, $dbo;
$fields_infos = array();
//$t = GetCreateTable($db, $table);
$sqlf = "SHOW FULL FIELDS FROM `$db`.`$table`;";
$res = $dbo->query($sqlf, MsdDbFactory::ARRAY_ASSOC);
$num_fields = sizeof($res);
$f = array(); //will hold all info
for ($x = 0; $x < $num_fields; $x++)
{
$row = $res[$x]; //mysql_fetch_array($res, MYSQL_ASSOC);
$i = $row['Field']; // define name of field as index of array
//define field defaults - this way the index of the array is defined anyway
$f[$i]['field'] = '';
$f[$i]['collation'] = '';
$f[$i]['comment'] = '';
$f[$i]['type'] = '';
$f[$i]['size'] = '';
$f[$i]['attributes'] = '';
$f[$i]['null'] = '';
$f[$i]['default'] = '';
$f[$i]['extra'] = '';
$f[$i]['privileges'] = '';
$f[$i]['key'] = $row['Key']; //array();
if (isset($row['Collation'])) $f[$i]['collate'] = $row['Collation'];
if (isset($row['COLLATE'])) $f[$i]['collate'] = $row['COLLATE']; // MySQL <4.1
if (isset($row['Comment'])) $f[$i]['comment'] = $row['Comment'];
if (isset($row['Type'])) $f[$i]['type'] = $row['Type'];
if (isset($row['Field'])) $f[$i]['field'] = $row['Field'];
$f[$i]['size'] = get_attribut_size_from_type($f[$i]['type']);
// remove size from type for readability in output
$f[$i]['type'] = str_replace('(' . $f[$i]['size'] . ')', '', $f[$i]['type']);
// look for attributes, everthing behind the first space is an atribut
$attributes = explode(' ', $f[$i]['type'], 2);
if (isset($attributes[1]))
{
// we found attributes
unset($attributes[0]); // delete type
$f[$i]['attributes'] = trim(implode(' ', $attributes)); //merge all other attributes
// remove attributes from type
$f[$i]['type'] = trim(str_replace($f[$i]['attributes'], '', $f[$i]['type']));
}
if (isset($row['NULL'])) $f[$i]['null'] = $row['NULL'];
if (isset($row['Null'])) $f[$i]['null'] = $row['Null'];
if (isset($row['Default'])) $f[$i]['default'] = $row['Default'];
if (isset($row['Extra'])) $f[$i]['extra'] = $row['Extra'];
if (isset($row['Privileges'])) $f[$i]['privileges'] = $row['Privileges'];
if (isset($row['privileges'])) $f[$i]['privileges'] = $row['privileges'];
}
return $f;
}
/**
* Returns an unique Identifier for a record in a table
*
* @param string $db Database
* @param string $table Table
* @param array &$record Complete records
*
* @return string Where-Condition to identify the record
*/
function getRecordIdentifier($db, $table, &$record)
{
global $table_infos;
$where = '';
if (!isset($table_infos[$db]['tables'][$table]['keys']))
{
$table_infos = getTableInfo($db, $table);
$keys = getKeys($db, $table);
$table_infos[$db]['tables'][$table]['keys'] = $keys;
}
if (isset($table_infos[$db]['tables'][$table]['keys']['PRIMARY']))
{
// table has a primary key -> we can build the identifier by it
foreach ($table_infos[$db]['tables'][$table]['keys']['PRIMARY'] as $column => $val)
{
$where .= $where > '' ? ' AND ' : '';
$where .= '`' . $column . '` = \'' . $record[$column] . '\'';
}
}
else
{
// shame on the table design -> no key given -> build key from all values of record
foreach ($record as $column => $val)
{
$where .= $where > '' ? ' AND ' : '';
$where .= '`' . $column . '` = \'' . $record[$column] . '\'';
}
}
return $where;
}
/**
* Get Keys from a table and store them in an ass. array $array[Key-Name][column_name]=$keys
*
* @param string $db
* @param string $table
*
* @return array
*/
function getKeys($db, $table)
{
global $dbo;
$keys = array();
$sql = 'SHOW KEYS FROM `' . $db . '`.`' . $table . '`';
$res = $dbo->query($sql, MsdDbFactory::ARRAY_ASSOC);
foreach ($res as $row)
{
$keys[$row['Key_name']][$row['Column_name']] = $row;
}
return $keys;
}
/**
* Extracts the part in brackets in a string, e.g. int(11) => 11
*
* @param string $type
* @return string
*/
function get_attribut_size_from_type($type)
{
$size = '';
$matches = array();
$pattern = '/\((\d.*?)\)/msi';
preg_match($pattern, $type, $matches);
if (isset($matches[1])) $size = $matches[1];
return $size;
}

119
inc/home/home.php Normale Datei
Datei anzeigen

@ -0,0 +1,119 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$sumFiles = $sumSize = 0;
$lastBu = Array();
if ($action == '') {
$action = 'status';
}
include ('./inc/define_icons.php');
if (isset($_POST['htaccess']) || $action == 'schutz') {
include ('./inc/home/protection_create.php');
} elseif ($action == 'edithtaccess') {
include ('./inc/home/protection_edit.php');
} elseif ($action == 'deletehtaccess') {
include ('./inc/home/protection_delete.php');
}
if ($action == 'status') {
$htaExists = (file_exists('./.htaccess'));
if (!defined('MSD_MYSQL_VERSION')) GetMySQLVersion();
// find latest backup file
$dh = opendir($config['paths']['backup']);
while (false !== ($fileName = readdir($dh))) {
if ($fileName != '.' && $fileName != '..'
&& !is_dir($config['paths']['backup'] . $fileName)) {
$files[] = $fileName;
$sumFiles++;
$sumSize += filesize($config['paths']['backup'] . $fileName);
$ft = filectime($config['paths']['backup'] . $fileName);
if (!isset($lastBu[2]) || (isset($lastBu[2]) && $ft > $lastBu[2])) {
$lastBu[0] = $fileName;
$lastBu[1] = date("d.m.Y H:i", $ft);
$lastBu[2] = $ft;
}
}
}
$directoryWarnings = checkDirectories();
$tplHome = new MSDTemplate();
$tplHome->set_filenames(array('tplHome' => 'tpl/home/home.tpl'));
$tplHome->assign_vars(
array(
'ICON_EDIT' => $icon['edit'],
'ICON_DELETE' => $icon['delete'],
'ICON_SEARCH' => $icon['search'],
'THEME' => $config['theme'],
'MSD_VERSION' => MSD_VERSION . ' (' . MSD_VERSION_SUFFIX . ')',
'OS' => MSD_OS,
'OS_EXT' => MSD_OS_EXT,
'MYSQL_VERSION' => MSD_MYSQL_VERSION,
'MYSQL_CLIENT_VERSION' => $dbo->getClientInfo(),
'PHP_VERSION' => PHP_VERSION,
'MEMORY' => byteOutput($config['php_ram'] * 1024 * 1024),
'MAX_EXECUTION_TIME' => intval(@get_cfg_var('max_execution_time')),
'MAX_EXEC_USED_BY_MSD' => $config['max_execution_time'],
'PHP_EXTENSIONS' => $config['phpextensions'],
'SERVER_NAME' => $_SERVER['SERVER_NAME'],
'MSD_PATH' => $config['paths']['root'],
'DB' => $config['db_actual'],
'NR_OF_BACKUP_FILES' => $sumFiles,
'SIZE_BACKUPS' => byteOutput($sumSize),
'FREE_DISKSPACE' => getFreeDiskSpace()
)
);
if ($directoryWarnings > '') {
$tplHome->assign_block_vars(
'DIRECTORY_WARNINGS', array('MSG' => $directoryWarnings)
);
}
if ($config['disabled'] > '') {
$tplHome->assign_block_vars(
'DISABLED_FUNCTIONS',
array(
'PHP_DISABLED_FUNCTIONS' =>
str_replace(',', ', ', $config['disabled'])
)
);
}
// Zlib is buggy from version 4.3.0 upto 4.3.2,
// so lets check for these versions
if (version_compare(PHP_VERSION, '4.3.0', '>=')
&& version_compare(PHP_VERSION, '4.3.2', '<=')) {
$tplHome->assign_block_vars('ZLIBBUG', array());
}
if (!extension_loaded('ftp')) {
$tplHome->assign_block_vars('NO_FTP', array());
}
if (!$config['zlib']) {
$tplHome->assign_block_vars('NO_ZLIB', array());
}
if ($htaExists) {
$tplHome->assign_block_vars('HTACCESS_EXISTS', array());
} else {
$tplHome->assign_block_vars('HTACCESS_DOESNT_EXISTS', array());
}
if ($sumFiles > 0 && isset($lastBu[1])) {
$fileSize = @filesize($config['paths']['backup'] . $lastBu[0]);
$tplHome->assign_block_vars(
'LAST_BACKUP',
array(
'INFO' => $lastBu[1],
'LINK' => $config['paths']['backup'] . urlencode($lastBu[0]),
'NAME' => $lastBu[0],
'SIZE' => byteOutput($fileSize)
)
);
}
}

12
inc/home/phpinfo.php Normale Datei
Datei anzeigen

@ -0,0 +1,12 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
phpinfo();

144
inc/home/protection_create.php Normale Datei
Datei anzeigen

@ -0,0 +1,144 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$dba = $htaDir = $overwrite = $msg = '';
$error = array();
$type = 0; // default encryption type set to crypt()
if (strtoupper(substr(MSD_OS, 0, 3)) == 'WIN') {
$type = 2; // we are on a Win-System; pre-select encryption type
}
if (isset($_POST['type'])) {
$type = (int) $_POST['type'];
}
$username = (isset($_POST['username'])) ? $_POST['username'] : '';
$userpassOne = (isset($_POST['userpass1'])) ? $_POST['userpass1'] : '';
$userpassConfirm = (isset($_POST['userpass2'])) ? $_POST['userpass2'] : '';
$tplHomeProtectionCreate = new MSDTemplate();
$tplHomeProtectionCreate->set_filenames(
array('tplHomeProtectionCreate' => 'tpl/home/protection_create.tpl')
);
$tplHomeProtectionCreate->assign_vars(array('THEME' => $config['theme']));
if (isset($_POST['username'])) {
// Form submitted
if ($username == '') {
$error[] = $lang['L_HTACC_NO_USERNAME'];
}
if (($userpassOne != $userpassConfirm) || ($userpassOne == '')) {
$error[] = $lang['L_PASSWORDS_UNEQUAL'];
}
if (sizeof($error) == 0) {
$realm = 'MySQLDumper';
$htaccess = "AuthName \"" . $realm
. "\"\nAuthType Basic\nAuthUserFile \""
. $config['paths']['root'] . ".htpasswd\"\nrequire valid-user\n";
switch ($type)
{
// Crypt
case 0:
$userpass = crypt($userpassOne);
break;
// MD5
case 1:
$userpass = md5($username . ':' . $realm . ':' . $userpassOne);
break;
// Win - no encryption
case 2:
$userpass = $userpassOne;
break;
// SHA
case 3:
if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
$userpass = '{SHA}' . base64_encode(sha1($userpassOne, TRUE));
} else {
$userpass = '{SHA}' . base64_encode(sha1($userpassOne));
}
break;
}
$htpasswd = $username . ':' . $userpass;
@chmod($config['paths']['root'], 0777);
$saved = true;
// save .htpasswd
if ($f = @fopen('.htpasswd', 'w')) {
$saved = fputs($f, $htpasswd);
fclose($f);
}
// save .htaccess
if (false !== $saved) {
$f = @fopen('.htaccess', 'w');
if ($f) {
$saved = fputs($f, $htaccess);
fclose($f);
} else {
$saved = false;
}
}
if (false !== $saved) {
$msg = $lang['L_HTACC_CREATED'];
$tplHomeProtectionCreate->assign_block_vars(
'CREATE_SUCCESS',
array(
'HTACCESS' => nl2br(Html::replaceQuotes($htaccess)),
'HTPASSWD' => nl2br(Html::replaceQuotes($htpasswd))
)
);
@chmod($config['paths']['root'], 0755);
} else {
$tplHomeProtectionCreate->assign_block_vars(
'CREATE_ERROR',
array(
'HTACCESS' => Html::replaceQuotes($htaccess),
'HTPASSWD' => Html::replaceQuotes($htpasswd)
)
);
}
}
}
if (sizeof($error) > 0 || !isset($_POST['username'])) {
$tplHomeProtectionCreate->assign_vars(
array(
'PASSWORDS_UNEQUAL' =>
Html::getJsQuote($lang['L_PASSWORDS_UNEQUAL']),
'HTACC_CONFIRM_DELETE' =>
Html::getJsQuote($lang['L_HTACC_CONFIRM_DELETE'])
)
);
$tplHomeProtectionCreate->assign_block_vars(
'INPUT',
array(
'USERNAME' => Html::replaceQuotes($username),
'USERPASS1' => Html::replaceQuotes($userpassOne),
'USERPASS2' => Html::replaceQuotes($userpassConfirm),
'TYPE0_CHECKED' => Html::getChecked($type, 0),
'TYPE1_CHECKED' => Html::getChecked($type, 1),
'TYPE2_CHECKED' => Html::getChecked($type, 2),
'TYPE3_CHECKED' => Html::getChecked($type, 3)
)
);
}
if (!empty($error)) {
$msg = '<span class="error">' . implode('<br />', $error) . '</span>';
}
if ($msg > '') {
$tplHomeProtectionCreate->assign_block_vars(
'MSG', array('TEXT' => $msg)
);
}

Datei anzeigen

@ -0,0 +1,17 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
@unlink($config['paths']['root'] . '.htaccess');
@unlink($config['paths']['root'] . '.htpasswd');
$action = 'status';
//TODO -> give user info about success or failure of deleting action

57
inc/home/protection_edit.php Normale Datei
Datei anzeigen

@ -0,0 +1,57 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/define_icons.php');
$hta = '';
$tplHomeProtectionEdit = new MSDTemplate();
$tplHomeProtectionEdit->set_filenames(
array('tplHomeProtectionEdit' => 'tpl/home/protection_edit.tpl')
);
if (isset($_POST['hta_content'])) {
if ($fp = fopen('./.htaccess', 'w')) {
if (fwrite($fp, $_POST['hta_content'])) {
$tplHomeProtectionEdit->assign_block_vars(
'HTA_SAVED_SUCCESSFULLY', array()
);
} else {
$tplHomeProtectionEdit->assign_block_vars(
'HTA_SAVED_UNSUCCESSFULLY', array()
);
}
fclose($fp);
} else {
$tplHomeProtectionEdit->assign_block_vars(
'ERROR_OPENING_HTACCESS', array()
);
}
}
if (file_exists('./.htaccess') && is_readable('./.htaccess')) {
$hta = implode('', file('./.htaccess'));
} else {
$tplHomeProtectionEdit->assign_block_vars(
'ERROR_OPENING_HTACCESS', array()
);
}
$tplHomeProtectionEdit->assign_vars(
array(
'HTA_CONTENT' => htmlspecialchars($hta, ENT_COMPAT, 'UTF-8'),
'ICON_SEARCH' => $icon['search'],
'ICON_OPEN_FILE' => $icon['small']['open_file'],
'ICON_SAVE' => $icon['small']['save'],
'ICON_DELETE' => $icon['delete'],
'ICON_ARROW_LEFT' => $icon['arrow_left']
)
);

133
inc/log.php Normale Datei
Datei anzeigen

@ -0,0 +1,133 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
include ('./inc/define_icons.php');
$logType = (isset($_GET['log'])) ? $_GET['log'] : Log::PHP;
$revers = (isset($_GET['revers'])) ? $_GET['revers'] : 1;
$offset = (isset($_GET['offset'])) ? $_GET['offset'] : 0;
$entriesShown = 25;
// define template
$tplLog = new MSDTemplate();
$tplLog->set_filenames(array('tplLog' => 'tpl/log/log.tpl'));
//Delete log
if (isset($_GET['delete_log'])) {
$log->delete($logType);
// switch back to standard log - other log file was deleted
$logType = Log::PHP;
}
// get log filename to show
$lfile = $log->getLogfile($logType);
// if PHP-Log doesn't exists for any reason -> create it
if (!file_exists($lfile) && $logType == 0) $log->delete($config['files']['log'], true);
$loginfo = array();
$sum = $loginfo['log_size'] = $loginfo['perllog_size'] = 0;
$loginfo['perllogcomplete_size'] = 0;
$loginfo['errorlog_size'] = $loginfo['log_totalsize'] = 0;
if ($config['logcompression'] == 1) {
$loginfo['log'] = $config['files']['log'] . ".gz";
$loginfo['perllog'] = $config['files']['perllog'] . ".gz";
$loginfo['perllogcomplete'] = $config['files']['perllogcomplete'] . ".gz";
$loginfo['errorlog'] = $config['paths']['log'] . "error.log.gz";
} else {
$loginfo['log'] = $config['files']['log'];
$loginfo['perllog'] = $config['files']['perllog'];
$loginfo['perllogcomplete'] = $config['files']['perllogcomplete'];
$loginfo['errorlog'] = $config['paths']['log'] . "error.log";
}
$loginfo['log_size'] += @filesize($loginfo['log']);
$sum += $loginfo['log_size'];
$loginfo['perllog_size'] += @filesize($loginfo['perllog']);
$sum += $loginfo['perllog_size'];
$loginfo['perllogcomplete_size'] += @filesize($loginfo['perllogcomplete']);
$sum += $loginfo['perllogcomplete_size'];
$loginfo['errorlog_size'] += @filesize($loginfo['errorlog']);
$sum += $loginfo['errorlog_size'];
$loginfo['log_totalsize'] += $sum;
$tplLog->assign_vars(
array(
'ICON_VIEW' => $icon['view'],
'ICON_OPEN_FILE' => $icon['open_file'],
'ICON_DELETE' => $icon['delete'],
'ICON_ARROW_DOWN' => $icon['arrow_down'],
'ICON_ARROW_UP' => $icon['arrow_up'],
'ICON_SORT' => $revers == 0 ? $icon['arrow_up'] : $icon['arrow_down'],
'SORT_ORDER' => $revers == 0 ? 1 : 0,
'LOG' => str_replace($config['paths']['log'], '', $lfile))
);
$tplLog->assign_vars(
array(
'LOGPATH' => $config['paths']['log'],
'PHPLOG' => str_replace($config['paths']['log'], '', $loginfo['log']),
'PHPLOG_SIZE' => byteOutput($loginfo['log_size']))
);
if (@file_exists($loginfo['errorlog'])) {
$outErrLog = str_replace($config['paths']['log'], '', $loginfo['errorlog']);
$tplLog->assign_block_vars(
'ERRORLOG', array(
'ERRORLOG' => $outErrLog,
'SIZE' => byteOutput($loginfo['errorlog_size']))
);
} else {
$tplLog->assign_vars(
array('ERRORLOG_DISABLED' => Html::getDisabled(true, true))
);
}
if (@file_exists($loginfo['perllog'])) {
$perl = str_replace($config['paths']['log'], '', $loginfo['perllog']);
$tplLog->assign_block_vars(
'PERLLOG',
array(
'FILE_NAME' => $perl,
'SIZE' => byteOutput($loginfo['perllog_size']))
);
} else {
$tplLog->assign_vars(
array(
'PERLLOG_DISABLED' => Html::getDisabled(true, true))
);
}
if (@file_exists($loginfo['perllogcomplete'])) {
$perlComplete = str_replace(
$config['paths']['log'],
'',
$loginfo['perllogcomplete']
);
$tplLog->assign_block_vars(
'PERLCOMPLETELOG',
array(
'FILE_NAME' => $perlComplete,
'SIZE' => byteOutput($loginfo['perllogcomplete_size']))
);
} else {
$tplLog->assign_vars(
array(
'PERLCOMPLETELOG_DISABLED' => Html::getDisabled(true, true))
);
}
$tplLog->assign_vars(
array(
'LOG_TYPE' => $logType,
'LOGSIZE_TOTAL' => byteOutput($loginfo['log_totalsize']),
'REVERS' => $revers)
);
unset($lfile);

151
inc/menu.php Normale Datei
Datei anzeigen

@ -0,0 +1,151 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
include ('./language/lang_list.php');
$langOld = $config['language'];
// define template
$tplMenu = new MSDTemplate();
$tplMenu->set_filenames(array('tplMenu' => 'tpl/menu/menu.tpl'));
$tplMenu->assign_vars(
array(
'PAGE' => $p,
'ACTION_SET' => $action > '' ? '&amp;action=' . $action : '',
'MSD_VERSION' => MSD_VERSION . ' (' . MSD_VERSION_SUFFIX . ')',
'CONFIG_HOMEPAGE' => $config['homepage'],
'CONFIG_THEME' => $config['theme'],
'CONFIG_FILE' => $config['config_file']
)
);
// set picture according to mode
if ($config['msd_mode'] == 0) {
$tplMenu->assign_block_vars('MSD_MODE_EASY', array());
} else {
$tplMenu->assign_block_vars('MSD_MODE_EXPERT', array());
}
if (isset($_POST['selected_config']) || isset($_GET['config'])) {
// Configuration was switched in menu frame
if (isset($_POST['selected_config'])) {
$newConfig = $_POST['selected_config'];
}
if (is_readable($config['paths']['config'] . $newConfig . '.php')) {
clearstatcache();
unset($databases);
$databases = array();
if (getConfig($newConfig)) {
$config['config_file'] = $newConfig;
$_SESSION['config_file'] = $newConfig;
$tplMenu->assign_vars(
array('CONFIG_FILE' => urlencode($newConfig))
);
$p = 'config'; // switch to configuration page
// hand over message to config page
$msg = sprintf($lang['L_CONFIG_LOADED'], $config['config_file']);
$msg = Html::getOkMsg($msg);
}
}
}
// show Server caption?
if ($config['interface_server_caption'] == 1) {
$tplMenu->assign_block_vars(
'SHOW_SERVER_CAPTION',
array(
'KIND' => $config['interface_server_caption_position'],
'LINK' => getServerProtocol() . $_SERVER['SERVER_NAME'],
'NAME' => $_SERVER['SERVER_NAME']
)
);
}
if (isset($_GET['dbrefresh'])) {
// remember the name of the selected database
$oldDbName = $config['db_actual'];
if (isset($_GET['db_name'])) {
// new db created -> switch to it
$oldDbName = base64_decode($_GET['db_name']);
}
setDefaultConfig();
// lets lookup if the old database is still there
if (isset($databases[$oldDbName])) {
$dbo->selectDb($oldDbName);
} else {
$dbo->selectDb($dbo->databases[0]);
}
ksort($databases);
$_SESSION['databases'] = $databases;
}
if (isset($_POST['dbindex']) || isset($_GET['dbindex'])) {
if (isset($_POST['dbindex'])) {
$dbName = $_POST['dbindex'];
}
if (isset($_GET['dbindex'])) {
$dbName = $_GET['dbindex'];
}
$dbName = base64_decode($dbName);
$config['db_actual'] = $dbName;
$dbo->selectDb($dbName);
saveConfig();
}
$tplMenu->assign_var('GET_FILELIST', getConfigFilelist($config['config_file']));
if (count($databases) > 0) {
// show menu items related to databases
$tplMenu->assign_block_vars('MAINTENANCE', array());
$tplMenu->assign_vars(
array('DB_ACTUAL_URLENCODED' => base64_encode($config['db_actual']))
);
ksort($databases);
$tplMenu->assign_block_vars('DB_LIST', array());
foreach ($databases as $dbName => $val) {
$selected = Html::getSelected($dbName, $config['db_actual']);
$tplMenu->assign_block_vars(
'DB_LIST.DB_ROW', array(
'ID' => base64_encode($dbName),
'NAME' => $dbName,
'SELECTED' => $selected)
);
}
} else {
$tplMenu->assign_block_vars('NO_DB_FOUND', array());
}
$tplMenu->assign_vars(array('TIMESTAMP' => time()));
if (count($databases) == 0) {
$tplMenu->assign_block_vars('DB_NAME_TRUE', array());
} else {
$tplMenu->assign_block_vars('DB_NAME_FALSE', array());
}
// PayPal-Button - show German or English one?
if (in_array($config['language'], array('de', 'de_du', 'ch'))) {
$tplMenu->assign_block_vars('PAYPAL_DEUTSCH', array());
} else {
$tplMenu->assign_block_vars('PAYPAL_ENGLISH', array());
}
// set class for active menuitem
$filesActive = ($p == 'files' && $action != 'dump' && $action != 'restore');
$restoreActive = $p == 'restore' || $action =='restore';
$tplMenu->assign_vars(
array(
'HOME_ACTIVE' => $p == 'home' ? ' class="active"' : '',
'CONFIG_ACTIVE' => $p == 'config' ? ' class="active"' : '',
'DUMP_ACTIVE' => $p == 'dump' ? ' class="active"' : '',
'RESTORE_ACTIVE' => $restoreActive ? ' class="active"' : '',
'FILES_ACTIVE' => $filesActive ? ' class="active"' : '',
'SQL_ACTIVE' => $p == 'sql' ? ' class="active"' : '',
'LOG_ACTIVE' => $p == 'log' ? ' class="active"' : ''
)
);

225
inc/mysql.php Normale Datei
Datei anzeigen

@ -0,0 +1,225 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$sql_keywords = array(
'ALTER',
'AND',
'ADD',
'AUTO_INCREMENT',
'BETWEEN',
'BINARY',
'BOTH',
'BY',
'BOOLEAN',
'CHANGE',
'CHARSET',
'CHECK',
'COLLATE',
'COLUMNS',
'COLUMN',
'CROSS',
'CREATE',
'DATABASES',
'DATABASE',
'DATA',
'DELAYED',
'DESCRIBE',
'DESC',
'DISTINCT',
'DELETE',
'DROP',
'DEFAULT',
'ENCLOSED',
'ENGINE',
'ESCAPED',
'EXISTS',
'EXPLAIN',
'FIELDS',
'FIELD',
'FLUSH',
'FOR',
'FOREIGN',
'FUNCTION',
'FROM',
'GROUP',
'GRANT',
'HAVING',
'IGNORE',
'INDEX',
'INFILE',
'INSERT',
'INNER',
'INTO',
'IDENTIFIED',
'JOIN',
'KEYS',
'KILL',
'KEY',
'LEADING',
'LIKE',
'LIMIT',
'LINES',
'LOAD',
'LOCAL',
'LOCK',
'LOW_PRIORITY',
'LEFT',
'LANGUAGE',
'MEDIUMINT',
'MODIFY',
'MyISAM',
'NATURAL',
'NOT',
'NULL',
'NEXTVAL',
'OPTIMIZE',
'OPTION',
'OPTIONALLY',
'ORDER',
'OUTFILE',
'OR',
'OUTER',
'ON',
'PROCEEDURE',
'PROCEDURAL',
'PRIMARY',
'READ',
'REFERENCES',
'REGEXP',
'RENAME',
'REPLACE',
'RETURN',
'REVOKE',
'RLIKE',
'RIGHT',
'SHOW',
'SONAME',
'STATUS',
'STRAIGHT_JOIN',
'SELECT',
'SETVAL',
'TABLES',
'TEMINATED',
'TO',
'TRAILING',
'TRUNCATE',
'TABLE',
'TEMPORARY',
'TRIGGER',
'TRUSTED',
'UNIQUE',
'UNLOCK',
'USE',
'USING',
'UPDATE',
'UNSIGNED',
'VALUES',
'VARIABLES',
'VIEW',
'WITH',
'WRITE',
'WHERE',
'ZEROFILL',
'XOR',
'ALL',
'ASC',
'AS',
'SET',
'IN',
'IS',
'IF');
$mysql_SQLhasRecords = array(
'SELECT',
'SHOW',
'EXPLAIN',
'DESCRIBE',
'DESC');
function GetMySQLVersion()
{
global $dbo;
$version=$dbo->getServerInfo();
if (!defined('MSD_MYSQL_VERSION')) define('MSD_MYSQL_VERSION', $version);
$versions = explode('.', $version);
$new = false;
if ($versions[0] == 4 && $versions[1] >= 1) $new = true;
if ($versions[0] > 4) $new = true;
if (!defined('MSD_NEW_VERSION')) define('MSD_NEW_VERSION', $new);
return $version;
}
function SQLError($sql, $error, $return_output = false)
{
//v(debug_backtrace());
global $lang;
$ret = '<div align="center"><table style="border:1px solid #ff0000" cellspacing="0">
<tr bgcolor="#ff0000"><td style="color:white;font-size:16px;"><strong>MySQL-ERROR</strong></td></tr>
<tr><td style="width:80%;overflow: auto;">' . $lang['L_SQL_ERROR2'] . '<br /><span style="color:red;">' . $error . '</span></td></tr>';
if ($sql > '')
{
$ret .= '<tr><td width="600"><br />' . $lang['L_SQL_ERROR1'] . '<br />' . Highlight_SQL($sql) . '</td></tr>';
}
$ret .= '</table></div>';
if ($return_output) return $ret;
else echo $ret;
}
function Highlight_SQL($sql)
{
global $sql_keywords;
$end = '';
$tickstart = false;
if (function_exists("token_get_all")) $a = @token_get_all("<?$sql?>");
else return $sql;
foreach ($a as $token)
{
if (!is_array($token))
{
if ($token == '`') $tickstart = !$tickstart;
$end .= $token;
}
else
{
if ($tickstart) $end .= $token[1];
else
{
switch (token_name($token[0]))
{
case "T_STRING":
case "T_AS":
case "T_FOR":
$end .= (in_array(strtoupper($token[1]), $sql_keywords)) ? "<span style=\"color:#990099;font-weight:bold;\">" . $token[1] . "</span>" : $token[1];
break;
case "T_IF":
case "T_LOGICAL_AND":
case "T_LOGICAL_OR":
case "T_LOGICAL_XOR":
$end .= (in_array(strtoupper($token[1]), $sql_keywords)) ? "<span style=\"color:#0000ff;font-weight:bold;\">" . $token[1] . "</span>" : $token[1];
break;
case "T_CLOSE_TAG":
case "T_OPEN_TAG":
break;
default:
$end .= $token[1];
}
}
}
}
$end = preg_replace("/`(.*?)`/si", "<span style=\"color:red;\">`$1`</span>", $end);
return $end;
}

19
inc/restore.php Normale Datei
Datei anzeigen

@ -0,0 +1,19 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
include ('./inc/functions/functions_restore.php');
include ('./inc/functions/functions_files.php');
include ('./inc/define_icons.php');
if ($action == 'done') {
include('./inc/restore/restore_finished.php');
} else {
include('./inc/restore/restore_start.php');
}

Datei anzeigen

@ -0,0 +1,91 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: $
* @author $Author$
* @lastmodified $Date$
*/
// Restore is finished
include ('./inc/define_icons.php');
$restore = $_SESSION['restore'];
$tplRestoreFinished = new MSDTemplate();
$tplRestoreFinished->set_filenames(
array('tplRestoreFinished' => 'tpl/restore/restore_finished.tpl')
);
$recordsInserted = String::formatNumber($restore['records_inserted']);
$recordsInserted = sprintf($lang['L_RECORDS_INSERTED'], $recordsInserted);
$tablesCreated = sprintf(
$lang['L_RESTORE_COMPLETE'], $restore['table_ready']
);
$timeElapsed = getTimeFormat(time() - $restore['restore_start_time']);
$tplRestoreFinished->assign_vars(
array(
'SESSION_ID' => session_id(),
'ICON_OPEN_FILE' => $icon['small']['open_file'],
'ICON_EDIT' => $icon['small']['edit'],
'ICON_VIEW' => $icon['small']['view'],
'SESSION_ID' => session_id(),
'BACKUPPATH' => $config['paths']['backup'],
'PAGE_REFRESHS' => $restore['page_refreshs'],
'TIME_ELAPSED' => $timeElapsed,
'TABLES_CREATED' => $tablesCreated,
'RECORDS_INSERTED' => $recordsInserted,
'ICONPATH' => $config['files']['iconpath']
)
);
if (count($_SESSION['log']['errors']) > 0) {
$i = 1;
$tplRestoreFinished->assign_block_vars('ERRORS', array());
foreach ($_SESSION['log']['errors'] as $logError) {
$timestamp = substr($logError, 0, 19);
$message = substr($logError, 20);
$tplRestoreFinished->assign_block_vars(
'ERRORS.ERROR',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'TIMESTAMP' => $timestamp,
'MSG' => $message
)
);
$i++;
}
}
$i = 1;
foreach ($_SESSION['log']['actions'] as $logAction) {
$timestamp = substr($logAction, 0, 19);
$message = substr($logAction, 20);
$tplRestoreFinished->assign_block_vars(
'ACTION',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'TIMESTAMP' => $timestamp,
'ACTION' => $message
)
);
$i++;
}
$i = 1;
if (count($_SESSION['log']['notices']) > 0) {
$tplRestoreFinished->assign_block_vars('NOTICES', array());
foreach ($_SESSION['log']['notices'] as $logAction) {
$timestamp = substr($logAction, 0, 19);
$message = substr($logAction, 20);
$tplRestoreFinished->assign_block_vars(
'NOTICES.NOTICE',
array(
'NR' => $i,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'TIMESTAMP' => $timestamp,
'NOTICE' => $message
)
);
$i++;
}
}

Datei anzeigen

@ -0,0 +1,250 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/define_icons.php');
$msg = '';
$showFilelist = true;
// call after selecting tables to restore
//-> save selection and head over to restore.php
if (isset($_POST['restore_tbl'])) {
echo '<script type="text/javascript">'
. 'location.href="index.php?p=restore&filename='
. urlencode($_POST['filename']) . '";</script></body></html>';
exit();
}
if (isset($_POST['restore'])) {
if (isset($_POST['file'])) {
if (isset($_POST['select_tables']) && $_POST['select_tables'] == 1) {
// select tables to restore
include ('./inc/restore/select_tables.php');
$showFilelist = false;
} else {
$encodingFound = true;
$file = $_POST['file'][0];
$statusline = readStatusline($file);
if (isset($_POST['sel_dump_encoding_restore'])) {
// encoding of file was selected -> we can start
$dumpEncoding = $_POST['sel_dump_encoding_restore'];
} else {
if (!isset($statusline['charset'])
|| trim($statusline['charset']) == '?') {
// unknown encoding of a file not created by MySQLDumper
// -> ask user what encoding should be used
$charsets = $dbo->getCharsets();
foreach ($charsets as $name => $val) {
$charsetsDescription[$name] = $name . ' - '
. $val['Description'];
}
$tplRestoreSelectEncoding = new MSDTemplate();
$tplRestoreSelectEncoding->set_filenames(
array(
'tplRestoreSelectEncoding' =>
'tpl/restore/file_select_encoding.tpl'
)
);
$encSelect = Html::getOptionlist(
$charsetsDescription, 'utf8'
);
$tplRestoreSelectEncoding->assign_vars(
array(
'PAGETITLE' => $lang['L_FM_RESTORE'] . ': ' . $file,
'DATABASE' => $config['db_actual'],
'ENCODING_SELECT' => $encSelect,
'FILE_NAME' => $file
)
);
$encodingFound = false;
} else {
// file was created by MySQLDumper ->
// get encoding from statusline
$dumpEncoding = $statusline['charset'];
}
}
if ($encodingFound) {
echo '<script type="text/javascript">'
.'location.href="index.php?p=restore&filename='
. urlencode($file) . '&dump_encoding='
. urlencode($dumpEncoding) . '";</script></body></html>';
obend();
}
}
$showFilelist = false;
} else {
$msg .= Html::getErrorMsg($lang['L_FM_NOFILE']);
}
}
if ($showFilelist) {
// Reset Session
$_SESSION['restore'] = array();
$restore = array();
$tplRestorePrepare = new MSDTemplate();
$tplRestorePrepare->set_filenames(
array('tplRestorePrepare' => 'tpl/restore/restorePrepare.tpl')
);
$dbactualOutput = $dbactive;
if ($dbactive == '~unknown') {
$dbactualOutput = '<i>' . $lang['L_UNKNOWN'] . '</i>';
}
if ($dbactive == '~converted') {
$dbactualOutput = '<i>' . $lang['L_CONVERTED_FILES'] . '</i>';
}
$pageTitle = sprintf($lang['L_FM_RESTORE_HEADER'], $config['db_actual']);
$tplRestorePrepare->assign_vars(
array(
'SESSION_ID' => session_id(),
'PAGETITLE' => $pageTitle,
'DB_ACTUAL' => $config['db_actual'],
'DB_ACTIVE' => $dbactualOutput,
)
);
if ($msg > '') $tplRestorePrepare->assign_block_vars(
'MESSAGE', array('TEXT' => Html::getJsQuote($msg, true))
);
// get info of all backup files
$backups = getBackupfileInfo();
if (!isset($backups['databases'][$dbactive])) {
$tplRestorePrepare->assign_block_vars('NO_FILE_FOUND', array());
}
$i = 0;
// show detailed file info of the selected database at top
foreach ($backups['files'] as $backup) {
if ($backup['db'] == $dbactive) {
$compressed = '-';
if (substr($backup['name'], -3) == '.gz') {
$compressed = $icon['gz'];
}
$dbName = $backup['name'];
if (!in_array($backup['db'], array('~unknown', '~converted'))) {
$dbName = $backup['db'];
}
$scriptVersion = $lang['L_UNKNOWN'];
if ($backup['script'] > '') {
$scriptVersion = $backup['script'];
}
$comment ='&nbsp;';
if ($backup['comment'] > '') {
$comment = nl2br(wordwrap($backup['comment'], 50));
}
$nrOfTables = $lang['L_UNKNOWN'];
if ($backup['tables'] > -1) {
$nrOfTables = String::formatNumber($backup['tables']);
}
$nrOfRecords = $lang['L_UNKNOWN'];
if ($backup['records'] > -1) {
$nrOfRecords = String::formatNumber($backup['records']);
}
$fileCharset = $lang['L_UNKNOWN'];
if ($backup['charset'] != '?') {
$fileCharset = $backup['charset'];
}
$tplRestorePrepare->assign_block_vars(
'FILE',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'FILE_INDEX' => $i,
'FILE_NAME' => $backup['name'],
'DB_NAME' => $dbName,
'DB_EXPAND_LINK' => $backup['db'],
'ICON_COMPRESSED' => $compressed,
'SCRIPT_VERSION' => $scriptVersion,
'COMMENT' => $comment,
'FILE_CREATION_DATE' => $backup['date'],
'NR_OF_TABLES' => $nrOfTables,
'NR_OF_RECORDS' => $nrOfRecords,
'FILESIZE' => byteOutput($backup['size']),
'FILE_CHARSET' => $fileCharset,
'NR_OF_MULTIPARTS' => $backup['multipart']
)
);
if ($backup['multipart'] > 0) {
$fileCount = $lang['L_FILES'];
if ($backup['multipart'] == 1) {
$fileCount = $lang['L_FILE'];
}
$tplRestorePrepare->assign_block_vars(
'FILE.IS_MULTIPART', array('FILES' => $fileCount)
);
} else {
$tplRestorePrepare->assign_block_vars(
'FILE.NO_MULTIPART', array()
);
}
$i++;
}
}
// list summary of other backup files grouped by databases
ksort($backups['databases']);
if (count($backups['databases']) > 0) {
$i = 0;
foreach ($backups['databases'] as $db => $info) {
$rowclass = $i % 2 ? 'dbrow' : 'dbrow1';
if ($db == $dbactive) $rowclass = 'dbrowsel';
$dbNameOutput = $db;
if ($db == '~unknown') {
$dbNameOutput = '<i>' . $lang['L_NO_MSD_BACKUPFILE'] . '</i>';
}
if ($db == '~converted') {
$dbNameOutput = '<i>' . $lang['L_CONVERTED_FILES'] . '</i>';
}
$nrOfBackups = '-';
if (isset($info['backup_count'])) {
$nrOfBackups = $info['backup_count'];
}
$latestBackup = '';
if (isset($info['latest_backup_timestamp'])) {
$latestBackup = $info['latest_backup_timestamp'];
}
$sumSize = 0;
if (isset($info['backup_size_total'])) {
$sumSize = byteOutput($info['backup_size_total']);
}
$tplRestorePrepare->assign_block_vars(
'DB',
array(
'ROWCLASS' => $rowclass,
'DB_NAME_LINK' => $db,
'DB_NAME' => $dbNameOutput,
'NR_OF_BACKUPS' => $nrOfBackups,
'LATEST_BACKUP' => $latestBackup,
'SUM_SIZE' => $sumSize
)
);
$i++;
}
}
$tplRestorePrepare->assign_vars(
array(
'ICON_VIEW' => $icon['view'],
'ICON_RESTORE' => $icon['restore'],
'SUM_SIZE' => byteOutput($backups['filesize_total']),
'NOTIFICATION_POSITION' => $config['notification_position']
)
);
$_SESSION['restore'] = $restore;
$_SESSION['log'] = array();
$_SESSION['log']['actions'] = array();
$_SESSION['log']['errors'] = array();
$_SESSION['log']['notices'] = array();
}

148
inc/restore/restore_start.php Normale Datei
Datei anzeigen

@ -0,0 +1,148 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: $
* @author $Author$
* @lastmodified $Date$
*/
// start the magic
if (isset($_GET['filename']) || isset($_POST['filename'])) {
// first call -> set defaults
getConfig();
$restore = $_SESSION['restore'];
$restore['filename'] = '';
if (isset($_POST['filename'])) {
$restore['filename'] = urldecode($_POST['filename']);
}
if (isset($_GET['filename'])) {
$restore['filename'] = urldecode($_GET['filename']);
}
$restore['compressed'] = 0;
if (substr(strtolower($restore['filename']), -2) == 'gz') {
$restore['compressed'] = 1;
}
$restore['dump_encoding'] = 'utf8';
if (isset($_POST['sel_dump_encoding'])) {
$restore['dump_encoding'] = $_POST['sel_dump_encoding'];
}
if (isset($_GET['dump_encoding'])) {
$restore['dump_encoding'] = $_GET['dump_encoding'];
}
$restore['part'] = 0;
// Read Statusline of file
$sline = readStatusline($restore['filename']);
// if it is a backup done by MSD we get the charset from the statusline
if (isset($sline['charset']) && $sline['charset']!='?') {
$restore['dump_encoding'] = $sline['charset'];
}
// init some values
$restore['tables_total'] = $sline['tables'];
$restore['records_total'] = $sline['records'];
if ($sline['part'] != 'MP_0') $restore['part'] = 1;
if ($config['empty_db_before_restore'] == 1) {
truncateDb($config['db_actual']);
}
$restore['max_zeit'] = intval(
$config['max_execution_time'] * $config['time_buffer']
);
$restore['restore_start_time'] = time();
$restore['speed'] = $config['minspeed'];
$restore['restore_start_time'] = time();
$restore['fileEOF'] = false;
$restore['actual_table'] = '';
$restore['offset'] = 0;
$restore['page_refreshs'] = 0;
$restore['table_ready'] = 0;
$restore['errors'] = 0;
$restore['notices'] = 0;
$restore['actual_fieldcount'] = 0;
$restore['records_inserted'] = 0;
$restore['records_inserted_table'] = array();
$restore['extended_inserts'] = 0;
$restore['extended_insert_flag'] = -1;
$restore['last_parser_status'] = 0;
$restore['EOB'] = false;
$restore['fileEOF'] = false;
$restore['file_progress_percent'] = 0;
$restore['tables_to_restore'] = false; // restore complete file
// Should we restore the complete file or are only some tables selected ?
if (isset($_POST['sel_tbl'])) {
$restore['tables_to_restore'] = $_POST['sel_tbl'];
//correct the nr of tables and total records to restore
$restore['tables_total'] = 0;
$restore['records_total'] = 0;
$tabledata = getTableHeaderInfoFromBackup($restore['filename']);
foreach ($tabledata as $key => $val) {
if (in_array($val['name'], $restore['tables_to_restore'])) {
$restore['tables_total']++;
$restore['records_total'] += $val['records'];
}
}
}
$_SESSION['config'] = $config;
$_SESSION['databases'] = $databases;
$_SESSION['restore'] = $restore;
$logMsg = sprintf(
$lang['L_START_RESTORE_DB_FILE'],
$config['db_actual'],
$restore['filename']
);
$log->write(Log::PHP, $logMsg);
} else {
$config = $_SESSION['config'];
$databases = $_SESSION['databases'];
$restore = $_SESSION['restore'];
}
// tables to create
$tablesDone = 0;
if ($restore['table_ready'] > 0) {
$tablesDone = $restore['table_ready'];
}
if ($restore['tables_total'] > 0) {
$tablesToDo = $restore['tables_total'];
} else {
$tablesToDo = $lang['L_UNKNOWN'];
}
if ($restore['tables_total'] > 0) {
$tablesToCreate = sprintf(
$lang['L_RESTORE_TABLES_COMPLETED'],
$tablesDone,
$tablesToDo
);
} else {
$tablesToCreate = sprintf(
$lang['L_RESTORE_TABLES_COMPLETED0'], $tablesDone
);
}
$tplRestore = new MSDTemplate();
$tplRestore->set_filenames(array('tplRestore' => 'tpl/restore/restore.tpl'));
$restoringDb = sprintf(
$lang['L_RESTORE_DB'], $config['db_actual'], $config['dbhost']
);
$tplRestore->assign_vars(
array(
'SESSION_ID' => session_id(),
'ICONPATH' => $config['files']['iconpath'],
'ICON_PLUS' => $icon['plus'],
'DB_ON_SERVER' => $restoringDb,
'FILENAME' => $restore['filename'],
'CHARSET' => $restore['dump_encoding'],
'TABLES_TO_CREATE' => $tablesToCreate,
'NOTIFICATION_POSITION' => $config['notification_position']
)
);
if ($restore['part'] > 0) {
$tplRestore->assign_block_vars(
'MULTIPART',
array('PART' => $restore['part'])
);
}
$_SESSION['restore'] = $restore;

Datei anzeigen

@ -0,0 +1,63 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$fileName = (isset($_GET['filename'])) ? urldecode($_GET['filename']) : '';
if (isset($_POST['file'][0])) {
$fileName = $_POST['file'][0];
}
$tplRestoreSelectTables = new MSDTemplate();
$tplRestoreSelectTables->set_filenames(
array('tplRestoreSelectTables' => 'tpl/restore/selectTables.tpl')
);
//Get Header-Infos from file
$sline = readStatusline($fileName);
if ($sline['records'] == -1) {
// not a backup of MySQLDumper
$tplRestoreSelectTables->assign_block_vars('NO_MSD_BACKUP', array());
} else {
// Get Tableinfo from file header
$tabledata = getTableHeaderInfoFromBackup($fileName);
for ($i = 0; $i < sizeof($tabledata); $i++) {
$klasse = ($i % 2) ? 1 : '';
$tplRestoreSelectTables->assign_block_vars(
'ROW',
array(
'CLASS' => 'dbrow' . $klasse,
'ID' => $i,
'NR' => $i + 1,
'TABLENAME' => $tabledata[$i]['name'],
'RECORDS' => String::formatNumber($tabledata[$i]['records']),
'SIZE' => byteOutput($tabledata[$i]['size']),
'LAST_UPDATE' => $tabledata[$i]['update'],
'TABLETYPE' => $tabledata[$i]['engine']
)
);
}
}
$confirmRestore = $lang['L_FM_ALERTRESTORE1'] . ' `' . $config['db_actual']
. '` ' . $lang['L_FM_ALERTRESTORE2'] . ' ' . $fileName . ' '
. $lang['L_FM_ALERTRESTORE3'];
$tplRestoreSelectTables->assign_vars(
array(
'PAGETITLE' => $lang['L_RESTORE'] . ' - ' . $lang['L_TABLESELECTION'],
'DATABASE' => $config['db_actual'],
'FILENAME' => $fileName,
'ICON_OK' => $icon['ok'],
'ICON_DELETE' => $icon['delete'],
'ICON_RESTORE' => $icon['restore'],
'L_NO_MSD_BACKUP' => $lang['L_NOT_SUPPORTED'],
'CONFIRM_RESTORE' => $confirmRestore
)
);

229
inc/runtime.php Normale Datei
Datei anzeigen

@ -0,0 +1,229 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
define('MSD_VERSION', '1.25');
define('MSD_VERSION_SUFFIX', 'dev');
if (!defined('MSD_VERSION')) die('No direct access.');
@ini_set('display_errors', 'On');
// Output all errors - we want to know everything that could go wrong. ;)
error_reporting(E_ALL);
if (function_exists("date_default_timezone_set")) {
date_default_timezone_set('Europe/Berlin');
}
define('MSD_OS', PHP_OS);
define('MSD_OS_EXT', @php_uname());
define('MULTIPART_FILESIZE_BUFFER', 10 * 1024);
$config = array();
$databases = array();
$tableInfos = array();
$lang = array();
if (!isset($_SESSION['config']) || isset($install)) {
// set configuration default values if page is loaded the first time or
// while installation is running
// will be overwritten by saved values in configuration profile if present
// this way we make double sure all values are defined
if (isset($_SESSION['config'])) {
$config = $_SESSION['config'];
}
$config['msd_mode'] = 0; // 0=easy, 1=expert
$config['paths'] = array();
$config['files'] = array();
$config['paths']['root'] = myRealpath();
define('MSD_PATH', $config['paths']['root']);
$config['paths']['work'] = 'work/';
$config['paths']['backup'] = $config['paths']['work'] . 'backup/';
$config['paths']['log'] = $config['paths']['work'] . 'log/';
$config['paths']['config'] = $config['paths']['work'] . 'config/';
$config['paths']['perlexec'] = 'msd_cron/';
$config['files']['log'] = $config['paths']['log'] . 'mysqldump.log';
$config['files']['perllog'] = $config['paths']['log'] . 'mysqldump_perl.log';
$config['files']['perllogcomplete'] =
$config['paths']['log'] . 'mysqldump_perl.complete.log';
$config['config_file'] = 'mysqldumper';
$config['theme'] = 'msd';
// gui related values
// show server caption
$config['interface_server_caption'] = 1;
// show server caption in main frame
$config['interface_server_caption_position'] = 0;
//Height of the SQL-Box in SQLBrowser in pixel
$config['interface_sqlboxsize'] = 70;
// don't use compact view when showing data or tables
$config['interface_table_compact'] = 0;
// don't auto delete backup files automatically. User must turn on this
$config['auto_delete'] = 0;
$config['refresh_processlist'] = 3;
$config['notification_position'] = 'mc';
$config['resultsPerPage']=30;
// Multipart
$config['multi_part'] = 0;
$config['multipartgroesse1'] = 1;
$config['multipartgroesse2'] = 2;
// set first ftp-connection
$config['ftp'] = array();
$config['ftp'][0]['server'] = '';
$config['ftp'][0]['user'] = '';
$config['ftp'][0]['transfer'] = 0;
$config['ftp'][0]['timeout'] = 10;
$config['ftp'][0]['mode'] = 0;
$config['ftp'][0]['ssl'] = 0;
$config['ftp'][0]['port'] = 21;
$config['ftp'][0]['pass'] = '';
$config['ftp'][0]['dir'] = '/';
// e-mail
$config['email'] = array();
$config['email']['recipient_address'] = '';
$config['email']['recipient_name'] = '';
$config['email']['recipient_cc'] = array();
$config['email']['recipient_cc'][0]['name'] = '';
$config['email']['recipient_cc'][0]['address'] = '';
$config['email']['sender_name'] = '';
$config['email']['sender_address'] = '';
$config['email']['attach_backup'] = 0;
$config['send_mail'] = 0; // send an email?
$config['use_mailer'] = 0; // use PHP mail()=0, use sendmail=1, use smtp 2
$config['email_maxsize1'] = 3;
$config['email_maxsize2'] = 2;
$config['sendmail_call'] = @ini_get('sendmail_path');
$config['smtp_server'] = 'localhost';
$config['smtp_port'] = 25;
$config['smtp_useauth'] = 0;
$config['smtp_user'] = '';
$config['smtp_pass'] = '';
$config['smtp_usessl'] = 0;
$config['smtp_pop3_server'] = '';
$config['smtp_pop3_port'] = 110;
// Perl related settings
$config['cron_extender'] = 0;
$config['cron_compression'] = 1;
$config['cron_printout'] = 1;
$config['cron_completelog'] = 1;
$config['cron_comment'] = '';
// log -> if zlib is disabled it will be turned off automatically later on
$config['logcompression'] = 1; // compress log files
$config['compression'] = 1; // compression of backup files is possible
$config['log_maxsize1'] = 1;
$config['log_maxsize2'] = 2;
$config['log_maxsize'] = 1048576;
$config['optimize_tables_beforedump'] = 1;
$config['backup_using_updates'] = 0;
$config['empty_db_before_restore'] = 0;
$config['stop_with_error'] = 1; // Restore -> stop on errors and show them
//Tuning-Corner -> values to process speed calculations
$config['minspeed'] = 100;
$config['maxspeed'] = 10000;
$config['tuning_add'] = 1.1;
$config['tuning_sub'] = 0.9;
$config['time_buffer'] = 0.75;
$config['perlspeed'] = 10000; // nr of records to be read at once
//dynamic parameters - read from server configuration
$config['safe_mode'] = get_cfg_var('safe_mode');
$config['magic_quotes_gpc'] = get_magic_quotes_gpc();
$config['disabled'] = get_cfg_var('disable_functions');
$config['ob_gzhandler'] = false;
@ini_set('magic_quotes_runtime', 0);
$config['max_execution_time'] = get_cfg_var('max_execution_time');
if ($config['max_execution_time'] <= 4) {
// we didn't get the real value from the server - some deliver "-1"
$config['max_execution_time'] = $config['max_execution_time'];
}
// we don't use more than 30 seconds to avoid brower timeouts
if ($config['max_execution_time'] > 30) {
$config['max_execution_time'] = 30;
}
$config['upload_max_filesize'] = get_cfg_var('upload_max_filesize');
// value in Megabytes? If yes create output else leave output untouched
if (strpos($config['upload_max_filesize'], 'M')) {
$config['upload_max_filesize'] =
trim(str_replace('M', '', $config['upload_max_filesize']));
$config['upload_max_filesize'] *= 1024 * 1024; // re-calculate to Bytes
// get a string ready to output
$config['upload_max_filesize'] =
byteOutput($config['upload_max_filesize']);
}
$config['phpextensions'] = implode(', ', get_loaded_extensions());
// read ram size
$m = trim(str_replace('M', '', @ini_get('memory_limit')));
// fallback if ini_get doesn't work
if (intval($m) == 0) {
$m = trim(str_replace('M', '', get_cfg_var('memory_limit')));
}
$config['php_ram'] = $m;
// always calculate memory limit
// we don't trust the value delivered by server config if < 8
if ($config['php_ram'] < 8) {
$config['php_ram'] = 8;
}
// use maximum of 90% of the memory limit
$config['memory_limit'] = round($config['php_ram'] * 1024 * 1024 * 0.9, 0);
// server html compression check routine
// detect if we can use output compression
$config['ob_gzhandler'] = false;
$check = array(NULL, false, '', 0, '0'); // Values to check
if (in_array(
preg_match('/ob_gzhandler|ini_get/i', $config['disabled']), $check
) && in_array(@ini_get('output_handler'), $check)
&& in_array(@ini_get('zlib.output_compression'), $check)
&& in_array(@ini_get('zlib.output_handler'), $check)) {
}
if (function_exists('apache_get_modules') && $config['ob_gzhandler'] == true
&& in_array('mod_deflate', @apache_get_modules())) {
$config['ob_gzhandler'] = false;
}
//is zlib-compression possible?
$extensions = explode(', ', $config['phpextensions']);
$disabledExtensions = str_replace(' ', '', $config['disabled']);
$disabledExtensions = explode(',', $disabledExtensions);
$config['zlib'] = (in_array('zlib', $extensions)
&& (!in_array('gzopen', $disabledExtensions)
|| !in_array('gzwrite', $disabledExtensions)
|| !in_array('gzgets', $disabledExtensions)
|| !in_array('gzseek', $disabledExtensions)
|| !in_array('gztell', $disabledExtensions)));
if (!$config['zlib']) {
// we can't use compression -> turn it off
$config['logcompression'] = 0;
$config['compression'] = 0;
}
$config['homepage'] = 'http://mysqldumper.net';
}
if (isset($_SESSION['config'])) {
$config = $_SESSION['config'];
}
if (isset($_SESSION['databases'])) {
$databases = $_SESSION['databases'];
}
$config['files']['iconpath'] = './css/' . $config['theme'] . '/icons/';
// config-vars that mustn't be saved in configuration profile,
// because they should be get dynamically from the server
$configDontsave = Array(
'homepage',
'max_execution_time',
'safe_mode',
'magic_quotes_gpc',
'disabled',
'phpextensions',
'php_ram',
'zlib',
'tuning_add',
'tuning_sub',
'time_buffer',
'perlspeed',
'cron_configurationfile',
'dbconnection',
'version',
'config_file',
'upload_max_filesize',
'cron_samedb',
'paths',
'files',
'ob_gzhandler');

61
inc/sql.php Normale Datei
Datei anzeigen

@ -0,0 +1,61 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
include ('./inc/functions/functions_sql.php');
include ('./inc/define_icons.php');
//get standard values from get and post
$db = $config['db_actual'];
if (isset($_GET['db'])) {
$db = base64_decode($_GET['db']);
if (!isset($databases[$db])) $db = $config['db_actual'];
}
$action = (isset($_GET['action'])) ? $_GET['action'] : 'list_databases';
include ('./inc/sqlbrowser/nav/topnav_general.php');
switch ($action)
{
case 'list_databases':
include ('./inc/sqlbrowser/db/list_databases.php');
break;
case 'list_tables':
include ('./inc/sqlbrowser/table/list_tables.php');
break;
case 'edit_table':
include ('./inc/sqlbrowser/table/edit_table.php');
break;
case 'edit_field':
include ('./inc/sqlbrowser/table/edit_field.php');
break;
case 'show_tabledata':
include ('./inc/sqlbrowser/table/show_tabledata.php');
break;
case 'new_db':
include ('./inc/sqlbrowser/general/tools.php');
break;
case 'general_vars':
include ('./inc/sqlbrowser/general/mysql_variables.php');
break;
case 'general_status':
include ('./inc/sqlbrowser/general/status.php');
break;
case 'general_process':
include ('./inc/sqlbrowser/general/process.php');
break;
case 'general_sqlbox_show_results':
case 'general_sqlbox':
include ('./inc/sqlbrowser/general/sqlbox.php');
break;
}
if (isset($db)) $_SESSION['db_actual']=$db;
include ('./inc/sqlbrowser/general/footer.php');

Datei anzeigen

@ -0,0 +1,185 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$do = isset($_POST['do']) ? $_POST['do'] : '';
$dbs = isset($_POST['database']) ? $_POST['database'] : array();
// truncte 1 db
if (isset($_GET['truncate_db'])) {
$do = 'db_truncate';
$dbs = array(
$_GET['truncate_db']);
}
// drop 1 db
if (isset($_GET['drop_db'])) {
$do = 'db_delete';
$dbs = array(
$_GET['drop_db']);
}
if ($do > '' && sizeof($dbs) > 0) {
$sql = array();
$associatedDatabase = array();
$tplSqlbrowserDbOperation = new MSDTemplate();
$tplSqlbrowserDbOperation->set_filenames(
array(
'tplSqlbrowserDbOperation' => 'tpl/sqlbrowser/db/operation.tpl'
)
);
$i = 0;
foreach ($dbs as $database) {
$database = base64_decode($database);
// truncate all tables but keep database
if ($do == 'db_truncate') {
$actionOutput = $lang['L_CLEAR_DATABASE'];
// clear table array to not delete other tables by accident
unset($tableInfos);
$tableInfos = getTableInfo($database);
$sql[] = 'SET FOREIGN_KEY_CHECKS=0';
$associatedDatabase[] = $database;
foreach ($tableInfos[$database]['tables'] as $table => $val) {
$query = $val['engine'] == 'VIEW' ? 'DROP VIEW ' : 'DROP TABLE ';
$sql[] = sprintf($query . '`%s`.`%s`', $database, $table);
$associatedDatabase[] = $database;
}
$sql[] = 'SET FOREIGN_KEY_CHECKS=1';
$associatedDatabase[] = $database;
}
// delete complete database
if ($do == 'db_delete') {
$actionOutput = $lang['L_DELETE_DATABASE'];
$sql[] = 'DROP DATABASE `' . $database . '`';
$associatedDatabase[] = $database;
}
}
$tplSqlbrowserDbOperation->assign_vars(
array(
'ACTION' => $actionOutput,
'ICON_OK' => $icon['ok'],
'ICON_NOTOK' => $icon['not_ok']
)
);
//process all sql commands and output result to template
foreach ($sql as $index => $query) {
//$res = MSD_query($query, false);
$res = $dbo->query($query, MsdDbFactory::SIMPLE);
if (true === $res) {
$tplSqlbrowserDbOperation->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $index % 2 ? 'dbrow' : 'dbrow1',
'NR' => $index + 1,
'DBNAME' => $associatedDatabase[$index],
'ACTION' => $actionOutput,
'QUERY' => $query
)
);
} else {
$tplSqlbrowserDbOperation->assign_block_vars(
'ERROR',
array(
'ROWCLASS' => $index % 2 ? 'dbrow' : 'dbrow1',
'NR' => $index + 1,
'DBNAME' => $associatedDatabase[$index],
'ACTION' => $actionOutput,
'QUERY' => $query,
'ERROR' => mysql_error($config['dbconnection'])
)
);
}
$i++;
}
if ($do == 'db_delete') {
setDefaultConfig();
}
}
//list databases
$tplSqlbrowserDbListDatabases = new MSDTemplate();
$tplSqlbrowserDbListDatabases->set_filenames(
array(
'tplSqlbrowserDbListDatabases' => 'tpl/sqlbrowser/db/list_databases.tpl'
)
);
$tplSqlbrowserDbListDatabases->assign_vars(
array(
'ICON_DB' => $icon['db'],
'ICON_VIEW' => $icon['view'],
'ICON_EDIT' => $icon['edit'],
'ICON_DELETE' => $icon['delete'],
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'],
'ICON_TRUNCATE' => $icon['truncate'],
'CONFIRM_TRUNCATE_DATABASES' =>
Html::getJsQuote($lang['L_CONFIRM_TRUNCATE_DATABASES'], true),
'CONFIRM_DROP_DATABASES' =>
Html::getJsQuote($lang['L_CONFIRM_DROP_DATABASES'], true)
)
);
$i = 0;
foreach ($databases as $dbName => $val) {
$rowclass = ($i % 2) ? 'dbrow' : 'dbrow1';
if ($dbName == $config['db_actual']) {
$rowclass = "dbrowsel";
}
//does the database exist?
if (!$dbo->selectDb($dbName, true)) {
// no -> show message "doesn't exist"
$tplSqlbrowserDbListDatabases->assign_block_vars(
'DB_NOT_FOUND',
array(
'ROWCLASS' => $rowclass,
'NR' => ($i + 1),
'DB_NAME' => $dbName,
'DB_ID' => $i
)
);
// if this happens the list is not accurate
// -> reload db-list to remove deleted dbs
setDefaultConfig();
} else {
// yes, db exists -> show nr of tables
$tables=$dbo->getTableStatus();
$numTables = (int) sizeof($tables);
$tplSqlbrowserDbListDatabases->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $rowclass,
'NR' => ($i + 1),
'DB_NAME' => $dbName,
'DATABASE_NAME_URLENCODED' => base64_encode($dbName),
'DB_ID' => base64_encode($dbName),
'TABLE_COUNT' => $numTables,
'CONFIRM_DELETE' =>
Html::getJsQuote(sprintf($lang['L_ASKDBDELETE'], $dbName)),
'CONFIRM_TRUNCATE' =>
Html::getJsQuote(sprintf($lang['L_ASKDBEMPTY'], $dbName))
)
);
if ($numTables == 1) {
$tplSqlbrowserDbListDatabases->assign_block_vars(
'ROW.TABLE', array()
);
} else {
$tplSqlbrowserDbListDatabases->assign_block_vars(
'ROW.TABLES', array()
);
}
}
$i++;
}

Datei anzeigen

@ -0,0 +1,17 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1205 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$tplSqlbrowserGeneralFooter = new MSDTemplate();
$tplSqlbrowserGeneralFooter->set_filenames(
array(
'tplSqlbrowserGeneralFooter' => 'tpl/sqlbrowser/general/footer.tpl')
);

Datei anzeigen

@ -0,0 +1,65 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$selectedFilter = -1;
if (isset($_POST['filter_selected'])) {
$selectedFilter = $_POST['filter_selected'];
}
$vars = array();
$res = $dbo->query('SHOW VARIABLES', MsdDbFactory::ARRAY_ASSOC);
$numrows = @sizeof($res);
foreach ($res as $row) {
$vars[$row['Variable_name']] = $row['Value'];
}
$filter = getPrefixArray($vars);
$tplSqlbrowserGeneralMysqlVariables = new MSDTemplate();
$tplSqlbrowserGeneralMysqlVariables->set_filenames(
array(
'tplSqlbrowserGeneralMysqlVariables' =>
'tpl/sqlbrowser/general/mysqlVariables.tpl'
)
);
$tplSqlbrowserGeneralMysqlVariables->assign_vars(
array('SEL_FILTER' => Html::getOptionlist($filter, $selectedFilter))
);
if (count($vars) == 0) {
$tpl->assign_block_vars('NO_VALUES', array());
} else {
$i = 0;
foreach ($vars as $name => $val) {
if ($selectedFilter != '-1'
&& substr($name, 0, strlen($selectedFilter)) != $selectedFilter) {
continue;
}
if (is_numeric($val)) {
if (strpos($name, 'time') === false) {
$val = String::formatNumber($val);
} else {
$val = getTimeFormat($val);
}
}
$tplSqlbrowserGeneralMysqlVariables->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'VAR_NAME' => $name,
'VAR_VALUE' => htmlspecialchars($val, ENT_COMPAT, 'UTF-8')
)
);
$i++;
}
}

Datei anzeigen

@ -0,0 +1,96 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$tplSqlbrowserGeneralProcess = new MSDTemplate();
$tplSqlbrowserGeneralProcess->set_filenames(
array('tplSqlbrowserGeneralProcess' => 'tpl/sqlbrowser/general/process.tpl')
);
$killid = 0;
if (isset($_GET['killid']) && $_GET['killid'] > 0) {
$killid = (int) $_GET['killid'];
if (isset($_POST['killid'])) intval($killid = $_POST['killid']);
$wait = (isset($_POST['wait'])) ? $_POST['wait'] : 0;
if ($wait == 0) {
$tplSqlbrowserGeneralProcess->assign_block_vars(
'KILL_STARTED', array('KILL_ID' => $killid)
);
$wait = $config['refresh_processlist'];
try
{
$ret = $dbo->query('KILL ' . $_GET['killid'], MsdDbFactory::SIMPLE);
}
catch (Exception $e)
{
$tplSqlbrowserGeneralProcess->assign_block_vars(
'KILL_ERROR',
array('MESSAGE' => '('.$e->getCode().') '.$e->getMessage())
);
}
} else {
$tplSqlbrowserGeneralProcess->assign_block_vars(
'KILL_WAIT',
array(
'KILL_ID' => $killid,
'WAIT_TIME' => $wait
)
);
$wait += $config['refresh_processlist'];
}
}
$res = $dbo->query('SHOW FULL PROCESSLIST', MsdDbFactory::ARRAY_NUMERIC);
$numrows = (int) @sizeof($res);
if ($numrows == 0) {
$tplSqlbrowserGeneralProcess->assign_block_vars('NO_PROCESS', array());
} else {
$processFound = false;
foreach ($res as $row) {
if ($row[0] == $killid) {
$processFound = true;
if ($row[4] == "Killed") $killid = 0;
}
$tplSqlbrowserGeneralProcess->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'ID' => $row[0],
'USER' => $row[1],
'HOST' => $row[2],
'DB' => $row[3],
'QUERY' => $row[4],
'TIME' => $row[5],
'STATE' => $row[6],
'INFO' => $row[7]
)
);
if ($killid == 0) {
$tplSqlbrowserGeneralProcess->assign_block_vars(
'ROW.KILL', array()
);
}
}
if (!$processFound) {
$killid = 0;
}
}
$tplSqlbrowserGeneralProcess->assign_vars(
array(
'REFRESHTIME' => $config['refresh_processlist'],
'REFRESHTIME_MS' => $config['refresh_processlist'] * 1000,
'ICON_DELETE' => $icon['kill_process'],
'KILL_ID' => $killid
)
);

Datei anzeigen

@ -0,0 +1,122 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
include ('./inc/functions/functions_restore.php');
$sql['sql_statements'] = '';
$queries = array();
$db = (!isset($_GET['db'])) ? $config['db_actual'] : base64_decode($_GET['db']);
if (isset($_GET['db'])) $config['db_actual'] = $db;
$tablename = '';
if (isset($_GET['tablename'])) {
$tablename = base64_decode($_GET['tablename']);
}
if (isset($_POST['tablename'])) $tablename = base64_decode($_POST['tablename']);
if (isset($_POST['sqltextarea'])) {
$sql['sql_statements'] = $_POST['sqltextarea'];
} else {
if (isset($_SESSION['sql']['statements'])) {
$sql['sql_statements'] = $_SESSION['sql']['statements'];
}
}
$tdcompact = $config['interface_table_compact'];
if (isset($_GET['tdc'])) {
$tdcompact = $_GET['tdc'];
}
if (isset($_POST['tableselect']) && $_POST['tableselect'] != '1') {
$tablename = $_POST['tableselect'];
}
$dbo->selectDb($db);
//Start SQL-Box
$tplSqlbrowserSqlbox = new MSDTemplate();
$tplSqlbrowserSqlbox->set_filenames(
array('tplSqlbrowserSqlbox' => 'tpl/sqlbrowser/sqlbox/sqlbox.tpl')
);
if (isset($_GET['readfile']) && $_GET['readfile'] == 1) {
$tplSqlbrowserSqlbox->assign_block_vars(
'SQLUPLOAD',
array(
'POSTTARGET' => $params,
'LANG_OPENSQLFILE' => $lang['L_SQL_OPENFILE'],
'LANG_OPENSQLFILE_BUTTON' => $lang['L_SQL_OPENFILE_BUTTON'],
'LANG_SQL_MAXSIZE' => $lang['L_MAX_UPLOAD_SIZE'],
'MAX_FILESIZE' => $config['upload_max_filesize']
)
);
}
if (isset($_POST['submit_openfile'])) {
//open file
if (!isset($_FILES['upfile']['name']) || empty($_FILES['upfile']['name'])) {
$aus .= '<span class="error">' . $lang['L_FM_UPLOADFILEREQUEST'] . '</span>';
} else {
$fn = $_FILES['upfile']['tmp_name'];
if (strtolower(substr($_FILES['upfile']['name'], -3)) == ".gz") {
$readUserSqlfile = gzfile($fn);
} else {
$readUserSqlfile = file($fn);
}
$sqlLoaded = implode("", $readUserSqlfile);
}
}
// Do we have SQL-Queries in User-SQLLib?
$sqlcombo = getSqlLibraryComboBox();
if ($sqlcombo > '') {
$tplSqlbrowserSqlbox->assign_block_vars(
'SQLCOMBO', array('SQL_COMBOBOX' => $sqlcombo)
);
}
// create Table select box
$tables = $dbo->getTables($db);
$tableSelectBox = Html::getOptionlist($tables, false, $lang['L_TABLE'] . ' `%s`');
$tplSqlbrowserSqlbox->assign_vars(
array(
'LANG_SQL_WARNING' => $lang['L_SQL_WARNING'],
'ICONPATH' => $config['files']['iconpath'],
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'],
'MYSQL_REF' => 'http://dev.mysql.com/doc/',
'BOXSIZE' => $config['interface_sqlboxsize'],
'BOXCONTENT' => $sql['sql_statements'],
'LANG_SQL_BEFEHLE' => $lang['L_SQL_COMMANDS'],
'TABLE_COMBOBOX' => $tableSelectBox,
'LANG_SQL_EXEC' => $lang['L_SQL_EXEC'],
'LANG_RESET' => $lang['L_RESET'],
'DB' => $db,
'DB_ENCODED' => base64_encode($db),
'ICON_SEARCH' => $icon['search'],
'ICON_UPLOAD' => $icon['upload'],
'ICON_ARROW_LEFT' => $icon['arrow_left'],
'ICON_MYSQL_HELP' => $icon['mysql_help'],
'ICON_CLOSE' => $icon['close'],
'MYSQL_HELP' => $lang['L_TITLE_MYSQL_HELP'],
'LANG_TOOLBOX' => $lang['L_TOOLS_TOOLBOX'],
'LANG_TOOLS' => $lang['L_TOOLS'],
'LANG_DB' => $lang['L_DB'],
'LANG_TABLE' => $lang['L_TABLE'],
'LANG_SQL_TABLEVIEW' => $lang['L_SQL_TABLEVIEW'],
'LANG_BACK_TO_DB_OVERVIEW' => $lang['L_SQL_BACKDBOVERVIEW']
)
);
if (isset($_POST['execsql']) || $action == 'general_sqlbox_show_results'
|| $sql['sql_statements'] > '') {
include ('./inc/sqlbrowser/sqlbox/show_results.php');
}
$_SESSION['db'] = $db;
$_SESSION['tablename'] = $tablename;
$_SESSION['sql']['statements'] = $sql['sql_statements'];

Datei anzeigen

@ -0,0 +1,72 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$selectedFilter = -1;
if (isset($_POST['filter_selected'])) {
$selectedFilter = $_POST['filter_selected'];
}
$res = $dbo->query('SHOW GLOBAL STATUS', MsdDbFactory::ARRAY_ASSOC);
foreach ($res as $row) {
$status[$row['Variable_name']] = $row['Value'];
}
$filter = getPrefixArray($status);
// values that will be formatted as times
$timeValues = array('Uptime', 'Uptime_since_flush_status');
$tplSqlbrowserGeneralStatus = new MSDTemplate();
$tplSqlbrowserGeneralStatus->set_filenames(
array(
'tplSqlbrowserGeneralStatus' => 'tpl/sqlbrowser/general/status.tpl'
)
);
if ($selectedFilter != '-1') {
$query = 'SHOW GLOBAL STATUS LIKE \'' . $selectedFilter . '_%\'';
$res = $dbo->query($query, MsdDbFactory::ARRAY_ASSOC);
}
if (@sizeof($res) == 0) {
$tpl->assign_block_vars('NO_STATUS', array());
} else {
if (count($filter) > 0) {
$tplSqlbrowserGeneralStatus->assign_block_vars(
'FILTER',
array(
'SEL_FILTER' => Html::getOptionlist($filter, $selectedFilter)
)
);
}
$i = 0;
foreach ($status as $key => $val) {
if ($selectedFilter != '-1'
&& substr($key, 0, strlen($selectedFilter)) != $selectedFilter) {
continue;
}
if (in_array($key, $timeValues)) {
$val = getTimeFormat($val);
} else {
$val = String::formatNumber($val);
}
$tplSqlbrowserGeneralStatus->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'VAR_NAME' => $key,
'VAR_VALUE' => $val
)
);
$i++;
}
}

Datei anzeigen

@ -0,0 +1,405 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//alle Tabellen der aktuellen Datenbank ermitteln und Zugriffs-Array aufbauen
$sql = 'SHOW TABLES FROM `' . $db . '`';
$tables = ARRAY();
$link = MSD_mysql_connect();
$res = mysql_query($sql, $link);
if (!$res === false)
{
WHILE ($row = mysql_fetch_array($res, MYSQL_NUM))
{
$tables[] = $row[0];
}
}
else
die("No Tables in Database!");
// Suchkriterien aus Session holen oder aus POST-Umgebung
// so bleiben die Suchkriterien auch erhalten wenn man zwischendurch woanders klickt
if (isset($_POST['suchbegriffe'])) $_SESSION['mysql_search']['suchbegriffe'] = $_POST['suchbegriffe'];
if (!isset($_SESSION['mysql_search']['suchbegriffe'])) $_SESSION['mysql_search']['suchbegriffe'] = '';
$suchbegriffe = $_SESSION['mysql_search']['suchbegriffe'];
if (isset($_POST['suchart'])) $_SESSION['mysql_search']['suchart'] = $_POST['suchart'];
if (!isset($_SESSION['mysql_search']['suchart']) || strlen($_SESSION['mysql_search']['suchart']) < 2) $_SESSION['mysql_search']['suchart'] = 'AND';
$suchart = $_SESSION['mysql_search']['suchart'];
if (isset($_POST['table_selected'])) $_SESSION['mysql_search']['table_selected'] = $_POST['table_selected'];
if (!isset($_SESSION['mysql_search']['table_selected'])) $_SESSION['mysql_search']['table_selected'] = 0;
$table_selected = $_SESSION['mysql_search']['table_selected'];
// Falls zwischendurch Tabellen geloescht wurden und der Index nicht mehr existiert, zuruecksetzen
if ($table_selected > count($tables) - 1) $table_selected = 0;
$offset = (isset($_POST['offset'])) ? intval($_POST['offset']) : 0;
// Delete
if (isset($_GET['mode']) && $_GET['mode'] == "kill" && $rk > '')
{
//echo "<br /> RK ist: ".$rk."<br /><br />";
if (strpos($rk, "|") != false) $rk = str_replace('|', ' AND ', $rk);
$sqlk = "DELETE FROM `$tablename` WHERE " . $rk . " LIMIT 1";
echo $sqlk;
$res = MSD_query($sqlk);
// echo "<br />".$res;
$aus .= '<p class="success">' . $lang['L_SQL_RECORDDELETED'] . '</p>';
}
function mysql_search($db, $tabelle, $suchbegriffe, $suchart, $offset = 0, $anzahl_ergebnisse = 20, $auszuschliessende_tabellen = '')
{
global $tables, $config;
$ret = false;
$link = MSD_mysql_connect();
if (sizeof($tables) > 0)
{
$suchbegriffe = trim(str_replace('*', '', $suchbegriffe));
$suchworte = explode(' ', $suchbegriffe);
if (($suchbegriffe > '') && (is_array($suchworte)))
{
// Leere Einträge (durch doppelte Leerzeichen) entfernen
$anzahl_suchworte = sizeof($suchworte);
for ($i = 0; $i < $anzahl_suchworte; $i++)
{
if (trim($suchworte[$i]) == '') unset($suchworte[$i]);
}
$bedingung = '';
$where = '';
$felder = '';
// Felder ermitteln
$sql = 'SHOW COLUMNS FROM `' . $db . '`.`' . $tables[$tabelle] . '`';
$res = mysql_query($sql, $link);
unset($felder);
if (!$res === false)
{
// Felder der Tabelle ermitteln
WHILE ($row = mysql_fetch_object($res))
{
$felder[] = $row->Field;
}
}
$feldbedingung = '';
if ($suchart == 'CONCAT')
{
if (is_array($felder))
{
//Concat-String bildem
$concat = implode('`),LOWER(`', $felder);
$concat = 'CONCAT_WS(\'\',LOWER(`' . $concat . '`))';
$where = '';
foreach ($suchworte as $suchbegriff)
{
$where .= $concat . ' LIKE \'%' . strtolower($suchbegriff) . '%\' AND ';
}
$where = substr($where, 0, -4); // letztes AND entfernen
$sql = 'SELECT * FROM `' . $db . '`.`' . $tables[$tabelle] . '` WHERE ' . $where . ' LIMIT ' . $offset . ',' . $anzahl_ergebnisse;
}
}
else
{
$pattern = '`{FELD}` LIKE \'%{SUCHBEGRIFF}%\'';
if (is_array($felder))
{
foreach ($felder as $feld)
{
unset($feldbedingung);
foreach ($suchworte as $suchbegriff)
{
$suchen = ARRAY(
'{FELD}',
'{SUCHBEGRIFF}');
$ersetzen = ARRAY(
$feld,
$suchbegriff);
$feldbedingung[] = str_replace($suchen, $ersetzen, $pattern);
}
$bedingung[] = '(' . implode(' ' . $suchart . ' ', $feldbedingung) . ') ';
}
}
else
die('<br />Fehler bei Suche: ich konnte nicht ermitteln welche Felder die Tabelle "' . $tabelle . '" hat!');
$where = implode(' OR ', $bedingung);
$sql = 'SELECT * FROM `' . $db . '`.`' . $tables[$tabelle] . '` WHERE (' . $where . ') LIMIT ' . $offset . ',' . $anzahl_ergebnisse;
}
}
else
$sql = 'SELECT * FROM `' . $db . '`.`' . $tables[$tabelle] . '` LIMIT ' . $offset . ',' . $anzahl_ergebnisse;
$res = @mysql_query($sql, $link);
if ($res)
{
WHILE ($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
//Treffer markieren
foreach ($row as $key => $val)
{
foreach ($suchworte as $suchbegriff)
{
$row[$key] = markiere_suchtreffer($suchbegriff, $row[$key]);
}
$row[$key] = ersetze_suchtreffer($row[$key]);
}
$ret[] = $row;
}
}
}
return $ret;
}
// Markiert den Suchbegriff mit einem Code (ASCII 01/02)
// - falls nicht gefunden : Rückgabe des Originalstrings
//
function markiere_suchtreffer($suchbegriff, $suchstring)
{
$str = strtolower($suchstring);
$suchbegriff = strtolower($suchbegriff);
if ((strlen($str) > 0) && (strlen($suchbegriff) > 0))
{
// Treffer Position bestimmen
$offset = 0;
$trefferpos = 0;
while (($offset <= strlen($str)))
//Wenn nur der erste Treffer markiert werden soll, so muss die Zeile so lauten
// while ( ($offset<=strlen($str)) || ($in_html==false) )
{
for ($offset = $trefferpos; $offset <= strlen($str); $offset++)
{
$start = strpos($str, $suchbegriff, $offset);
if ($start === false) $offset = strlen($str) + 1;
else
{
if ($offset <= strlen($str))
{
//Treffer überprüfen
$in_html = false;
// Steht die Fundstelle zwischen < und > (also im HTML-Tag) ?
for ($position = $start; $position >= 0; $position--)
{
if (substr($str, $position, 1) == ">")
{
$in_html = false;
$position = -1; // Schleife verlassen
}
if (substr($str, $position, 1) == "<")
{
$in_html = true;
$position = -1; // Schleife verlassen
}
}
if ($in_html)
{
for ($position2 = $start; $position2 < strlen($str); $position2++)
{
if (substr($str, $position2, 1) == "<")
{
$position2 = strlen($str) + 1;
}
if (substr($str, $position2, 1) == ">")
{
$in_html = true;
$position2 = strlen($str) + 1;
$offset = strlen($str) + 1;
}
}
}
if (!$in_html)
{
$ersetzen = substr($suchstring, $start, strlen($suchbegriff));
$str = substr($suchstring, 0, $start);
$str .= chr(1) . $ersetzen . chr(2);
$str .= substr($suchstring, ($start + strlen($ersetzen)), (strlen($suchstring) - strlen($ersetzen)));
$suchstring = $str;
}
if ($in_html)
{
$trefferpos = $start + 1;
$offset = $trefferpos;
}
}
$offset = $start + 1;
}
}
}
}
return $suchstring;
}
// Ersetzt die Codes letztlich durch die Fontangabe
function ersetze_suchtreffer($text)
{
$such = ARRAY(
chr(1),
chr(2));
$ersetzen = ARRAY(
'<span class="treffer">',
'</span>');
return str_replace($such, $ersetzen, htmlspecialchars($text));
}
$suchbegriffe = trim($suchbegriffe); // Leerzeichen vorne und hinten wegschneiden
if (isset($_POST['reset']))
{
$suchbegriffe = '';
$_SESSION['mysql_search']['suchbegriffe'] = '';
$suchart = 'AND';
$_SESSION['mysql_search']['suchart'] = 'AND';
$table_selected = 0;
$_SESSION['mysql_search']['table_selected'] = 0;
}
$showtables = 0; // Anzeige der Tabellendaten im restlichen SQL-Browser ausschalten
// Fix bis zur kompletten Umstellung auf Templates
echo $aus;
$aus = '';
$anzahl_tabellen = sizeof($tables);
$table_options = '';
if ($anzahl_tabellen > 0)
{
for ($i = 0; $i < $anzahl_tabellen; $i++)
{
if (isset($tables[$i]))
{
$table_options .= '<option value="' . $i . '"';
if (($i == $table_selected) || ($tables[$i] == $tablename))
{
$table_options .= ' selected';
$table_selected = $i;
}
$table_options .= '>' . $tables[$i] . '</option>' . "\n";
}
}
}
$tpl = new MSDTemplate();
$tpl->set_filenames(array(
'show' => 'tpl/sqlbrowser/mysql_search.tpl'));
$tpl->assign_vars(array(
'DB_NAME_URLENCODED' => base64_encode($db),
'LANG_SQLSEARCH' => $lang['L_SQL_SEARCH'],
'LANG_SQL_SEARCHWORDS' => $lang['L_SQL_SEARCHWORDS'],
'SUCHBEGRIFFE' => $suchbegriffe,
'LANG_START_SQLSEARCH' => $lang['L_START_SQL_SEARCH'],
'LANG_RESET_SEARCHWORDS' => $lang['L_RESET_SEARCHWORDS'],
'LANG_SEARCH_OPTIONS' => $lang['L_SEARCH_OPTIONS'],
'AND_SEARCH' => $suchart == 'AND' ? ' checked' : '',
'OR_SEARCH' => $suchart == 'OR' ? ' checked' : '',
'CONCAT_SEARCH' => $suchart == 'CONCAT' ? ' checked' : '',
'TABLE_OPTIONS' => $table_options,
'LANG_SEARCH_OPTIONS_AND' => $lang['L_SEARCH_OPTIONS_AND'],
'LANG_SEARCH_OPTIONS_OR' => $lang['L_SEARCH_OPTIONS_OR'],
'LANG_SEARCH_OPTIONS_CONCAT' => $lang['L_SEARCH_OPTIONS_CONCAT'],
'LANG_SEARCH_IN_TABLE' => $lang['L_SEARCH_IN_TABLE']));
$max_treffer = 20;
$treffer = mysql_search($db, $table_selected, $suchbegriffe, $suchart, $offset, $max_treffer + 1);
if (is_array($treffer) && isset($treffer[0]))
{
$search_message = sprintf($lang['L_SEARCH_RESULTS'], $suchbegriffe, $tables[$table_selected]);
$anzahl_treffer = count($treffer);
// Blaettern-Buttons
$tpl->assign_block_vars('HITS', array(
'LANG_SEARCH_RESULTS' => $search_message,
'LAST_OFFSET' => $offset - $max_treffer,
'BACK_BUTTON_DISABLED' => $offset > 0 ? '' : ' disabled',
'NEXT_OFFSET' => $offset + $max_treffer,
'NEXT_BUTTON_DISABLED' => ($anzahl_treffer != $max_treffer + 1) ? ' disabled' : '',
'LANG_ACCESS_KEYS' => $lang['L_SEARCH_ACCESS_KEYS']));
// Ausgabe der Treffertabelle
$anzahl_felder = sizeof($treffer[0]);
// Ausgabe der Tabellenueberschrift/ Feldnamen
foreach ($treffer[0] as $key => $val)
{
$tpl->assign_block_vars('HITS.TABLEHEAD', array(
'KEY' => $key));
}
// Ausgabe der Daten
$zeige_treffer = sizeof($treffer);
if ($zeige_treffer == $max_treffer + 1) $zeige_treffer = $max_treffer;
// build key - does a primary key exist?
$fieldinfos = getExtendedFieldinfo($db, $tables[$table_selected]);
//v($fieldinfos);
// auf zusammengesetzte Schlüssel untersuchen
$table_keys = isset($fieldinfos['primary_keys']) ? $fieldinfos['primary_keys'] : '';
for ($a = 0; $a < $zeige_treffer; $a++)
{
$tablename = array_keys($treffer[$a]);
if (is_array($table_keys) && sizeof($table_keys) > 0)
{
// a primary key exitst
$keystring = '';
foreach ($table_keys as $k)
{
// remove hit marker from value
$x = str_replace('<span class="treffer">', '', $treffer[$a][$k]);
$x = str_replace('</span>', '', $x);
$keystring .= '`' . $k . '`="' . addslashes($x) . '"|';
}
$keystring = substr($keystring, 0, -1);
$rk = build_recordkey($keystring);
}
else
{
$rk = urlencode(build_where_from_record($treffer[$a])); // no keys
}
$delete_link = 'sql.php?search=1&mode=kill&db=' . base64_encode($db) . '&tablename=' . base64_encode($tables[$table_selected]) . '&rk=' . $rk;
$edit_link = 'sql.php?mode=searchedit&db=' . base64_encode($db) . '&tablename=' . base64_encode($tables[$table_selected]) . '&recordkey=' . $rk;
$tpl->assign_block_vars('HITS.TABLEROW', array(
'CLASS' => ($a % 2) ? 'dbrow' : 'dbrow1',
'NR' => $a + $offset + 1,
'TABLENAME' => $tables[$table_selected],
'LINK_EDIT' => $edit_link,
'ICON_EDIT' => $icon['edit'],
'LINK_DELETE' => $delete_link,
'ICON_DELETE' => $icon['delete']));
foreach ($treffer[$a] as $key => $val)
{
if ($val == '') $val = "&nbsp;";
$tpl->assign_block_vars('HITS.TABLEROW.TABLEDATA', array(
'VAL' => $val));
}
}
}
else
{
if (!isset($tables[$table_selected])) $tables[$table_selected] = '';
if ($suchbegriffe == '') $tpl->assign_block_vars('NO_ENTRIES', array(
'LANG_NO_ENTRIES' => sprintf($lang['L_NO_ENTRIES'], $tables[$table_selected])));
else $tpl->assign_block_vars('NO_RESULTS', array(
'LANG_SEARCH_NO_RESULTS' => sprintf($lang['L_SEARCH_NO_RESULTS'], $suchbegriffe, $tables[$table_selected])));
}
$tpl->pparse('show');

Datei anzeigen

@ -0,0 +1,26 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$tplSqlbrowserTopnav = new MSDTemplate();
$tplSqlbrowserTopnav->set_filenames(
array(
'tplSqlbrowserTopnav' => 'tpl/sqlbrowser/nav/topnav_general.tpl'
)
);
$tplSqlbrowserTopnav->assign_vars(
array(
'ICON_DB' => $icon['db'],
'ICON_VIEW' => $icon['view'],
'ICON_EDIT' => $icon['edit']
)
);

Datei anzeigen

@ -0,0 +1,382 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version $Rev$
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$orderDirection = 'ASC';
if (isset($_SESSION['sql']['order_direction'])) {
$orderDirection = $_SESSION['sql']['order_direction'];
}
if (isset($_GET['order_direction'])) {
$orderDirection = $_GET['order_direction'];
}
if (!isset($_GET['order_by_field'])) {
$orderByField = '';
} else {
$orderByField = base64_decode($_GET['order_by_field']);
}
$offset = 0;
if (isset($_SESSION['sql']['offset'])) {
$offset = (int) $_SESSION['sql']['offset'];
}
$tplSqlbrowserSqlboxShowResults = new MSDTemplate();
$tplSqlbrowserSqlboxShowResults->set_filenames(
array(
'tplSqlbrowserSqlboxShowResults' =>
'tpl/sqlbrowser/sqlbox/showResults.tpl'
)
);
if (!isset($_SESSION['sql']['last_statement'])) {
$_SESSION['sql']['last_statement'] = '';
}
// execute last statement if we came from another site
if (isset($sql['sql_statements']) && $sql['sql_statements'] > '') {
$_POST['execsql'] = 1;
$_POST['sqltextarea'] = $sql['sql_statements'];
}
//SQL-Statement given? Analyse and execute
if ($_POST['sqltextarea'] > '' && (isset($_POST['execsql'])
|| $action == 'general_sqlbox_show_results')) {
//TODO Create class that handles queries and result sets using the same
// parser like when restoring a backup file.
// For the moment we do it quick and dirty by writing a temp file and hand
// it over to the parser, pretending that this is a file to be restored.
// do we have only 1 query or more?
if (isset($_POST['sqltextarea']) &&
$_POST['sqltextarea'] != $_SESSION['sql']['last_statement']) {
$_SESSION['sql']['last_statement'] = $_POST['sqltextarea'];
$offset = 0;
$data = $_POST['sqltextarea'];
}
if ($action == 'general_sqlbox_show_results') {
$data = $_SESSION['sql']['statements'];
}
if (isset($_POST['sqltextarea'])) {
$data = $_POST['sqltextarea'];
}
// save as file and prepare vars to let the restore parser handle it
$fileName = 'sqlbox_' . session_id() . '.sql';
if (file_exists($config['paths']['backup'] . $fileName)) {
unlink($config['paths']['backup'] . $fileName);
}
$f = fopen($config['paths']['backup'] . $fileName, 'w');
fwrite($f, $data);
fclose($f);
$restore['filename'] = $fileName;
$restore['filehandle'] = fopen($config['paths']['backup'] . $fileName, 'r');
$restore['compressed'] = 0;
$restore['dump_encoding'] = 'utf8';
$restore['max_zeit'] = intval(
$config['max_execution_time'] * $config['time_buffer']
);
if ($restore['max_zeit'] == 0) $restore['max_zeit'] = 20;
$restore['restore_start_time'] = time();
$restore['speed'] = $config['minspeed'];
$restore['fileEOF'] = false;
$restore['actual_table'] = '';
$restore['offset'] = 0;
$restore['page_refreshs'] = 0;
$restore['table_ready'] = 0;
$restore['errors'] = 0;
$restore['notices'] = 0;
$restore['actual_fieldcount'] = 0;
$restore['records_inserted'] = 0;
$restore['records_inserted_table'] = array();
$restore['extended_inserts'] = 0;
$restore['extended_insert_flag'] = -1;
$restore['last_parser_status'] = 0;
$restore['EOB'] = false;
$restore['fileEOF'] = false;
$restore['tables_to_restore'] = false; // restore complete file
do {
$query = getQueryFromFile(false);
if (!is_array($query)) {
$queries[] = $query;
} else {
// error in Query
$error[] = $query[1];
break;
}
} while (!$restore['fileEOF']);
// close and remove temp file after the job is done
fclose($restore['filehandle']);
@unlink($config['paths']['backup'].$fileName);
if (isset($_POST['tablecombo']) && $_POST['tablecombo'] > '') {
$sql['sql_statements'] = $_POST['tablecombo'];
$tablename = extractTablenameFromSQL($sql['sql_statements']);
}
$sql['sql_statements'] = implode("\n", $queries);
}
//Pager clicked?
if (isset($_POST['page_back'])) {
$offset -= $config['resultsPerPage'];
if ($offset < 0) $offset = 0;
}
if (isset($_POST['page_full_back'])) {
$offset = 0;
}
if (isset($_POST['page_forward'])) {
$offset += $config['resultsPerPage'];
}
if (isset($_POST['page_full_forward'])) {
$offset = $_SESSION['num_records_total'] - $config['resultsPerPage'];
}
if (sizeof($queries) == 1) {
$tablename = extractTablenameFromSQL($queries[0]);
$tplSqlbrowserSqlbox->assign_block_vars(
'SHOW_TABLENAME', array(
'TABLE' => $tablename,
'TABLE_ENCODED' => base64_encode($tablename))
);
// remove all values and names in query
$tempQuery = preg_replace('/"(.*?)"/si', '', $queries[0]);
$tempQuery = preg_replace('/\'(.*?)\'/si', '', $queries[0]);
$tempQuery = preg_replace('/`(.*?)`/si', '', $queries[0]);
// now we can decide if we can add a limit clause or if it already has one
if (strripos($tempQuery, ' LIMIT ') === false) {
$queries[0] .= ' LIMIT ' . $offset . ', ' . $config['resultsPerPage'];
}
// handle order direction if query doesn't have one
if ($orderByField > '' && strripos($tempQuery, ' ORDER BY') === false) {
$limitPosition = strripos($queries[0], ' LIMIT ');
$orderClause = ' ORDER BY `' . $orderByField . '` ' . $orderDirection;
if (false === $limitPosition) {
// no limit found -> concat
$queries[0] .= ' ORDER BY `' . $orderByField . '` ' . $orderDirection;
} else {
//inject order-clause in front of limit-clause
$tempOne = substr($queries[0], 0, $limitPosition);
$tempTwo = substr($queries[0], $limitPosition);
$queries[0] = $tempOne . $orderClause . $tempTwo;
}
}
// Injcet SQL_CALC_NUM_ROWS if we have a select query
if (strtoupper(substr($queries[0], 0, 7)) == 'SELECT ') {
$queries[0] = 'SELECT SQL_CALC_FOUND_ROWS ' . substr($queries[0], 7);
}
try
{
$res = $dbo->query($queries[0], MsdDbFactory::ARRAY_ASSOC);
$error = '';
}
catch (Exception $e)
{
//v($res);
$error = '(' . $e->getCode() . ') ' . $e->getMessage();
$_SESSION['sql']['offset'] = $offset;
$_SESSION['num_records_total'] = 0;
//echo "MySQL-Fehler: " . $queries[0] . "<br>" . $error;
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'MESSAGE', array(
'TEXT' => Html::getJsQuote($error, true),
'NOTIFICATION_POSITION' => $config['notification_position'])
);
}
if ($error == '') {
// get nr of total hits
$query = 'SELECT FOUND_ROWS() as `num_rows`';
$resRows = $dbo->query($query, MsdDbFactory::ARRAY_OBJECT);
$numRecordsTotal = $resRows[0]->num_rows;
$_SESSION['num_records_total'] = $numRecordsTotal;
$showHeader = true;
if ($offset + $config['resultsPerPage'] > $numRecordsTotal) {
$entryTo = $numRecordsTotal;
} else {
$entryTo = $offset + $config['resultsPerPage'];
}
$showing = sprintf(
$lang['L_SHOWING_ENTRY_X_TO_Y_OF_Z'],
$offset + 1,
$entryTo,
$numRecordsTotal
);
$tplSqlbrowserSqlboxShowResults->assign_vars(
array(
'ICON_UP' => $icon['arrow_up'],
'ICON_DOWN' => $icon['arrow_down'])
);
if ($numRecordsTotal > 0) {
$forwardDisabled='';
if ($offset + $config['resultsPerPage'] >= $numRecordsTotal) {
$forwardDisabled = ' disabled="disabled"';
}
$backwardDisabled='';
if ($offset == 0) {
$backwardDisabled = ' disabled="disabled"';
}
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'PAGER', array(
'PAGE_FORWARD_DISABLED' => $forwardDisabled,
'PAGE_BACK_DISABLED' => $backwardDisabled,
'SHOWING_ENTRY_X_OF_Y' => $showing)
);
}
$i = 0;
foreach ($res as $row) {
if ($showHeader) {
// show Headline of table
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'HEADLINE', array()
);
foreach ($row as $field => $val) {
$nextOrderDirection = 'DESC';
if ($orderDirection == 'DESC') {
$nextOrderDirection = 'ASC';
}
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'HEADLINE.FIELDS', array(
'NAME' => $field,
'FIELD_ENCODED' => base64_encode($field),
'DIRECTION' => $nextOrderDirection)
);
// show order icon
if ($field == $orderByField) {
if ($orderDirection == 'ASC') {
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'HEADLINE.FIELDS.ICON_UP', array()
);
} else {
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'HEADLINE.FIELDS.ICON_DOWN', array()
);
}
}
$showHeader = false;
}
}
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'ROW', array(
'NR' => $i + 1 + $offset,
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1')
);
foreach ($row as $field => $val) {
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'ROW.FIELD', array(
'VAL' => $val)
);
if (is_numeric($val)) {
$tplSqlbrowserSqlboxShowResults->assign_block_vars(
'ROW.FIELD.NUMERIC', array()
);
}
}
$i++;
}
}
} else {
$count = array(
'create' => 0,
'delete' => 0,
'drop' => 0,
'update' => 0,
'insert' => 0,
'select' => 0,
'alter' => 0
);
$tplSqlbrowserSqlboxShowQueryResults = new MSDTemplate();
$tplSqlbrowserSqlboxShowQueryResults->set_filenames(
array(
'tplSqlbrowserSqlboxShowQueryResults' =>
'tpl/sqlbrowser/sqlbox/showQueryResults.tpl')
);
$tplSqlbrowserSqlboxShowQueryResults->assign_vars(
array(
'NOTIFICATION_POSITION' => $config['notification_position'])
);
$i = 0;
foreach ($queries as $key => $query) {
$skip = false;
$compare = strtoupper(substr($query, 0, 4));
switch ($compare)
{
case 'CREA':
$count['create']++;
break;
case 'DROP':
$count['drop']++;
break;
case 'UPDA':
$count['update']++;
break;
case 'INSE':
$count['insert']++;
break;
case 'SELE':
$count['select']++;
break;
case 'ALTE':
$count['alter']++;
break;
case 'DELE':
$count['delete']++;
break;
default:
if (substr($compare, 0, 2) == '--' ||
substr($compare, 0, 1) == '#') {
$skip = true;
}
}
if (!$skip) {
$start = getMicrotime();
try
{
$res = $dbo->query($query, MsdDbFactory::SIMPLE);
}
catch (Exception $e)
{
$logMsg = '(' . $e->getCode() . ') ' . $e->getMessage();
$tplSqlbrowserSqlboxShowQueryResults->assign_block_vars(
'ERROR', array(
'TEXT' => Html::getJsQuote($logMsg))
);
}
$end = getMicrotime();
$queries[$key]['time'] = $end - $start;
$i++;
$tplSqlbrowserSqlboxShowQueryResults->assign_block_vars(
'SQL_COMMAND', array(
'SQL' => substr($query, 0, 100),
'EXEC_TIME' => $queries[$key]['time'],
'NR' => $i)
);
}
$tplSqlbrowserSqlboxShowQueryResults->assign_vars(
array(
'COUNT_DROP' => String::formatNumber($count['drop']),
'COUNT_DELETE' => String::formatNumber($count['delete']),
'COUNT_CREATE' => String::formatNumber($count['create']),
'COUNT_ALTER' => String::formatNumber($count['alter']),
'COUNT_INSERT' => String::formatNumber($count['insert']),
'COUNT_SELECT' => String::formatNumber($count['select']),
'COUNT_UPDATE' => String::formatNumber($count['update']))
);
}
}
$_SESSION['sql']['statements'] = $sql['sql_statements'];
$_SESSION['sql']['order_by_field'] = $orderByField;
$_SESSION['sql']['order_direction'] = $orderDirection;
$_SESSION['sql']['offset'] = $offset;

Datei anzeigen

@ -0,0 +1,115 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1205 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
/*
* Fetch and check _GET variables
*/
$db = isset($_GET['db']) ? base64_decode($_GET['db']) : $config['db_actual'];
$tablename = isset($_GET['tablename']) ? base64_decode($_GET['tablename']) : '';
$dbo->selectDb($db);
$tableInfos=$dbo->getTableColumns($tablename, $db);
$tplSqlbrowserTableEditTable = new MSDTemplate();
$tplSqlbrowserTableEditTable->set_filenames(
array(
'tplSqlbrowserTableEditTable' => 'tpl/sqlbrowser/table/edit_table.tpl'
)
);
$tplSqlbrowserTableEditTable->assign_vars(
array(
'DB' => $db,
'TABLE' => $tablename
)
);
$sumSize = 0;
$i = 0;
foreach ($tableInfos as $key => $tableInfo) {
if ($key != 'primary_keys') {
$type = $tableInfo['Type'];
$typeTemp = array();
// ENUM-/SET-Handling
if (strpos($type, 'enum') !== false || strpos($type, 'set') !== false) {
$toBeReplaced = array(
'set(',
'enum(',
')',
'\'');
$typeTemp = str_replace($toBeReplaced, '', $type);
$typeTemp = explode(',', $typeTemp);
sort($typeTemp);
if (strpos($type, 'enum') !== false) {
$type = 'enum';
} else {
$type = 'set';
}
}
$tplSqlbrowserTableEditTable->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => ($i + 1),
'NAME' => $tableInfo['Field'],
'TYPE' => $type,
'NULL' => $tableInfo['Null']=='NO' ? $lang['L_NO']:$lang['L_YES'],
'KEY' => $tableInfo['Key'],
'DEFAULT' => $tableInfo['Default'],
'EXTRA' => $tableInfo['Extra'],
'SORTIERUNG' => $tableInfo['Collation']
)
);
if (count($typeTemp) > 0) {
$tplSqlbrowserTableEditTable->assign_block_vars(
'ROW.ENUM_SET',
array(
'SIZE' => count($typeTemp) < 5 ? count($typeTemp) : 5,
'ICON_BROWSE' => $icon['browse'],
'NR' => $i
)
);
foreach ($typeTemp as $val) {
$tplSqlbrowserTableEditTable->assign_block_vars(
'ROW.ENUM_SET.ENUM_SET_ELEMENT',
array('ELEMENT' => $val)
);
}
}
$i++;
}
}
// Output list of tables of the selected database
$tplSqlbrowserTableEditTable->assign_vars(
array(
'DB_NAME_URLENCODED' => base64_encode($db),
'TABLE_NAME_URLENCODED' => base64_encode($tablename),
'ICON_VIEW' => $icon['view'],
'ICON_EDIT' => $icon['edit'],
'ICON_OK' => $icon['ok'],
'ICON_NOT_OK' => $icon['not_ok'],
'ICON_DELETE' => $icon['delete'],
'ICON_UP' => $icon['arrow_up'],
'ICON_DOWN' => $icon['arrow_down'],
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'],
'ICON_CANCEL' => $icon['cancel'],
'DB' => $db,
'DB_ENCODED' => base64_encode($db),
'TABLE_ENCODED' => base64_encode($tablename),
'ICONPATH' => $config['files']['iconpath']
)
);

Datei anzeigen

@ -0,0 +1,259 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$checkit = (isset($_GET['checkit'])) ? base64_decode($_GET['checkit']) : '';
$repair = (isset($_GET['repair'])) ? base64_decode($_GET['repair']) : 0;
$tables = isset($_POST['table']) ? $_POST['table'] : array();
$sortColumn = isset($_POST['sort_by_column']) ? $_POST['sort_by_column'] : 'name';
$sortDirection = isset($_POST['sort_direction']) ? $_POST['sort_direction'] : 'a';
$dbo->selectDb($db);
$tableInfos = array();
// is there any operation to do?
if (isset($_POST['do']) && $_POST['do']>'' && sizeof($tables) > 0) {
// which action should we perform?
$queryResultType = MsdDbFactory::ARRAY_ASSOC;
switch ($_POST['do'])
{
case 'analyze':
$query = 'ANALYZE TABLE `%s`.`%s`';
$actionOutput = $lang['L_ANALYZE'];
break;
case 'check':
$query = 'CHECK TABLE `%s`.`%s`';
$actionOutput = $lang['L_CHECK'];
break;
case 'repair':
$query = 'REPAIR TABLE `%s`.`%s`';
$actionOutput = $lang['L_REPAIR'];
break;
case 'drop':
$query = 'DROP TABLE `%s`.`%s`';
$actionOutput = $lang['L_DELETE'];
$queryResultType = MsdDbFactory::SIMPLE;
break;
case 'truncate':
$query = 'TRUNCATE TABLE `%s`.`%s`';
$actionOutput = $lang['L_EMPTY'];
$queryResultType = MsdDbFactory::SIMPLE;
break;
default:
$query = 'OPTIMIZE TABLE `%s`.`%s`';
$actionOutput = $lang['L_OPTIMIZE'];
break;
}
$tplSqlbrowserTableOperation = new MSDTemplate();
$tplSqlbrowserTableOperation->set_filenames(
array(
'tplSqlbrowserTableOperation' => 'tpl/sqlbrowser/table/operation.tpl'
)
);
$tplSqlbrowserTableOperation->assign_vars(
array(
'ACTION' => $actionOutput,
'ICON_DELETE' => $icon['delete'],
'ICON_OK' => $icon['ok'],
'ICON_NOTOK' => $icon['not_ok'],
)
);
$i = 0;
foreach ($tables as $table) {
$table = base64_decode($table);
$res = $dbo->query(sprintf($query, $db, $table), $queryResultType);
if ($res) {
if (!is_array($res)) {
// simple action without result (delete, truncate, ..)
$tplSqlbrowserTableOperation->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'TABLENAME' => $table,
'ACTION' => $actionOutput,
'TYPE' => sprintf($query, $db, $table),
'MESSAGE' => ''
)
);
} else {
$row = $res[0];
// mainatining functions with result
// (optimize, repair, analyze,..
$msgType = isset($row['Msg_type']) ? $row['Msg_type'] : '';
$msgTxt = isset($row['Msg_text']) ? $row['Msg_text'] : '';
$tplSqlbrowserTableOperation->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'TABLENAME' => $table,
'ACTION' => isset($row['Op']) ? $row['Op'] : '',
'TYPE' => $msgType,
'MESSAGE' => $msgTxt
)
);
}
} else {
// error
$tplSqlbrowserTableOperation->assign_block_vars(
'ERROR',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => $i + 1,
'TABLENAME' => $table,
'ERROR' => mysql_error(),
'QUERY' => sprintf($query, $db, $table)
)
);
}
$i++;
}
}
// Output list of tables of the selected database
$tableInfos = getTableInfo($db);
// extract sorted one-dimensional array with infos we need
$orderArray = get_orderarray($sortColumn . ',' . $sortDirection . '|name,a');
$sortedTableInfos = arfsort($tableInfos[$db]['tables'], $orderArray);
$tplSqlbrowserTableListTables = new MSDTemplate();
$tplSqlbrowserTableListTables->set_filenames(
array(
'tplSqlbrowserTableListTables' => 'tpl/sqlbrowser/table/listTables.tpl'
)
);
$numrows = $tableInfos[$db]['table_count'];
$up = $icon['arrow_up'];
$down = $icon['arrow_down'];
$sortName = $sortColumn == 'name' ? ($sortDirection == 'd' ? $down : $up) : '';
$sD = $sortDirection;
$sC = $sortColumn;
$tplSqlbrowserTableListTables->assign_vars(
array(
'ICON_VIEW' => $icon['view'],
'ICON_EDIT' => $icon['edit'],
'ICON_OK' => $icon['ok'],
'ICON_NOT_OK' => $icon['not_ok'],
'ICON_DELETE' => $icon['delete'],
'ICON_TRUNCATE' => $icon['truncate'],
'ICON_UP' => $up,
'ICON_DOWN' => $down,
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'],
'ICON_CANCEL' => $icon['cancel'],
'DB_NAME' => $db,
'DB_NAME_URLENCODED' => base64_encode($db),
'TABLE_COUNT' => String::formatNumber($numrows),
'ICONPATH' => $config['files']['iconpath'],
'SORT_BY_COLUMN' => $sC,
'SORT_DIRECTION' => $sD,
'SORT_NAME' => $sortName,
'SORT_RECORDS' => $sC == 'records' ? ($sD == 'D' ? $down : $up) : '',
'SORT_DATA_LENGTH' =>
$sC == 'data_length' ? ($sD == 'D' ? $down : $up) : '',
'SORT_INDEX_LENGTH' =>
$sC == 'index_length' ? ($sD == 'D' ? $down : $up) : '',
'SORT_AUTO_INCREMENT' =>
$sC == 'auto_increment' ? ($sD == 'D' ? $down : $up) : '',
'SORT_DATA_FREE' =>
$sC == 'data_free' ? ($sD == 'D' ? $down : $up) : '',
'SORT_UPDATE_TIME' =>
$sC == 'update_time' ? ($sD == 'd' ? $down : $up) : '',
'SORT_ENGINE' =>
$sC == 'engine' ? ($sD == 'd' ? $down : $up) : '',
'SORT_COLLATION' =>
$sC == 'collation' ? ($sD == 'd' ? $down : $up) : '',
'SORT_COMMENT' => $sC == 'comment' ? ($sD == 'd' ? $down : $up) : '',
'CONFIRM_TRUNCATE_TABLES' =>
Html::getJsQuote($lang['L_CONFIRM_TRUNCATE_TABLES']),
'CONFIRM_DELETE_TABLES' =>
Html::getJsQuote($lang['L_CONFIRM_DELETE_TABLES']),
)
);
if ($numrows > 1) {
$tplSqlbrowserTableListTables->assign_block_vars('MORE_TABLES', array());
} elseif ($numrows == 1) {
$tplSqlbrowserTableListTables->assign_block_vars('1_TABLE', array());
} elseif ($numrows == 0) {
$tplSqlbrowserTableListTables->assign_block_vars(
'NO_TABLE',
array(
'HIDE' => ' style="display:none;"'
)
);
}
$lastUpdate = 0; // remember the latest update for sum-line
$i = 0;
foreach ($sortedTableInfos as $val) {
if ($val['update_time'] > $lastUpdate) {
$lastUpdate = $val['update_time'];
}
$updateTime = $val['update_time'] > '' ? $val['update_time'] : '&nbsp;';
$autoIncrement = '-';
if ((int) $val['auto_increment'] > 0) {
$autoIncrement = String::formatNumber($val['auto_increment']);
}
$tplSqlbrowserTableListTables->assign_block_vars(
'ROW',
array(
'ROWCLASS' => $i % 2 ? 'dbrow' : 'dbrow1',
'NR' => ($i + 1),
'TABLE_NAME' => $val['name'],
'TABLE_NAME_URLENCODED' => base64_encode($val['name']),
'RECORDS' => String::formatNumber($val['records']),
'DATA_LENGTH' => byteOutput($val['data_length']),
'INDEX_LENGTH' => byteOutput($val['index_length']),
'LAST_UPDATE' => $updateTime,
'ENGINE' => $val['engine'],
'COLLATION' => $val['collation'],
'COMMENT' => $val['comment'] > '' ? $val['comment'] : '',
'AUTO_INCREMENT' => $autoIncrement
)
);
// re-check table if it was checked before
if (in_array(base64_encode($val['name']), $tables)) {
$tplSqlbrowserTableListTables->assign_block_vars(
'ROW.TABLE_CHECKED', array()
);
}
// is table optimized?
if (in_array($val['engine'], array('MyISAM', 'ARCHIVE'))) {
if ($val['data_free'] == 0) {
$tplSqlbrowserTableListTables->assign_block_vars(
'ROW.OPTIMIZED', array()
);
} else {
$tplSqlbrowserTableListTables->assign_block_vars(
'ROW.NOT_OPTIMIZED',
array('VALUE' => byteOutput($val['data_free']))
);
}
}
else // optimize is not supported for this engine
$tplSqlbrowserTableListTables->assign_block_vars(
'ROW.OPTIMIZE_NOT_SUPPORTED', array()
);
$i++;
}
// Output sum-line
$indexLen = $tableInfos[$db]['size_total'] - $tableInfos[$db]['datasize_total'];
$tplSqlbrowserTableListTables->assign_block_vars(
'SUM',
array(
'RECORDS' => String::formatNumber($tableInfos[$db]['records_total']),
'DATA_LENGTH' => byteOutput($tableInfos[$db]['datasize_total']),
'INDEX_LENGTH' => byteOutput($indexLen),
'LAST_UPDATE' => $lastUpdate
)
);

Datei anzeigen

@ -0,0 +1,230 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version $Rev$
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
$tablename = isset($_POST['tablename']) ? base64_decode($_POST['tablename']) : '';
if (isset($_GET['tablename'])) {
$tablename = base64_decode($_GET['tablename']);
}
$dbo->selectDb($db);
$tableInfos = $dbo->getTableColumns($tablename);
if ($tablename == '') {
$tablenames = array_keys($tableInfos[$db]['tables']);
$tablename = $tablenames[0];
}
//v($_POST);
$tableInfos = $dbo->getTableColumns($tablename);
$sortByColumn = '';
if (isset($_POST['sort_by_column']) && isset($tableInfos[$sortByColumn])) {
$sortByColumn = base64_decode($_POST['sort_by_column']);
}
$sortDirection = 'ASC';
if (isset($_POST['sort_direction'])) {
$sortDirection = (string) $_POST['sort_direction'];
}
if (in_array($sortDirection, array('d', 'D'))) {
$desc = 'DESC';
}
$maxEntries = $config['resultsPerPage'];
if (isset($_GET['limit_max_entries'])) {
$maxEntries =(int) $_GET['limit_max_entries'];
}
$showAll = 0;
$limitStart = 0;
if (isset($_GET['limit_start']) && $_GET['limit_start'] > 0 && !$showAll) {
$limitStart = $_GET['limit_start'];
}
$tplSqlbrowserTableShowTabledata = new MSDTemplate();
$tplSqlbrowserTableShowTabledata->set_filenames(
array(
'tplSqlbrowserTableShowTabledata' =>
'tpl/sqlbrowser/table/show_tabledata.tpl'
)
);
//TODO: Language_vars im Sprachlabor anlegen und hier entfernen.
$languageVars =
array(
'L_SQL_DATAOFTABLE' => 'Datensätze der Tabelle',
'L_SQL_SHOW_NUM_ENTRIES' => 'Zeige Datensätze: ',
'L_SHOW' => 'Zeige',
'L_ENTRIES_PER_PAGE' => 'pro Seite (0 = alle anzeigen)',
'L_STARTING_WITH' => 'beginnend mit Eintrag',
'L_EDIT_ENTRY' => 'Eintrag editieren',
'L_VIEW_ENTRY' => 'Eintrag anzeigen',
'L_NEW_ENTRY' => 'Eintrag anlegen',
'L_EXECUTED_QUERY' => 'Ausgeführte MySQL-Query:',
'L_ROWS_AFFECTED' => 'Zeilen betroffen',
'L_QUERY_FAILED' => 'Query fehlgeschlagen'
);
$tplSqlbrowserTableShowTabledata->assign_vars($languageVars);
if (isset($_POST['action'])) {
processPostAction($tplSqlbrowserTableShowTabledata, $db, $tablename);
}
$query = "SELECT COUNT(*) as count FROM `$tablename`";
$res=$dbo->query($query, MsdDbFactory::ARRAY_ASSOC);
$numRecords=(int) $res[0];
if (isset($_GET['pager'])) {
switch ($_GET['pager'])
{
case '<':
$limitStart -= $maxEntries;
break;
case '<<':
$limitStart = 0;
break;
case '>>':
$limitStart = $showAll ? 0 : $numRecords - $maxEntries;
break;
case '>':
$limitStart += $maxEntries;
break;
}
$limitStart = min($numRecords - $maxEntries, $limitStart);
$limitStart = max($limitStart, 0);
}
$templateVars =
array(
'DB_NAME' => $db,
'TABLE_NAME' => $tablename,
'DB_NAME_URLENCODED' => base64_encode($db),
'TABLE_NAME_URLENCODED' => base64_encode($tablename),
'ENTRY_COUNT' => $numRecords,
'LIMIT_START' => $limitStart,
'FIRST_ENTRY_NUM' => $limitStart + 1,
'LAST_ENTRY_NUM' => $showAll ? $num["count"] : $limitStart + $maxEntries,
'MAX_ENTRIES' => $maxEntries,
'SORT_DIRECTION' => $sortDirection == 'ASC' ? 'd':'a',
'SORT_BY_COLUMN' => $sortByColumn,
'ICON_VIEW' => $icon['view'],
'ICON_EDIT' => $icon['edit'],
'ICON_PLUS' => $icon['plus'],
'ICON_MINUS' => $icon['minus'],
'ICON_DELETE' => $icon['delete'],
'ICON_EDIT' => $icon['edit']
);
$tplSqlbrowserTableShowTabledata->assign_vars($templateVars);
/*
* Build the Table-Header columns
*/
$field_infos = getExtendedFieldInfo($db, $tablename);
foreach ($field_infos as $field => $val) {
$sD = '';
if ($val['field'] == $sortByColumn) {
$sD = $desc == 'DESC' ? $icon['arrow_down'] : $icon['arrow_up'];
}
$tplSqlbrowserTableShowTabledata->assign_block_vars(
'COL_HEADER',
array(
'LABEL' => $val['field'],
'NAME' => base64_encode($val['field']),
'COMMENT' => $val['comment'],
'SORT' => $sD
)
);
}
/*
* Add the Datarows
*/
$query = "SELECT * FROM `$tablename`";
if ($sortByColumn>'') {
$query .= ' ORDER BY `'.$sortByColumn.'` '.$sortDirection;
}
if ($limitStart>0) {
$query .= " LIMIT $limitStart, $maxEntries";
}
$result = $dbo->query($query, MsdDbFactory::ARRAY_ASSOC);
$entryNum = $limitStart;
//echo $order;
//Daten holen:
$nr_of_fields = 0;
$i = 1;
foreach ($result as $row) {
$nr_of_fields = sizeof($row);
$tplSqlbrowserTableShowTabledata->assign_block_vars(
'ROW',
array(
'NR' => $i,
'RECORD_KEY_ENCODED' => base64_encode(getRecordIdentifier($db, $tablename, $row)),
'ROW_CLASS' => $i % 2 ? 'dbrow' : 'dbrow1'
)
);
foreach ($row as $val) {
$tplSqlbrowserTableShowTabledata->assign_block_vars(
'ROW.COL',
array(
'VAL' => htmlentities($val, ENT_COMPAT, 'utf-8'),
'CLASS' => is_numeric($val) ? ' right' : ''
)
);
}
$i++;
}
$tplSqlbrowserTableShowTabledata->assign_vars(
array('BUTTONBAR_COLSPAN' => $nr_of_fields + 3)
);
function processPostAction($tplSqlbrowserTableShowTabledata, $db, $tablename)
{
global $dbo;
$action = $_POST['action'];
if (!in_array($action, array('edit', 'new'))) {
return;
}
$fields = implode(', ', fetchSetFields($_POST, 'field_'));
$sql = "INSERT INTO `$tablename` SET " . $fields . ";";
if ($action == 'edit') {
$sql = "UPDATE `$tablename` SET " . $fields . " WHERE "
. base64_decode($_POST['key']) . ' LIMIT 1;';
}
$result = $dbo->query($sql,MsdDbFactory::SIMPLE);
if (!$result) {
$tplSqlbrowserTableShowTabledata->assign_block_vars(
'MYSQL_ERROR',
array(
'QUERY' => htmlspecialchars($sql),
'ERROR' => mysql_error()
)
);
return;
}
$tplSqlbrowserTableShowTabledata->assign_block_vars(
'POSTED_MYSQL_QUERY',
array(
'QUERY' => htmlspecialchars($sql),
'ROWS_AFFECTED' => $dbo->getAffectedRows()
)
);
}
function fetchSetFields($arr, $prefix)
{
global $dbo;
$answer = array();
foreach ($arr as $key => $value) {
if (strpos($key, $prefix) === 0) {
$field = base64_decode(substr($key, strlen($prefix)));
$answer[] = "`$field` = \"" . $dbo->escape($value) . "\"";
}
}
return $answer;
}

60
inc/sqllib.php Normale Datei
Datei anzeigen

@ -0,0 +1,60 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @version SVN: $rev: 1207 $
* @author $Author$
* @lastmodified $Date$
*/
if (!defined('MSD_VERSION')) die('No direct access.');
//SQL-Library
/*
Template
if $sqllib[$i]['sql']=trenn, Then it is a Heading
$sqllib[$i]['name']="";
$sqllib[$i]['sql']="";
$i++;
*/
$i = 0;
$sqllib = ARRAY();
$sqllib[$i]['name'] = $lang['L_SQLLIB_GENERALFUNCTIONS'];
$sqllib[$i]['sql'] = "trenn";
$i++;
$sqllib[$i]['name'] = $lang['L_SQLLIB_RESETAUTO'];
$sqllib[$i]['sql'] = "ALTER TABLE `table` AUTO_INCREMENT=1;";
$i++;
/********* phpBB-Boards *********************************/
$sqllib[$i]['name'] = "phpBB-" . $lang['L_SQLLIB_BOARDS'];
$sqllib[$i]['sql'] = "trenn";
$i++;
// Bord de-/aktivieren
$sqllib[$i]['name'] = $lang['L_SQLLIB_DEACTIVATEBOARD'] . ' [phpBB]';
$sqllib[$i]['sql'] = "UPDATE `phpbb_config` set config_value=1 where config_name='board_disable'";
$i++;
$sqllib[$i]['name'] = $lang['L_SQLLIB_ACTIVATEBOARD'] . ' [phpBB]';
$sqllib[$i]['sql'] = "UPDATE `phpbb_config` set config_value=0 where config_name='board_disable'";
$i++;
// Bord de-/aktivieren
$sqllib[$i]['name'] = "vBulletin-" . $lang['L_SQLLIB_BOARDS'];
$sqllib[$i]['sql'] = "trenn";
$i++;
// Bord de-/aktivieren
$sqllib[$i]['name'] = $lang['L_SQLLIB_DEACTIVATEBOARD'] . ' [vBulletin]';
$sqllib[$i]['sql'] = "UPDATE forum SET options = options - 1 WHERE options & 1";
$i++;
$sqllib[$i]['name'] = $lang['L_SQLLIB_ACTIVATEBOARD'] . ' [vBulletin]';
$sqllib[$i]['sql'] = "UPDATE forum SET options = options + 1 WHERE NOT (options & 1)";
$i++;