1
0
Fork 0
Dieser Commit ist enthalten in:
DSB 2011-06-10 21:55:32 +00:00
Ursprung 2b21070b1a
Commit f7a7c71f86
1583 geänderte Dateien mit 454759 neuen und 0 gelöschten Zeilen

Datei anzeigen

@ -0,0 +1,59 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Controllers
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Assign config- and language to view
*
* Helper to auto assign the config- and language instance to view instances
*
* @package MySQLDumper
* @subpackage Action_Helper
*/
class Msd_Action_Helper_AssignConfigAndLanguage
extends Zend_Controller_Action_Helper_Abstract
{
/**
* Actual Zend_View instance
* @var Zend_View
*/
protected $_view;
/**
* PreDispatcher
*
* @return void
*/
public function preDispatch()
{
$controllerName = $this->getRequest()->getControllerName();
if ($controllerName == 'install') {
return;
}
$view = $this->getView();
$view->config = Msd_Configuration::getInstance();
$view->lang = Msd_Language::getInstance();
}
/**
* Get the view instance of the actual controller
*
* @return Zend_View
*/
public function getView()
{
if (null !== $this->_view) {
return $this->_view;
} else {
$controller = $this->getActionController();
$this->_view = $controller->view;
return $this->_view;
}
}
}

Datei anzeigen

@ -0,0 +1,116 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Auth_adapter
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Adapter to use Zend_Auth with INI files.
*
* @package MySQLDumper
* @subpackage Auth_adapter
*/
class Msd_Auth_Adapter_Ini implements Zend_Auth_Adapter_Interface
{
/**
* User database
*
* @var array
*/
private $_users = null;
/**
* Username for authentication.
*
* @var string
*/
private $_username = null;
/**
* Password for authentication.
*
* @var string
*/
private $_password = null;
/**
* Class constructor
*
* @param string $iniFilename Filename for registered users
*
* @return void
*/
public function __construct($iniFilename)
{
if (!file_exists($iniFilename)) {
throw new Msd_Exception(
'INI file with authentication information doesn\'t exists!'
);
}
$this->_users = parse_ini_file($iniFilename, true);
}
/**
* set the username, which is used for authentication.
*
* @return void
*/
public function setUsername($username)
{
$this->_username = (string) $username;
}
/**
* Set the password, which is used for authentication.
*
* @return void
*/
public function setPassword($password)
{
$this->_password = (string) $password;
}
/**
* Authenticate with the given credentials.
*
* @return Zend_Auth_Result
*/
public function authenticate()
{
if ($this->_username == null || $this->_password == null) {
throw new Msd_Exception(
'You must set the username and password first!'
);
}
$authResult = false;
foreach ($this->_users as $userId => $user) {
if (
$this->_username == $user['name'] &&
md5($this->_password) == $user['pass']
) {
$authResult = array(
'id' => $userId,
'name' => $user['name'],
);
}
}
if ($authResult === false) {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
array(),
array('L_LOGIN_INVALID_USER')
);
}
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$authResult
);
}
}

318
library/Msd/Configuration.php Normale Datei
Datei anzeigen

@ -0,0 +1,318 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Configuration
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Configuration class implemented as singleton
*
* Handles getting and setting of configuration variables
*
* @package MySQLDumper
* @subpackage Configuration
*/
class Msd_Configuration
{
/**
* Instance
*
* @var Msd_Configuration
*/
private static $_instance = NULL;
/**
* Configuration params
*
* @var StdClass
*/
private $_data = null;
/**
* Session to old values
*
* @var Zend_Session_Namespace
*/
private $_session = null;
/**
* Constructor
*
* @param string $configName The name of the configuration file to load.
* If not set we will load the config from
* session if present.
* @param bool $forceLoading Force loading of configuration from file
*/
private function __construct($configName = '', $forceLoading = false)
{
$this->_session = new Zend_Session_Namespace('MySQLDumper');
if ($forceLoading === false && isset($this->_session->dynamic->configFile)) {
$this->loadConfigFromSession();
return;
}
$this->_data = new stdClass;
if ($configName == '') {
$configName = 'defaultConfig';
}
$this->_data->dynamic = Msd_ConfigurationPhpValues::getDynamicValues();
$this->_data->paths = $this->_loadUserDirectories();
$this->loadConfiguration($configName);
$this->set('dynamic.configFile', $configName);
$defaultDb = $this->get('config.dbuser.defaultDb');
if ($defaultDb != '') {
$this->set('dynamic.dbActual', $defaultDb);
}
$this->saveConfigToSession();
}
/**
* No cloning for singleton
*
* @return void
*/
public function __clone()
{
throw new Msd_Exception('Cloning is not allowed');
}
/**
* Returns the configuration instance
*
* @param string $configName The name of the configuration file to load.
* If not set we will load the config from
* session if present.
* @param boolean $forceLoading If set the config will be read from file.
*
* @return Msd_Configuration
*/
public static function getInstance($configName = '', $forceLoading = false)
{
if (null == self::$_instance) {
self::$_instance = new self($configName, $forceLoading);
}
if ($forceLoading) {
self::$_instance->loadConfiguration($configName, true);
}
return self::$_instance;
}
/**
* Set a key to a val
*
* @param string $configPath Must begin with "config", "dynamic" or "paths"
* @param string $val The value to set
*
* @return Msd_Configuration
*/
public function set($configPath, $val)
{
$args = explode('.', $configPath);
if (!in_array($args[0], array('config', 'paths', 'dynamic'))) {
$msg = 'Trying to set config value with illegal key. First key '
. 'must be "config", "paths" or "dynamic"';
throw new Msd_Exception($msg);
}
switch (count($args)) {
case 2:
list($type, $var) = $args;
$this->_data->$type->$var = $val;
break;
case 3:
list($type, $section, $var) = $args;
$this->_data->$type->$section->$var = $val;
break;
default:
$backTrace = debug_backtrace(false);
throw new Msd_Exception(
'Path couldn\'t be set!' . PHP_EOL . $configPath .
' invoked from ' . $backTrace[0]['file'] . '[' .
$backTrace[0]['line'] . ']',
E_USER_NOTICE
);
}
return $this;
}
/**
* Get a config parameter
*
* If first part isn't config, paths or dynamic, we assume config is meant.
*
* @param string $key Path to get
*
* @return string|array
*/
public function get($key)
{
$params = explode('.', $key);
if (!in_array($params[0], array('config', 'paths', 'dynamic'))) {
$msg = 'Trying to get config value with illegal key. First key '
. 'must be "config", "paths" or "dynamic"';
throw new Msd_Exception($msg);
}
$values = $this->_data->$params[0];
if (!is_array($values)) {
$values = $this->_data->$params[0]->toArray();
}
if (sizeof($params) == 1) {
return $values;
}
unset($params[0]);
foreach ($params as $index) {
if (isset($values[$index])) {
$values = $values[$index];
} else {
$values = null;
break;
}
}
return $values;
}
/**
* Save configurations to file
*
* @param string $fileName Name of configuration without extension .ini
* @param array $configArray Data to save as array
*
* @return void
*/
public function save($fileName = null, $configArray = null)
{
if ($fileName === null) {
$fileName = $this->get('dynamic.configFile');
}
$fileName .= '.ini';
// save branch config and skip groups "dynamic" and "paths"
if ($configArray !== null) {
$configData = new Zend_Config($configArray, true);
} else {
$configData = $this->_data->config;
}
$configWriter = new Zend_Config_Writer_Ini(
array(
'filename' => $this->get('paths.config') . DS . $fileName,
'config' => $configData,
)
);
$configWriter->write();
$this->_data->config = $configData;
$this->set('dynamic.configFile', basename($fileName, '.ini'));
$this->saveConfigToSession();
}
/**
* Save config to session
*
* @return void
*/
public function saveConfigToSession()
{
$this->_session->unsetAll();
$this->_session->config = $this->_data->config;
$this->_session->dynamic = $this->_data->dynamic;
$this->_session->paths = $this->_data->paths;
}
/**
* Get config from session
*
* @return object
*/
public function loadConfigFromSession()
{
if (isset($this->_session->config)) {
$this->_data->config = $this->_session->config;
}
if (isset($this->_session->dynamic)) {
$this->_data->dynamic = $this->_session->dynamic;
}
if (isset($this->_session->paths)) {
$this->_data->paths = $this->_session->paths;
}
}
/**
* Load configuration file
*
* @param string $configName The configuration file to load
* @param boolean $applyValues Whether to apply loaded values to config
*
* @return Zend_Config_ini Loaded configuration as Zend_Config_Ini
*/
public function loadConfiguration($configName, $applyValues = true)
{
$this->_loadUserDirectories();
if ($configName != 'defaultConfig') {
$configName .= '.ini';
$configPath = $this->get('paths.config');
$configFile = $configPath . DS . $configName;
} else {
// special case - defaultConfig.ini is in application/configs
$configFile = realpath(APPLICATION_PATH . DS . 'configs')
. DS . 'defaultConfig.ini';
}
if (!is_readable($configFile)) {
throw new Msd_Exception(
'Couldn\'t read configuration file ' . $configFile
);
}
$options = array('allowModifications' => true);
$config = new Zend_Config_Ini($configFile, null, $options);
if (!$applyValues) {
return $config;
}
$this->_data->config = null;
$this->_data->config = $config;
$this->set('dynamic.configFile', basename($configFile, '.ini'));
$iconPath = 'css/' . $this->get('config.interface.theme') . '/icons';
$this->set('paths.iconpath', $iconPath);
$this->saveConfigToSession();
return $config;
}
/**
* Get user directories and save them to config
*
* @return Zend_Config Directories as object
*/
private function _loadUserDirectories()
{
// set paths
$workRoot = realpath(APPLICATION_PATH . DS . '..') . DS . 'work' . DS;
$directories = array(
'work' => $workRoot,
'log' => $workRoot . 'log',
'backup' => $workRoot . 'backup',
'config' => $workRoot . 'config'
);
return new Zend_Config($directories, true);
}
/**
* Return name of configuration
*
* @return string
*/
public function getTitle()
{
return $this->get('config.general.title');
}
/**
* Reloads the configuration from the current ini file.
*
* @return void
*/
public function reloadConfig()
{
$this->loadConfiguration($this->get('dynamic.configFile'));
}
}

Datei anzeigen

@ -0,0 +1,136 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Configuration
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Helper for getting dynamic configuration values like phpRam etc.
*
* @package MySQLDumper
* @subpackage Configuration
*/
class Msd_ConfigurationPhpValues
{
/**
* Read dynamic PHP config values
*
* @return Zend_Config
*/
public static function getDynamicValues ()
{
$phpRam = self::_getPhpRam();
$dynConfig = array(
'sendmailCall' => self::_getConfigSetting('sendmail_path'),
'safeMode' => self::_getConfigSetting('safe_mode', true),
'magicQuotesGpc' => get_magic_quotes_gpc(),
'disabledPhpFunctions' =>
str_replace(
',',
', ',
self::_getConfigSetting('disable_functions')
),
'maxExecutionTime' => self::_getMaxExecutionTime(),
'uploadMaxFilesize' => self::_getUploadMaxFilesize(),
'phpextensions' => implode(', ', get_loaded_extensions()),
'phpRam' => $phpRam,
'memoryLimit' => round($phpRam * 1024 * 1024 * 0.9, 0),
'compression' => self::_hasZlib(),
);
return new Zend_Config($dynConfig, true);
}
/**
* Read PHP's max_execution_time
*
* @return int
*/
private static function _getMaxExecutionTime()
{
$maxExecutionTime =
self::_getConfigSetting('max_execution_time', true);
if ($maxExecutionTime <= 5) {
// we didn't get the real value from the server - some deliver "-1"
$maxExecutionTime = 30;
} elseif ($maxExecutionTime > 30) {
// we don't use more than 30 seconds to avoid brower timeouts
$maxExecutionTime = 30;
}
return $maxExecutionTime;
}
/**
* Get PHP's upload_max_filesize
*
* @return int
*/
private static function _getUploadMaxFilesize()
{
$uploadMaxFilesize = self::_getConfigSetting('upload_max_filesize');
// Is value in Megabytes? If yes create output
if (strpos($uploadMaxFilesize, 'M')) {
$uploadMaxFilesize = str_replace('M', '', $uploadMaxFilesize);
$uploadMaxFilesize = trim($uploadMaxFilesize);
// re-calculate to Bytes
$uploadMaxFilesize *= 1024 * 1024;
}
return (int) $uploadMaxFilesize;;
}
/**
* Get PHP's ram size
*
* @return integer The memory limit in MB
*/
private static function _getPhpRam()
{
$ram = self::_getConfigSetting('memory_limit');
// we don't trust the value delivered by server config if < 16
if ($ram < 16) {
$ram = 16;
}
return $ram;
}
/**
* Detect if zlib is installed
*
* @return boolean
*/
private static function _hasZlib()
{
$zlib = false;
$extensions = get_loaded_extensions();
if (in_array('zlib', $extensions)) {
$zlib = true;
};
return (boolean) $zlib;
}
/**
* Returns a PHP-Setting from ini
*
* First try to read via ini_get(), then fall back to get_cfg_var()
*
* @param string $varName The name of the setting to read
* @param boolean $returnAsInt Whether to return value as integer
*/
private function _getConfigSetting($varName, $returnAsInt = false)
{
$value = @ini_get($varName);
// fallback if ini_get doesn't work
if ($value == '' || $value === null) {
$value = @get_cfg_var($varName);
}
if ($returnAsInt) {
$value = (int) $value;
}
return $value;
}
}

248
library/Msd/Crypt.php Normale Datei
Datei anzeigen

@ -0,0 +1,248 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Encryption
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Class for text en- and decryption.
*
* @package MySQLDumper
* @subpackage Encryption
*/
class Msd_Crypt
{
/**
* Holds the encryption descriptor
*
* @var resource
*/
private $_encDescriptor = null;
/**
* Holds the initialization vector
*
* @var resource
*/
private $_initVector = null;
/**
* Holds the algorithm wichc is currently used.
*
* @var string
*/
private $_algorithm = MCRYPT_TWOFISH;
/**
* Holds the current encryption key.
*
* @var string
*/
private $_encryptionKey = null;
/**
* Instance of this class.
*
* @var Msd_Crypt
*/
private static $_instance = null;
/**
* Identificator for encrypted text
*
* @var string
*/
private $_cryptIdent = 'Z';
/**
* Class constructor
*
* @param string $cryptKey Encryption key
* @param string $algorithm Algorithm for encryption
*
* @return void
*/
private function __construct($cryptKey = null, $algorithm = null)
{
if ($cryptKey === null) {
$cryptKey = md5(time());
}
if ($algorithm === null) {
$algorithm = $this->_algorithm;
}
$this->init($cryptKey, $algorithm);
}
/**
* Get the instance of this class.
*
* @param string $cryptKey Encryption key
* @param string $algorithm Algorithm for encryption
*
* @return Msd_Crypt
*/
public static function getInstance($cryptKey = null, $algorithm = null)
{
if (self::$_instance === null) {
self::$_instance = new self($cryptKey, $algorithm);
}
return self::$_instance;
}
/**
* Initializes the encryption descriptor.
*
* @param string $encryptionKey Key for encryption
* @param string $algorithm Algorithm for encryption
*
* @return void
*/
public function init($encryptionKey = null, $algorithm = null)
{
if ($encryptionKey === null) {
$encryptionKey = $this->_encryptionKey;
}
if ($algorithm === null) {
$algorithm = $this->_algorithm;
}
if (!is_resource($this->_encDescriptor)) {
$this->_encDescriptor = mcrypt_module_open(
$algorithm,
'',
MCRYPT_MODE_ECB,
''
);
$vectorSize = mcrypt_enc_get_iv_size($this->_encDescriptor);
$this->_initVector = mcrypt_create_iv($vectorSize, MCRYPT_RAND);
$keySize = mcrypt_enc_get_key_size($this->_encDescriptor);
$key = substr(md5($encryptionKey), 0, $keySize);
mcrypt_generic_init(
$this->_encDescriptor,
$key,
$this->_initVector
);
$this->_encryptionKey = $encryptionKey;
}
}
/**
* Uninitialize the encryption descriptor.
*
* @return void
*/
public function deinit()
{
if (is_resource($this->_encDescriptor)) {
mcrypt_generic_deinit($this->_encDescriptor);
}
}
/**
* Close the encryption descriptor
*
* @return void
*/
public function close()
{
$this->deinit();
if (is_resource($this->_encDescriptor)) {
mcrypt_module_close($this->_encDescriptor);
}
$this->_encDescriptor = null;
}
/**
* Decodes an base64 encoded string.
*
* @param string $encodedString base64 encoded string
*
* @return sting
*/
private function _base64Decode($encodedString)
{
if (substr($encodedString, 0, 1) !== $this->_cryptIdent) {
return $encodedString;
}
$encodedString = str_replace(
array('.', '_', '-'),
array('+', '/', '='),
substr($encodedString, 1)
);
$decodedString = base64_decode($encodedString);
return $decodedString;
}
/**
* Encode a string into base64 notation.
*
* @param string $plainString Plaintext
*
* @return string
*/
private function _base64Encode($plainString)
{
$encodedString = base64_encode($plainString);
$encodedString = str_replace(
array('+', '/', '='),
array('.', '_', '-'),
$encodedString
);
return $this->_cryptIdent . $encodedString;
}
/**
* Decrypts a text.
*
* @param string $encryptedText Text to decrypt
*
* @return string
*/
public function decrypt($encryptedText)
{
$encryptedText = $this->_base64Decode($encryptedText);
if (!is_resource($this->_encDescriptor)) {
$this->init($this->_encryptionKey);
}
$clearText = mdecrypt_generic(
$this->_encDescriptor,
$encryptedText
);
return trim($clearText);
}
/**
* Encrypts a text
*
* @param string $clearText Text to encrypt
*
* @return string
*/
public function encrypt($clearText)
{
if (!is_resource($this->_encDescriptor)) {
$this->init();
}
$encryptedText = mcrypt_generic(
$this->_encDescriptor,
$clearText
);
return $this->_base64Encode($encryptedText);
}
/**
* Class destructor
*
* @return void
*/
public function __destruct()
{
$this->close();
}
}

346
library/Msd/Db.php Normale Datei
Datei anzeigen

@ -0,0 +1,346 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Db
* @version SVN: $rev: 1212 $
* @author $Author$
*/
/**
* DB-Factory
*
* @abstract
* @package MySQLDumper
* @subpackage Db
*/
abstract class Msd_Db
{
// 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
/**
* SQL-Server
*
* @var string
*/
protected $_server;
/**
* SQL user used to authenticate at server
*
* @var string
*/
protected $_user;
/**
* SQL user password used to authenticate
*
* @var string
*/
protected $_password;
/**
* Port used for connection to server
*
* @var int
*/
protected $_port;
/**
* Socket used for connection
*
* @var string
*/
protected $_socket;
/**
* List of databases adn default settings
* @var array
*/
protected $_databases = null;
/**
* charset to use (default utf8)
*
* @var string
*/
protected $_connectionCharset = 'utf8';
/**
* the selected db
*
* @var string
*/
protected $_dbSelected = '';
/**
* List of cached tables
*
* @var array
*/
protected $_tables = array();
/**
* Meta informations about tables
*
* @var array
*/
protected $_metaTables = array();
/**
* Charsets the server supports (cached)
*
* @var array
*/
protected $_charsets = array();
/**
* Init database object
*
* @param array $options Array containing connection options
*
* @return void
*/
protected function __construct ($options)
{
$this->_server = $options['host'];
$this->_user = $options['user'];
$this->_password = $options['pass'];
$this->_port = (int) $options['port'];
$this->_socket = $options['socket'];
}
/**
* Create database adapter
*
* @param array $options Connection options
* @param boolean $forceMysql Whether to force the use of MySQL
*
* @return MsdDbFactory
*/
public static function getAdapter($options = null, $forceMysql = false)
{
if ($options === null) {
$config = Msd_Configuration::getInstance();
$options = array(
'host' => $config->get('config.dbuser.host'),
'user' => $config->get('config.dbuser.user'),
'pass' => $config->get('config.dbuser.pass'),
'port' => (int) $config->get('config.dbuser.port'),
'socket' => $config->get('config.dbuser.socket'),
);
}
if (function_exists('mysqli_connect') && !$forceMysql) {
$dbObject = new Msd_Db_Mysqli($options);
} else {
$dbObject = new Msd_Db_Mysql($options);
}
return $dbObject;
}
/**
* Establish a connection to SQL-Server. The connection is stored and used
* for further DB requests.
*
* @return bool if connection is successfull
* */
abstract protected function _dbConnect ();
/**
* 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 array
*/
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 query and set _resultHandle
*
* If $getRows is true alls rows are fetched and returned
*
* @param string $query The query to execute
* @param const $kind Type of result set
* @param boolean $getRows Whether to fetch all rows and return them
*
* @return boolean|array
*/
abstract public function query ($query,
$kind = self::ARRAY_OBJECT, $getRows = true);
/**
* Get next row from result set
*
* @param const $kind
*
* @return array|object
*/
abstract public function getNextRow($kind);
/**
* Get the list of tables of given database
*
* @param string $dbName Name of database
*
* @return array
*/
abstract public function getTables ($dbName);
/**
* Gets extended table information for one or all tables
*
* @param string $table
*
* @return array
*/
abstract public function getTableStatus ($table = false);
/**
* Returns the CREATE Statement of a table.
*
* @throws Exception
* @param string $table Get CREATE-Statement for this table
*
* @return string Create statement
*/
abstract public function getTableCreate ($table);
/**
* 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
*
* @return array
*/
abstract public function getTableColumns ($table);
/**
* Gets the number of affected rows of the last query
*
* @return int
*/
abstract public function getAffectedRows ();
/**
* Gets the servers variables
*
* @return array
*/
abstract public function getVariables ();
/**
* Escape a value for inserting it in query
*
* @param string $val
*
* @return string
*/
abstract public 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 public function optimizeTable ($table);
/**
* Creates a new database with the given name, charackter set and collation.
*
* @abstract
*
* @param string $databaseName Name of the new database
* @param string $databaseCharset Charackter set of the new database
* @param string $databaseCollation Collation of the new database
*
* @return bool
*/
abstract public function createDatabase(
$databaseName,
$databaseCharset = '',
$databaseCollation = ''
);
/**
* Retrieves the collations from information schema.
*
* @param string|null $charsetName Name of the charset
*
* @return array
*/
abstract public function getCollations($charsetName = null);
/**
* Retrieves the default collation for the charset or the given charset.
*
* @param string|null $charsetName Name of the charset
*
* @return array|string
*/
abstract public function getDefaultCollations($charsetName = null);
/**
* Retrieves the last MySQL error.
*
* @return array
*/
abstract public function getLastError();
/**
* Handles a SQL-Error
*
* @param string $errmsg
* @param int $errno
* @throws MsdEception
*
* @return void
*/
public function sqlError ($errmsg, $errno)
{
throw new Msd_Exception($errmsg, $errno);
}
}

240
library/Msd/Db/Mysql.php Normale Datei
Datei anzeigen

@ -0,0 +1,240 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Db
* @version SVN: $rev: 1205 $
* @author $Author$
*/
/**
* Capsules all database related actions.
*
* @package MySQLDumper
* @subpackage Db
*/
class Msd_Db_Mysql extends Msd_Db_MysqlCommon
{
/**
* Mysql connection handle
*
* @var resource
*/
protected $_connectionHandle = null;
/**
* Mysql result handle
*
* @var resource
*/
protected $_resultHandle = null;
/**
* Establish a connection to MySQL.
*
* Creates a connection to the database and stores the connection handle in
* $this->_connectionHandle.
* Returns true on success or false if connection couldn't be established.
*
* @throws Exception
* @return bool
**/
protected function _dbConnect()
{
if (is_resource($this->_connectionHandle)) {
return true;
}
if ($this->_port == 0) {
$this->_port = 3306;
}
$connectionString = $this->_server . ':' . $this->_port;
if ($this->_socket != '') {
$connectionString .= ':' . $this->_socket;
}
$this->_connectionHandle = @mysql_connect(
$connectionString,
$this->_user, $this->_password
);
if (false === $this->_connectionHandle) {
throw new Msd_Exception(mysql_error(), mysql_errno());
}
$this->setConnectionCharset();
return true;
}
/**
* Returns the connection handle if already established or creates one.
*
* @return resource The connection handle
*/
private function _getHandle()
{
if (!is_resource($this->_connectionHandle)) {
$this->_dbConnect();
}
return $this->_connectionHandle;
}
/**
* Return version nr of MySql server.
*
* @return string Version number
*/
public function getServerInfo()
{
return mysql_get_server_info($this->_getHandle());
}
/**
* Get version nr of MySql client.
*
* @return string Version nr
*/
public function getClientInfo()
{
return mysql_get_client_info();
}
/**
* Sets the character set of the MySQL-connection.
*
* Trys to set the connection charset and returns it.
*
* @param string $charset The wanted charset of the connection
*
* @return string The set charset
*/
public function setConnectionCharset($charset = 'utf8')
{
if (function_exists('mysql_set_charset')
&& @mysql_set_charset($charset, $this->_getHandle())) {
$this->_connectionCharset = $charset;
return $this->_connectionCharset;
} else {
$this->query('SET NAMES \'' . $charset . '\'', self::SIMPLE);
$this->_connectionCharset = $charset;
return $charset;
}
}
/**
* 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 The database to select
*
* @return bool
*/
public function selectDb($database)
{
$res = @mysql_select_db($database, $this->_getHandle());
if ($res === false) {
throw new Msd_Exception(mysql_error(), mysql_errno());
}
$this->_dbSelected = $database;
return true;
}
/**
* Execute a query and set _resultHandle
*
* If $getRows is true all rows are fetched and returned.
* If $getRows is false, query will be executed, but the result handle
* is returned.
*
* @param string $query The query to execute
* @param const $kind Type of result set
* @param boolean $getRows Wether to fetch all rows and return them
*
* @return boolean|array
*/
public function query($query, $kind = self::ARRAY_OBJECT, $getRows = true)
{
$this->_resultHandle = @mysql_query($query, $this->_getHandle());
if (false === $this->_resultHandle) {
$this->sqlError(
mysql_error($this->_connectionHandle),
mysql_errno($this->_connectionHandle)
);
}
if ($kind === self::SIMPLE || is_bool($this->_resultHandle)) {
return $this->_resultHandle;
}
// return result set?
if ($getRows) {
$ret = array();
WHILE ($row = $this->getNextRow($kind)) {
$ret[] = $row;
}
$this->_resultHandle = null;
return $ret;
}
}
/**
* Get next row from a result set that is returned by $this->query().
*
* Can be used to walk through result sets.
*
* @param const $kind
*
* @return array|object
*/
public function getNextRow($kind)
{
switch ($kind)
{
case self::ARRAY_OBJECT:
return mysql_fetch_object($this->_resultHandle);
break;
case self::ARRAY_NUMERIC:
return mysql_fetch_array($this->_resultHandle, MYSQL_NUM);
break;
case self::ARRAY_ASSOC:
return mysql_fetch_array($this->_resultHandle, MYSQL_ASSOC);
}
}
/**
* 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->_getHandle());
}
/**
* Escape a value with real_escape_string() 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->_getHandle());
}
/**
* Retrieves the last MySQL error.
*
* @return void
*/
public function getLastError()
{
return array(
'code' => mysql_errno($this->_getHandle()),
'message' => mysql_error($this->_getHandle()),
);
}
}

533
library/Msd/Db/MysqlCommon.php Normale Datei
Datei anzeigen

@ -0,0 +1,533 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Db
* @version SVN: $rev: 1205 $
* @author $Author$
*/
/**
* Class offers some db related methods that are equal for Mysql and MySQLi.
*
* @package MySQLDumper
* @subpackage Db
*/
abstract class Msd_Db_MysqlCommon extends Msd_Db
{
/**
* Get the list of table and view names of given database
*
* @param string $dbName Name of database
*
* @return array
*/
public function getTables($dbName)
{
$tables = array();
$sql = 'SHOW TABLES FROM `' . $dbName . '`';
$res = $this->query($sql, self::ARRAY_NUMERIC);
foreach ($res as $val) {
$tables[] = $val[0];
}
return $tables;
}
/**
* Get the list of tables of the given database. The result include tables
* meta data.
*
* @param string $dbName Name of database
*
* @return array
*/
public function getTablesMeta($dbName)
{
$tablesSql = 'SELECT * FROM `information_schema`.`TABLES` '
. 'WHERE `TABLE_SCHEMA` = \'' . $this->escape($dbName) . '\'';
$rawTables = $this->query($tablesSql, self::ARRAY_ASSOC);
$tables = array();
foreach ($rawTables as $rawTable) {
$tables[$rawTable['TABLE_NAME']] = $rawTable;
}
return $tables;
}
/**
* Get information of databases
*
* Gets list and info of all databases that the actual MySQL-User can access
* and saves it in $this->databases.
*
* @param bool $addViews If set nr of views and routines are added
*
* @return array
*/
public function getDatabases($addViews = false)
{
$query = 'SELECT `is`.*, count(`t`.`TABLE_NAME`) `tables`'
. ' FROM `information_schema`.`SCHEMATA` `is`'
. ' LEFT JOIN `information_schema`.`TABLES` `t` '
. ' ON `t`.`TABLE_SCHEMA` = `is`.`SCHEMA_NAME`'
. ' GROUP BY `is`.`SCHEMA_NAME`'
. ' ORDER BY `is`.`SCHEMA_NAME` ASC';
$res = $this->query($query, self::ARRAY_ASSOC, true);
if ($addViews) {
$views = $this->getNrOfViews();
$routines = $this->getNrOfRoutines();
$sizes = $this->getDatabaseSizes();
}
foreach ($res as $row) {
$database = $row['SCHEMA_NAME'];
if ($addViews) {
$row['views'] = 0;
$row['routines'] = 0;
$row['size'] = 0;
$row[$database] = 0;
if (isset($sizes[$database])) {
$row['size'] = $sizes[$database];
}
// add views
if (isset($views[$database])) {
$row['views'] = $views[$database];
$row['tables'] -= $views[$database];
}
// add routines
if (isset($routines[$database])) {
$row['routines'] = $routines[$database];
}
}
unset($row['SCHEMA_NAME']);
$this->_databases[$database] = $row;
}
return $this->_databases;
}
/**
* Return assoc array with the names of accessable databases
*
* @return array Assoc array with database names
*/
public function getDatabaseNames()
{
if ($this->_databases == null) {
$this->getDatabases();
}
return array_keys($this->_databases);
}
/**
* Returns the actual selected database.
*
* @return string
*/
public function getSelectedDb()
{
return $this->_dbSelected;
}
/**
* Returns the CREATE Statement of a table.
*
* @param string $table
*
* @return string
*/
public function getTableCreate($table)
{
$sql = 'SHOW CREATE TABLE `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
return $res[0]['Create Table'];
}
/**
* Gets the full description of all columns of a table.
*
* Saves it to $this->metaTables[$database][$table].
*
* @param string $table
*
* @return array
*/
public function getTableColumns($table)
{
$dbName = $this->getSelectedDb();
$sql = 'SHOW FULL FIELDS FROM `' . $table . '`';
$res = $this->query($sql, self::ARRAY_ASSOC);
if (!isset($this->_metaTables[$dbName])) {
$this->_metaTables[$dbName] = array();
}
if (is_array($res)) {
$this->_metaTables[$dbName][$table] = array();
foreach ($res as $r) {
$this->_metaTables[$dbName][$table][$r['Field']] = $r;
}
}
return $this->_metaTables[$dbName][$table];
}
/**
* Optimize given table.
*
* Returns false on error or Sql's Msg_text if query succeeds.
*
* @param string $table Name of table
*
* @return array
*/
public function optimizeTable($table)
{
return $this->_executeMaintainAction('OPTIMIZE', $table);
}
/**
* Analyze given table.
*
* Returns false on error or Sql's Msg_text if query succeeds.
*
* @param string $table Name of table
*
* @return array
*/
public function analyzeTable($table)
{
return $this->_executeMaintainAction('ANALYZE', $table);
}
/**
* Check given table.
*
* Returns false on error or Sql's Msg_text if query succeeds.
*
* @param string $table Name of table
*
* @return array
*/
public function checkTable($table)
{
return $this->_executeMaintainAction('CHECK', $table);
}
/**
* Repair given table.
*
* Returns false on error or Sql's Msg_text if query succeeds.
*
* @param string $table Name of table
*
* @return array
*/
public function repairTable($table)
{
return $this->_executeMaintainAction('REPAIR', $table);
}
/**
* Truncate a table (delete all records)
*
* @param string $table The tabel to truncate
*
* @return bool
*/
public function truncateTable($table)
{
$sql = 'TRUNCATE `' . $this->escape($table) . '`';
$res = $this->query($sql, self::SIMPLE);
return $res;
}
/**
* Execute maintaining action on a table (optimize, analyze, check, repair)
*
* @param string $action Action to perform
*
* @return array Result array conataining messages
*/
private function _executeMaintainAction($action, $table)
{
$sql = $action . ' TABLE `' . $this->escape($table) . '`';
try {
$res = $this->query($sql, Msd_Db::ARRAY_ASSOC);
if (isset($res[0]['Msg_text'])) {
return $res[0];
}
} catch (Msd_Exception $e) {
unset($e);
}
$ret = array('Table' => $table);
return array_merge($ret, $this->getLastError());
}
/**
* Get list of known charsets from MySQL-Server.
*
* @return array
*/
public function getCharsets()
{
if (!empty($this->_charsets)) {
return $this->_charsets;
}
$sql = 'SELECT * FROM `information_schema`.`CHARACTER_SETS` ORDER BY `CHARACTER_SET_NAME`';
$result = $this->query($sql, self::ARRAY_ASSOC);
$this->_charsets = array();
foreach ($result as $res) {
$this->_charsets[$res['CHARACTER_SET_NAME']] = $res;
}
return $this->_charsets;
}
/**
* Gets extended table information for one or all tables.
*
* @param string | false $tableName
* @param string | false $databaseName
*
* @return array
*/
public function getTableStatus($tableName = false, $databaseName = false)
{
if ($databaseName === false) {
$databaseName = $this->getSelectedDb();
}
$sql = "SELECT * FROM `information_schema`.`TABLES` WHERE "
. "`TABLE_SCHEMA`='" . $this->escape($databaseName) . "'";
if ($tableName !== false) {
$sql .= " AND `TABLE_NAME` LIKE '" . $this->escape($tableName) . "'";
}
$res = $this->query($sql, self::ARRAY_ASSOC);
return $res;
}
/**
* Get variables of SQL-Server and return them as assoc array
*
* @return array
*/
public function getVariables()
{
$ret = array();
$variables = $this->query('SHOW VARIABLES', Msd_Db::ARRAY_ASSOC);
foreach ($variables as $val) {
$ret[$val['Variable_name']] = $val['Value'];
}
return $ret;
}
/**
* Get global status variables of SQL-Server and return them as assoc array
*
* @return array
*/
public function getGlobalStatus()
{
$ret = array();
$variables = $this->query('SHOW GLOBAL STATUS', Msd_Db::ARRAY_ASSOC);
foreach ($variables as $val) {
$ret[$val['Variable_name']] = $val['Value'];
}
return $ret;
}
/**
* Get the number of records of a table by query SELECT COUNT(*)
*
* @param string $tableName The name of the table
* @param string $dbName The name of the database
*
* @return integer The number of rows isnide table
*/
public function getNrOfRowsBySelectCount($tableName, $dbName = null)
{
if ($dbName === null) {
$dbName = $this->getSelectedDb();
}
;
$sql = 'SELECT COUNT(*) as `Rows` FROM `%s`.`%s`';
$sql = sprintf($sql, $this->escape($dbName), $this->escape($tableName));
$rows = $this->query($sql, Msd_Db::ARRAY_ASSOC);
return (int)$rows[0]['Rows'];
}
/**
* Retrieves the collations from information schema.
*
* @param string|null $charsetName Name of the charset
*
* @return array
*/
public function getCollations($charsetName = null)
{
$where = "";
if (!empty($charsetName)) {
$where = "WHERE `CHARACTER_SET_NAME` = '" . $this->escape($charsetName) . "'";
}
$collationSql = "SELECT `CHARACTER_SET_NAME` `charset`, "
. "GROUP_CONCAT(`COLLATION_NAME` ORDER BY `COLLATION_NAME`) "
. "`collations` FROM `information_schema`."
. "`COLLATION_CHARACTER_SET_APPLICABILITY` GROUP BY "
. "`CHARACTER_SET_NAME` $where";
$rawCollations = $this->query($collationSql, Msd_Db::ARRAY_ASSOC);
$collations = array();
foreach ($rawCollations as $charset) {
$collations[$charset['charset']] = explode(
",",
$charset['collations']
);
}
return $collations;
}
/**
* Retrieves the default collation for the charset or the given charset.
*
* @param string|null $charsetName Name of the charset
*
* @return array|string
*/
public function getDefaultCollations($charsetName = null)
{
if (!empty($charsetName)) {
$defaultCollationSql = 'SELECT `DEFAULT_COLLATE_NAME` FROM '
. '`information_schema`.`CHARACTER_SETS` WHERE '
. '`CHARACTER_SET_NAME` = \'' . $this->escape($charsetName)
. '\'';
$result = $this->query($defaultCollationSql, self::ARRAY_NUMERIC);
$defaultCollation = $result[0][0];
} else {
$defaultCollationSql = 'SELECT `CHARACTER_SET_NAME` `charset`, '
. '`DEFAULT_COLLATE_NAME` `collation` FROM '
. '`information_schema`.`CHARACTER_SETS`';
$result = $this->query($defaultCollationSql, self::ARRAY_ASSOC);
$defaultCollation = array();
foreach ($result as $row) {
$defaultCollation[$row['charset']] = $row['collation'];
}
}
return $defaultCollation;
}
/**
* Gets the views of the given database.
*
* @param string $dbName Name of database
*
* @return array
*/
public function getViews($dbName)
{
$sql = 'SELECT * FROM `information_schema`.`VIEWS` WHERE '
. '`TABLE_SCHEMA` = \'' . $this->escape($dbName) . '\'';
$rawViews = $this->query($sql, self::ARRAY_ASSOC);
$views = array();
foreach ($rawViews as $rawView) {
$views[$rawView['TABLE_NAME']] = $rawView;
}
return $views;
}
/**
* Get the number of views per database.
*
* @return array
*/
public function getNrOfViews()
{
$sql = 'SELECT `TABLE_SCHEMA`, count(*) as `views` FROM '
. '`information_schema`.`VIEWS` '
. ' GROUP BY `TABLE_SCHEMA`';
$res = $this->query($sql, self::ARRAY_ASSOC);
$views = array();
foreach ($res as $view) {
$views[$view['TABLE_SCHEMA']] = $view['views'];
}
return $views;
}
/**
* Get the number of routines (procedures and functions).
*
* @return array
*/
public function getNrOfRoutines()
{
$sql = 'SELECT `ROUTINE_SCHEMA`, count(`ROUTINE_NAME`) as `routines`'
. ' FROM `information_schema`.`ROUTINES` '
. ' GROUP BY `ROUTINE_SCHEMA`';
$res = $this->query($sql, self::ARRAY_ASSOC);
$routines = array();
foreach ($res as $routine) {
$routines[$routine['ROUTINE_SCHEMA']] = $routine['routines'];
}
return $routines;
}
/**
* Get the size of tabledata in bytes
*
* @return array
*/
public function getDatabaseSizes()
{
$sql = 'SELECT `TABLE_SCHEMA`, sum(`DATA_LENGTH`) as `size`'
. ' FROM `information_schema`.`TABLES` '
. ' GROUP BY `TABLE_SCHEMA`';
$res = $this->query($sql, self::ARRAY_ASSOC);
$sizes = array();
foreach ($res as $size) {
$sizes[$size['TABLE_SCHEMA']] = $size['size'];
}
return $sizes;
}
/**
* Gets the stored procedurs of the given database.
*
* @param string $dbName Name of database
*
* @return array
*/
public function getStoredProcedures($dbName)
{
$routinesSql = 'SELECT * FROM `information_schema`.`ROUTINES` WHERE '
. '`ROUTINE_SCHEMA` = \'' . $this->escape($dbName) . '\'';
$rawRoutines = $this->query($routinesSql, self::ARRAY_ASSOC);
$routines = array();
foreach ($rawRoutines as $rawRoutine) {
$routines[$rawRoutine['ROUTINE_NAME']] = $rawRoutine;
}
return $routines;
}
/**
* Creates a new database via building a MySQL statement and its execution.
*
* @param string $databaseName Name of the new database
* @param string $databaseCharset Charackter set of the new database
* @param string $databaseCollation Collation of the new database
*
* @return boolean
*/
public function createDatabase(
$databaseName,
$databaseCharset = '',
$databaseCollation = ''
)
{
if ($databaseCharset != '') {
$databaseCharset = "DEFAULT CHARSET "
. $this->escape($databaseCharset);
}
if ($databaseCollation != '') {
$databaseCollation = "DEFAULT COLLATE "
. $this->escape($databaseCollation);
}
$sql = "CREATE DATABASE `" . $databaseName
. "` $databaseCharset $databaseCollation";
$dbCreated = $this->query($sql, Msd_Db::SIMPLE);
return $dbCreated;
}
}

240
library/Msd/Db/Mysqli.php Normale Datei
Datei anzeigen

@ -0,0 +1,240 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Db
* @version SVN: $rev: 1208 $
* @author $Author$
*/
/**
* Capsules all database related actions.
*
* @package MySQLDumper
* @subpackage Db
*/
class Msd_Db_Mysqli extends Msd_Db_MysqlCommon
{
/**
* @var mysqli
*/
private $_mysqli = null;
/**
* @var resource
*/
private $_resultHandle = null;
/**
* Establish a connection to MySQL.
*
* Create a connection to MySQL and store the connection handle in
* $this->connectionHandle.
*
* @return boolean
**/
protected function _dbConnect()
{
$errorReporting = error_reporting(0);
if ($this->_port == 0) {
$this->_port = 3306;
}
$this->_mysqli = new mysqli(
$this->_server,
$this->_user,
$this->_password,
$this->_dbSelected,
$this->_port,
$this->_socket
);
error_reporting($errorReporting);
if ($this->_mysqli->connect_errno) {
$error = $this->_mysqli->connect_error;
$errno = $this->_mysqli->connect_errno;
$this->_mysqli = null;
throw new Msd_Exception($error, $errno);
}
$this->setConnectionCharset();
return true;
}
/**
* Returns the connection handle if already set or creates one.
*
* @return mysqli The instance of mysqli
*/
private function _getHandle()
{
if (!$this->_mysqli instanceof mysqli) {
$this->_dbConnect();
}
return $this->_mysqli;
}
/**
* Returns the version nr of MySql server.
*
* @return string Version nr
*/
public function getServerInfo()
{
return $this->_getHandle()->server_info;
}
/**
* Return version nr of MySql client.
*
* @return string Version nr
*/
public function getClientInfo()
{
return $this->_getHandle()->client_info;
}
/**
* Sets the character set of the MySQL-connection.
*
* Trys to set the connection charset and returns it.
*
* @param string $charset The wanted charset of the connection
*
* @return string The set charset
*/
public function setConnectionCharset($charset = 'utf8')
{
if (!@$this->_getHandle()->set_charset($charset)) {
$this->sqlError(
$charset . ' ' . $this->_mysqli->error,
$this->_mysqli->errno
);
}
$this->_connectionCharset = $this->_getHandle()->character_set_name();
return $this->_connectionCharset;
}
/**
* Select the given database to use it as the target for following queries.
*
* Returns true if selection was succesfull, otherwise false.
*
* @param string $database Database to select
*
* @return boolean True on success
*/
public function selectDb($database)
{
$res = @$this->_getHandle()->select_db($database);
if ($res === false) {
return $this->_getHandle()->error;
} else {
$this->_dbSelected = $database;
return true;
}
}
/**
* Execute a query and set _resultHandle
*
* If $getRows is true all rows are fetched and returned.
* If $getRows is false, query will be executed, but the result handle
* is returned.
*
* @param string $query The query to execute
* @param const $kind Type of result set
* @param boolean $getRows Wether to fetch all rows and return them
*
* @return resource|array
*/
public function query($query, $kind = self::ARRAY_OBJECT, $getRows = true)
{
try {
$this->_resultHandle = $this->_getHandle()->query($query);
if (false === $this->_resultHandle) {
$this->sqlError(
$this->_getHandle()->error,
$this->_getHandle()->errno
);
}
if (!$this->_resultHandle instanceof mysqli_result
|| $kind === self::SIMPLE) {
return $this->_resultHandle;
}
// return result set?
if ($getRows) {
$ret = array();
WHILE ($row = $this->getNextRow($kind)) {
$ret[] = $row;
}
$this->_resultHandle = null;
return $ret;
}
} catch (Exception $e) {
$this->sqlError(
$this->_getHandle()->error,
$this->_getHandle()->errno
);
}
}
/**
* Get next row from a result set that is returned by $this->query().
*
* Can be used to walk through result sets.
*
* @param const $kind
*
* @return array|object
*/
public function getNextRow($kind)
{
switch ($kind)
{
case self::ARRAY_ASSOC:
return $this->_resultHandle->fetch_assoc();
case self::ARRAY_OBJECT:
return $this->_resultHandle->fetch_object();
break;
case self::ARRAY_NUMERIC:
return $this->_resultHandle->fetch_array(MYSQLI_NUM);
break;
}
}
/**
* Gets the number of affected rows for the last executed query.
*
* @see inc/classes/db/MsdDbFactory#affectedRows()
* @return integer
*/
public function getAffectedRows()
{
return $this->_getHandle()->affected_rows;
}
/**
* Escape a value with real_escape_string() 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->_getHandle()->real_escape_string($val);
}
/**
* Retrieves the last MySQL error.
*
* @return array
*/
public function getLastError()
{
return array(
'code' => $this->_getHandle()->errno,
'message' => $this->_getHandle()->error,
);
}
}

206
library/Msd/Dump.php Normale Datei
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
* @subpackage Dump
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* Dump Class
*
* Offers some methods to wrap some common SQL-commands
*
* @package MySQLDumper
* @subpackage Dump
*/
class Msd_Dump
{
/**
* Constructor
*
* return void
*/
public function __construct()
{
$this->dbsToBackup = array();
$this->tableInfo = array();
$this->recordsTotal = 0;
$this->tablesTotal = 0;
$this->datasizeTotal = 0;
$this->dbActual = null;
$this->sumTotal = $this->_initSum();
$this->dbo = Msd_Db::getAdapter();
}
/**
* Get databases to backup and calculate sum array
*
* @return void
*/
function prepareDumpProcess()
{
$taskList = Msd_TaskManager::getInstance('backupTasks', true);
$this->dbsToBackup = $this->_getDbsToBackup();
$dbNames=array_keys($this->dbsToBackup);
foreach ($dbNames as $dbName) {
$sumInfo = $this->_getDatabaseSums($dbName);
$this->_addDatabaseSums($sumInfo);
$this->buildTaskList($dbName, $taskList);
}
// set db to be dumped first -> start index is needed
$this->dbActual = $dbNames[0];
//Debug::out($taskList->getTasks());
}
/**
* Get list of databases that shold be dumped
*
* @return array
*/
private function _getDbsToBackup()
{
$config = Msd_Configuration::getInstance();
$databases = $config->get('dynamic.databases');
// first check if any db is marked to be dumped
$dbToDumpExists = false;
if (!empty($databases)) {
foreach ($databases as $dbName => $val) {
$this->databases[$dbName] = array();
if (isset($val['dump']) && $val['dump'] == 1) {
$this->dbsToBackup[$dbName] = $val;
$dbToDumpExists = true;
}
}
}
if (!$dbToDumpExists) {
// no db selected for dump -> set actual db to be dumped
$index = $config->get('dynamic.dbActual');
$this->dbsToBackup[$index] = array();
$this->dbsToBackup[$index]['dump'] = 1;
}
return $this->dbsToBackup;
}
/**
* Get sum of tables, records and data size grouped by table type
*
* @param string $db The database to check
*
* @return void
*/
private function _getDatabaseSums($dbName)
{
$this->dbo->selectDb($dbName);
$metaInfo = $this->dbo->getTableStatus();
$sum = array();
foreach ($metaInfo as $index => $vals) {
if ($vals['TABLE_TYPE'] == 'BASE TABLE') {
$type = $vals['ENGINE'];
if (!isset($sum[$type])) {
$sum[$type] = $this->_initSum();
}
$sum[$type]['tablesTotal']++;
if (!in_array($type, array('VIEW', 'MEMORY'))) {
$sum[$type]['recordsTotal'] += $vals['TABLE_ROWS'];
$sum[$type]['datasizeTotal'] += $vals['DATA_LENGTH'];
}
}
}
if (!empty($sum)) {
ksort($sum);
}
return $sum;
}
/**
* Add sums of a database to the total sum array $this->sumTotal
*
* @param $sum Array containing the sum values for a database
*
* @return void
*/
private function _addDatabaseSums($sum)
{
$types = array_keys($sum);
foreach ($types as $type) {
if (!isset($this->sumTotal['tables'][$type])) {
$this->sumTotal['tables'][$type] = $this->_initSum();
}
$this->sumTotal['tables'][$type] =$this->_sumAdd(
$this->sumTotal['tables'][$type], $sum[$type]
);
$this->sumTotal['tablesTotal'] += $sum[$type]['tablesTotal'];
$this->sumTotal['recordsTotal'] += $sum[$type]['recordsTotal'];
$this->sumTotal['datasizeTotal'] += $sum[$type]['datasizeTotal'];
}
}
/**
* Init a sum array
*
* @return array
*/
private function _initSum()
{
$sum = array();
$sum['tablesTotal'] = 0;
$sum['recordsTotal'] = 0;
$sum['datasizeTotal'] = 0;
return $sum;
}
/**
* Add a sum array
*
* @return array
*/
private function _sumAdd($baseArr, $addArr)
{
$baseArr['tablesTotal'] += $addArr['tablesTotal'];
$baseArr['recordsTotal'] += $addArr['recordsTotal'];
$baseArr['datasizeTotal'] += $addArr['datasizeTotal'];
return $baseArr;
}
/**
* Add the task "get create table" for each table to the task list
*
* @param string $dbName Name of database
* @param Msd_TaskManager $tasks TaskManager instance
*
* @return void
*/
public function buildTaskList($dbName, Msd_TaskManager $taskList)
{
$tables = $this->dbo->getTableStatus(false, $dbName);
foreach ($tables as $table) {
// add create table
$taskList->addTask(
Msd_TaskManager::GET_CREATE_TABLE,
array('db' => $dbName,
'table' => $table['TABLE_NAME']
)
);
// add dump data
if ($table['TABLE_TYPE'] === 'BASE TABLE') {
$taskList->addTask(
Msd_TaskManager::BACKUP_TABLE_DATA,
array('db' => $dbName,
'table' => $table['TABLE_NAME']
)
);
}
// add keys and indexes
$taskList->addTask(
Msd_TaskManager::GET_ALTER_TABLE_ADD_KEYS,
array('db' => $dbName,
'table' => $table['TABLE_NAME']
)
);
}
}
}

19
library/Msd/Exception.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
* @subpackage Exception
* @version SVN: $Rev$
* @author $Author$
*/
/**
* MySQLDumper Exception
*
* @package MySQLDumper
* @subpackage Exception
*/
class Msd_Exception extends Exception
{
}

130
library/Msd/File.php Normale Datei
Datei anzeigen

@ -0,0 +1,130 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage File
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* File-Helper Class
*
* Class offers some methods for file handling
*
* @package MySQLDumper
* @subpackage File
*/
class Msd_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)
{
$fileValidator = new Msd_Validate_File_Accessible(
array('accessType' => array('write'))
);
if (!$fileValidator->isValid($path)) {
@chmod($path, $chmod);
}
return $fileValidator->isValid($path);
}
/**
* Get information of latest backup file
*
* @return array
*/
public static function getLatestBackupInfo()
{
$config = Msd_Configuration::getInstance();
$latestBackup = array();
$dir = new DirectoryIterator($config->get('paths.backup'));
foreach ($dir as $file) {
if ($file->isFile()) {
$fileMtime = $file->getMTime();
if (!isset($latestBackup['mtime']) ||
$fileMtime > $latestBackup['mtime']) {
$filename = $file->getFilename();
$latestBackup['filename'] = $filename;
$latestBackup['fileMtime'] = date("d.m.Y H:i", $fileMtime);
}
}
}
return $latestBackup;
}
/**
* Returns an array with the names of all saved configuration files
*
* Strips extensions.
*
* @return array List of configuration names
*/
public static function getConfigNames()
{
$config = Msd_Configuration::getInstance();
$configPath = $config->get('paths.config');
if (!is_readable($configPath)) {
return array();
}
$dir = new DirectoryIterator($configPath);
$files = array();
foreach ($dir as $file) {
if ($file->isFile()) {
$filename = $file->getFilename();
if (substr($filename, -4) == '.ini') {
$files[] = substr($filename, 0, - 4);
}
}
}
@sort($files);
return $files;
}
/**
* Get list of available themes.
*
* @return array
*/
public static function getThemeList()
{
$dir = new DirectoryIterator(APPLICATION_PATH . '/../public/css/');
$themes = array();
while ($dir->valid()) {
$current = $dir->current();
if ($current->isDir() &&
!$current->isDot() &&
$current->getBasename() != '.svn'
) {
$themeName= $current->getBasename();
$themes[$themeName] = $themeName;
}
$dir->next();
}
return $themes;
}
}

126
library/Msd/File/Dump.php Normale Datei
Datei anzeigen

@ -0,0 +1,126 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage File
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* Dumpfile-Helper Class
*
* Class offers some methods for file handling
*
* @package MySQLDumper
* @subpackage File
*/
class Msd_File_Dump extends Msd_File
{
/**
* Get statusline information from backup file
*
* @param string $filename Name of file to read
*
* @param array
*/
public static function getStatusline($filename)
{
$config = Msd_Configuration::getInstance();
$path = $config->get('paths.backup'). DS;
if (strtolower(substr($filename, -3)) == '.gz') {
$fileHandle = gzopen($path . $filename, "r");
if ($fileHandle === false) {
throw new Exception('Can\'t open file '.$filename);
}
$statusline = gzgets($fileHandle, 40960);
gzclose($fileHandle);
} else {
$fileHandle=fopen($path . $filename, "r");
if ($fileHandle === false) {
throw new Exception('Can\'t open file '.$filename);
}
$statusline = fgets($fileHandle, 5000);
fclose($fileHandle);
}
return self::_explodeStatusline($statusline);
}
/**
* Get information from stausline string
*
* @param string $line
*
* @return array
*/
private function _explodeStatusline($line)
{
/*Construction of statusline (first line in backup file):
-- Status : NrOfTables : nrOfRecords : Multipart : DatabaseName :
script : scriptversion : Comment : MySQLVersion :
Backupflags (unused): SQLBefore : SQLAfter : Charset : EXTINFO
*/
$statusline = array();
$compare = substr($line, 0, 8);
if ( $compare != '# Status' && $compare != '-- Statu') {
// not a backup of MySQLDumper
return self::_getDefaultStatusline();
} else {
// extract informationen
$flag = explode(':', $line);
if (count($flag)<12) {
// fill missing elements for backwards compatibility
array_pop($flag);
for ($i = count($flag) - 1; $i < 12; $i++) {
$flag[]='';
}
}
$statusline['tables'] = $flag[1];
$statusline['records'] = $flag[2];
if ($flag[3] == '' || $flag[3] == 'MP_0') {
$statusline['part']= 'MP_0';
} else {
$statusline['part'] = $flag[3];
}
$statusline['dbname'] = $flag[4];
$statusline['script'] = $flag[5];
$statusline['scriptversion'] = $flag[6];
$statusline['comment'] = $flag[7];
$statusline['mysqlversion'] = $flag[8];
$statusline['flags'] = $flag[9];
$statusline['sqlbefore'] = $flag[10];
$statusline['sqlafter'] = $flag[11];
if ( isset($flag[12]) && trim($flag[12])!='EXTINFO') {
$statusline['charset']=$flag[12];
} else {
$statusline['charset']='?';
}
}
return $statusline;
}
/**
* Get default statusline
*
* @return array
*/
private function _getDefaultStatusline()
{
$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'] = '?';
return $statusline;
}
}

Datei anzeigen

@ -0,0 +1,116 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Abstract decorator for form elements of Msd_Form
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
abstract class Msd_Form_Decorator_Abstract extends Zend_Form_Decorator_Abstract
{
/**
* Build and translate the label of an element.
*
* @return string
*/
public function buildLabel()
{
$element = $this->getElement();
$label = $element->getLabel();
if (empty($label)) {
return '';
}
$translator = $element->getTranslator();
if ($translator !== null) {
$label = $translator->translate($label);
}
$attribs = $element->getAttribs();
if (!isset($attribs['noColon']) || $attribs['noColon'] != true) {
$label .= ':';
}
return $label;
}
/**
* Build the HTML-Code of the element.
*
* @return string
*/
public function buildInput()
{
$element = $this->getElement();
$helper = $element->helper;
$value = $element->getValue();
$translator = $element->getTranslator();
if ($translator !== null) {
$value = $translator->translate($value);
}
$ret = $element->getView()->$helper(
$element->getName(),
$value,
$this->_getCleanAttribs(),
$element->options
);
return $ret;
}
/**
* Build the error message, if there is any.
*
* @return string
*/
public function buildErrors()
{
$lang = Msd_Language::getInstance();
$element = $this->getElement();
$messages = $element->getMessages();
if (empty($messages)) {
return '';
}
$html = '<ul>';
foreach (array_keys($messages) as $messageId) {
$html .= '<li>' . $lang->translateZendId($messageId) . '</li>';
}
$html .= '<ul>';
return $html;
}
/**
* Build the description.
*
* @return string
*/
public function buildDescription()
{
$element = $this->getElement();
$desc = $element->getDescription();
return $desc;
}
/**
* Clean up attributes we don't want to appear in Html code.
*
* @return array Array with allowed attributes
*/
private function _getCleanAttribs()
{
$attribsToRemove = array(
'noColon', 'helper', 'secondLabel' , 'rowclass'
);
$attribsOfElement = $this->getElement()->getAttribs();
foreach ($attribsToRemove as $attrib) {
if (isset($attribsOfElement[$attrib])) {
unset($attribsOfElement[$attrib]);
}
}
return $attribsOfElement;
}
}

Datei anzeigen

@ -0,0 +1,48 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for main ConfigForm.
*
* Fetches all sub forms, renders all sub elements and returns
* the complete form.
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_ConfigForm extends Msd_Form_Decorator_Abstract
{
/**
* Render the form
*
* @param string $content HTML content rendered so far
*
* @return string HTML content after decorating the complete form
*/
public function render($content)
{
$element = $this->getElement();
$form = '';
if (!empty($content)) {
$form .= $content;
} else {
$subForms = $element->getSubForms();
foreach (array_keys($subForms) as $subFormKey) {
$form .= (string) $subForms[$subFormKey];
}
$subElements = $element->getElements();
foreach (array_keys($subElements) as $subElementKey) {
$form .= (string) $subElements[$subElementKey];
}
}
return $form;
}
}

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
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Default decorator for form elements
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_Default extends Msd_Form_Decorator_Abstract
{
/**
* Render the element.
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating
*/
public function render($content)
{
$element = $this->getElement();
if (! $element instanceof Zend_Form_Element) {
return $content;
}
if (null === $element->getView()) {
return $content;
}
$label = $this->buildLabel();
$input = $this->buildInput();
$errors = strip_tags($this->buildErrors());
$desc = $this->buildDescription();
$descOutput = '';
if ($desc != '') {
$descOutput = sprintf('<span class="description">%s</span>', $desc);
}
$attribs = $element->getAttribs();
$output = '<tr>';
$rowclass = '';
if (isset($attribs['rowclass'])) {
$rowclass = $attribs['rowclass'];
$output = '<tr class="' . $rowclass . '">';
}
$output .= ' <td>%s</td>
<td>%s '. $descOutput . '</td>
</tr>';
$output = sprintf($output, $label, $input);
$separator = $this->getSeparator();
$placement = $this->getPlacement();
switch ($placement) {
case (self::PREPEND):
return $output . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $output;
}
}
}

Datei anzeigen

@ -0,0 +1,66 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for display groups
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_DisplayGroup extends Msd_Form_Decorator_Abstract
{
/**
* Decorator for display groups.
*
* Walks through all sub elements and decorates them.
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating all sub elements
*/
public function render($content)
{
$element = $this->getElement();
$legend = $element->getLegend();
$translator = $element->getTranslator();
$attributes = $element->getAttribs();
if ($translator !== null) {
$legend = $translator->translate($legend);
}
$sElements = '<fieldset';
if (isset($attributes['class'])) {
$sElements .= ' class="' . $attributes['class'] . '"';
}
if (isset($attributes['id'])) {
$sElements .= ' id="' . $attributes['id'] . '"';
}
if (isset($attributes['style'])) {
$sElements .= ' style="' . $attributes['style'] . '"';
}
$sElements .= '>';
$sElements .= '<legend>' . $legend . '</legend>';
$sElements .= '<table summary="">';
$formElements = $element->getElements();
foreach (array_keys($formElements) as $formElementKey) {
$sElements .= (string) $formElements[$formElementKey];
}
$sElements .= '</table></fieldset>';
$placement = $this->getPlacement();
$separator = $this->getSeparator();
switch ($placement) {
case (self::PREPEND):
return $sElements . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $sElements;
}
}
}

Datei anzeigen

@ -0,0 +1,95 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for an element with two labels
*
* (label -> text input -> second label (unit)) or
* (Label -> select box -> second label (unit)
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_DoubleLabel extends Msd_Form_Decorator_Abstract
{
/**
* Build the second label.
*
* @return string
*/
public function buildSecondLabel()
{
$element = $this->getElement();
$label = $element->getAttrib('secondLabel');
if (empty($label)) {
return '';
}
$translator = $element->getTranslator();
if ($translator !== null) {
$label = $translator->translate($label);
}
if ($element->isRequired()) {
$label .= '*';
}
$label .= '';
return '<label for="' . $element->getId() . '">' . $label . '</label>';
}
/**
* Render the form element.
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating
*/
public function render($content)
{
$element = $this->getElement();
if (! $element instanceof Zend_Form_Element) {
return $content;
}
if (null === $element->getView()) {
return $content;
}
$separator = $this->getSeparator();
$placement = $this->getPlacement();
$label = $this->buildLabel();
$secondLabel = $this->buildSecondLabel();
$input = $this->buildInput();
$errorOutput = '';
/*
// error output is handled by validators
$errors = $this->buildErrors();
if ($errors != '') {
$errorOutput = sprintf('<span class="error">%s</span>', $errors);
}
*/
$descOutput = '';
$desc = $this->buildDescription();
if ($desc != '') {
$descOutput = sprintf('<span class="description">%s</span>', $desc);
}
$output = ' <tr>
<td>%s</td>
<td>%s %s' . $errorOutput . $descOutput .'</td>
</tr>';
$output = sprintf($output, $label, $input, $secondLabel);
switch ($placement) {
case (self::PREPEND):
return $output . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $output;
}
}
}

Datei anzeigen

@ -0,0 +1,43 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for an element at the end of a table row
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_LineEnd extends Msd_Form_Decorator_Abstract
{
/**
* Render Element
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating
*/
public function render($content)
{
$label = $this->buildLabel();
if ($label != '' ) {
$label = ' ' . $label;
}
$output = $label . $this->buildInput() . '</td></tr>';
$separator = $this->getSeparator();
$placement = $this->getPlacement();
switch ($placement) {
case (self::PREPEND):
return $output . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $output;
}
}
}

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
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for table data between start and end of a table row
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_LineMiddle extends Msd_Form_Decorator_Abstract
{
/**
* Render element
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating
*/
public function render($content)
{
$label = $this->buildLabel();
if ($label != '' ) {
$label = ' ' . $label;
}
$output = $label . $this->buildInput() . ' ';
$separator = $this->getSeparator();
$placement = $this->getPlacement();
switch ($placement) {
case (self::PREPEND):
return $output . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $output;
}
}
}

Datei anzeigen

@ -0,0 +1,48 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for the beginning of a table row
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_LineStart extends Msd_Form_Decorator_Abstract
{
/**
* Render the element.
*
* @param string $content HTML content so far
*
* @return string HTML content after decorating
*/
public function render($content)
{
$element = $this->getElement();
if (! $element instanceof Zend_Form_Element) {
return $content;
}
if (null === $element->getView()) {
return $content;
}
$separator = $this->getSeparator();
$placement = $this->getPlacement();
$label = $this->buildLabel();
$input = $this->buildInput();
$output = '<tr><td>' . $label . '</td>' . '<td>' . $input;
switch ($placement) {
case (self::PREPEND):
return $output . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $output;
}
}
}

Datei anzeigen

@ -0,0 +1,55 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Form_Decorator
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Decorator for a complete sub form
*
* @package MySQLDumper
* @subpackage Form_Decorator
*/
class Msd_Form_Decorator_SubForm extends Msd_Form_Decorator_Abstract
{
/**
* Render content
*
* @param string $content The HTML content rendered so far
*
* @return string The HTML content after decorating
*/
public function render($content)
{
$element = $this->getElement();
$htmlOutput = '<div id="tab_' . $element->getId() . '">';
$headElement = $element->getElement('headElement');
if ($headElement !== null) {
$htmlOutput .='<table summary="">';
$htmlOutput .= (string) $headElement;
$htmlOutput .= '</table>' . "\n";
$htmlOutput .= '<br/><br/>' . "\n";
}
$displayGroups = $element->getDisplayGroups();
foreach (array_keys($displayGroups) as $displayGroupKey) {
$htmlOutput .= (string) $displayGroups[$displayGroupKey];
}
$htmlOutput .= '</div>';
$separator = $this->getSeparator();
$placement = $this->getPlacement();
switch ($placement) {
case (self::PREPEND):
return $htmlOutput . $separator . $content;
case (self::APPEND):
default:
return $content . $separator . $htmlOutput;
}
return $htmlOutput;
}
}

93
library/Msd/Html.php Normale Datei
Datei anzeigen

@ -0,0 +1,93 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Html
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* HTML-Helper Class
*
* Class has some static methods for building HTML-output
*
* @package MySQLDumper
* @subpackage Html
*/
class Msd_Html
{
/**
* 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);
}
/**
* Extract group prefixes from key names of array
*
* Returns a new array containing the different prefixes. Used for building
* filter select boxes (e.g. sqlserver/show.variables).
*
* @param array $array Array to scan for prefixes
* @param boolean $addNoneOption Whether to add a first entry '---'
*
* @return $prefix_array array The array conatining the unique prefixes
*/
public static 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;
}
}
}
ksort($prefixes);
return $prefixes;
}
/**
* Build Html option string from array
*
* @param array $array Array['name'] = $val
* @param string $selected Selected key
* @param boolean $selectAll Show option to select all
*
* @return string Html option string
*/
public static function getHtmlOptions($array, $selected, $selectAll = true)
{
$options = '';
if ($selectAll) {
$options = '<option value="">---</option>'."\n";
}
foreach ($array as $key => $val) {
$options .='<option value="' . $key . '"';
if ($key === $selected) {
$options .=' selected="selected"';
}
$options .='>' . $val .'</option>'."\n";
}
return $options;
}
}

192
library/Msd/Ini.php Normale Datei
Datei anzeigen

@ -0,0 +1,192 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Ini
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Class to handle ini-files
*
* @package MySQLDumper
* @subpackage Ini
*/
class Msd_Ini
{
/**
* Data of loaded INI file.
*
* @var array
*/
private $_iniData = null;
/**
* Filename of current INI file.
*
* @var string
*/
private $_iniFilename = null;
/**
* Class constructor
*
* @param array|string $options Configuration or filename of INI to load
*
* @return void
*/
public function __construct($options = array())
{
if (is_string($options)) {
$options = array(
'filename' => $options,
);
} elseif (!is_array($options)) {
$options = (array) $options;
}
if (isset($options['filename'])) {
$this->_iniFilename = (string) $options['filename'];
}
if ($this->_iniFilename !== null) {
$this->loadFile();
}
}
/**
* Loads an INI file.
*
* @param string $filename Name of file to load
*
* @return void
*/
public function loadFile($filename = null)
{
if ($filename === null) {
$filename = $this->_iniFilename;
}
if (realpath($filename) === false) {
throw new Msd_Exception(
"INI file " . $filename . "doesn't exists."
);
}
$zfConfig = new Zend_Config_Ini(realpath($filename));
$this->_iniData = $zfConfig->toArray();
}
/**
* Save to INI file.
*
* @param string $filename Name of file to save
*
* @return void
*/
public function save($filename = null)
{
if ($filename === null) {
$filename = $this->_iniFilename;
}
if ($filename === null) {
throw new Msd_Exception(
'You must specify a filename to save the INI!'
);
}
$fileHandle = fopen($filename, 'w+');
fwrite($fileHandle, (string) $this);
fclose($fileHandle);
}
/**
* Converts an array into the INI file format.
*
* @param array $array Array to convert.
* @param integer $level Current depthlevel in the array.
*
* @return string
*/
private function _arrayToIniString($array = null, $level = -1)
{
if ($array === null) {
$array = $this->_iniData;
}
$level++;
$resultString = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
$resultString .= ($level == 0) ?
'[' . $key . ']' . "\n" :
$key . '.';
$resultString .= $this->_arrayToIniString($value);
} else {
$newValue = str_replace(
array('\\', '"'),
array('\\\\', '\\"'),
$value
);
$resultString .= $key . ' = "' . (string) $newValue . '"';
}
$resultString .= "\n";
}
return $resultString;
}
/**
* Get a variable from the data.
*
* @param string $key Name of variable
* @param string $section Name of section
*
* @return mixed
*/
public function get($key, $section = null)
{
if ($section === null) {
return $this->_iniData[$key];
} else {
return $this->_iniData[$section][$key];
}
}
/**
* Set a variable
*
* @param string $key Name of variable
* @param mixed $value Value of variable
* @param string $section Section of variable
*
* @return void
*/
public function set($key, $value, $section = null)
{
if ($section === null) {
$this->_iniData[$key] = $value;
} else {
$this->_iniData[$section][$key] = $value;
}
}
/**
* Get the complete INI.
*
* @return array
*/
public function getAll()
{
return $this->_iniData;
}
/**
* Convert this class into a string.
*
* @return string
*/
public function __toString()
{
return $this->_arrayToIniString();
}
}

185
library/Msd/Language.php Normale Datei
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
* @subpackage Language
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Language class implemented as singleton
*
* Handles translation of language variables.
*
* @package MySQLDumper
* @subpackage Language
*/
class Msd_Language
{
/**
* Instance
*
* @var Msd_Configuration
*/
private static $_instance = NULL;
/**
* Translator
*
* @var Zend_Translate
*/
private $_translate = NULL;
/**
* Base directory for language files
*
* @var string
*/
private $_baseLanguageDir = null;
/**
* Constructor gets the configuration params
*
* @return array
*/
private function __construct ()
{
$config = Msd_Configuration::getInstance();
$language = $config->get('config.interface.language');
$this->loadLanguage($language);
}
/**
* Load new language.
*
* @param string $language New language
*
* @return void
*/
public function loadLanguage($language)
{
$this->_baseLanguageDir = APPLICATION_PATH . DS . 'language' . DS;
$file = $this->_baseLanguageDir . $language . DS . 'lang.php';
$translator = $this->getTranslator();
if ($translator === null) {
$translator = new Zend_Translate('array', $file, $language);
} else {
$translator->setAdapter(
array(
'adapter' => 'array',
'content' => $file,
'locale' => $language
)
);
}
$this->setTranslator($translator);
Zend_Registry::set('Zend_Translate', $translator);
}
/**
* No cloning for singleton
*
* @return void
*/
public function __clone()
{
throw new Msd_Exception('Cloning of Msd_Language is not allowed!');
}
/**
* Magic getter to keep syntax in rest of script short
*
* @param mixed $var
*
* @return mixed
*/
public function __get ($property)
{
$translated = $this->getTranslator()->_($property);
if ($translated == $property && substr($property, 0, 2) == 'L_') {
// no translation found -> remove prefix L_
return substr($property, 2);
}
return $translated;
}
/**
* Returns the single instance
*
* @return Msd_Language
*/
public static function getInstance ()
{
if (NULL == self::$_instance) {
self::$_instance = new self;
}
return self::$_instance;
}
/**
* Translate a Message from Zend_Validate.
*
* @param string $zendMessageId Message ID from Zend_Validate
* @param string $messageText Pre-translatet message
*
* @return string
*/
public function translateZendId($zendMessageId, $messageText = '')
{
if (substr($zendMessageId, 0, 6) =='access' && $messageText > '') {
// message is already translated by validator access
return $messageText;
}
return $this->_translate->_(
$this->_transformMessageId($zendMessageId)
);
}
/**
* Transforms a message ID in Zend_Validate format into Msd_Language format.
*
* @param string $zendMessageId Message ID from Zend_Validate
*
* @return string
*/
private function _transformMessageId($zendMessageId)
{
$result = preg_replace('/([A-Z])/', '_${1}', $zendMessageId);
$result = strtoupper($result);
return 'L_ZEND_ID_' . $result;
}
/**
* Get Translator
*
* @return Zend_Translate
*/
public function getTranslator()
{
return $this->_translate;
}
/**
* Set Translator
*
* @param Zend_Translate $translate
*
* @return void
*/
public function setTranslator(Zend_Translate $translate)
{
$this->_translate = $translate;
}
/**
* Retrieve a list of available languages.
*
* @return array
*/
public function getAvailableLanguages()
{
$lang = array();
include $this->_baseLanguageDir . 'lang_list.php';
return $lang;
}
}

205
library/Msd/Log.php Normale Datei
Datei anzeigen

@ -0,0 +1,205 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Log
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Log Class
*
* @package MySQLDumper
* @subpackage Log
*/
class Msd_Log
{
// Define constants
const PHP = 'PHP-Log';
const PERL = 'PERL-Log';
const PERL_COMPLETE = 'PERL-Complete-Log';
const ERROR = 'Error-Log';
// Define static Instance
private static $_instance = NULL;
private $_paths = NULL;
/**
* Init file handles
*
* @return void
*/
public function __construct()
{
// define instance handler
$this->handle = array();
$this->handle[self::PHP] = false;
$this->handle[self::PERL] = false;
$this->handle[self::PERL_COMPLETE] = false;
$this->handle[self::ERROR] = false;
// get config
$config = Msd_Configuration::getInstance();
$this->_paths = (object)$config->get('paths');
}
/**
* 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);
}
}
/**
* Close a filehandle
*
* @param Loge $file The file to close
*/
private function _close($file)
{
$filename = $this->getFile($file);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($extension == 'gz') {
gzclose($this->handle[$file]);
} else {
fclose($this->handle[$file]);
}
}
/**
* Get an instance of Msd_Log
*
* @return Msd_Log
*/
public static function getInstance()
{
if (self::$_instance === NULL) {
self::$_instance = new self;
}
return self::$_instance;
}
/**
* Get an instance of Msd_Log for a special type
*
* Allowed types are self::PHP, self::PERL, self::PERL_COMPLETE or
* self::ERROR
*
* @param Msd_Log $type
*
* @return Msd_Log
*/
public function getLogInstance($type)
{
if (!isset($this->_logInstance[$type])) {
$writer = new Zend_Log_Writer_Stream($this->getFile($type));
$formatter =
new Zend_Log_Formatter_Simple("%timestamp% %message%\n");
$writer->setFormatter($formatter);
$this->_logInstance[$type] = new Zend_Log($writer);
}
return $this->_logInstance[$type];
}
/**
* Write to log file
*
* @param string $type The type of log file to write to
* @param string $message The message to add to the file
*
* @return bool
*/
public static function write($type, $message)
{
// @todo if log_maxsize reached => archive/delete log
$logger = self::getInstance();
$log = $logger->getLogInstance($type);
return $log->info($message);
}
/**
* Get the concrete filename with path for the given type.
*
* @param const $file
*
* @return string Filename of logfile
*/
public function getFile($file)
{
$filename = '';
switch ($file) {
case self::PHP:
$filename = $this->_paths->log . DS . 'php.log';
break;
case self::PERL:
$filename = $this->_paths->log . DS . 'perl.log';
break;
case self::PERL_COMPLETE:
$filename = $this->_paths->log . DS . 'perlComplete.log';
break;
case self::ERROR:
$filename = $this->_paths->log . DS . 'phpError.log';
}
return $filename;
}
/**
* Delete a log file and recreate it.
*
* @param string $file Filename
*
* @return void
*/
public function delete($type)
{
$filename = self::getFile($type);
@unlink($filename);
// re-create log file
$translator = Msd_Language::getInstance()->getTranslator();
$this->write($type, $translator->_('L_LOG_CREATED'));
}
/**
* Read a logfile and return content as array.
*
* If $revers is set to true the ordering of lines is reversed.
*
* @param parent::const $type The type of logfile to read
* @param boolean $reverse Wether to place latest entries first
*
* @return array Log data from file as array
*/
public function read($type = self::PHP, $reverse = false)
{
$filename = $this->getFile($type);
if (!is_readable($filename)) {
$timestamp = Zend_Date::ISO_8601;
$lang = Msd_Language::getInstance()->getTranslator();
$msg = $timestamp . ' <span class="error">' .
sprintf($lang->_('L_LOG_NOT_READABLE'), $filename) . '</span>';
return array($msg);
} else {
$output = file($filename);
}
if ($reverse == 1) {
$output = array_reverse($output);
}
return $output;
}
}

48
library/Msd/Log/Reader.php Normale Datei
Datei anzeigen

@ -0,0 +1,48 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Log
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Reader Class
*
* @package MySQLDumper
* @subpackage Log
*/
class Msd_Log_Reader extends Msd_Log
{
/**
* Read a logfile and return content as array.
*
* If $revers is set to true the ordering of lines is reversed.
*
* @param parent::const $type The type of logfile to read
* @param boolean $reverse Wether to place latest entries first
*
* @return array Log data from file as array
*/
public function read ($type = parent::PHP, $reverse = false)
{
$filename = parent::getFile($type);
if (!is_readable($filename)) {
$timestamp = Zend_Date::ISO_8601;
$lang = Msd_Language::getInstance()->getTranslator();
$msg = $timestamp . ' <span class="error">' .
sprintf($lang->_('L_LOG_NOT_READABLE'), $filename) . '</span>';
return array($msg);
} else {
$output = file($filename);
}
if ($reverse == 1) {
$output = array_reverse($output);
}
return $output;
}
}

78
library/Msd/Sqlparser.php Normale Datei
Datei anzeigen

@ -0,0 +1,78 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Sql
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* Sql Parser Class
*
* @package MySQLDumper
* @subpackage Sqlparser
*/
define('*', 'SQL_TOKEN');
class Msd_Sqlparser
{
/**
* @var array Array containing the parsed queries
*/
private $_queries = array();
/**
* @var string Input text to analyse
*/
private $_text = '';
/**
* @param string $text Text to be later parsed as sql
*/
public function __construct($text = '')
{
$this->addText($text);
}
/**
* Add text to internal text buffer
*
* @param string $text The text to add
* @return void
*/
public function addText($text)
{
$this->_text .= $text;
}
/**
* Parse added text as sql und split into queries
*
* @return void
*/
public function parse()
{
//TODO implement parser
return $this->_text;
$i=1;
$tokens = token_get_all('<?php '.$this->_text.'?>');
unset($tokens[0]);
unset($tokens[count($tokens)]);
//unset($tokens[count($tokens)]);
//unset($tokens[0]);
foreach ($tokens as $token) {
if (is_string($token)) {
// simple 1-character token
echo "<br>$i. $token";
} else {
// token array
list($token, $text) = $token;
echo "<br>$i. ". token_name($token)." => "
. htmlspecialchars($text);
}
$i++;
}
}
}

188
library/Msd/TaskManager.php Normale Datei
Datei anzeigen

@ -0,0 +1,188 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage File
* @version SVN: $rev: 1207 $
* @author $Author$
*/
/**
* Task Manager Class (Singleton)
*
* Class handles task lists
*
* @package MySQLDumper
* @subpackage TaskManager
*/
class Msd_TaskManager
{
/**
* Define task types.
* The integer value defines the ordering in wich tasks are executed.
* @var int
*/
const GET_CREATE_TABLE = 100;
const BACKUP_TABLE_DATA = 200;
const GET_ALTER_TABLE_ADD_KEYS = 300;
/**
* Instance
*
* @var Msd_Configuration
*/
private static $_instance = NULL;
/**
* Task Namespace
* @var Zend_Session_Namespace
*/
private $_session;
private $_tasks = array();
/**
* Constructor
*
* Get task list from session or init an empty list.
*
* @param string $taskType Task type to get or create.
* Defaults to "backupTasks".
* @param boolean Whether to create a new task list and delete all entries
* or to get it from the session
*
* @return void
*/
private function __construct($taskType, $clear = false)
{
$this->_session = new Zend_Session_Namespace($taskType, true);
if (isset($this->_session->tasks)) {
$this->_tasks = $this->_session->tasks;
}
if ($clear === true) {
$this->clearTasks();
}
}
/**
* Returns the task manager instance
*
* @param string $configname The name of the configuration file to load.
* If not set we will load the config from
* session if present.
* @param boolean $forceLoading If set the config will be read from file.
*
* @return Msd_Configuration
*/
public static function getInstance($taskType = 'backupTasks',
$clear = false)
{
if (null == self::$_instance) {
self::$_instance = new self($taskType, $clear);
}
return self::$_instance;
}
/**
* Add a task
*
* @param string $type Type of tasks
* @param array $options Option array
*
* @return void
*/
public function addTask($type, $options = array())
{
$tasks = $this->_tasks;
if (empty($tasks[$type])) {
$tasks[$type] = array();
}
$tasks[$type][] = $options;
$this->_tasks = $tasks;
$this->_saveTasksToSession();
}
/**
* Get tasks of given type
*
* Returns false if type is not present in task list.
*
* @param string $type
*
* @return array|false
*/
public function getTasks($type = '')
{
if ($type > '') {
if (!isset($this->_tasks[$type])) {
return false;
}
return $this->_tasks[$type];
}
return $this->_tasks;
}
/**
* Reset tasks array
*
* @return void
*/
public function clearTasks()
{
$this->_tasks = array();
$this->_saveTasksToSession();
}
/**
* Remove the first task of the given type
*
* @param string $type
*
* @return void
*/
public function removeActualTask($type)
{
$tasks = $this->getTasks($type);
print_r($tasks);
if ($tasks === false) {
return;
}
if (empty($tasks)) {
// no task of that type left - remove type
unset($this->_tasks[$type]);
}
unset($tasks[0]);
//rebuild index
sort($tasks);
$this->_tasks[$type] = $tasks;
$this->_saveTasksToSession();
}
/**
* Return the first task of given type or false if there is none.
*
* @param $type The type of the task to get.
*
* @return array|false
*/
public function getActualTask($type)
{
$tasks = $this->getTasks($type);
if (isset($tasks[0])) {
return $tasks[0];
};
return false;
}
/**
* Save task list to session
*
* @return void
*/
private function _saveTasksToSession()
{
$this->_session->tasks = $this->_tasks;
}
}

194
library/Msd/Update.php Normale Datei
Datei anzeigen

@ -0,0 +1,194 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Update
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Class handles loading of files from MySQLDumper update server.
*
* @package MySQLDumper
* @subpackage Update
*/
class Msd_Update
{
/**
* Cofiguration for updater
*
* @var Msd_Ini
*/
private $_updateConfig = null;
/**
* HTTP-Client for updates and update checks
*
* @var Zend_Http_Client
*/
private $_httpClient = null;
/**
* Parameters for GET-Request.
*
* @var array
*/
private $_requestParams = array();
/**
* Parameters for update information.
*
* @var array
*/
private $_updateParams = array();
/**
* Class constructor
*
* @param array $updateConfigFile
*
* @return void
*/
public function __construct($updateConfigFile)
{
$this->_updateConfig = new Msd_Ini($updateConfigFile);
$updateUrl = $this->_buildUpdateUrl();
$this->_httpClient = new Zend_Http_Client($updateUrl);
}
/**
* Start the update for the specified files.
*
* @param string $updateSection INI-Section with update information
* @param array $fileList List of files to update.
*
* @return true|array
*/
public function doUpdate($updateSection, $fileList)
{
$httpClient = $this->_httpClient;
$config = $this->_updateConfig->get($updateSection);
$params = $this->getRequestParams();
$params += $config['request']['params'];
while (false !== (list($paramKey, $paramValue) = each($params))) {
$params[$paramKey] = $this->_applyUpdateParams($paramValue);
}
$sourceFileKey = $config['request']['sourceFileKey'];
$targetPath = $config['targetBaseDir'] . DS;
foreach ($fileList as $sourceFile => $targetFile) {
$sourceFilename = $this->_applyUpdateParams($sourceFile);
$params[$sourceFileKey] = $sourceFile;
$httpClient->setParameterGet($params);
try {
$response = $httpClient->request('GET');
} catch(Zend_Http_Exception $e) {
return array(
'action' => 'connection',
'file' => $targetFile,
'server' => $httpClient->getUri()->getHost()
);
}
if ($response->getStatus() == 200 && $response->getBody() > '') {
$targetFilename = $this->_applyUpdateParams($targetFile);
if (substr($response->getBody(), 0, 6) == 'Error:') {
return array(
'action' => 'saveresponse',
'file' => $targetFilename,
'status' => $response->getBody(),
);
}
$targetFile = $targetPath . $targetFilename;
@mkdir(dirname($targetFile), 0777, true);
$fileHandle = @fopen($targetFile, 'w+');
if ($fileHandle === false) {
@chmod($targetFile, 0777);
$fileHandle = @fopen($targetFile, 'w+');
}
if ($fileHandle === false) {
return array(
'action' => 'createfile',
'file' => $targetFile,
'status' => 'HTTP/' . $response->getVersion() . ' ' .
$response->getStatus() . ' ' .
$response->getMessage(),
);
}
if (@fwrite($fileHandle, $response->getBody()) === false) {
return array(
'action' => 'createfile',
'file' => $targetFile,
'status' => 'HTTP/' . $response->getVersion() . ' ' .
$response->getStatus() . ' ' .
$response->getMessage(),
);
}
fclose($fileHandle);
} else {
return array(
'action' => 'getrequest',
'file' => $sourceFilename,
'status' => 'HTTP/' . $response->getVersion() . ' ' .
$response->getStatus() . ' ' . $response->getMessage(),
);
}
}
return true;
}
/**
* Build the URL for the GET-Requests.
*
* @return string
*/
private function _buildUpdateUrl()
{
$updateConfig = $this->_updateConfig->get('update');
$updateUrl = $updateConfig['protocol'] . '://'
. $updateConfig['host'] . $updateConfig['path']
. $updateConfig['file'];
$updateUrl = $this->_applyUpdateParams($updateUrl);
return $updateUrl;
}
/**
* Get the parameters for the GET-Request.
*
* @return array
*/
public function getRequestParams()
{
return $this->_requestParams;
}
/**
* Set an update information parameter.
*
* @param string $param Name of the parameter to set
* @param string $value Value of the parameter to set
*
* @return void
*/
public function setUpdateParam($param, $value)
{
$this->_updateParams[$param] = (string) $value;
}
/**
* Applies the update information parameters to the given string.
*
* @param string $string String to apply the update information parameters
*
* @return string
*/
private function _applyUpdateParams($string)
{
foreach ($this->_updateParams as $key => $value) {
$string = str_replace(':' . $key, $value, $string);
}
return $string;
}
}

252
library/Msd/User.php Normale Datei
Datei anzeigen

@ -0,0 +1,252 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Users
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Class for user login and logout actions.
*
* @package MySQLDumper
* @subpackage Users
*/
class Msd_User
{
/**
* The executed process was successfully completed.
*
* @var int
*/
const SUCCESS = 0x00;
/**
* There is no file with user identities and credentials.
*
* @var int
*/
const NO_USER_FILE = 0x01;
/**
* The user file doesn't contain any valid user logins.
*
* @var int
*/
const NO_VALID_USER = 0x02;
/**
* The given identity is unknown or the password is wrong.
*
* @var int
*/
const UNKNOWN_IDENTITY = 0x03;
/**
* An unknown error occured.
*
* @var int
*/
const GENERAL_FAILURE = 0xFF;
/**
* Path and filename of the user ini file.
*
* @var string
*/
private $_usersFile;
/**
* Instance to authentication storage.
*
* @var Zend_Auth_Storage_Session
*/
private $_authStorage = null;
/**
* Id of currently loggedin user.
*
* @var int
*/
private $_userId = null;
/**
* Name of currently loggedin user.
*
* @var string
*/
private $_userName = null;
/**
* Current login status.
*
* @var boolean
*/
private $_isLoggedIn = false;
/**
* Messages from Zend_Auth_Result.
*
* @var array
*/
private $_authMessages = array();
/**
* Constructor
*
* @return void
*/
public function __construct()
{
$this->_usersFile = APPLICATION_PATH . DS . 'configs' . DS
. 'users.ini';
$this->_authStorage = new Zend_Auth_Storage_Session();
$auth = $this->_authStorage->read();
if (!empty($auth)) {
if (isset($auth['name'])) {
$this->_userName = $auth['name'];
}
if (isset($auth['id'])) {
$this->_userId = $auth['id'];
}
if ($this->_userName !== null && $this->_userId !== null) {
$this->_isLoggedIn = true;
}
} else {
$this->_loginByCookie();
}
}
/**
* Returns the messages which comes from Zend_Auth_Result.
*
* @return array
*/
public function getAuthMessages()
{
return $this->_authMessages;
}
/**
* Return the loggedin status.
*
* @return boolean
*/
public function isLoggedIn()
{
return $this->_isLoggedIn;
}
/**
* Login the user with the given identity and credentials.
* Set cookie if automatic login is wanted.
*
* Returns true if login was successful, otherwise false.
*
* @param string $username Identity for login process.
* @param string $password Credentials for login procress.
* @param boolean $autoLogin Set cookie for automatic login?
*
* @return int
*/
public function login($username, $password, $autoLogin = false)
{
if (!file_exists($this->_usersFile)) {
return self::NO_USER_FILE;
}
$usersIni = new Msd_Ini($this->_usersFile);
$users = $usersIni->getAll();
$hasValidUser = false;
foreach ($users as $user) {
if (isset($user['name']) && isset($user['pass'])) {
$hasValidUser = true;
break;
}
}
if (!$hasValidUser) {
return self::NO_VALID_USER;
}
$authAdapter = new Msd_Auth_Adapter_Ini($this->_usersFile);
$authAdapter->setUsername($username);
$authAdapter->setPassword($password);
$auth = Zend_Auth::getInstance();
$authResult = $auth->authenticate($authAdapter);
$this->_authMessages = $authResult->getMessages();
if ($authResult->isValid()) {
$this->_isLoggedIn = true;
if ($autoLogin) {
Zend_Session::regenerateId();
$crypt = Msd_Crypt::getInstance('MySQLDumper27112010');
$identity = $crypt->encrypt(
$username . ':' . $password
);
if (PHP_SAPI != 'cli') {
setcookie(
'msd_autologin',
$identity . ':' . md5($identity),
time() + 365 * 24 * 60 * 60,
'/'
);
}
}
$this->setDefaultConfiguration();
return self::SUCCESS;
}
return self::UNKNOWN_IDENTITY;
}
private function _loginByCookie()
{
$request = Zend_Controller_Front::getInstance()->getRequest();
$cookie = $request->get('msd_autologin');
if ($cookie === null || $cookie == '') {
// no cookie found
return false;
}
list($authInfo, $checksum) = explode(':', $cookie);
if (md5($authInfo) != $checksum) {
// autologin not valid - return
return false;
}
$crypt = Msd_Crypt::getInstance('MySQLDumper27112010');
list($username, $pass) = explode(':', $crypt->decrypt($authInfo));
// Try to login the user and refresh the cookie. Because you want
// to stay logged in until you logout.
$this->login($username, $pass, true);
}
/**
* Clear the user identity and logout the user.
*
* @return void
*/
public function logout()
{
Zend_Auth::getInstance()->clearIdentity();
$this->_isLoggedIn = false;
$this->setDefaultConfiguration();
}
/**
* Set default configuration for user
*
* @return void
*/
public function setDefaultConfiguration()
{
$configFile = 'defaultConfig';
if ($this->_isLoggedIn) {
$files = Msd_File::getConfigNames();
if (isset($files[0])) {
$configFile = $files[0];
}
}
Msd_Configuration::getInstance($configFile, true);
}
}

Datei anzeigen

@ -0,0 +1,21 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Exception
* @version SVN: $Rev$
* @author $Author$
*/
require_once 'Msd/Exception.php';
/**
* MySQLDumper Validator Exception
*
* @package MySQLDumper
* @subpackage Exception
*/
class Msd_Validate_Exception extends Msd_Exception
{
}

Datei anzeigen

@ -0,0 +1,246 @@
<?php
/**
* This file is part of MySQLDumper released under the GNU/GPL 2 license
* http://www.mysqldumper.net
*
* @package MySQLDumper
* @subpackage Ini
* @version SVN: $Rev$
* @author $Author$
*/
require_once 'Zend/Validate/Abstract.php';
/**
* Class to check the accessibility for files and directories.
*
* @package MySQLDumper
* @subpackage Validate
*/
class Msd_Validate_File_Accessible extends Zend_Validate_Abstract
{
/**
* @const string Error constant, file/directory doesn't exists.
*/
const NOT_EXISTS = 'accessNotExists';
/**
* @const string Error constant, file/directory isn't readable.
*/
const NOT_READABLE = 'accessNotReadable';
/**
* @const string Error constant, file/directory isn't writable.
*/
const NOT_WRITABLE = 'accessNotWritable';
/**
* @const string Error constant, file/directory isn't executable.
*/
const NOT_EXECUTABLE = 'accessNotExecutable';
/**
* @const string Error constant, file/directory isn't a directory.
*/
const NOT_A_DIRECTORY = 'accessNotADirectory';
/**
* @const string Error constant, file/directory isn't file.
*/
const NOT_A_FILE = 'accessNotAFile';
/**
* @const string Error constant, file/directory isn't link.
*/
const NOT_A_LINK = 'accessNotALink';
/**
* @const string Error constant, file/directory wasn't uploaded.
*/
const NOT_UPLOADED = 'accessNotUploaded';
/**
* @var array Error message templates
*/
protected $_messageTemplates = array();
/**
* @var array Options that determine which access types must checked.
*
* 'pathPrefix' - Will be prepended to the filename in checking method.
* 'accessTypes' - Access variants, that will be checked.
*/
protected $_options = array(
'pathPrefix' => '',
'accessTypes' => array(
'read' => false,
'write' => false,
'execute' => false,
'dir' => false,
'file' => false,
'uploaded' => false,
),
);
/**
* Class constructor. creates and initializes an instance of this validator.
*
* @param array $options Access checking options.
* 'pathPrefix' must be a string.
* 'accessTypes' could be an array, string or an
* instance of Zend_config
* @see self::$options
* @return void
*/
public function __construct($options = null)
{
///get error messages from selected language
$lang = Msd_Language::getInstance()->getTranslator();
$this->_messageTemplates = array(
self::NOT_EXISTS => $lang->_('L_ZEND_ID_ACCESS_NOT_EXISTS'),
self::NOT_READABLE => $lang->_('L_ZEND_ID_ACCESS_NOT_READABLE'),
self::NOT_WRITABLE => $lang->_('L_ZEND_ID_ACCESS_NOT_WRITABLE'),
self::NOT_EXECUTABLE => $lang->_('L_ZEND_ID_ACCESS_NOT_EXECUTABLE'),
self::NOT_A_FILE => $lang->_('L_ZEND_ID_ACCESS_NOT_A_FILE'),
self::NOT_A_DIRECTORY =>
$lang->_('L_ZEND_ID_ACCESS_NOT_A_DIRECTORY'),
self::NOT_A_LINK => $lang->_('L_ZEND_ID_ACCESS_NOT_A_LINK'),
self::NOT_UPLOADED => $lang->_('L_ZEND_ID_ACCESS_NOT_UPLOADED'),
);
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Sets the options for validation.
*
* @throws Msd_Validate_Exception
* @param array $options Options for the validation
* @see self::$options
* @return void
*/
public function setOptions($options)
{
if (!is_array($options)) {
include_once 'Msd/Validate/Exception.php';
throw new Msd_Validate_Exception(
'Options must be an array, string or instance '
. 'of Zend_Config!'
);
}
if (isset($options['accessTypes'])) {
$accessTypes = array();
if (is_array($options['accessTypes'])) {
$accessTypes = $options['accessTypes'];
} else if (is_string($options['accessTypes'])) {
$accessTypes = explode(',', $options['accessTypes']);
} else if ($options['accessTypes'] instanceof Zend_Config) {
$accessTypes = $options['accessTypes']->toArray();
} else {
include_once 'Msd/Validate/Exception.php';
throw new Msd_Validate_Exception(
'Access types must be an array, string or instance '
. 'of Zend_Config!'
);
}
foreach ($accessTypes as $accessType) {
if (isset($this->_options['accessTypes'][$accessType])) {
$this->_options['accessTypes'][$accessType] = true;
}
}
}
if (isset($options['pathPrefix'])) {
$this->_options['pathPrefix'] = $options['pathPrefix'];
}
}
/**
* Returns the current options array.
*
* @return array
*/
public function getOptions()
{
return $this->_options;
}
/**
* Defiend by Zend_Validate_Interface
*
* Checks the accessibility of a file.
*
* @param string $fileName Name of the file to be checked.
* @return bool
*/
public function isValid($fileName)
{
clearstatcache(true, $fileName);
$this->_setValue($fileName);
$fileName = $this->_options['pathPrefix'] . $fileName;
$isValid = true;
$accessTypes = $this->_options['accessTypes'];
if (!file_exists($fileName)) {
$this->_error(self::NOT_EXISTS);
$isValid = false;
}
if ($accessTypes['read']) {
if (!is_readable($fileName)) {
$this->_throw($fileName, self::NOT_READABLE);
$isValid = false;
}
}
if ($accessTypes['write']) {
if (!is_writable($fileName)) {
$this->_throw($fileName, self::NOT_WRITABLE);
$isValid = false;
}
}
if ($accessTypes['execute']) {
if (!is_executable($fileName)) {
$this->_throw($fileName, self::NOT_EXECUTABLE);
$isValid = false;
}
}
if ($accessTypes['dir']) {
if (!is_dir($fileName)) {
$this->_throw($fileName, self::NOT_A_DIRECTORY);
$isValid = false;
}
}
if ($accessTypes['file']) {
if (!is_file($fileName)) {
$this->_throw($fileName, self::NOT_A_FILE);
$isValid = false;
}
}
if ($accessTypes['uploaded']) {
if (!is_uploaded_file($fileName)) {
$this->_throw($fileName, self::NOT_UPLOADED);
$isValid = false;
}
}
return $isValid;
}
/**
* Throws an error of the given type
*
* @param string $fileName checked file which caused an error
* @param string $errorType Type of error
* @return false
*/
protected function _throw($fileName, $errorType)
{
if ($fileName !== null) {
$this->_setValue($fileName);
}
$this->_error($errorType);
return false;
}
}

119
library/Msd/Version.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
* @subpackage Version
* @version SVN: $Rev$
* @author $Author$
*/
/**
* Show MySQLDumper's version number
*
* @package MySQLDumper
* @subpackage Version
*/
class Msd_Version
{
/**
* Current application version
* @var string
*/
private $_msdVersion = '2.0.0';
/**
* Minimum version of PHP which is required.
*
* @var string
*/
private $_requiredPhpVersion = '5.2.0';
/**
* Minimum version of MySQL which is required.
*
* @var string
*/
private $_requiredMysqlVersion = '4.1.2';
/**
* Constructor
*
* @param array $options Option-array to overwrite required PHP/MySQL
* versions
*
* @return void
*/
public function __construct($options = array())
{
if (isset($options['requiredPhpVersion'])) {
$this->_requiredPhpVersion = $options['requiredPhpVersion'];
}
if (isset($options['requiredMysqlVersion'])) {
$this->_requiredMysqlVersion = $options['requiredMysqlVersion'];
}
}
/**
* Get actual MySQLDumper version
*
* @return string The version number of MySQLDumper
*/
public function getMsdVersion()
{
return $this->_msdVersion;
}
/**
* Get required PHP version
*
* @return string The required version number of PHP
*/
public function getRequiredPhpVersion()
{
return $this->_requiredPhpVersion;
}
/**
* Get required MySQL version
*
* @return string The required version number of MySQL
*/
public function getRequiredMysqlVersion()
{
return $this->_requiredMysqlVersion;
}
/**
* Checks for required PHP version.
*
* @return boolean
*/
public function checkPhpVersion()
{
$res = version_compare(PHP_VERSION, $this->_requiredPhpVersion);
if ($res >= 0) {
return true;
}
return false;
}
/**
* Checks for required MySQL version.
*
* @return boolean
*/
public function checkMysqlVersion()
{
$dbObject = Msd_Db::getAdapter();
$mysqlVersion = $dbObject->getServerInfo();
$res = version_compare(
$mysqlVersion,
$this->_requiredMysqlVersion
);
if ($res >= 0) {
return true;
}
return false;
}
}