msd Backup hinzugefügt

This commit is contained in:
aschwarz
2023-07-25 19:16:12 +02:00
parent 50297c1d25
commit 1d3ed789b5
680 changed files with 103120 additions and 0 deletions

44
msd/inc/define_icons.php Normal file
View File

@ -0,0 +1,44 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
//define icons
$icon['arrow_up'] = '<img src="'.$config['files']['iconpath'].'arrow_up.gif" alt="">';
$icon['arrow_down'] = '<img src="'.$config['files']['iconpath'].'arrow_down.gif" alt="">';
$icon['blank'] = $config['files']['iconpath'].'blank.gif';
$icon['browse'] = '<img src="'.$config['files']['iconpath'].'browse.gif" alt="'.$lang['L_TITLE_SHOW_DATA'].'" title="'.$lang['L_TITLE_SHOW_DATA'].'">';
$icon['edit'] = '<img src="'.$config['files']['iconpath'].'edit.gif" alt="'.$lang['L_EDIT'].'" title="'.$lang['L_EDIT'].'">';
$icon['delete'] = '<img src="'.$config['files']['iconpath'].'delete.gif" alt="'.$lang['L_DELETE'].'" title="'.$lang['L_DELETE'].'">';
$icon['index'] = '<img src="'.$config['files']['iconpath'].'index.gif" alt="'.$lang['L_TITLE_INDEX'].'" title="'.$lang['L_TITLE_INDEX'].'">';
$icon['key_primary'] = '<img src="'.$config['files']['iconpath'].'key_primary.gif" alt="'.$lang['L_TITLE_KEY_PRIMARY'].'" title="'.$lang['L_TITLE_KEY_PRIMARY'].'">';
$icon['key_fulltext'] = '<img src="'.$config['files']['iconpath'].'key_fulltext.gif" alt="'.$lang['L_TITLE_KEY_FULLTEXT'].'" title="'.$lang['L_TITLE_KEY_FULLTEXT'].'">';
$icon['key_unique'] = '<img src="'.$config['files']['iconpath'].'key_unique.gif" alt="'.$lang['L_TITLE_KEY_UNIQUE'].'" title="'.$lang['L_TITLE_KEY_UNIQUE'].'">';
$icon['key_nokey'] = '<img src="'.$config['files']['iconpath'].'key_nokey.gif" alt="'.$lang['L_TITLE_NOKEY'].'" title="'.$lang['L_TITLE_NOKEY'].'">';
$icon['table_truncate'] = '<img src="'.$config['files']['iconpath'].'table_truncate.gif" alt="'.$lang['L_EMPTY'].'" title="'.$lang['L_EMPTY'].'">';
$icon['table_truncate_reset'] = '<img src="'.$config['files']['iconpath'].'table_truncate_reset.gif" alt="'.$lang['L_EMPTYKEYS'].'" title="'.$lang['L_EMPTYKEYS'].'">';
$icon['back2db_overview'] = '<img src="'.$config['files']['iconpath'].'arrowleft.gif" alt="'.$lang['L_SQL_BACKDBOVERVIEW'].'" title="'.$lang['L_SQL_BACKDBOVERVIEW'].'">';
$icon['search'] = '<img src="'.$config['files']['iconpath'].'search.gif" alt="'.$lang['L_TITLE_SEARCH'].'" title="'.$lang['L_TITLE_SEARCH'].'">';
$icon['mysql_help'] = '<img src="'.$config['files']['iconpath'].'mysql_help.gif" alt="'.$lang['L_TITLE_MYSQL_HELP'].'" title="'.$lang['L_TITLE_MYSQL_HELP'].'">';
$icon['upload'] = '<img src="'.$config['files']['iconpath'].'openfile.gif" alt="'.$lang['L_TITLE_UPLOAD'].'" title="'.$lang['L_TITLE_UPLOAD'].'">';
//other pics
$icon['logo'] = $config['theme'].'pics/h1_logo.gif';

841
msd/inc/functions.php Normal file
View File

@ -0,0 +1,841 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
/* ensure this file is being included by a parent file */
defined('OOS_VALID_MOD') or exit('Direct Access to this location is not allowed.');
if (!function_exists('get_page_parameter')) {
include './inc/functions_global.php';
}
if (!function_exists('str_ireplace')) { // borrowed from http://www.dscripts.net
function str_ireplace($find, $replace, $string)
{
if (!is_array($find)) {
$find = [
$find,
];
}
if (!is_array($replace)) {
if (!is_array($find)) {
$replace = [
$replace,
];
} else {
// this will duplicate the string into an array the size of $find
$c = count($find);
$rString = $replace;
unset($replace);
for ($i = 0; $i < $c; ++$i) {
$replace[$i] = $rString;
}
}
}
foreach ($find as $fKey => $fItem) {
$between = explode(strtolower($fItem), strtolower($string));
$pos = 0;
foreach ($between as $bKey => $bItem) {
$between[$bKey] = substr($string, $pos, strlen($bItem));
$pos += strlen($bItem) + strlen($fItem);
}
$string = implode($replace[$fKey], $between);
}
return $string;
}
}
if (!function_exists('stripos')) { // borrowed from php.net comments
function stripos($haystack, $needle)
{
return strpos($haystack, stristr($haystack, $needle));
}
}
function Help($ToolTip, $Anker, $imgsize = 12)
{/*
global $config;
if($Anker!=""){
return '<a href="language/'.$config['language'].'/help.html#'.$Anker.'" title="'.$ToolTip.'"><img src="'.$config['files']['iconpath'].'help16.gif" width="'.$imgsize.'" height="'.$imgsize.'" hspace="'.(round($imgsize/4,0)).'" vspace="0" border="0" alt="Help"></a>';
} else {
return '<img src="'.$config['files']['iconpath'].'help16.gif" width="'.$imgsize.'" height="'.$imgsize.'" alt="Help" title="'.$ToolTip.'" border="0" hspace="'.(round($imgsize/4,0)).'" vspace="0" >';
}
*/
}
function DeleteFilesM($dir, $pattern = '*.*')
{
$deleted = [];
$pattern = str_replace([
"\*",
"\?",
], [
'.*',
'.',
], preg_quote($pattern));
if ('/' != substr($dir, -1)) {
$dir .= '/';
}
if (is_dir($dir)) {
$d = dir($dir);
while ($file = $d->read()) {
if (is_file($dir.$file) && preg_match('/^'.$pattern.'$/', $file)) {
if (unlink($dir.$file)) {
$deleted[$file] = true;
} else {
$deleted[$file] = false;
}
}
}
$d->close();
return $deleted;
}
}
function SetDefault($load_default = false)
{
global $config, $databases, $nl, $out, $lang, $preConfig;
if (true == $load_default) {
if (file_exists($config['files']['parameter']) && (is_readable($config['files']['parameter']))) {
include $config['files']['parameter'];
} // alte Config lesen
}
$restore_values = [];
$restore_values['cron_dbindex'] = isset($config['cron_dbindex']) ? $config['cron_dbindex'] : -3;
$restore_values['cron_dbpraefix_array'] = isset($config['cron_dbpraefix_array']) ? $config['cron_dbpraefix_array'] : '';
if ($restore_values['cron_dbindex'] >= 0 && isset($databases['Name'][$config['cron_dbindex']])) { // eine bestimmte Db gewaehlt?
// Ja, Namen merken, um spaeter den Index wieder herzustellen
$restore_values['db_actual_cron'] = $databases['Name'][$config['cron_dbindex']];
}
$restore_values['db_actual'] = isset($databases['db_actual']) ? $databases['db_actual'] : '';
$old_lang = isset($config['language']) && in_array($config['language'], $lang['languages']) ? $config['language'] : '';
if (true == $load_default) {
if (file_exists($config['files']['parameter'])) {
@unlink($config['files']['parameter']);
}
include './config.php';
if (is_array($preConfig)) {
foreach ($preConfig as $key => $val) {
$config[$key] = $val;
}
}
if ('' != $old_lang) {
$config['language'] = $old_lang;
}
include './language/'.$config['language'].'/lang.php';
}
$oldVals = [];
// Zuordnung nach Namen der Db zwischenspeichern, um Eingaben nicht zu verlieren
if (isset($databases) && isset($databases['Name'])) {
foreach ($databases['Name'] as $k => $v) {
if (!isset($oldVals[$k])) {
$oldVals[$v] = [];
}
$oldVals[$v]['praefix'] = $databases['praefix'][$k];
$oldVals[$v]['command_before_dump'] = $databases['command_before_dump'][$k];
$oldVals[$v]['command_after_dump'] = $databases['command_after_dump'][$k];
}
}
$oldDbArray = [];
if (isset($databases['Name'])) {
$oldDbArray = $databases['Name'];
}
$databases['Name'] = [];
$found_dbs = [];
//DB-Liste holen
mod_mysqli_connect();
$create_statement = 'CREATE TABLE `myoosdumper_test_abcxyvfgh` (`test` varchar(200) default NULL, `id` bigint(20) unsigned NOT NULL auto_increment,'.'PRIMARY KEY (`id`)) TYPE=MyISAM;';
$res = mysqli_query($config['dbconnection'], 'SHOW DATABASES');
while ($row = mysqli_fetch_row($res)) {
$found_dbs[] = $row[0];
}
$found_dbs = array_merge($oldDbArray, $found_dbs);
$found_dbs = array_unique($found_dbs);
sort($found_dbs);
// now check each db
$a = 0;
for ($i = 0; $i < count($found_dbs); ++$i) {
$found_db = $found_dbs[$i];
// Testverbindung - Tabelle erstellen, nachschauen, ob es geklappt hat und dann wieder löschen
$use = mysqli_select_db($config['dbconnection'], $found_db);
if ($use) {
/*
Undefined variable: $old_db
if (isset($old_db) && $found_db == $old_db) {
$databases['db_selected_index'] = $a;
}
*/
$databases['Name'][$a] = $found_db;
$databases['praefix'][$a] = '';
$databases['command_before_dump'][$a] = '';
$databases['command_after_dump'][$a] = '';
if (isset($oldVals[$found_db])) {
$databases['praefix'][$a] = $oldVals[$found_db]['praefix'];
$databases['command_before_dump'][$a] = $oldVals[$found_db]['command_before_dump'];
$databases['command_after_dump'][$a] = $oldVals[$found_db]['command_after_dump'];
}
$out .= $lang['L_SAVING_DB_FORM'].' '.$found_db.' '.$lang['L_ADDED']."$nl";
++$a;
}
}
if (!isset($databases['db_selected_index'])) {
$databases['db_selected_index'] = 0;
$databases['db_actual'] = $databases['Name'][0];
}
WriteParams(1, $restore_values);
if (true === $load_default) {
WriteLog('default settings loaded.');
}
return $out;
}
function WriteParams($as = 0, $restore_values = false)
{
// wenn $as=1 wird versucht den aktuellen Index der Datenbank nach dem Einlesen wieder zu ermitteln
// auch wenn sich die Indexnummer durch Loeschaktionen geaendert hat
global $config, $databases, $config_dontsave;
$nl = "\n";
// alte Werte retten
if ($as) {
if (is_array($restore_values)) {
if ($restore_values['cron_dbindex'] < 0) {
// Multidump oder "alle Datenbanken" war gewaehlt
$config['cron_dbindex'] = $restore_values['cron_dbindex'];
} else {
//den Index der konkreten Datenbank aus der alten Konfiguration ermitteln
$db_names = [];
$db_names = array_flip($databases['Name']);
if (isset($db_names[$restore_values['db_actual']])) {
// alte Db existiert noch -> Index uebernehmen
$databases['db_actual'] = $restore_values['db_actual'];
} else {
$databases['db_actual'] = $databases['Name'][0];
}
//Cron-Index wiederfinden
if (isset($db_names[$restore_values['cron_dbindex']])) {
$config['cron_dbindex'] = $db_names[$restore_values['cron_dbindex']];
} else {
// DB wurde zwischenzeitlich geloescht - sicherheitshalber alle DBs sichern
$databases['cron_dbindex'] = -3;
}
}
}
}
FillMultiDBArrays();
//Parameter zusammensetzen
$config['multipartgroesse1'] = isset($config['multipartgroesse1']) ? $config['multipartgroesse1'] : 1;
$config['multipartgroesse2'] = isset($config['multipartgroesse2']) ? $config['multipartgroesse2'] : 1;
$config['multipart_groesse'] = $config['multipartgroesse1'] * ((1 == $config['multipartgroesse2']) ? 1024 : 1024 * 1024);
$param = $pars_all = '<?php '.$nl;
$config['email_maxsize1'] = isset($config['email_maxsize1']) ? $config['email_maxsize1'] : 1;
$config['email_maxsize2'] = isset($config['email_maxsize2']) ? $config['email_maxsize2'] : 1;
if (!isset($config['email_maxsize'])) {
$config['email_maxsize'] = $config['email_maxsize1'] * ((1 == $config['email_maxsize2']) ? 1024 : 1024 * 1024);
}
if (!isset($config['cron_execution_path'])) {
$config['cron_execution_path'] = 'mod_cron/';
}
if (0 == $as) {
$config['paths']['root'] = addslashes(Realpfad('./'));
}
$config['files']['parameter'] = $config['paths']['config'].$config['config_file'].'.php';
$config['theme'] = isset($config['theme']) ? $config['theme'] : 'mod';
$config['files']['iconpath'] = './css/'.$config['theme'].'/icons/';
foreach ($config as $var => $val) {
if (!in_array($var, $config_dontsave)) {
if (is_array($val)) {
$pars_all .= '$config[\''.$var.'\'] = [];'.$nl;
foreach ($val as $var2 => $val2) {
$pars_all .= '$config[\''.$var.'\']['.((is_int($var2)) ? $var2 : "'".$var2."'").'] = \''.my_addslashes($val2)."';$nl";
}
} else {
if (!in_array($var, $config_dontsave)) {
$pars_all .= '$config[\''.$var.'\'] = \''.my_addslashes($val)."';$nl";
}
}
}
}
foreach ($databases as $var => $val) {
if (is_array($val)) {
$pars_all .= '$databases[\''.$var.'\'] = [];'.$nl;
foreach ($val as $var2 => $val2) {
if (1 == $as) {
$pars_all .= '$databases[\''.$var.'\']['.((is_int($var2)) ? $var2 : "'".$var2."'").'] = \''.my_addslashes(stripslashes($val2))."';$nl";
} else {
$pars_all .= '$databases[\''.$var.'\']['.((is_int($var2)) ? $var2 : "'".$var2."'").'] = \''.my_addslashes($val2)."';$nl";
}
}
} else {
if (1 == $as) {
$pars_all .= '$databases[\''.$var.'\'] = \''.addslashes($val)."';$nl";
} else {
$pars_all .= '$databases[\''.$var.'\'] = \''.$val."';$nl";
}
}
}
$param .= '?>';
$pars_all .= '?>';
//Datei öffnen und schreiben
$ret = true;
$file = $config['paths']['config'].$config['config_file'].'.php';
if ($fp = fopen($file, 'wb')) {
if (!fwrite($fp, $pars_all)) {
$ret = false;
}
if (!fclose($fp)) {
$ret = false;
}
@chmod($file, 0777);
} else {
$ret = false;
}
$ret = WriteCronScript($restore_values);
return $ret;
}
function escape_specialchars($text)
{
$suchen = [
'@',
'$',
'\\\\',
'"',
];
$ersetzen = [
'\@',
'\$',
'\\',
'\"',
];
$text = str_replace($suchen, $ersetzen, $text);
return $text;
}
// definiert einen String, der ein Array nach Perlsyntax aufbaut
function my_implode($arr, $mode = 0) // 0=String, 1=intval
{
global $nl;
if (!is_array($arr)) {
return false;
}
foreach ($arr as $key => $val) {
if (0 == $mode) {
$arr[$key] = escape_specialchars($val);
} else {
$arr[$key] = intval($val);
}
}
if ($mode == 0) {
$ret='("' . implode('","', $arr) . '");' . $nl;
} else {
$ret='(' . implode(',', $arr) . ');' . $nl;
}
return $ret;
}
function WriteCronScript($restore_values = false)
{
global $nl, $config, $databases, $cron_db_array, $cron_dbpraefix_array, $cron_db_cbd_array, $cron_db_cad_array, $dontBackupDatabases;
if (!isset($databases['db_selected_index'])) {
$databases['db_selected_index'] = 0;
}
if (!isset($databases['command_before_dump'])) {
$databases['command_before_dump'] = '';
}
if (!isset($databases['command_after_dump'])) {
$databases['command_after_dump'] = '';
}
if (!isset($databases['praefix'][$databases['db_selected_index']])) {
$databases['praefix'][$databases['db_selected_index']] = '';
}
if (!isset($databases['db_actual_cronindex'])) {
$databases['db_actual_cronindex'] = $databases['db_selected_index'];
}
if (!isset($config['email_maxsize'])) {
$config['email_maxsize'] = $config['email_maxsize1'] * ((1 == $config['email_maxsize2']) ? 1024 : 1024 * 1024);
}
$cron_dbname = $databases['db_actual'];
// -2 = Multidump configuration
// -3 = all databases - nothing to do
// get standard values for all databases
$cron_db_array = $databases['Name'];
$cron_dbpraefix_array = $databases['praefix'];
$cron_command_before_dump = $databases['command_before_dump'];
$cron_command_after_dump = $databases['command_after_dump'];
if (!isset($config['cron_dbindex'])) {
$config['cron_dbindex'] = -3;
}
if (-2 == intval($config['cron_dbindex'])) {
// get selected dbs from multidump-settings
$cron_db_array = $databases['multi'];
$cron_dbpraefix_array = $databases['multi_praefix'];
$cron_command_before_dump = $databases['multi_commandbeforedump'];
$cron_command_after_dump = $databases['multi_commandafterdump'];
}
// we need to correct the index of the selected database after we cleaned
// the db-array from information_schema and mysql if it points to a db-name
if ($config['cron_dbindex'] >= 0) {
$cronDbIndexDbName = $databases['Name'][$config['cron_dbindex']];
} else {
$cronDbIndex = $config['cron_dbindex'];
}
$newDbNames = $databases['Name'];
//remove database we don't want to backup
// from newDbNames
foreach ($databases['Name'] as $k=>$v) {
if (in_array($v, $dontBackupDatabases)) {
unset($newDbNames[$k]);
}
}
// and from cron (cron_db_array has different length to newDbNames: at least mysql and information_schema are missing)
foreach ($cron_db_array as $k=>$v) {
if (in_array($v, $dontBackupDatabases)) {
unset($cron_db_array[$k],
$cron_dbpraefix_array[$k],
$cron_command_before_dump[$k],
$cron_command_after_dump[$k]
);
}
}
// find new index
if ($config['cron_dbindex'] >= 0) {
sort($newDbNames);
$dbNames = array_flip($newDbNames);
if (isset($dbNames[$cronDbIndexDbName])) {
$cronDbIndex = $dbNames[$cronDbIndexDbName];
} else {
$cronDbIndex = 0;
}
}
$r = str_replace('\\\\', '/', $config['paths']['root']);
$r = str_replace('@', "\@", $r);
$p1 = $r.$config['paths']['backup'];
$p2 = $r.$config['files']['perllog'].((isset($config['logcompression']) && (1 == $config['logcompression'])) ? '.gz' : '');
$p3 = $r.$config['files']['perllogcomplete'].((isset($config['logcompression']) && (1 == $config['logcompression'])) ? '.gz' : '');
// auf manchen Server wird statt 0 ein leerer String gespeichert -> fuehrt zu einem Syntax-Fehler
// hier die entsprechenden Ja/Nein-Variablen sicherheitshalber in intvalues aendern
$int_array = [
'dbport',
'cron_compression',
'cron_printout',
'multi_part',
'multipart_groesse',
'email_maxsize',
'auto_delete',
'max_backup_files',
'perlspeed',
'optimize_tables_beforedump',
'logcompression',
'log_maxsize',
'cron_completelog',
'cron_use_sendmail',
'cron_smtp_port',
];
foreach ($int_array as $i) {
if (is_array($i)) {
foreach ($i as $key => $val) {
$int_array[$key] = intval($val);
}
} else {
$config[$i] = isset($config[$i]) ? intval($config[$i]) : 0;
}
}
if (0 == $config['dbport']) {
$config['dbport'] = 3306;
}
$config['cron_sendmail'] = isset($config['cron_sendmail']) ? $config['cron_sendmail'] : '';
$config['cron_printout'] = isset($config['cron_printout']) ? $config['cron_printout'] : '';
$config['send_mail'] = isset($config['send_mail']) ? $config['send_mail'] : '';
$config['send_mail_dump'] = isset($config['send_mail_dump']) ? $config['send_mail_dump'] : '';
$config['email_recipient'] = isset($config['email_recipient']) ? $config['email_recipient'] : '';
$config['email_recipient_cc'] = isset($config['email_recipient_cc']) ? $config['email_recipient_cc'] : '';
$config['email_sender'] = isset($config['email_sender']) ? $config['email_sender'] : '';
$config['cron_smtp'] = isset($config['cron_smtp']) ? $config['cron_smtp'] : '';
$config['ftp_server'] = isset($config['ftp_server']) ? $config['ftp_server'] : '';
$config['ftp_port'] = isset($config['ftp_port']) ? $config['ftp_port'] : '';
$config['ftp_mode'] = isset($config['ftp_mode']) ? $config['ftp_mode'] : '';
$config['ftp_user'] = isset($config['ftp_user']) ? $config['ftp_user'] : '';
$config['ftp_pass'] = isset($config['ftp_pass']) ? $config['ftp_pass'] : '';
$config['ftp_dir'] = isset($config['ftp_dir']) ? $config['ftp_dir'] : '';
$config['ftp_timeout'] = isset($config['ftp_timeout']) ? $config['ftp_timeout'] : '';
$config['ftp_useSSL'] = isset($config['ftp_useSSL']) ? $config['ftp_useSSL'] : '';
$config['ftp_transfer'] = isset($config['ftp_transfer']) ? $config['ftp_transfer'] : '';
$config['sftp_server'] = isset($config['sftp_server']) ? $config['sftp_server'] : '';
$config['sftp_port'] = isset($config['sftp_port']) ? $config['sftp_port'] : '';
$config['sftp_user'] = isset($config['sftp_user']) ? $config['sftp_user'] : '';
$config['sftp_pass'] = isset($config['sftp_pass']) ? $config['sftp_pass'] : '';
$config['sftp_dir'] = isset($config['sftp_dir']) ? $config['sftp_dir'] : '';
$config['sftp_path_to_private_key'] = isset($config['sftp_path_to_private_key']) ? $config['sftp_path_to_private_key'] : null;
$config['sftp_secret_passphrase_for_private_key'] = isset($config['sftp_secret_passphrase_for_private_key']) ? $config['sftp_secret_passphrase_for_private_key'] : null;
$config['sftp_fingerprint'] = isset($config['sftp_fingerprint']) ? $config['sftp_fingerprint'] : null;
$config['sftp_timeout'] = isset($config['sftp_timeout']) ? $config['sftp_timeout'] : '';
$config['sftp_transfer'] = isset($config['sftp_transfer']) ? $config['sftp_transfer'] : '';
$config['cron_comment'] = isset($config['cron_comment']) ? $config['cron_comment'] : '';
$cronscript = "<?php\n#Vars - written at ".date('Y-m-d').$nl;
$cronscript .= '$dbhost="'.$config['dbhost'].'";'.$nl;
$cronscript .= '$dbname="'.$cron_dbname.'";'.$nl;
$cronscript .= '$dbuser="'.escape_specialchars($config['dbuser']).'";'.$nl;
$cronscript .= '$dbpass="'.escape_specialchars($config['dbpass']).'";'.$nl;
$cronscript .= '$dbport='.$config['dbport'].';'.$nl;
$cronscript .= '$dbsocket="'.escape_specialchars($config['dbsocket']).'";'.$nl;
$cronscript .= '$compression='.$config['cron_compression'].';'.$nl;
$cronscript .= '$backup_path="'.$p1.'";'.$nl;
$cronscript .= '$logdatei="'.$p2.'";'.$nl;
$cronscript .= '$completelogdatei="'.$p3.'";'.$nl;
$cronscript .= '$sendmail_call="'.escape_specialchars($config['cron_sendmail']).'";'.$nl;
$cronscript .= '$nl="\n";'.$nl;
$cronscript .= '$cron_dbindex='.$cronDbIndex.';'.$nl;
$cronscript .= '$cron_printout='.$config['cron_printout'].';'.$nl;
$cronscript .= '$cronmail='.$config['send_mail'].';'.$nl;
$cronscript .= '$cronmail_dump='.$config['send_mail_dump'].';'.$nl;
$cronscript .= '$cronmailto="'.escape_specialchars($config['email_recipient']).'";'.$nl;
$cronscript .= '$cronmailto_cc="'.escape_specialchars($config['email_recipient_cc']).'";'.$nl;
$cronscript .= '$cronmailfrom="'.escape_specialchars($config['email_sender']).'";'.$nl;
$cronscript .= '$cron_use_sendmail='.$config['cron_use_sendmail'].';'.$nl;
$cronscript .= '$cron_smtp="'.escape_specialchars($config['cron_smtp']).'";'.$nl;
$cronscript .= '$cron_smtp_port="'.$config['cron_smtp_port'].'";'.$nl;
$cronscript .= '@cron_db_array='.my_implode($cron_db_array);
$cronscript .= '@cron_dbpraefix_array='.my_implode($cron_dbpraefix_array);
$cronscript .= '@cron_command_before_dump='.my_implode($cron_command_before_dump);
$cronscript .= '@cron_command_after_dump='.my_implode($cron_command_after_dump);
$cronscript .= '@ftp_server='.my_implode($config['ftp_server']);
$cronscript .= '@ftp_port='.my_implode($config['ftp_port'], 1);
$cronscript .= '@ftp_mode='.my_implode($config['ftp_mode'], 1);
$cronscript .= '@ftp_user='.my_implode($config['ftp_user']);
$cronscript .= '@ftp_pass='.my_implode($config['ftp_pass']);
$cronscript .= '@ftp_dir='.my_implode($config['ftp_dir']);
$cronscript .= '@ftp_timeout='.my_implode($config['ftp_timeout'], 1);
$cronscript .= '@ftp_useSSL='.my_implode($config['ftp_useSSL'], 1);
$cronscript .= '@ftp_transfer='.my_implode($config['ftp_transfer'], 1);
$cronscript .= '$mp='.$config['multi_part'].';'.$nl;
$cronscript .= '$multipart_groesse='.$config['multipart_groesse'].';'.$nl;
$cronscript .= '$email_maxsize='.$config['email_maxsize'].';'.$nl;
$cronscript .= '$auto_delete='.$config['auto_delete'].';'.$nl;
$cronscript .= '$max_backup_files='.$config['max_backup_files'].';'.$nl;
$cronscript .= '$perlspeed='.$config['perlspeed'].';'.$nl;
$cronscript .= '$optimize_tables_beforedump='.$config['optimize_tables_beforedump'].';'.$nl;
$cronscript .= '$logcompression='.$config['logcompression'].';'.$nl;
$cronscript .= '$log_maxsize='.$config['log_maxsize'].';'.$nl;
$cronscript .= '$complete_log='.$config['cron_completelog'].';'.$nl;
$cronscript .= '$my_comment="'.escape_specialchars(stripslashes($config['cron_comment'])).'";'.$nl;
$cronscript .= '';
// Save config
$ret = true;
$sfile = $config['paths']['config'].$config['config_file'].'.conf.php';
if (file_exists($sfile)) {
@unlink($sfile);
}
if ($fp = fopen($sfile, 'wb')) {
if (!fwrite($fp, $cronscript)) {
$ret = false;
}
if (!fclose($fp)) {
$ret = false;
}
@chmod("$sfile", 0777);
} else {
$ret = false;
}
// if standard config was deleted -> restore it with the actual values
if (!file_exists($config['paths']['config'].'myoosdumper.conf.php')) {
$sfile = $config['paths']['config'].'myoosdumper.conf.php';
if ($fp = fopen($sfile, 'wb')) {
if (!fwrite($fp, $cronscript)) {
$ret = false;
}
if (!fclose($fp)) {
$ret = false;
}
@chmod("$sfile", 0777);
} else {
$ret = false;
}
}
return $ret;
}
function LogFileInfo($logcompression)
{
global $config;
$l = [];
$sum = $s
= $l['log_size'] = $l['perllog_size'] = $l['perllogcomplete_size'] = $l['errorlog_size'] = $l['log_totalsize'] = 0;
if ((isset($config['logcompression']) && 1 == $config['logcompression'])) {
$l['log'] = $config['files']['log'].'.gz';
$l['perllog'] = $config['files']['perllog'].'.gz';
$l['perllogcomplete'] = $config['files']['perllogcomplete'].'.gz';
$l['errorlog'] = $config['paths']['log'].'error.log.gz';
} else {
$l['log'] = $config['files']['log'];
$l['perllog'] = $config['files']['perllog'];
$l['perllogcomplete'] = $config['files']['perllogcomplete'];
$l['errorlog'] = $config['paths']['log'].'error.log';
}
$l['log_size'] += @filesize($l['log']);
$sum += $l['log_size'];
$l['perllog_size'] += @filesize($l['perllog']);
$sum += $l['perllog_size'];
$l['perllogcomplete_size'] += @filesize($l['perllogcomplete']);
$sum += $l['perllogcomplete_size'];
$l['errorlog_size'] += @filesize($l['errorlog']);
$sum += $l['errorlog_size'];
$l['log_totalsize'] += $sum;
return $l;
}
function DeleteLog()
{
global $config;
//Datei öffnen und schreiben
$log = date('d.m.Y H:i:s')." Log created.\n";
if (file_exists($config['files']['log'].'.gz')) {
@unlink($config['files']['log'].'.gz');
}
if (file_exists($config['files']['log'].'.gz')) {
@unlink($config['files']['log']);
}
if ((isset($config['logcompression']) && 1 == $config['logcompression'])) {
$fp = @gzopen($config['files']['log'].'.gz', 'wb');
@gzwrite($fp, $log);
@gzclose($fp);
@chmod($config['files']['log'].'.gz', 0777);
} else {
$fp = @fopen($config['files']['log'], 'wb');
@fwrite($fp, $log);
@fclose($fp);
@chmod($config['files']['log'], 0777);
}
}
function CreateDirsFTP()
{
global $config, $lang, $install_ftp_server, $install_ftp_port, $install_ftp_user_name, $install_ftp_user_pass, $install_ftp_path;
// Herstellen der Basis-Verbindung
echo '<hr>'.$lang['L_CONNECT_TO'].' `'.$install_ftp_server.'` Port '.$install_ftp_port.' ...<br>';
$conn_id = ftp_connect($install_ftp_server);
// Einloggen mit Benutzername und Kennwort
$login_result = ftp_login($conn_id, $install_ftp_user_name, $install_ftp_user_pass);
// Verbindung überprüfen
if ((!$conn_id) || (!$login_result)) {
echo $lang['L_FTP_NOTCONNECTED'];
echo $lang['L_CONNWITH']." $install_ftp_server ".$lang['L_ASUSER']." $install_ftp_user_name ".$lang['L_NOTPOSSIBLE'];
return 0;
} else {
if (1 == $config['ftp_mode']) {
ftp_pasv($conn_id, true);
}
//Wechsel in betroffenes Verzeichnis
echo $lang['L_CHANGEDIR'].' `'.$install_ftp_path.'` ...<br>';
ftp_chdir($conn_id, $install_ftp_path);
// Erstellen der Verzeichnisse
echo $lang['L_DIRCR1'].' ...<br>';
ftp_mkdir($conn_id, 'work');
ftp_site($conn_id, 'CHMOD 0777 work');
echo $lang['L_CHANGEDIR'].' `work` ...<br>';
ftp_chdir($conn_id, 'work');
echo $lang['L_INDIR'].' `'.ftp_pwd($conn_id).'`<br>';
echo $lang['L_DIRCR5'].' ...<br>';
ftp_mkdir($conn_id, 'config');
ftp_site($conn_id, 'CHMOD 0777 config');
echo $lang['L_DIRCR2'].' ...<br>';
ftp_mkdir($conn_id, 'backup');
ftp_site($conn_id, 'CHMOD 0777 backup');
echo $lang['L_DIRCR4'].' ...<br>';
ftp_mkdir($conn_id, 'log');
ftp_site($conn_id, 'CHMOD 0777 log');
// Schließen des FTP-Streams
ftp_quit($conn_id);
return 1;
}
}
function ftp_mkdirs($config, $dirname)
{
$path = '';
$dir = preg_split('/\//', $dirname);
for ($i = 0; $i < count($dir) - 1; ++$i) {
$path .= $dir[$i].'/';
@ftp_mkdir($config['dbconnection'], $path);
}
if (@ftp_mkdir($config['dbconnection'], $dirname)) {
return 1;
}
}
function IsWritable($dir)
{
$testfile = $dir.'/.writetest';
if ($writable = @fopen($testfile, 'w')) {
@fclose($writable);
@unlink($testfile);
}
return $writable;
}
function IsAccessProtected()
{
$rc = false;
$url = sprintf('%s://%s%s', $_SERVER['REQUEST_SCHEME'], $_SERVER['HTTP_HOST'], dirname($_SERVER['PHP_SELF']));
$headers = @get_headers($url);
if (is_array($headers) && count($headers) > 0) {
$rc = (preg_match('/\s+(?:401|403)\s+/', $headers[0])) ? 1 : 0;
}
return $rc;
}
function SearchDatabases($printout, $db = '')
{
global $databases, $config, $lang;
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
$db_list = [];
if ($db > '') {
$db_list[] = $db; // DB wurde manuell angegeben
}
// Datenbanken automatisch erkennen
$show_dbs = mysqli_query($config['dbconnection'], 'SHOW DATABASES');
if (false === !$show_dbs) {
while ($row = mysqli_fetch_row($show_dbs)) {
if (trim($row[0]) > '') {
$db_list[] = $row[0];
}
}
}
$db_list = array_unique($db_list);
sort($db_list);
if (sizeof($db_list) > 0) {
$databases['db_selected_index'] = 0;
for ($i = 0; $i < sizeof($db_list); ++$i) {
// Test-Select um zu sehen, ob Berechtigungen existieren
if (false === !@mysqli_query($config['dbconnection'], 'SHOW TABLES FROM `'.$db_list[$i].'`')) {
$databases['Name'][$i] = $db_list[$i];
$databases['praefix'][$i] = '';
$databases['command_before_dump'][$i] = '';
$databases['command_after_dump'][$i] = '';
if (1 == $printout) {
echo $lang['L_FOUND_DB'].' `'.$db_list[$i].'`<br />';
}
} else {
if (1 == $printout) {
echo '<span class="error">'.sprintf($lang['L_DB_MANUAL_ERROR'], $db_list[$i]).'</span><br />';
}
}
}
}
if (isset($databases['Name'][0])) {
$databases['db_actual'] = $databases['Name'][0];
}
}
// removes tags from inputs recursivly
function my_strip_tags($value)
{
global $dont_strip;
if (is_array($value)) {
foreach ($value as $key => $val) {
if (!in_array($key, $dont_strip)) {
$ret[$key] = my_strip_tags($val);
} else {
$ret[$key] = $val;
}
}
} else {
$ret = trim(strip_tags($value));
}
return $ret;
}
/**
* Add a slashes only before '.
*
* Used for escaping strings in JS-alerts and config-files
*
* @param $string
*
* @return string
*/
function my_addslashes($string)
{
if (is_string($string)) {
$string = str_replace("'", "\'", $string);
}
return $string;
}
/**
* Replaces quotes for outputting value in HTML-attributes.
*
* Replaces quotes for outputing value in HTML-attributes without breaking HTML
*
* @param string $value value to output
*
* @return string
*/
function my_quotes($value)
{
return str_replace('"', '&quot;', $value);
}
// prepares a string for executing it as query
function db_escape($string)
{
global $config;
if (function_exists('mysqli_real_escape_string')) {
$string = mysqli_real_escape_string($config['dbconnection'], $string);
} elseif (function_exists('mysqli_escape_string')) {
$string = mysqli_escape_string($config['dbconnection'], $string);
} else {
$string = addslashes($string);
}
return $string;
}

568
msd/inc/functions_dump.php Normal file
View File

@ -0,0 +1,568 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
/* ensure this file is being included by a parent file */
defined('OOS_VALID_MOD') or exit('Direct Access to this location is not allowed.');
include './inc/functions_global.php';
//Buffer fuer Multipart-Filesizepruefung
$buffer = 10 * 1024;
function new_file($last_groesse = 0)
{
global $dump, $databases, $config, $out, $lang, $nl, $mysql_commentstring;
// Dateiname aus Datum und Uhrzeit bilden
if ($dump['part'] - $dump['part_offset'] == 1) {
$dump['filename_stamp'] = date('Y_m_d_H_i', time());
}
if (isset($config['multi_part']) && (1 == $config['multi_part'])) {
$dateiname = $databases['Name'][$dump['dbindex']].'_'.$dump['filename_stamp'].'_part_'.($dump['part'] - $dump['part_offset']);
} else {
$dateiname = $databases['Name'][$dump['dbindex']].'_'.date('Y_m_d_H_i', time());
}
$endung = (isset($config['compression']) && ($config['compression'])) ? '.sql.gz' : '.sql';
$dump['backupdatei'] = $dateiname.$endung;
if (file_exists($config['paths']['backup'].$dump['backupdatei'])) {
unlink($config['paths']['backup'].$dump['backupdatei']);
}
$cur_time = date('Y-m-d H:i');
$statuszeile = GetStatusLine().$nl.$mysql_commentstring.' Dump by MyOOS [Dumper] '.MOD_VERSION.' ('.$config['homepage'].')'.$nl;
$statuszeile .= '/*!40101 SET NAMES \''.$dump['dump_encoding'].'\' */;'.$nl;
$statuszeile .= 'SET FOREIGN_KEY_CHECKS=0;'.$nl;
if ($dump['part'] - $dump['part_offset'] == 1) {
if (isset($config['multi_part']) && (0 == $config['multi_part'])) {
if (isset($config['multi_part']) && 1 == $config['multi_dump'] && 0 == $dump['dbindex']) {
WriteLog('starting Multidump with '.count($databases['multi']).' Datenbases.');
}
WriteLog('Start Dump \''.$dump['backupdatei'].'\'');
} else {
WriteLog('Start Multipart-Dump \''.$dateiname.'\'');
}
$out .= '<strong>'.$lang['L_STARTDUMP'].' `'.$databases['Name'][$dump['dbindex']].'`</strong>'.(('' != $databases['praefix'][$dump['dbindex']]) ? ' ('.$lang['L_WITHPRAEFIX'].' <span style="color:blue">'.$databases['praefix'][$dump['dbindex']].'</span>)' : '').'... ';
if (1 == $dump['part']) {
$dump['table_offset'] = 0;
$dump['countdata'] = 0;
}
// Seitenerstaufruf -> Backupdatei anlegen
$dump['data'] = $statuszeile.$mysql_commentstring.' Dump created: '.$cur_time;
} else {
if (0 != $config['multi_part']) {
WriteLog('Continue Multipart-Dump with File '.($dump['part'] - $dump['part_offset']).' (last file was '.$last_groesse.' Bytes)');
$dump['data'] = $statuszeile.$mysql_commentstring.' This is part '.($dump['part'] - $dump['part_offset']).' of the backup.'.$nl.$nl.$dump['data'];
}
}
WriteToDumpFile();
++$dump['part'];
}
function GetStatusLine($kind = 'php')
{
/*AUFBAU der Statuszeile:
-- Status:tabellenzahl:datensätze:Multipart:Datenbankname:script:scriptversion:Kommentar:MySQLVersion:Backupflags:SQLBefore:SQLAfter:Charset:CharsetEXTINFO
Aufbau Backupflags (1 Zeichen pro Flag, 0 oder 1, 2=unbekannt)
(complete inserts)(extended inserts)(ignore inserts)(delayed inserts)(downgrade)(lock tables)(optimize tables)
*/
global $databases, $config, $lang, $dump, $mysql_commentstring;
$t_array = explode('|', $databases['db_actual_tableselected']);
$t = 0;
$r = 0;
$t_zeile = "$mysql_commentstring\n$mysql_commentstring TABLE-INFO\r\n";
mod_mysqli_connect();
$res = mysqli_query($config['dbconnection'], 'SHOW TABLE STATUS FROM `'.$databases['Name'][$dump['dbindex']].'`');
$numrows = intval(@mysqli_num_rows($res));
for ($i = 0; $i < $numrows; ++$i) {
$erg = mysqli_fetch_array($res);
// Get nr of records -> need to do it this way because of incorrect returns when using InnoDBs
$sql_2 = 'SELECT count(*) as `count_records` FROM `'.$databases['Name'][$dump['dbindex']].'`.`'.$erg['Name'].'`';
$res2 = mysqli_query($config['dbconnection'], $sql_2);
if (false === $res2) {
// error reading table definition
$read_create_error = sprintf($lang['L_FATAL_ERROR_DUMP'], $databases['Name'][$dump['dbindex']], $erg['Name']).': '.mysqli_error($config['dbconnection']);
Errorlog('DUMP', $databases['Name'][$dump['dbindex']], '', $read_create_error, 0);
WriteLog($read_create_error);
if ($config['stop_with_error'] > 0) {
exit($read_create_error);
}
++$dump['errors'];
//$i++; // skip corrupted table
} else {
$row2 = mysqli_fetch_array($res2);
$erg['Rows'] = $row2['count_records'];
if (('' == $databases['db_actual_tableselected'] || ('' != $databases['db_actual_tableselected'] && (in_array($erg[0], $t_array)))) && (substr($erg[0], 0, strlen($databases['praefix'][$dump['dbindex']])) == $databases['praefix'][$dump['dbindex']])) {
++$t;
$r += $erg['Rows'];
if (isset($erg['Type'])) {
$erg['Engine'] = $erg['Type'];
}
$t_zeile .= "$mysql_commentstring TABLE|".$erg['Name'].'|'.$erg['Rows'].'|'.($erg['Data_length'] + $erg['Index_length']).'|'.$erg['Update_time'].'|'.$erg['Engine']."\n";
}
}
}
//$dump['totalrecords'] = $r;
$flags = 1;
$mp = (isset($config['multi_part']) && (1 == $config['multi_part'])) ? $mp = 'MP_'.($dump['part'] - $dump['part_offset']) : 'MP_0';
$statusline = "$mysql_commentstring Status:$t:$r:$mp:".$databases['Name'][$dump['dbindex']].":$kind:".MOD_VERSION.':'.$dump['kommentar'].':';
$statusline .= MOD_MYSQL_VERSION.":$flags:::".$dump['dump_encoding'].":EXTINFO\n".$t_zeile."$mysql_commentstring"." EOF TABLE-INFO\n$mysql_commentstring";
return $statusline;
}
// Liest die Eigenschaften der Tabelle aus der DB und baut die CREATE-Anweisung zusammen
function get_def($db, $table, $withdata = 1)
{
global $config, $nl, $mysql_commentstring, $dump;
$def = "\n\n$mysql_commentstring\n$mysql_commentstring Create Table `$table`\n$mysql_commentstring\n\n";
if ('VIEW' == $dump['table_types'][getDBIndex($db, $table)]) {
$def .= "DROP VIEW IF EXISTS `$table`;\n";
$withdata = 0;
} else {
$def .= "DROP TABLE IF EXISTS `$table`;\n";
}
mysqli_select_db($config['dbconnection'], $db);
$result = mysqli_query($config['dbconnection'], 'SHOW CREATE TABLE `'.$table.'`');
$row = mysqli_fetch_row($result);
if (false === $row) {
return false;
}
$def .= $row[1].';'."\n\n";
if (1 == $withdata) {
$def .= "$mysql_commentstring\n$mysql_commentstring Data for Table `$table`\n$mysql_commentstring\n\n";
$def .= "/*!40000 ALTER TABLE `$table` DISABLE KEYS */;".$nl;
}
return $def;
}
// Liest die Daten aus der DB aus und baut die INSERT-Anweisung zusammen
function get_content($db, $table)
{
global $config, $nl, $dump, $buffer;
$content = '';
$complete = Fieldlist($db, $table).' ';
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
$table_ready = 0;
$query = 'SELECT * FROM `'.$table.'` LIMIT '.$dump['zeilen_offset'].','.($dump['restzeilen'] + 1);
mysqli_select_db($config['dbconnection'], $db);
$result = mysqli_query($config['dbconnection'], $query);
$ergebnisse = mysqli_num_rows($result);
if (false !== $ergebnisse) {
// $num_felder=mysqli_field_count($result);
$num_felder = mysqli_field_count($config['dbconnection']);
$first = 1;
if ($ergebnisse > $dump['restzeilen']) {
$dump['zeilen_offset'] += $dump['restzeilen'];
--$ergebnisse;
$dump['restzeilen'] = 0;
} else {
++$dump['table_offset'];
$dump['zeilen_offset'] = 0;
$dump['restzeilen'] = $dump['restzeilen'] - $ergebnisse;
$table_ready = 1;
}
$ax = 0;
for ($x = 0; $x < $ergebnisse; ++$x) {
$row = mysqli_fetch_row($result);
++$ax;
$insert = 'INSERT INTO `'.$table.'` '.$complete.'VALUES (';
for ($j = 0; $j < $num_felder; ++$j) {
if (!isset($row[$j])) {
$insert .= 'NULL,';
} else {
$fieldinfo = mysqli_fetch_field_direct($result, $j);
if (($fieldinfo->flags & 128) == true && isset($config['use_binary_container']) && 1 == $config['use_binary_container']) {
if ('' != $row[$j]) {
$insert .= '_binary 0x'.bin2hex($row[$j]).',';
} else {
$insert .= '_binary \'\',';
}
} elseif ('' != $row[$j]) {
$insert .= '\''.mysqli_real_escape_string($config['dbconnection'], $row[$j]).'\',';
} else {
$insert .= '\'\',';
}
}
}
$insert = substr($insert, 0, -1).');'.$nl;
$dump['data'] .= $insert;
++$dump['countdata'];
$config['memory_limit'] = isset($config['memory_limit']) ? $config['memory_limit'] : 0;
if (strlen($dump['data']) > $config['memory_limit'] || (1 == $config['multi_part'] && strlen($dump['data']) + $buffer > $config['multipart_groesse'])) {
WriteToDumpFile();
}
}
if (1 == $table_ready && 'VIEW' != $dump['table_types'][getDBIndex($db, $table)]) {
$dump['data'] .= "/*!40000 ALTER TABLE `$table` ENABLE KEYS */;\n";
}
} else {
// table corrupt -> skip it
++$dump['table_offset'];
$dump['zeilen_offset'] = 0;
$dump['restzeilen'] = $dump['restzeilen'] - $ergebnisse;
$dump['data'] .= "/*!40000 ALTER TABLE `$table` ENABLE KEYS */;\n";
if (strlen($dump['data']) > $config['memory_limit'] || (1 == $config['multi_part'] && strlen($dump['data']) + $buffer > $config['multipart_groesse'])) {
WriteToDumpFile();
}
}
@mysqli_free_result($result);
}
function WriteToDumpFile()
{
global $config, $dump, $buffer;
$dump['filesize'] = 0;
$df = $config['paths']['backup'].$dump['backupdatei'];
if (isset($config['compression']) && (1 == $config['compression'])) {
if ('' != $dump['data']) {
$fp = gzopen($df, 'ab');
gzwrite($fp, $dump['data']);
gzclose($fp);
}
} else {
if ('' != $dump['data']) {
$fp = fopen($df, 'ab');
fwrite($fp, $dump['data']);
fclose($fp);
}
}
$dump['data'] = '';
if (!isset($dump['fileoperations'])) {
$dump['fileoperations'] = 0;
}
++$dump['fileoperations'];
if (isset($config['multi_part']) && (1 == $config['multi_part'])) {
clearstatcache();
}
$dump['filesize'] = filesize($df);
if ((isset($config['multi_part']) && 1 == $config['multi_part']) && ($dump['filesize'] + $buffer > $config['multipart_groesse'])) {
@chmod($df, 0777);
new_file($dump['filesize']); // Wenn maximale Dateigroesse erreicht -> neues File starten
}
}
function ExecuteCommand($when)
{
global $config, $databases, $dump, $out, $lang;
$lf = '<br>';
if (!isset($dump['dbindex'])) {
return;
}
if ('b' == $when) { // before dump
$cd = $databases['command_before_dump'][$dump['dbindex']];
//WriteLog('DbIndex: '.$dump['dbindex'].' Before: '.$databases['command_before_dump'][$dump['dbindex']]);
} else {
$cd = $databases['command_after_dump'][$dump['dbindex']];
//WriteLog('DbIndex: '.$dump['dbindex'].' After: '.$databases['command_after_dump'][$dump['dbindex']]);
}
if ('' != $cd) {
//jetzt ausführen
if ('system:' != substr(strtolower($cd), 0, 7)) {
$cad = [];
@mysqli_select_db($config['dbconnection'], $databases['Name'][$dump['dbindex']]);
if (strpos($cd, ';')) {
$cad = explode(';', $cd);
} else {
$cad[0] = $cd;
}
for ($i = 0; $i < sizeof($cad); ++$i) {
if (trim($cad[$i]) > '') {
$result = mysqli_query($config['dbconnection'], $cad[$i]);
if (false === $result) {
WriteLog("Error executing Query '$cad[$i]'! MySQL returns: ".trim(mysqli_error($config['dbconnection'])));
ErrorLog("Error executing Query '$cad[$i]'!", $databases['Name'][$dump['dbindex']], $cad[$i], mysqli_error($config['dbconnection']), 0);
++$dump['errors'];
$out .= '<span class="error">Error executing Query '.$cad[$i].'</span>'.$lf;
} else {
WriteLog("Successfully executed Query: '$cad[$i]'");
$out .= '<span class="success">Successfully executed Query: \''.$cad[$i].'\'</span>'.$lf;
}
}
}
} elseif ('system:' == substr(strtolower($cd), 0, 7)) {
$command = substr($cd, 7);
$result = @system($command, $returnval);
if (!$result) {
WriteLog("Error while executing System Command '$command'");
++$dump['errors'];
$out .= $lf.'<span class="error">ERROR executing System Command \''.$command.'\'</span><br>';
} else {
WriteLog("Successfully executed System Command '$command'. [$returnval]");
$out .= $lf.'<span class="success">Successfully executed System Command \''.$command.'.</span><br>';
}
}
}
}
function DoEmail()
{
global $config, $dump, $databases, $email, $lang, $out, $REMOTE_ADDR;
$header = '';
if (1 == $config['cron_use_sendmail']) {
//sendmail
if (ini_get('sendmail_path') != $config['cron_sendmail']) {
@ini_set('SMTP', $config['cron_sendmail']);
}
if (ini_get('sendmail_from') != $config['email_sender']) {
@ini_set('SMTP', $config['email_sender']);
}
} else {
//SMTP
}
if (ini_get('SMTP') != $config['cron_smtp']) {
@ini_set('SMTP', $config['cron_smtp']);
}
if (25 != ini_get('smtp_port')) {
@ini_set('smtp_port', 25);
}
if (0 == $config['multi_part']) {
$file = $dump['backupdatei'];
$file_name = (strpos('/', $file)) ? substr($file, strrpos('/', $file)) : $file;
$file_type = filetype($config['paths']['backup'].$file);
$file_size = filesize($config['paths']['backup'].$file);
if (($config['email_maxsize'] > 0 && $file_size > $config['email_maxsize']) || 0 == $config['send_mail_dump']) {
//anhang zu gross
$subject = "Backup '".$databases['Name'][$dump['dbindex']]."' - ".date("d\.m\.Y H:i", time());
$header .= 'FROM:'.$config['email_sender']."\n";
if (isset($config['email_recipient_cc']) && trim($config['email_recipient_cc']) > '') {
$header .= 'Cc: '.$config['email_recipient_cc']."\r\n";
}
$header .= "MIME-version: 1.0\n";
$header .= 'X-Mailer: PHP/'.phpversion()."\n";
$header .= "X-Sender-IP: $REMOTE_ADDR\n";
$header .= "Content-Type: text/html; charset=utf-8\n";
if (0 != $config['send_mail_dump']) {
$msg_body = sprintf(addslashes($lang['L_EMAILBODY_TOOBIG']), byte_output($config['email_maxsize']), $databases['Name'][$dump['dbindex']], "$file (".byte_output(filesize($config['paths']['backup'].$file)).')<br>');
} else {
$msg_body = sprintf(addslashes($lang['L_EMAILBODY_NOATTACH']), $databases['Name'][$dump['dbindex']], "$file (".byte_output(filesize($config['paths']['backup'].$file)).')');
}
include_once './inc/functions.php';
$msg_body .= '<a href="'.getServerProtocol().$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')).'/'.$config['paths']['backup'].$file.'">'.$file.'</a>';
$email_log = "Email sent to '".$config['email_recipient']."'";
$email_out = $lang['L_EMAIL_WAS_SEND'].'`'.$config['email_recipient'].'`<br>';
} else {
//alles ok, anhang generieren
$msg_body = sprintf(addslashes($lang['L_EMAILBODY_ATTACH']), $databases['Name'][$dump['dbindex']], "$file (".byte_output(filesize($config['paths']['backup'].$file)).')');
$subject = "Backup '".$databases['Name'][$dump['dbindex']]."' - ".date("d\.m\.Y", time());
$fp = fopen($config['paths']['backup'].$file, 'r');
$contents = fread($fp, $file_size);
$encoded_file = chunk_split(base64_encode($contents));
fclose($fp);
$header .= 'FROM:'.$config['email_sender']."\n";
if (isset($config['email_recipient_cc']) && trim($config['email_recipient_cc']) > '') {
$header .= 'Cc: '.$config['email_recipient_cc']."\r\n";
}
$header .= "MIME-version: 1.0\n";
$header .= 'Content-type: multipart/mixed; ';
$header .= "boundary=\"Message-Boundary\"\n";
$header .= "Content-transfer-encoding: 7BIT\n";
$header .= "X-attachments: $file_name";
$body_top = "--Message-Boundary\n";
$body_top .= "Content-type: text/html; charset=utf-8\n";
$body_top .= "Content-transfer-encoding: 7BIT\n";
$body_top .= "Content-description: Mail message body\n\n";
$msg_body = $body_top.$msg_body;
$msg_body .= "\n\n--Message-Boundary\n";
$msg_body .= "Content-type: $file_type; name=\"$file\"\n";
$msg_body .= "Content-Transfer-Encoding: BASE64\n";
$msg_body .= "Content-disposition: attachment; filename=\"$file\"\n\n";
$msg_body .= "$encoded_file\n";
$msg_body .= "--Message-Boundary--\n";
$email_log = "Email was sent to '".$config['email_recipient']."' with '".$dump['backupdatei']."'.";
$email_out = $lang['L_EMAIL_WAS_SEND'].'`'.$config['email_recipient'].'`'.$lang['L_WITH'].'`'.$dump['backupdatei'].'`.<br>';
}
} else {
//Multipart
$mp_sub = "Backup '".$databases['Name'][$dump['dbindex']]."' - ".date("d\.m\.Y", time());
$subject = $mp_sub;
$header .= 'FROM:'.$config['email_sender']."\n";
if (isset($config['email_recipient_cc']) && trim($config['email_recipient_cc']) > '') {
$header .= 'Cc: '.$config['email_recipient_cc']."\r\n";
}
$header .= "MIME-version: 1.0\n";
$header .= 'X-Mailer: PHP/'.phpversion()."\n";
$header .= "X-Sender-IP: $REMOTE_ADDR\n";
$header .= 'Content-Type: text/html; charset=utf-8';
$dateistamm = substr($dump['backupdatei'], 0, strrpos($dump['backupdatei'], 'part_')).'part_';
$dateiendung = (1 == $config['compression']) ? '.sql.gz' : '.sql';
$mpdatei = [];
$mpfiles = '';
for ($i = 1; $i < ($dump['part'] - $dump['part_offset']); ++$i) {
$mpdatei[$i - 1] = $dateistamm.$i.$dateiendung;
$sz = byte_output(@filesize($config['paths']['backup'].$mpdatei[$i - 1]));
$mpfiles .= $mpdatei[$i - 1].' ('.$sz.')<br>';
}
$msg_body = (1 == $config['send_mail_dump']) ? sprintf(addslashes($lang['L_EMAILBODY_MP_ATTACH']), $databases['Name'][$dump['dbindex']], $mpfiles) : sprintf(addslashes($lang['L_EMAILBODY_MP_NOATTACH']), $databases['Name'][$dump['dbindex']], $mpfiles);
$email_log = "Email was sent to '".$config['email_recipient']."'";
$email_out = $lang['L_EMAIL_WAS_SEND'].'`'.$config['email_recipient'].'`<br>';
}
if (@mail($config['email_recipient'], stripslashes($subject), $msg_body, $header)) {
$out .= '<span class="success">'.$email_out.'</span>';
WriteLog("$email_log");
} else {
$out .= '<span class="error">'.$lang['L_MAILERROR'].'</span><br>';
WriteLog("Email to '".$config['email_recipient']."' failed !");
ErrorLog('Email ', $databases['Name'][$dump['dbindex']], 'Subject: '.stripslashes($subject), $lang['L_MAILERROR']);
++$dump['errors'];
}
if (isset($mpdatei) && 1 == $config['send_mail_dump']) { // && ($config['email_maxsize'] ==0 || ($config['email_maxsize']>0 && $config['multipartgroesse2']<= $config['email_maxsize']))) {
for ($i = 0; $i < count($mpdatei); ++$i) {
$file_name = $mpdatei[$i];
$file_type = filetype($config['paths']['backup'].$mpdatei[$i]);
$file_size = filesize($config['paths']['backup'].$mpdatei[$i]);
$fp = fopen($config['paths']['backup'].$mpdatei[$i], 'r');
$contents = fread($fp, $file_size);
$encoded_file = chunk_split(base64_encode($contents));
fclose($fp);
$subject = $mp_sub.' [Part '.($i + 1).' / '.count($mpdatei).']';
$header = 'FROM:'.$config['email_sender']."\n";
if (isset($config['email_recipient_cc']) && trim($config['email_recipient_cc']) > '') {
$header .= 'Cc: '.$config['email_recipient_cc']."\r\n";
}
$header .= "MIME-version: 1.0\n";
$header .= 'Content-type: multipart/mixed; ';
$header .= "boundary=\"Message-Boundary\"\n";
$header .= "Content-transfer-encoding: 7BIT\n";
$header .= "X-attachments: $file_name";
$body_top = "--Message-Boundary\n";
$body_top .= "Content-type: text/html; charset=utf-8\n";
$body_top .= "Content-transfer-encoding: 7BIT\n";
$body_top .= "Content-description: Mail message body\n\n";
$msg_body = $body_top.addslashes($lang['L_EMAIL_ONLY_ATTACHMENT'].$lang['L_EMAILBODY_FOOTER']);
$msg_body .= "\n\n--Message-Boundary\n";
$msg_body .= "Content-type: $file_type; name=\"".$mpdatei[$i]."\"\n";
$msg_body .= "Content-Transfer-Encoding: BASE64\n";
$msg_body .= 'Content-disposition: attachment; filename="'.$mpdatei[$i]."\"\n\n";
$msg_body .= "$encoded_file\n";
$msg_body .= "--Message-Boundary--\n";
$email_log = "Email with $mpdatei[$i] was sent to '".$config['email_recipient']."'";
$email_out = $lang['L_EMAIL_WAS_SEND'].'`'.$config['email_recipient'].'`'.$lang['L_WITH'].'`'.$mpdatei[$i].'`.<br>';
if (@mail($config['email_recipient'], stripslashes($subject), $msg_body, $header)) {
$out .= '<span class="success">'.$email_out.'</span>';
WriteLog("$email_log");
} else {
$out .= '<span class="error">'.$lang['L_MAILERROR'].'</span><br>';
WriteLog("Email to '".$config['email_recipient']."' failed !");
ErrorLog('Email ', $databases['Name'][$dump['dbindex']], 'Subject: '.stripslashes($subject), $lang['L_MAILERROR']);
++$dump['errors'];
}
}
}
}
function DoFTP($i)
{
global $config, $dump, $out;
if (0 == $config['multi_part']) {
SendViaFTP($i, $dump['backupdatei'], 1);
} else {
$dateistamm = substr($dump['backupdatei'], 0, strrpos($dump['backupdatei'], 'part_')).'part_';
$dateiendung = (1 == $config['compression']) ? '.sql.gz' : '.sql';
for ($a = 1; $a < ($dump['part'] - $dump['part_offset']); ++$a) {
$mpdatei = $dateistamm.$a.$dateiendung;
SendViaFTP($i, $mpdatei, $a);
}
}
}
function SendViaFTP($i, $source_file, $conn_msg = 1)
{
global $config, $out, $lang;
flush();
if (1 == $conn_msg) {
$out .= '<span class="success">'.$lang['L_FILESENDFTP'].'('.$config['ftp_server'][$i].' - '.$config['ftp_user'][$i].')</span><br>';
}
// Herstellen der Basis-Verbindung
if (0 == $config['ftp_useSSL'][$i]) {
$conn_id = @ftp_connect($config['ftp_server'][$i], $config['ftp_port'][$i], $config['ftp_timeout'][$i]);
} else {
$conn_id = @ftp_ssl_connect($config['ftp_server'][$i], $config['ftp_port'][$i], $config['ftp_timeout'][$i]);
}
// Einloggen mit Benutzername und Kennwort
$login_result = @ftp_login($conn_id, $config['ftp_user'][$i], $config['ftp_pass'][$i]);
if (1 == $config['ftp_mode'][$i]) {
ftp_pasv($conn_id, true);
}
// Verbindung überprüfen
if ((!$conn_id) || (!$login_result)) {
$out .= '<span class="error">'.$lang['L_FTPCONNERROR'].$config['ftp_server'][$i].$lang['L_FTPCONNERROR1'].$config['ftp_user'][$i].$lang['L_FTPCONNERROR2'].'</span><br>';
} else {
if (1 == $conn_msg) {
$out .= '<span class="success">'.$lang['L_FTPCONNECTED1'].$config['ftp_server'][$i].$lang['L_FTPCONNERROR1'].$config['ftp_user'][$i].'</span><br>';
}
}
// Upload der Datei
$dest = $config['ftp_dir'][$i].$source_file;
$source = $config['paths']['backup'].$source_file;
$upload = @ftp_put($conn_id, $dest, $source, FTP_BINARY);
// Upload-Status überprüfen
if (!$upload) {
$out .= '<span class="error">'.$lang['L_FTPCONNERROR3']."<br>($source -> $dest)</span><br>";
} else {
$out .= '<span class="success">'.$lang['L_FILE'].' <a href="'.$config['paths']['backup'].$source_file.'" class="smallblack">'.$source_file.'</a>'.$lang['L_FTPCONNECTED2'].$config['ftp_server'][$i].$lang['L_FTPCONNECTED3'].'</span><br>';
WriteLog("'$source_file' sent via FTP.");
}
// Schließen des FTP-Streams
@ftp_quit($conn_id);
}
function DoSFTP($i)
{
global $config, $dump, $out;
if (0 == $config['multi_part']) {
SendViaSFTP($i, $dump['backupdatei'], 1);
} else {
$dateistamm = substr($dump['backupdatei'], 0, strrpos($dump['backupdatei'], 'part_')).'part_';
$dateiendung = (1 == $config['compression']) ? '.sql.gz' : '.sql';
for ($a = 1; $a < ($dump['part'] - $dump['part_offset']); ++$a) {
$mpdatei = $dateistamm.$a.$dateiendung;
SendViaSFTP($i, $mpdatei, $a);
}
}
}

486
msd/inc/functions_files.php Normal file
View File

@ -0,0 +1,486 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
function FilelisteCombo($fpath, $selected)
{
$r = '<select name="selectfile">';
$r .= '<option value="" '.(('' == $selected) ? 'SELECTED' : '').'></option>';
$dh = opendir($fpath);
while (false !== ($filename = readdir($dh))) {
if ('.' != $filename && '..' != $filename && !is_dir($fpath.$filename)) {
$r .= '<option value="'.$filename.'" ';
if ($filename == $selected) {
$r .= ' selected';
}
$r .= '>'.$filename.'</option>'."\n";
}
}
$r .= '</select>';
return $r;
}
function sortierdatum($datum)
{
$p = explode(' ', $datum);
$uhrzeit = $p[1];
$p2 = explode('.', $p[0]);
$day = $p2[0];
$month = $p2[1];
$year = $p2[2];
return $year.'.'.$month.'.'.$day.' '.$uhrzeit;
}
function FileList($multi = 0)
{
global $config, $fpath, $lang, $databases, $href, $dbactiv, $action, $expand;
$files = [];
//Backup-Dateien
$Theader = $lang['L_FM_FILES1'].' '.$lang['L_OF'].' "'.$dbactiv.'"';
$akind = 1;
$Sum_Files = 0;
$dh = opendir($fpath);
$fl = '';
$i = 0;
while (false !== ($filename = readdir($dh))) {
if ('.' != $filename && '..' != $filename && !is_dir($fpath.$filename)) {
$files[$i]['name'] = $filename;
++$Sum_Files;
++$i;
}
}
$fl .= '<div>'.$lang['L_FM_CHOOSE_FILE'].' ';
$fl .= '<span id="gd">&nbsp;</span><br><br>';
$fl .= '<table class="bdr">';
$fl .= '<tr><td colspan="8" align="left"><strong>'.$Theader.'</strong></td><td colspan="3" align="right"></td></tr>';
//Tableheader
$fl .= '<tr class="thead"><th colspan="3">'.$lang['L_DB'].'</th>
<th>gz</th>
<th>Script</th>
<th colspan="2">'.$lang['L_COMMENT'].'</th>
<th>'.$lang['L_FM_FILEDATE'].'</th>
<th>Multipart</th>
<th>'.$lang['L_FM_TABLES'].' / '.$lang['L_FM_RECORDS'].'</th>
<th>'.$lang['L_FM_FILESIZE'].'</th>
<th>'.$lang['L_ENCODING'].'</th></tr>';
$checkindex = $arrayindex = $gesamt = 0;
$db_summary_anzahl = [];
if (count($files) > 0) {
for ($i = 0; $i < sizeof($files); ++$i) {
// Dateigr&ouml;&szlig;e
$size = filesize($fpath.$files[$i]['name']);
$file_datum = date("d\.m\.Y H:i", filemtime($fpath.$files[$i]['name']));
//statuszeile auslesen
$sline = '';
if ('.gz' == substr($files[$i]['name'], -3)) {
if ($config['zlib']) {
$fp = gzopen($fpath.$files[$i]['name'], 'r');
$sline = gzgets($fp, 40960);
gzclose($fp);
}
} else {
$fp = fopen($fpath.$files[$i]['name'], 'r');
$sline = fgets($fp, 5000);
fclose($fp);
}
$statusline = ReadStatusline($sline);
$but = ExtractBUT($files[$i]['name']);
if ('' == $but) {
$but = $file_datum;
}
$dbn = $statusline['dbname'];
if ('unknown' == $dbn) {
$dbn = '~unknown';
} // needed for sorting - place unknown files at the end
//jetzt alle in ein Array packen
if ('MP_0' == $statusline['part'] || '' == $statusline['part']) {
$db_backups[$arrayindex]['name'] = $files[$i]['name'];
$db_backups[$arrayindex]['db'] = $dbn;
$db_backups[$arrayindex]['size'] = $size;
$db_backups[$arrayindex]['date'] = $but;
$db_backups[$arrayindex]['sort'] = sortierdatum($but);
$db_backups[$arrayindex]['tabellen'] = $statusline['tables'];
$db_backups[$arrayindex]['eintraege'] = $statusline['records'];
$db_backups[$arrayindex]['multipart'] = 0;
$db_backups[$arrayindex]['kommentar'] = $statusline['comment'];
$db_backups[$arrayindex]['script'] = ('' != $statusline['script']) ? $statusline['script'].'('.$statusline['scriptversion'].')' : '';
$db_backups[$arrayindex]['charset'] = $statusline['charset'];
if (!isset($db_summary_last[$dbn])) {
$db_summary_last[$dbn] = $but;
}
$db_summary_anzahl[$dbn] = (isset($db_summary_anzahl[$dbn])) ? $db_summary_anzahl[$dbn] + 1 : 1;
$db_summary_size[$dbn] = (isset($db_summary_size[$dbn])) ? $db_summary_size[$dbn] + $size : $size;
if (sortierdatum($but) > sortierdatum($db_summary_last[$dbn])) {
$db_summary_last[$dbn] = $but;
}
} else {
//multipart nur einmal
$done = 0;
if (!isset($db_summary_size[$dbn])) {
$db_summary_size[$dbn] = 0;
}
for ($j = 0; $j < $arrayindex; ++$j) {
if (isset($db_backups[$j])) {
if (($db_backups[$j]['date'] == $but) && ($db_backups[$j]['db'] == $dbn)) {
++$db_backups[$j]['multipart'];
$db_backups[$j]['size'] += $size;
$db_summary_size[$dbn] += $size;
$done = 1;
break;
}
}
}
if (1 == $done) {
--$arrayindex;
}
if (0 == $done) {
//Eintrag war noch nicht vorhanden
$db_backups[$arrayindex]['name'] = $files[$i]['name'];
$db_backups[$arrayindex]['db'] = $dbn;
$db_backups[$arrayindex]['size'] = $size;
$db_backups[$arrayindex]['date'] = $but;
$db_backups[$arrayindex]['sort'] = sortierdatum($but);
$db_backups[$arrayindex]['tabellen'] = $statusline['tables'];
$db_backups[$arrayindex]['eintraege'] = $statusline['records'];
$db_backups[$arrayindex]['multipart'] = 1;
$db_backups[$arrayindex]['kommentar'] = $statusline['comment'];
$db_backups[$arrayindex]['script'] = ('' != $statusline['script']) ? $statusline['script'].'('.$statusline['scriptversion'].')' : '';
$db_backups[$arrayindex]['charset'] = $statusline['charset'];
if (!isset($db_summary_last[$dbn])) {
$db_summary_last[$dbn] = $but;
}
$db_summary_anzahl[$dbn] = (isset($db_summary_anzahl[$dbn])) ? $db_summary_anzahl[$dbn] + 1 : 1;
$db_summary_size[$dbn] = (isset($db_summary_size[$dbn])) ? $db_summary_size[$dbn] + $size : $size;
if (sortierdatum($but) > sortierdatum($db_summary_last[$dbn])) {
$db_summary_last[$dbn] = $but;
}
}
}
// Gesamtgroesse aller Backupfiles
++$arrayindex;
$gesamt = $gesamt + $size;
}
}
//Schleife fertig - jetzt Ausgabe
if ((isset($db_backups)) && (is_array($db_backups))) {
$db_backups = mu_sort($db_backups, 'sort,name');
}
// Hier werden die Dateinamen ausgegeben
$rowclass = 0;
if ($arrayindex > 0) {
for ($i = $arrayindex; $i >= 0; --$i) {
if (isset($db_backups[$i]['db']) && $db_backups[$i]['db'] == $dbactiv) {
$cl = ($rowclass % 2) ? 'dbrow' : 'dbrow1';
$multi = ($db_summary_anzahl[$dbactiv] > 1 && 'files' == $action) ? 1 : 0;
if ($db_backups[$i]['multipart'] > 0) {
$dbn = NextPart($db_backups[$i]['name'], 1);
} else {
$dbn = $db_backups[$i]['name'];
}
$fl .= '<tr ';
$fl .= 'class="'.(($rowclass % 2) ? 'dbrow"' : 'dbrow1"');
$fl .= '>';
$fl .= '<td align="left" colspan="2" nowrap="nowrap">';
$fl .= '<input type="hidden" name="multi" value="'.$multi.'">';
if (0 == $multi) {
$fl .= '<input type="hidden" name="multipart[]" value="'.$db_backups[$i]['multipart'].'"><input name="file[]" type="radio" class="radio" value="'.$dbn.'" onClick="Check('.$checkindex++.',0);">';
} else {
$fl .= '<input type="hidden" name="multipart[]" value="'.$db_backups[$i]['multipart'].'"><input name="file[]" type="checkbox" class="checkbox" value="'.$dbn.'" onClick="Check('.$checkindex++.',1);">';
}
if (0 == $db_backups[$i]['multipart']) {
$fl .= '&nbsp;<a href="'.$fpath.urlencode($dbn).'" title="Backupfile: '.$dbn.'" style="font-size:8pt;" target="_blank">';
$fl .= (('~unknown' == $db_backups[$i]['db']) ? $dbn : $db_backups[$i]['db']).'</a></td>';
$fl .= '<td><a href="filemanagement.php?action=dl&amp;f='.urlencode($dbn).'" title="'.$lang['L_DOWNLOAD_FILE'].'" alt="'.$lang['L_DOWNLOAD_FILE'].'"><img src="'.$config['files']['iconpath'].'/openfile.gif"></a></td>';
} else {
$fl .= '&nbsp;<span style="font-size:8pt;">'.$db_backups[$i]['db'].'</span><td>&nbsp;</td></td>';
}
$fl .= '<td class="sm" nowrap="nowrap" align="center">'.(('.gz' == substr($dbn, -3)) ? '<img src="'.$config['files']['iconpath'].'gz.gif" alt="'.$lang['L_COMPRESSED'].'" width="16" height="16" border="0">' : '&nbsp;').'</td>';
$fl .= '<td class="sm" nowrap="nowrap" align="center">'.$db_backups[$i]['script'].'</td>';
$fl .= '<td class="sm" nowrap="nowrap" align="right">'.(('' != $db_backups[$i]['kommentar']) ? '<img src="'.$config['files']['iconpath'].'rename.gif" alt="'.$db_backups[$i]['kommentar'].'" title="'.$db_backups[$i]['kommentar'].'" width="16" height="16" border="0">' : '&nbsp;').'</td>';
$fl .= '<td class="sm" nowrap="nowrap" align="left">'.(('' != $db_backups[$i]['kommentar']) ? nl2br(wordwrap($db_backups[$i]['kommentar'], 50)) : '&nbsp;').'</td>';
$fl .= '<td class="sm" nowrap="nowrap">'.$db_backups[$i]['date'].'</td>';
$fl .= '<td style="text-align:center">';
$fl .= (0 == $db_backups[$i]['multipart']) ? $lang['L_NO'] : '<a style="font-size:11px;" href="filemanagement.php?action=files&amp;kind=0&amp;dbactiv='.$dbactiv.'&amp;expand='.$i.'">'.$db_backups[$i]['multipart'].' Files</a>';
$fl .= '</td><td style="text-align:right;padding-right:12px;" nowrap="nowrap">';
$fl .= (-1 != $db_backups[$i]['eintraege']) ? $db_backups[$i]['tabellen'].' / '.number_format($db_backups[$i]['eintraege'], 0, ',', '.') : $lang['L_FM_OLDBACKUP'];
$fl .= '</td>';
$fl .= '<td style="font-size:8pt;text-align:right">'.byte_output($db_backups[$i]['size']).'</td>';
$fl .= '<td style="font-size:8pt;text-align:right">'.$db_backups[$i]['charset'].'</td>';
$fl .= '</tr>';
if ($expand == $i) {
$fl .= '<tr '.(($dbactiv == $databases['db_actual']) ? 'class="dbrowsel"' : 'class="'.$cl.'"').'>';
$fl .= '<td class="sm" valign="top">All Parts:</td><td class="sm" colspan="11" align="left">'.PartListe($db_backups[$i]['name'], $db_backups[$i]['multipart']).'</td>';
}
++$rowclass;
}
}
}
//v($db_backups);
$fl .= '<tr><td colspan="11" align="left"><br><strong>'.$lang['L_FM_ALL_BU'].'</strong></td></tr>';
//Tableheader
$fl .= '<tr class="thead"><th colspan="5" align="left">'.$lang['L_FM_DBNAME'].'</th>
<th align="left">'.$lang['L_FM_ANZ_BU'].'</th><th>'.$lang['L_FM_LAST_BU'].'</th>
<th colspan="5" style="text-align:right;">'.$lang['L_FM_TOTALSIZE'].'</th></tr>';
//die anderen Backups
if (count($db_summary_anzahl) > 0) {
//lets sort the list
ksort($db_summary_last);
ksort($db_summary_anzahl);
ksort($db_summary_size);
$i = 0;
foreach ($db_summary_anzahl as $key => $val) {
$cl = ($i++ % 2) ? 'dbrow' : 'dbrow1';
$keyaus = ('~unknown' == $key) ? '<em>'.$lang['L_NO_MOD_BACKUPFILE'].'</em>' : $key;
$fl .= '<tr class="'.$cl.'"><td colspan="5" align="left"><a href="'.$href.'&amp;dbactiv='.$key.'">'.$keyaus.'</a></td>';
$fl .= '<td style="text-align:right">'.$val.'&nbsp;&nbsp;</td>';
$fl .= '<td class="sm" nowrap="nowrap">'.((isset($db_summary_last[$key])) ? $db_summary_last[$key] : '').'</td>';
$fl .= '<td style="text-align:right;font-size:8pt;" colspan="5">'.byte_output($db_summary_size[$key]).'&nbsp;</td>';
$fl .= '</tr>';
}
}
if (!is_array($files)) {
$fl .= '<tr><td colspan="11">'.$lang['L_FM_NOFILESFOUND'].'</td></tr>';
}
//--------------------------------------------------------
//*** Ausgabe der Gesamtgr&ouml;&szlig;e aller Backupfiles ***
//--------------------------------------------------------
$space = MD_FreeDiskSpace();
$fl .= '<tr>';
$fl .= '<td align="left" colspan="8"><b>'.$lang['L_FM_TOTALSIZE'].' ('.$Sum_Files.' files): </b> </td>';
$fl .= '<td style="text-align:right" colspan="4"><b>'.byte_output($gesamt).'</b></td>';
$fl .= '</tr>';
//--------------------------------------------------------
//*** Ausgabe des freien Speicher auf dem Rechner ***
//--------------------------------------------------------
$fl .= '<tr>';
$fl .= '<td colspan="8" align="left">'.$lang['L_FM_FREESPACE'].': </td>';
$fl .= '<td colspan="4" style="text-align:right"><b>'.$space.'</b></td>';
$fl .= '</tr>';
$fl .= '</table></div>';
return $fl;
}
function read_statusline_from_file($filename)
{
global $config;
if ('gz' == strtolower(substr($filename, -2))) {
$fp = gzopen($config['paths']['backup'].$filename, 'r');
if (false === $fp) {
exit('Can\'t open file '.$filename);
}
$sline = gzgets($fp, 40960);
gzclose($fp);
} else {
$fp = fopen($config['paths']['backup'].$filename, 'r');
if (false === $fp) {
exit('Can\'t open file '.$filename);
}
$sline = fgets($fp, 5000);
fclose($fp);
}
$statusline = ReadStatusline($sline);
return $statusline;
}
function PartListe($f, $nr)
{
global $config, $lang, $fpath;
$dateistamm = substr($f, 0, strrpos($f, 'part_')).'part_';
$dateiendung = ('gz' == substr(strtolower($f), -2)) ? '.sql.gz' : '.sql';
$s = '';
for ($i = 1; $i <= $nr; ++$i) {
if ($i > 1) {
$s .= '<br>';
}
$s .= '<a href="'.$fpath.urlencode($dateistamm.$i.$dateiendung).'">'.$dateistamm.$i.$dateiendung.'</a>&nbsp;&nbsp;&nbsp;'.byte_output(@filesize($config['paths']['backup'].$dateistamm.$i.$dateiendung));
$s .= '&nbsp;<a href="filemanagement.php?action=dl&amp;f='.urlencode($dateistamm.$i.$dateiendung).'" title="'.$lang['L_DOWNLOAD_FILE'].'" alt="'.$lang['L_DOWNLOAD_FILE'].'"><img src="'.$config['files']['iconpath'].'/openfile.gif"></a>';
}
return $s;
}
function Converter($filesource, $filedestination, $cp)
{
global $config, $lang;
$filesize = 0;
$max_filesize = 1024 * 1024 * 10; //10 MB splitsize
$part = 1;
$cps = ('gz' == substr(strtolower($filesource), -2)) ? 1 : 0;
$filedestination .= '_'.date('Y_m_d_H_i', time());
echo '<h5>'.sprintf($lang['L_CONVERT_FILEREAD'], $filesource).'.....</h5><span style="font-size:10px;">';
if (file_exists($config['paths']['backup'].$filedestination)) {
unlink($config['paths']['backup'].$filedestination);
}
$f = (1 == $cps) ? gzopen($config['paths']['backup'].$filesource, 'r') : fopen($config['paths']['backup'].$filesource, 'r');
$z = (1 == $cp) ? gzopen($config['paths']['backup'].$filedestination.'_part_1.sql.gz', 'w') : fopen($config['paths']['backup'].$filedestination.'_part_1.sql', 'w');
$zeile = get_pseudo_statusline($part, $filedestination)."\r\n";
(1 == $cp) ? gzwrite($z, $zeile) : fwrite($z, $zeile);
$zeile = '';
$insert = $mode = '';
$n = 0;
$eof = (1 == $cps) ? gzeof($f) : feof($f);
$splitable = false; // can the file be splitted? Try to avoid splitting before a command is completed
while (!$eof) {
$eof = (1 == $cps) ? gzeof($f) : feof($f);
$zeile = (1 == $cps) ? gzgets($f, 5144000) : fgets($f, 5144000);
$t = strtolower(substr($zeile, 0, 10));
if ($t > '') {
switch ($t) {
case 'insert int':
// eine neue Insert Anweisung beginnt
if (false === strpos($zeile, '(')) {
//Feldnamen stehen in der naechsten Zeile - holen
$zeile .= "\n\r";
$zeile .= (1 == $cps) ? trim(gzgets($f, 8192)) : trim(fgets($f, 8192));
$zeile .= ' ';
}
// get INSERT-Satement
$insert = substr($zeile, 0, strpos($zeile, '('));
if ('VALUES ' != substr(strtoupper($insert), -7)) {
$insert .= ' VALUES ';
}
$mode = 'insert';
$zeile = "\n\r".$zeile;
$splitable = false;
break;
case 'create tab':
$mode = 'create';
while (';' != substr(rtrim($zeile), -1)) {
$zeile .= fgets($f, 8192);
}
$zeile = "\n\r".MySQLi_Ticks($zeile)."\n\r";
$splitable = true;
break;
}
}
if ('insert' == $mode) {
if (');' == substr(rtrim($zeile), strlen($zeile) - 3, 2)) {
$splitable = true;
}
// Komma loeschen
$zeile = str_replace('),(', ");\n\r".$insert.' (', $zeile);
}
if (true == $splitable && $filesize > $max_filesize) { // start new file?
++$part;
if ('insert' == $mode) { // Insert -> first complete Insert-Statement, then begin new file
if (1 == $cp) {
gzwrite($z, $zeile);
gzclose($z);
$z = gzopen($config['paths']['backup'].$filedestination.'_part_'.$part.'.sql.gz', 'w');
$zeile = get_pseudo_statusline($part, $filedestination)."\r\n";
gzwrite($z, $zeile);
$zeile = '';
} else {
fwrite($z, $zeile);
echo '<br>Neue Datei.Zeile: <br>'.htmlspecialchars(substr($zeile, 0, 20)).'..'.htmlspecialchars(substr($zeile, strlen($zeile) - 41, 40)).'<br>';
fclose($z);
$z = fopen($config['paths']['backup'].$filedestination.'_part_'.$part.'.sql', 'w');
$zeile = get_pseudo_statusline($part, $filedestination)."\r\n";
gzwrite($z, $zeile);
$zeile = '';
}
} else { // first close last file, then begin new one and write new beginning command
if (1 == $cp) {
gzclose($z);
$z = gzopen($config['paths']['backup'].$filedestination.'_part_'.$part.'.sql.gz', 'w');
$zeile = get_pseudo_statusline($part, $filedestination)."\r\n".$zeile;
gzwrite($z, $zeile);
} else {
fclose($z);
$z = fopen($config['paths']['backup'].$filedestination.'_part_'.$part.'.sql', 'w');
$zeile = get_pseudo_statusline($part, $filedestination)."\r\n".$zeile;
fwrite($z, $zeile);
}
}
$filesize = 0;
$splitable = false;
} else { // no, append to actual file
$filesize += strlen($zeile);
if ($n > 600) {
$n = 0;
echo '<br>';
}
echo '.';
if (1 == $cps) {
gzwrite($z, $zeile);
} else {
fwrite($z, $zeile);
}
flush();
}
++$n;
//if ($part>4) break;
}
$zeile = "\n-- EOB";
if (1 == $cps) {
gzwrite($z, $zeile);
gzclose($z);
} else {
fwrite($z, $zeile);
fclose($z);
}
if (1 == $cps) {
gzclose($f);
} else {
fclose($f);
}
echo '</span><h5>'.sprintf($lang['L_CONVERT_FINISHED'], $filedestination).'</h5>';
}
function get_pseudo_statusline($part, $filedestination)
{
echo '<br>Continue with part: '.$part.'<br>';
$ret = '-- Status:-1:-1:MP_'.($part).':'.$filedestination.":php:converter2:converted:unknown:1:::latin1:EXTINFO\r\n"."-- TABLE-INFO\r\n"."-- TABLE|unknown|0|0|2009-01-24 20:39:39\r\n"."-- EOF TABLE-INFO\r\n";
return $ret;
}

1507
msd/inc/functions_global.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,418 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
function CheckCSVOptions()
{
global $sql;
if (!isset($sql['export']['trenn'])) {
$sql['export']['trenn'] = ';';
}
if (!isset($sql['export']['enc'])) {
$sql['export']['enc'] = '"';
}
if (!isset($sql['export']['esc'])) {
$sql['export']['esc'] = '\\';
}
if (!isset($sql['export']['ztrenn'])) {
$sql['export']['ztrenn'] = '\\r\\n';
}
if (!isset($sql['export']['null'])) {
$sql['export']['null'] = 'NULL';
}
if (!isset($sql['export']['namefirstline'])) {
$sql['export']['namefirstline'] = 0;
}
if (!isset($sql['export']['format'])) {
$sql['export']['format'] = 0;
}
if (!isset($sql['export']['sendfile'])) {
$sql['export']['sendfile'] = 0;
}
if (!isset($sql['export']['tables'])) {
$sql['export']['tables'] = [];
}
if (!isset($sql['export']['compressed'])) {
$sql['export']['compressed'] = 0;
}
if (!isset($sql['export']['htmlstructure'])) {
$sql['export']['htmlstructure'] = 0;
}
if (!isset($sql['export']['xmlstructure'])) {
$sql['export']['xmlstructure'] = 0;
}
if (!isset($sql['import']['trenn'])) {
$sql['import']['trenn'] = ';';
}
if (!isset($sql['import']['enc'])) {
$sql['import']['enc'] = '"';
}
if (!isset($sql['import']['esc'])) {
$sql['import']['esc'] = '\\';
}
if (!isset($sql['import']['ztrenn'])) {
$sql['import']['ztrenn'] = '\\r\\n';
}
if (!isset($sql['import']['null'])) {
$sql['import']['null'] = 'NULL';
}
if (!isset($sql['import']['namefirstline'])) {
$sql['import']['namefirstline'] = 0;
}
if (!isset($sql['import']['format'])) {
$sql['import']['format'] = 0;
}
}
function ExportCSV()
{
global $sql, $config;
$t = '';
$time_start = time();
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
for ($table = 0; $table < count($sql['export']['tables']); ++$table) {
$sqlt = 'SHOW Fields FROM `'.$sql['export']['db'].'`.`'.$sql['export']['tables'][$table].'`;';
$res = mod_query($sqlt);
if ($res) {
$numfields = mysqli_num_rows($res);
if (1 == $sql['export']['namefirstline']) {
for ($feld = 0; $feld < $numfields; ++$feld) {
$row = mysqli_fetch_row($res);
if ('' != $sql['export']['enc']) {
$t .= $sql['export']['enc'].$row[0].$sql['export']['enc'].(($feld + 1 < $numfields) ? $sql['export']['trenn'] : '');
} else {
$t .= $row[0].(($feld + 1 < $numfields) ? $sql['export']['trenn'] : '');
}
}
$t .= $sql['export']['endline'];
++$sql['export']['lines'];
}
}
$sqlt = 'SELECT * FROM `'.$sql['export']['db'].'`.`'.$sql['export']['tables'][$table].'`;';
$res = mod_query($sqlt);
if ($res) {
$numrows = mysqli_num_rows($res);
for ($data = 0; $data < $numrows; ++$data) {
$row = mysqli_fetch_row($res);
for ($feld = 0; $feld < $numfields; ++$feld) {
if (!isset($row[$feld]) || is_null($row[$feld])) {
$t .= $sql['export']['null'];
} elseif ('0' == $row[$feld] || '' != $row[$feld]) {
if ('' != $sql['export']['enc']) {
$t .= $sql['export']['enc'].str_replace($sql['export']['enc'], $sql['export']['esc'].$sql['export']['enc'], $row[$feld]).$sql['export']['enc'];
} else {
$t .= $row[$feld];
}
} else {
$t .= '';
}
$t .= ($feld + 1 < $numfields) ? $sql['export']['trenn'] : '';
}
$t .= $sql['export']['endline'];
++$sql['export']['lines'];
if ('' == $config['memory_limit']) {
$config['memory_limit'] = 0;
}
if (strlen($t) > $config['memory_limit']) {
CSVOutput($t);
$t = '';
}
$time_now = time();
if ($time_start >= $time_now + 30) {
$time_start = $time_now;
header('X-MODPing: Pong');
}
}
}
}
CSVOutput($t, 1);
}
function CSVOutput($str, $last = 0)
{
global $sql, $config;
if (0 == $sql['export']['sendfile']) {
//Display
echo $str;
} else {
if ('' == $sql['export']['header_sent']) {
if (1 == $sql['export']['compressed'] & !function_exists('gzencode')) {
$sql['export']['compressed'] = 0;
}
if ($sql['export']['format'] < 4) {
$file = $sql['export']['db'].((1 == $sql['export']['compressed']) ? '.csv.gz' : '.csv');
} elseif (4 == $sql['export']['format']) {
$file = $sql['export']['db'].((1 == $sql['export']['compressed']) ? '.xml.gz' : '.xml');
} elseif (5 == $sql['export']['format']) {
$file = $sql['export']['db'].((1 == $sql['export']['compressed']) ? '.html.gz' : '.html');
}
$mime = (0 == $sql['export']['compressed']) ? 'x-type/subtype' : 'application/x-gzip';
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Pragma: no-cache');
header('Content-Type: '.$mime);
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
$sql['export']['header_sent'] = 1;
}
if (1 == $sql['export']['compressed']) {
echo gzencode($str);
} else {
echo $str;
}
}
}
function DoImport()
{
global $sql, $lang;
$r = '<span class="swarnung">';
$zeilen = count($sql['import']['csv']) - $sql['import']['namefirstline'];
$sql['import']['first_zeile'] = explode($sql['import']['trenn'], $sql['import']['csv'][0]);
$importfelder = count($sql['import']['first_zeile']);
if (0 == $sql['import']['tablecreate']) {
$res = mod_query('show fields FROM '.$sql['import']['table']);
$tabellenfelder = mysqli_num_rows($res);
if ($importfelder != $tabellenfelder) {
$r .= '<br>'.sprintf($lang['L_CSV_FIELDCOUNT_NOMATCH'], $tabellenfelder, $importfelder);
} else {
$ok = 1;
}
} else {
$ok = ImportCreateTable();
if (0 == $ok) {
$r .= '<br>'.sprintf($lang['L_CSV_ERRORCREATETABLE'], $sql['import']['table']);
}
}
if (1 == $ok) {
$insert = '';
if (1 == $sql['import']['emptydb'] && 0 == $sql['import']['tablecreate']) {
MOD_DoSQL('TRUNCATE '.$sql['import']['table'].';');
}
$sql['import']['lines_imported'] = 0;
$enc = ('' == $sql['import']['enc']) ? "'" : '';
$zc = '';
for ($i = $sql['import']['namefirstline']; $i < $zeilen + $sql['import']['namefirstline']; ++$i) {
//Importieren
$insert = 'INSERT INTO '.$sql['import']['table'].' VALUES(';
if (1 == $sql['import']['createindex']) {
$insert .= "'', ";
}
$zc .= trim(rtrim($sql['import']['csv'][$i]));
//echo "Zeile $i: $zc<br>";
if ('' != $zc) { // && substr($zc,-1)== $enc) {
$zeile = explode($sql['import']['trenn'], $zc);
for ($j = 0; $j < $importfelder; ++$j) {
$a = ('' == $zeile[$j] && '' == $enc) ? "''" : $zeile[$j];
$insert .= $enc.$a.$enc.(($j == $importfelder - 1) ? ");\n" : ',');
}
MOD_DoSQL($insert);
++$sql['import']['lines_imported'];
$zc = '';
}
}
$r .= sprintf($lang['L_CSV_FIELDSLINES'], $importfelder, $sql['import']['lines_imported']);
}
$r .= '</span>';
return $r;
}
function ImportCreateTable()
{
global $sql, $lang, $db, $config;
$tbl = [];
$sql = "SHOW TABLES FROM $db";
$tabellen = mod_query($sql);
// while ($row = mysqli_fetch_row($num_tables))
while ($row = mysqli_fetch_row($tabellen)) {
$tbl[] = strtolower($row[0]);
}
$i = 0;
$sql['import']['table'] = $sql['import']['table'].$i;
while (in_array($sql['import']['table'], $tbl)) {
$sql['import']['table'] = substr($sql['import']['table'], 0, strlen($sql['import']['table']) - 1).++$i;
}
$create = 'CREATE TABLE `'.$sql['import']['table'].'` ('.((1 == $sql['import']['createindex']) ? '`import_id` int(11) unsigned NOT NULL auto_increment, ' : '');
if ($sql['import']['namefirstline']) {
for ($i = 0; $i < count($sql['import']['first_zeile']); ++$i) {
$create .= '`'.$sql['import']['first_zeile'][$i].'` VARCHAR(250) NOT NULL, ';
}
} else {
for ($i = 0; $i < count($sql['import']['first_zeile']); ++$i) {
$create .= '`FIELD_'.$i.'` VARCHAR(250) NOT NULL, ';
}
}
if (1 == $sql['import']['createindex']) {
$create .= 'PRIMARY KEY (`import_id`) ';
} else {
$create = substr($create, 0, strlen($create) - 2);
}
$create .= ') '.((MOD_NEW_VERSION) ? 'ENGINE' : 'TYPE')."=MyISAM COMMENT='imported at ".date('l dS of F Y H:i:s A')."'";
$res = mysqli_query($config['dbconnection'], $create) || exit(SQLError($create, mysqli_error($config['dbconnection'])));
return 1;
}
function ExportXML()
{
global $sql, $config;
$tab = "\t";
$level = 0;
$t = '<?xml version="1.0" encoding="UTF-8" ?>'."\n".'<database name="'.$sql['export']['db'].'">'."\n";
++$level;
$time_start = time();
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
for ($table = 0; $table < count($sql['export']['tables']); ++$table) {
$t .= str_repeat($tab, $level++).'<table name="'.$sql['export']['tables'][$table].'">'."\n";
$sqlt = 'SHOW Fields FROM `'.$sql['export']['db'].'`.`'.$sql['export']['tables'][$table].'`;';
$res = mod_query($sqlt);
if ($res) {
$numfields = mysqli_num_rows($res);
if (1 == $sql['export']['xmlstructure']) {
$t .= str_repeat($tab, $level++).'<structure>'."\n";
for ($feld = 0; $feld < $numfields; ++$feld) {
$row = mysqli_fetch_array($res);
$t .= str_repeat($tab, $level++).'<field no="'.$feld.'">'."\n";
$t .= str_repeat($tab, $level).'<name>'.$row['Field'].'</name>'."\n";
$t .= str_repeat($tab, $level).'<type>'.$row['Type'].'</type>'."\n";
$t .= str_repeat($tab, $level).'<null>'.$row['Null'].'</null>'."\n";
$t .= str_repeat($tab, $level).'<key>'.$row['Key'].'</key>'."\n";
$t .= str_repeat($tab, $level).'<default>'.$row['Default'].'</default>'."\n";
$t .= str_repeat($tab, $level).'<extra>'.$row['Extra'].'</extra>'."\n";
$t .= str_repeat($tab, --$level).'</field>'."\n";
}
$t .= str_repeat($tab, --$level).'</structure>'."\n";
}
}
$t .= str_repeat($tab, $level++).'<data>'."\n";
$sqlt = 'SELECT * FROM `'.$sql['export']['db'].'`.`'.$sql['export']['tables'][$table].'`;';
$res = mod_query($sqlt);
if ($res) {
$numrows = mysqli_num_rows($res);
for ($data = 0; $data < $numrows; ++$data) {
$t .= str_repeat($tab, $level)."<row>\n";
++$level;
$row = mysqli_fetch_row($res);
for ($feld = 0; $feld < $numfields; ++$feld) {
$t .= str_repeat($tab, $level).'<field no="'.$feld.'">'.$row[$feld].'</field>'."\n";
}
$t .= str_repeat($tab, --$level)."</row>\n";
++$sql['export']['lines'];
if ('' == $config['memory_limit']) {
$config['memory_limit'] = 0;
}
if (strlen($t) > $config['memory_limit']) {
CSVOutput($t);
$t = '';
}
$time_now = time();
if ($time_start >= $time_now + 30) {
$time_start = $time_now;
header('X-MODPing: Pong');
}
}
}
$t .= str_repeat($tab, --$level).'</data>'."\n";
$t .= str_repeat($tab, --$level).'</table>'."\n";
}
$t .= str_repeat($tab, --$level).'</database>'."\n";
CSVOutput($t, 1);
}
function ExportHTML()
{
global $sql, $config, $lang;
$header = '<html><head><title>MOD Export</title></head>';
$footer = "\n\n</body>\n</html>";
$content = '';
$content .= '<h1>'.$lang['L_DB'].' '.$sql['export']['db'].'</h1>';
$time_start = time();
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
for ($table = 0; $table < count($sql['export']['tables']); ++$table) {
$content .= '<h2>Tabelle '.$sql['export']['tables'][$table].'</h2>'."\n";
$fsql = 'show fields from `'.$sql['export']['tables'][$table].'`';
$dsql = 'select * from `'.$sql['export']['tables'][$table].'`';
//Struktur
$res = mod_query($fsql);
if ($res) {
$field = $fieldname = $fieldtyp = [];
$structure = "<table class=\"Table\">\n";
$numfields = mysqli_num_rows($res);
for ($feld = 0; $feld < $numfields; ++$feld) {
$row = mysqli_fetch_row($res);
$field[$feld] = $row[0];
if (0 == $feld) {
$structure .= "<tr class=\"Header\">\n";
for ($i = 0; $i < count($row); ++$i) {
$str = mysqli_fetch_field($res, $i);
$fieldname[$i] = $str->name;
$fieldtyp[$i] = $str->type;
$structure .= '<th>'.$str->name."</th>\n";
}
$structure .= "</tr>\n<tr>\n";
}
for ($i = 0; $i < count($row); ++$i) {
$structure .= '<td class="Object">'.(('' != $row[$i]) ? $row[$i] : '&nbsp;')."</td>\n";
}
$structure .= "</tr>\n";
}
$structure .= "</table>\n";
}
if (1 == $sql['export']['htmlstructure']) {
$content .= "<h3>Struktur</h3>\n".$structure;
}
//Daten
$res = mod_query($dsql);
if ($res) {
$anz = mysqli_num_rows($res);
$content .= "<h3>Daten ($anz Datens&auml;tze)</h3>\n";
$content .= "<table class=\"Table\">\n";
for ($feld = 0; $feld < count($field); ++$feld) {
if (0 == $feld) {
$content .= "<tr class=\"Header\">\n";
for ($i = 0; $i < count($field); ++$i) {
$content .= '<th>'.$field[$i]."</th>\n";
}
$content .= "</tr>\n";
}
}
for ($d = 0; $d < $anz; ++$d) {
$row = mysqli_fetch_row($res);
$content .= "<tr>\n";
for ($i = 0; $i < count($row); ++$i) {
$content .= '<td class="Object">'.(('' != $row[$i]) ? $row[$i] : '&nbsp;')."</td>\n";
}
$content .= "</tr>\n";
}
}
$content .= '</table>';
}
CSVOutput($header.$content.$footer);
}

View File

@ -0,0 +1,420 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
define('DEBUG', 0);
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
function get_sqlbefehl()
{
global $restore, $config, $databases, $lang;
//Init
$restore['fileEOF'] = false;
$restore['EOB'] = false;
$complete_sql = '';
$sqlparser_status = 0;
if (!isset($restore['eintraege_ready'])) {
$restore['eintraege_ready'] = 0;
}
//Parsen
while (100 != $sqlparser_status && !$restore['fileEOF'] && !$restore['EOB']) {
//nächste Zeile lesen
$zeile = ($restore['compressed']) ? gzgets($restore['filehandle']) : fgets($restore['filehandle']);
if (DEBUG) {
echo '<br><br>Zeile: '.htmlspecialchars($zeile);
}
/******************* Setzen des Parserstatus *******************/
// herausfinden um was für einen Befehl es sich handelt
if (0 == $sqlparser_status) {
//Vergleichszeile, um nicht bei jedem Vergleich strtoupper ausführen zu müssen
$zeile2 = strtoupper(trim($zeile));
// pre-built compare strings - so we need the CPU power only once :)
$sub9 = substr($zeile2, 0, 9);
$sub7 = substr($sub9, 0, 7);
$sub6 = substr($sub7, 0, 6);
$sub4 = substr($sub6, 0, 4);
$sub3 = substr($sub4, 0, 3);
$sub2 = substr($sub3, 0, 2);
$sub1 = substr($sub2, 0, 1);
if ('INSERT ' == $sub7) {
$sqlparser_status = 3; //Datensatzaktion
$restore['actual_table'] = get_tablename($zeile);
}
//Einfache Anweisung finden die mit Semikolon beendet werden
elseif ('LOCK TA' == $sub7) {
$sqlparser_status = 4;
} elseif ('COMMIT' == $sub6) {
$sqlparser_status = 7;
} elseif ('BEGIN' == substr($sub6, 0, 5)) {
$sqlparser_status = 7;
} elseif ('UNLOCK TA' == $sub9) {
$sqlparser_status = 4;
} elseif ('SET' == $sub3) {
$sqlparser_status = 4;
} elseif ('START ' == $sub6) {
$sqlparser_status = 4;
} elseif ('/*!' == $sub3) {
$sqlparser_status = 5;
} //MySQL-Condition oder Kommentar
elseif ('ALTER TAB' == $sub9) {
$sqlparser_status = 4;
} // Alter Table
elseif ('CREATE TA' == $sub9) {
$sqlparser_status = 2;
} //Create Table
elseif ('CREATE AL' == $sub9) {
$sqlparser_status = 2;
} //Create View
elseif ('CREATE IN' == $sub9) {
$sqlparser_status = 4;
} //Indexaktion
//Condition?
elseif ((5 != $sqlparser_status) && ('/*' == substr($zeile2, 0, 2))) {
$sqlparser_status = 6;
}
// Delete actions
elseif ('DROP TABL' == $sub9) {
$sqlparser_status = 1;
} elseif ('DROP VIEW' == $sub9) {
$sqlparser_status = 1;
}
// Befehle, die nicht ausgeführt werden sollen
elseif ('CREATE DA' == $sub9) {
$sqlparser_status = 7;
} elseif ('DROP DATA ' == $sub9) {
$sqlparser_status = 7;
} elseif ('USE' == $sub3) {
$sqlparser_status = 7;
}
// Am Ende eines MySQLDumper-Backups angelangt?
elseif ('-- EOB' == $sub6 || '# EO' == $sub4) {
$restore['EOB'] = true;
$restore['fileEOF'] = true;
$zeile = '';
$zeile2 = '';
$sqlparser_status = 100;
}
// Kommentar?
elseif ('--' == $sub2 || '#' == $sub1) {
$zeile = '';
$zeile2 = '';
$sqlparser_status = 0;
}
// Fortsetzung von erweiterten Inserts
if (1 == $restore['flag']) {
$sqlparser_status = 3;
}
if ((0 == $sqlparser_status) && (trim($complete_sql) > '') && (-1 == $restore['flag'])) {
// Unbekannten Befehl entdeckt
v($restore);
echo '<br>Sql: '.htmlspecialchars($complete_sql);
echo '<br>Erweiterte Inserts: '.$restore['erweiterte_inserts'];
exit('<br>'.$lang['L_UNKNOWN_SQLCOMMAND'].': '.$zeile.'<br><br>'.$complete_sql);
}
/******************* Ende von Setzen des Parserstatus *******************/
}
$last_char = substr(rtrim($zeile), -1);
// Zeilenumbrüche erhalten - sonst werden Schlüsselwörter zusammengefügt
// z.B. 'null' und in der nächsten Zeile 'check' wird zu 'nullcheck'
$complete_sql .= $zeile."\n";
if (3 == $sqlparser_status) {
//INSERT
if (SQL_Is_Complete($complete_sql)) {
$sqlparser_status = 100;
$complete_sql = trim($complete_sql);
if ('*/' == substr($complete_sql, -2)) {
$complete_sql = remove_comment_at_eol($complete_sql);
}
// letzter Ausdruck des erweiterten Inserts erreicht?
if (');' == substr($complete_sql, -2)) {
$restore['flag'] = -1;
}
// Wenn am Ende der Zeile ein Klammer Komma -> erweiterter Insert-Modus -> Steuerflag setzen
elseif ('),' == substr($complete_sql, -2)) {
// letztes Komme gegen Semikolon tauschen
$complete_sql = substr($complete_sql, 0, -1).';';
$restore['erweiterte_inserts'] = 1;
$restore['flag'] = 1;
}
if ('INSERT ' != substr(strtoupper($complete_sql), 0, 7)) {
// wenn der Syntax aufgrund eines Reloads verloren ging - neu ermitteln
if (!isset($restore['insert_syntax'])) {
$restore['insert_syntax'] = get_insert_syntax($restore['actual_table']);
}
$complete_sql = $restore['insert_syntax'].' VALUES '.$complete_sql.';';
} else {
// INSERT Syntax ermitteln und merken
$ipos = strpos(strtoupper($complete_sql), ' VALUES');
if (false === !$ipos) {
$restore['insert_syntax'] = substr($complete_sql, 0, $ipos);
} else {
$restore['insert_syntax'] = 'INSERT INTO `'.$restore['actual_table'].'`';
}
}
}
} elseif (1 == $sqlparser_status) {
//Löschaktion
if (';' == $last_char) {
$sqlparser_status = 100;
} //Befehl komplett
$restore['actual_table'] = get_tablename($complete_sql);
} elseif (2 == $sqlparser_status) {
// Createanweisung ist beim Finden eines ; beendet
if (';' == $last_char) {
if ($config['minspeed'] > 0) {
$restore['anzahl_zeilen'] = $config['minspeed'];
}
// Soll die Tabelle hergestellt werden?
$do_it = true;
if (is_array($restore['tables_to_restore'])) {
$do_it = false;
if (in_array($restore['actual_table'], $restore['tables_to_restore'])) {
$do_it = true;
}
}
if ($do_it) {
$tablename = submit_create_action($complete_sql);
$restore['actual_table'] = $tablename;
++$restore['table_ready'];
}
// Zeile verwerfen, da CREATE jetzt bereits ausgefuehrt wurde und naechsten Befehl suchen
$complete_sql = '';
$sqlparser_status = 0;
}
}
// Index
elseif (4 == $sqlparser_status) { //Createindex
if (';' == $last_char) {
if ($config['minspeed'] > 0) {
$restore['anzahl_zeilen'] = $config['minspeed'];
}
$complete_sql = del_inline_comments($complete_sql);
$sqlparser_status = 100;
}
}
// Kommentar oder Condition
elseif (5 == $sqlparser_status) { //Anweisung
$t = strrpos($zeile, '*/;');
if (false === !$t) {
$restore['anzahl_zeilen'] = $config['minspeed'];
$sqlparser_status = 100;
if ($config['ignore_enable_keys'] &&
false !== strrpos($zeile, 'ENABLE KEYS ')) {
$sqlparser_status = 100;
$complete_sql = '';
}
}
}
// Mehrzeiliger oder Inline-Kommentar
elseif (6 == $sqlparser_status) {
$t = strrpos($zeile, '*/');
if (false === !$t) {
$complete_sql = '';
$sqlparser_status = 0;
}
}
// Befehle, die verworfen werden sollen
elseif (7 == $sqlparser_status) { //Anweisung
if (';' == $last_char) {
if ($config['minspeed'] > 0) {
$restore['anzahl_zeilen'] = $config['minspeed'];
}
$complete_sql = '';
$sqlparser_status = 0;
}
}
if (($restore['compressed']) && (gzeof($restore['filehandle']))) {
$restore['fileEOF'] = true;
}
if ((!$restore['compressed']) && (feof($restore['filehandle']))) {
$restore['fileEOF'] = true;
}
}
// wenn bestimmte Tabellen wiederhergestellt werden sollen -> pruefen
if (is_array($restore['tables_to_restore']) && !(in_array($restore['actual_table'], $restore['tables_to_restore']))) {
$complete_sql = '';
}
return trim($complete_sql);
}
function submit_create_action($sql)
{
global $config;
//executes a create command
$tablename = get_tablename($sql);
if ('CREATE ALGORITHM' == strtoupper(substr($sql, 0, 16))) {
// It`s a VIEW. We need to substitute the original DEFINER with the actual MySQL-User
$parts = explode(' ', $sql);
for ($i = 0, $count = sizeof($parts); $i < $count; ++$i) {
if ('DEFINER=' == strtoupper(substr($parts[$i], 0, 8))) {
$parts[$i] = 'DEFINER=`'.$config['dbuser'].'`@`'.$config['dbhost'].'`';
$sql = implode(' ', $parts);
$i = $count;
}
}
}
$res = mysqli_query($config['dbconnection'], $sql);
if (false === $res) {
// erster Versuch fehlgeschlagen -> zweiter Versuch - vielleicht versteht der Server die Inline-Kommentare nicht?
$sql = del_inline_comments($sql);
$res = mysqli_query($config['dbconnection'], downgrade($sql));
}
if (false === $res) {
// wenn wir hier angekommen sind hat nichts geklappt -> Fehler ausgeben und abbrechen
SQLError($sql, mysqli_error($config['dbconnection']));
exit("<br>Fatal error: Couldn't create table or view `".$tablename.'´');
}
return $tablename;
}
function get_insert_syntax($table)
{
global $config;
$insert = '';
$sql = 'SHOW COLUMNS FROM `'.$table.'`';
$res = mysqli_query($config['dbconnection'], $sql);
if ($res) {
$insert = 'INSERT INTO `'.$table.'` (';
while ($row = mysqli_fetch_object($res)) {
$insert .= '`'.$row->Field.'`,';
}
$insert = substr($insert, 0, strlen($insert) - 1).') ';
} else {
global $restore;
v($restore);
SQLError($sql, mysqli_error($config['dbconnection']));
}
return $insert;
}
function del_inline_comments($sql)
{
//$sql=str_replace("\n",'<br>', $sql);
$array = [];
preg_match_all("/(\/\*(.+)\*\/)/U", $sql, $array);
if (is_array($array[0])) {
$sql = str_replace($array[0], '', $sql);
if (DEBUG) {
echo 'Nachher: :<br>'.$sql.'<br><hr>';
}
}
//$sql=trim(str_replace('<br>',"\n", $sql));
//Wenn nach dem Entfernen nur noch ein ; übrigbleibt -> entfernen
if (';' == $sql) {
$sql = '';
}
return $sql;
}
// extrahiert auf einfache Art den Tabellennamen aus dem "Create",Drop"-Befehl
function get_tablename($t)
{
// alle Schluesselbegriffe entfernen, bis der Tabellenname am Anfang steht
$t = substr($t, 0, 150); // verkuerzen, um Speicher zu sparen - wir brauchenhier nur den Tabellennamen
$t = str_ireplace('DROP TABLE', '', $t);
$t = str_ireplace('DROP VIEW', '', $t);
$t = str_ireplace('CREATE TABLE', '', $t);
$t = str_ireplace('INSERT INTO', '', $t);
$t = str_ireplace('REPLACE INTO', '', $t);
$t = str_ireplace('IF NOT EXISTS', '', $t);
$t = str_ireplace('IF EXISTS', '', $t);
if ('CREATE ALGORITHM' == substr(strtoupper($t), 0, 16)) {
$pos = strpos($t, 'DEFINER VIEW ');
$t = substr($t, $pos, strlen($t) - $pos);
}
$t = str_ireplace(';', ' ;', $t); // tricky -> insert space as delimiter
$t = trim($t);
// jetzt einfach nach dem ersten Leerzeichen suchen
$delimiter = substr($t, 0, 1);
if ('`' != $delimiter) {
$delimiter = ' ';
}
$found = false;
$position = 1;
while (!$found) {
if (substr($t, $position, 1) == $delimiter) {
$found = true;
}
if ($position >= strlen($t)) {
$found = true;
}
++$position;
}
$t = substr($t, 0, $position);
$t = trim(str_replace('`', '', $t));
return $t;
}
// decide if an INSERT-Command is complete - simply count quotes and look for ); at the end of line
function SQL_Is_Complete($string)
{
$string = str_replace('\\\\', '', trim($string)); // trim and remove escaped backslashes
$string = trim($string);
$quotes = substr_count($string, '\'');
$escaped_quotes = substr_count($string, '\\\'');
if (($quotes - $escaped_quotes) % 2 == 0) {
$compare = substr($string, -2);
if ('*/' == $compare) {
$compare = substr(trim(remove_comment_at_eol($string)), -2);
}
if (');' == $compare) {
return true;
}
if ('),' == $compare) {
return true;
}
}
return false;
}
function remove_comment_at_eol($string)
{
// check for Inline-Comments at the end of the line
if ('*/' == substr(trim($string), -2)) {
$pos = strrpos($string, '/*');
if ($pos > 0) {
$string = trim(substr($string, 0, $pos));
}
}
return $string;
}

1268
msd/inc/functions_sql.php Normal file

File diff suppressed because it is too large Load Diff

50
msd/inc/header.php Normal file
View File

@ -0,0 +1,50 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
$mod_path = realpath(dirname(__FILE__).'/../').'/';
if (!defined('MOD_PATH')) {
define('MOD_PATH', $mod_path);
}
session_name('MyOOSDumperID');
session_start();
if (!isset($download)) {
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
include MOD_PATH.'inc/functions.php';
include MOD_PATH.'inc/mysqli.php';
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
if (!file_exists($config['files']['parameter'])) {
$error = TestWorkDir();
}
read_config($config['config_file']);
include MOD_PATH.'language/lang_list.php';
if (!isset($databases['db_selected_index'])) {
$databases['db_selected_index'] = 0;
}
SelectDB($databases['db_selected_index']);
$config['theme'] = isset($config['theme']) ? $config['theme'] : 'mod';
$config['files']['iconpath'] = './css/'.$config['theme'].'/icons/';
if (isset($error)) {
echo $error;
}

View File

@ -0,0 +1,79 @@
<?php
namespace WhiteHat101\Crypt;
class APR1_MD5
{
public const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
public const APRMD5_ALPHABET = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Source/References for core algorithm:
// http://www.cryptologie.net/article/126/bruteforce-apr1-hashes/
// http://svn.apache.org/viewvc/apr/apr-util/branches/1.3.x/crypto/apr_md5.c?view=co
// http://www.php.net/manual/en/function.crypt.php#73619
// http://httpd.apache.org/docs/2.2/misc/password_encryptions.html
// Wikipedia
public static function hash($mdp, $salt = null)
{
if (is_null($salt)) {
$salt = self::salt();
}
$salt = substr($salt, 0, 8);
$max = strlen($mdp);
$context = $mdp.'$apr1$'.$salt;
$binary = pack('H32', md5($mdp.$salt.$mdp));
for ($i = $max; $i > 0; $i -= 16) {
$context .= substr($binary, 0, min(16, $i));
}
for ($i = $max; $i > 0; $i >>= 1) {
$context .= ($i & 1) ? chr(0) : $mdp[0];
}
$binary = pack('H32', md5($context));
for ($i = 0; $i < 1000; ++$i) {
$new = ($i & 1) ? $mdp : $binary;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $mdp;
}
$new .= ($i & 1) ? $binary : $mdp;
$binary = pack('H32', md5($new));
}
$hash = '';
for ($i = 0; $i < 5; ++$i) {
$k = $i + 6;
$j = $i + 12;
if (16 == $j) {
$j = 5;
}
$hash = $binary[$i].$binary[$k].$binary[$j].$hash;
}
$hash = chr(0).chr(0).$binary[11].$hash;
$hash = strtr(
strrev(substr(base64_encode($hash), 2)),
self::BASE64_ALPHABET,
self::APRMD5_ALPHABET
);
return '$apr1$'.$salt.'$'.$hash;
}
// 8 character salts are the best. Don't encourage anything but the best.
public static function salt()
{
$alphabet = self::APRMD5_ALPHABET;
$salt = '';
for ($i = 0; $i < 8; ++$i) {
$offset = hexdec(bin2hex(openssl_random_pseudo_bytes(1))) % 64;
$salt .= $alphabet[$offset];
}
return $salt;
}
public static function check($plain, $hash)
{
$parts = explode('$', $hash);
return self::hash($plain, $parts[2]) === $hash;
}
}

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Jeremy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1 @@
https://github.com/whitehat101/apr1-md5

230
msd/inc/home/databases.php Normal file
View File

@ -0,0 +1,230 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
include './language/'.$config['language'].'/lang_sql.php';
$checkit = (isset($_GET['checkit'])) ? urldecode($_GET['checkit']) : '';
$repair = (isset($_GET['repair'])) ? $_GET['repair'] : 0;
$enableKeys = (isset($_GET['enableKeys'])) ? $_GET['enableKeys'] : '';
for ($i = 0; $i < count($databases['Name']); ++$i) {
if (isset($_POST['empty'.$i])) {
EmptyDB($databases['Name'][$i]);
$dba = '<p class="green">'.$lang['L_DB'].' '.$databases['Name'][$i].' '.$lang['L_INFO_CLEARED'].'</p>';
break;
}
if (isset($_POST['kill'.$i])) {
$res = mysqli_query($config['dbconnection'], 'DROP DATABASE `'.$databases['Name'][$i].'`') or exit(mysqli_error($config['dbconnection']));
$dba = '<p class="green">'.$lang['L_DB'].' '.$databases['Name'][$i].' '.$lang['L_INFO_DELETED'].'</p>';
SetDefault();
include $config['files']['parameter'];
echo '<script>parent.MyOOS_Dumper_menu.location.href="menu.php?action=dbrefresh";</script>';
break;
}
if (isset($_POST['optimize'.$i])) {
mysqli_select_db($config['dbconnection'], $databases['Name'][$i]);
$res = mysqli_query($config['dbconnection'], 'SHOW TABLES FROM `'.$databases['Name'][$i].'`');
$tabellen = '';
while ($row = mysqli_fetch_row($res)) {
$tabellen .= '`'.$row[0].'`,';
}
$tabellen = substr($tabellen, 0, (strlen($tabellen) - 1));
if ($tabellen > '') {
$query = 'OPTIMIZE TABLE '.$tabellen;
$res = mysqli_query($config['dbconnection'], $query) or exit(mysqli_error($config['dbconnection']).'');
}
$_GET['dbid'] = $i;
$dba = '<p class="green">'.$lang['L_DB'].' <b>'.$databases['Name'][$i].'</b> '.$lang['L_INFO_OPTIMIZED'].'.</p>';
break;
}
if (isset($_POST['check'.$i])) {
$checkit = 'ALL';
$_GET['dbid'] = $i;
}
if (isset($_POST['enableKeys'.$i])) {
$enableKeys = 'ALL';
$_GET['dbid'] = $i;
}
}
//list databases
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => './tpl/home/databases_list_dbs.tpl', ]);
$tpl->assign_vars([
'ICONPATH' => $config['files']['iconpath'], ]);
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
for ($i = 0; $i < count($databases['Name']); ++$i) {
$rowclass = ($i % 2) ? 'dbrow' : 'dbrow1';
if ($i == $databases['db_selected_index']) {
$rowclass = 'dbrowsel';
}
//gibts die Datenbank überhaupt?
if (!mysqli_select_db($config['dbconnection'], $databases['Name'][$i])) {
$tpl->assign_block_vars('DB_NOT_FOUND', [
'ROWCLASS' => $rowclass,
'NR' => ($i + 1),
'DB_NAME' => $databases['Name'][$i],
'DB_ID' => $i, ]);
} else {
mysqli_select_db($config['dbconnection'], $databases['Name'][$i]);
$tabellen = mysqli_query($config['dbconnection'], 'SHOW TABLES FROM `'.$databases['Name'][$i].'`');
$num_tables = mysqli_num_rows($tabellen);
$tpl->assign_block_vars('ROW', [
'ROWCLASS' => $rowclass,
'NR' => ($i + 1),
'DB_NAME' => $databases['Name'][$i],
'DB_ID' => $i,
'TABLE_COUNT' => $num_tables, ]);
if (1 == $num_tables) {
$tpl->assign_block_vars('ROW.TABLE', []);
} else {
$tpl->assign_block_vars('ROW.TABLES', []);
}
}
}
$tpl->pparse('show');
//list tables of selected database
if (isset($_GET['dbid'])) {
$disabled_keys_found = false;
// Output list of tables of the selected database
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => 'tpl/home/databases_list_tables.tpl', ]);
$dbid = $_GET['dbid'];
$numrows = 0;
$res = mysqli_query($config['dbconnection'], 'SHOW TABLE STATUS FROM `'.$databases['Name'][$dbid].'`');
mysqli_select_db($config['dbconnection'], $databases['Name'][$dbid]);
if ($res) {
$numrows = mysqli_num_rows($res);
}
$tpl->assign_vars([
'DB_NAME' => $databases['Name'][$dbid],
'DB_NAME_URLENCODED' => urlencode($databases['Name'][$dbid]),
'DB_ID' => $dbid,
'TABLE_COUNT' => $numrows,
'ICONPATH' => $config['files']['iconpath'], ]);
$numrows = intval($numrows);
if ($numrows > 1) {
$tpl->assign_block_vars('MORE_TABLES', []);
} elseif (1 == $numrows) {
$tpl->assign_block_vars('1_TABLE', []);
} elseif (0 == $numrows) {
$tpl->assign_block_vars('NO_TABLE', []);
}
if ($numrows > 0) {
$last_update = '2000-01-01 00:00:00';
$sum_records = $sum_data_length = 0;
for ($i = 0; $i < $numrows; ++$i) {
$row = mysqli_fetch_array($res, MYSQLI_ASSOC);
// Get nr of records -> need to do it this way because of incorrect returns when using InnoDBs
$sql_2 = 'SELECT count(*) as `count_records` FROM `'.$databases['Name'][$dbid].'`.`'.$row['Name'].'`';
$res2 = mysqli_query($config['dbconnection'], $sql_2);
if (false === $res2) {
$row['Rows'] = 0;
$rowclass = 'dbrowsel';
} else {
$row2 = mysqli_fetch_array($res2);
$row['Rows'] = $row2['count_records'];
$rowclass = ($i % 2) ? 'dbrow' : 'dbrow1';
}
if (isset($row['Update_time']) && strtotime($row['Update_time']) > strtotime($last_update)) {
$last_update = $row['Update_time'];
}
$sum_records += $row['Rows'];
$sum_data_length += $row['Data_length'] + $row['Index_length'];
$keys_disabled = false;
if ('MyIsam' == $row['Engine']) {
}
$tpl->assign_block_vars('ROW', [
'ROWCLASS' => $rowclass,
'NR' => ($i + 1),
'TABLE_NAME' => $row['Name'],
'TABLE_NAME_URLENCODED' => urlencode($row['Name']),
'RECORDS' => $row['Rows'],
'SIZE' => byte_output($row['Data_length'] + $row['Index_length']),
'LAST_UPDATE' => $row['Update_time'],
'ENGINE' => $row['Engine'],
]);
// Otimize & Repair - only for MyISAM-Tables
if ('MyISAM' == $row['Engine']) {
if (0 == $row['Data_free']) {
$tpl->assign_block_vars('ROW.OPTIMIZED', []);
} else {
$tpl->assign_block_vars('ROW.NOT_OPTIMIZED', []);
}
if ($checkit == $row['Name'] || 1 == $repair) {
$tmp_res = mysqli_query($config['dbconnection'], 'REPAIR TABLE `'.$row['Name'].'`');
}
if (($checkit == $row['Name'] || 'ALL' == $checkit)) {
// table needs to be checked
$tmp_res = mysqli_query($config['dbconnection'], 'CHECK TABLE `'.$row['Name'].'`');
if ($tmp_res) {
$tmp_row = mysqli_fetch_row($tmp_res);
if ('OK' == $tmp_row[3]) {
$tpl->assign_block_vars('ROW.CHECK_TABLE_OK', []);
} else {
$tpl->assign_block_vars('ROW.CHECK_TABLE_NOT_OK', []);
}
}
} else {
// Show Check table link
$tpl->assign_block_vars('ROW.CHECK_TABLE', []);
}
if ($enableKeys == $row['Name'] || 'ALL' == $enableKeys) {
$sSql = 'ALTER TABLE `'.$databases['Name'][$dbid].'`.`'.$row['Name'].'` ENABLE KEYS';
$tmp_res = mysqli_query($config['dbconnection'], $sSql);
}
$res3 = mysqli_query($config['dbconnection'], 'SHOW INDEX FROM `'.$databases['Name'][$dbid].'`.`'.$row['Name'].'`');
while ($row3 = mysqli_fetch_array($res3, MYSQLI_ASSOC)) {
if ('disabled' == $row3['Comment']) {
$keys_disabled = true;
$disabled_keys_found = true;
}
}
if ($keys_disabled) {
$tpl->assign_block_vars('ROW.KEYS_DISABLED', []);
} else {
$tpl->assign_block_vars('ROW.KEYS_ENABLED', []);
}
}
}
// Output sum-row
$tpl->assign_block_vars('SUM', [
'RECORDS' => number_format($sum_records, 0, ',', '.'),
'SIZE' => byte_output($sum_data_length),
'LAST_UPDATE' => $last_update, ]);
if ($disabled_keys_found) {
$tpl->assign_block_vars('DISABLED_KEYS_FOUND', []);
}
}
$tpl->pparse('show');
}

144
msd/inc/home/home.php Normal file
View File

@ -0,0 +1,144 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
$Sum_Files = $Sum_Size = 0;
$Last_BU = [];
$is_htaccess = (file_exists('./.htaccess'));
$is_protected = IsAccessProtected();
$is_new_version_available = (isset($update) && is_object($update) && $check_update === true) ? $update->newVersionAvailable() : false;
// find latest backup file
$available = [];
if ('' == $databases['multisetting']) {
$available[0] = $databases['db_actual'];
} else {
$available = explode(';', $databases['multisetting']);
}
$dh = opendir($config['paths']['backup']);
while (false !== ($filename = readdir($dh))) {
if ('.' != $filename && '..' != $filename && !is_dir($config['paths']['backup'].$filename)) {
foreach ($available as $item) {
$pos = strpos($filename, $item);
if ($pos === false) {
// Der Datenbankname wurde nicht in der Konfiguration gefunden;
} else {
$files[] = $filename;
++$Sum_Files;
$Sum_Size += filesize($config['paths']['backup'].$filename);
$ft = filectime($config['paths']['backup'].$filename);
if (!isset($Last_BU[2]) || (isset($Last_BU[2]) && $ft > $Last_BU[2])) {
$Last_BU[0] = $filename;
$Last_BU[1] = date('d.m.Y H:i', $ft);
$Last_BU[2] = $ft;
}
}
}
}
}
if (!is_writable($config['paths']['temp'])) {
$ret = SetFileRechte($config['paths']['temp'], 1, 0777);
}
if (!is_writable($config['paths']['cache'])) {
$ret = SetFileRechte($config['paths']['cache'], 1, 0777);
}
$directory_warnings = DirectoryWarnings();
if ($is_new_version_available) {
$update_info = $lang['L_NEW_MOD_VERSION'] . ': ' . $update->getLatestVersion();
}
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => 'tpl/home/home.tpl', ]);
$tpl->assign_vars([
'THEME' => $config['theme'],
'MOD_VERSION' => MOD_VERSION,
'OS' => MOD_OS,
'OS_EXT' => MOD_OS_EXT,
'MYSQL_VERSION' => MOD_MYSQL_VERSION,
'PHP_VERSION' => PHP_VERSION,
'MEMORY' => byte_output($config['php_ram'] * 1024 * 1024),
'MAX_EXECUTION_TIME' => $config['max_execution_time'],
'PHP_EXTENSIONS' => $config['phpextensions'],
'SERVER_NAME' => $_SERVER['SERVER_NAME'],
'MOD_PATH' => $config['paths']['root'],
'DB' => $databases['db_actual'],
'NR_OF_BACKUP_FILES' => $Sum_Files,
'SIZE_BACKUPS' => byte_output($Sum_Size),
'FREE_DISKSPACE' => MD_FreeDiskSpace(),
]);
if ($is_new_version_available) {
$tpl->assign_block_vars('NEW_VERSION_EXISTS', []);
}
if (isset($update_info)) {
$tpl->assign_block_vars('UPDATE_INFO', [
'MSG' => $update_info, ]);
}
if ($directory_warnings > '') {
$tpl->assign_block_vars('DIRECTORY_WARNINGS', [
'MSG' => $directory_warnings, ]);
}
if ($config['disabled'] > '') {
$tpl->assign_block_vars('DISABLED_FUNCTIONS', [
'PHP_DISABLED_FUNCTIONS' => str_replace(',', ', ', $config['disabled']), ]);
}
if (!extension_loaded('ftp')) {
$tpl->assign_block_vars('NO_FTP', []);
}
if (!$config['zlib']) {
$tpl->assign_block_vars('NO_ZLIB', []);
}
if (false === $is_protected) {
$tpl->assign_block_vars('DIRECTORY_PROTECTION_STATUS_ERROR', ['MSG' => $lang['L_HTACC_CHECK_ERROR']]);
} elseif (1 === $is_protected && !$is_htaccess) {
$tpl->assign_block_vars('DIRECTORY_PROTECTION_STATUS', ['MSG' => $lang['L_HTACC_NOT_NEEDED']]);
} elseif (1 === $is_protected && $is_htaccess) {
$tpl->assign_block_vars('DIRECTORY_PROTECTION_STATUS', ['MSG' => $lang['L_HTACC_COMPLETE']]);
} elseif (0 === $is_protected && $is_htaccess) {
$tpl->assign_block_vars('DIRECTORY_PROTECTION_STATUS_ERROR', ['MSG' => $lang['L_HTACC_INCOMPLETE']]);
} else {
$tpl->assign_block_vars('DIRECTORY_PROTECTION_STATUS_ERROR', ['MSG' => $lang['L_HTACC_PROPOSED']]);
}
if ($is_htaccess) {
$tpl->assign_block_vars('HTACCESS_EXISTS', []);
} else {
$tpl->assign_block_vars('HTACCESS_DOESNT_EXISTS', []);
}
if ($Sum_Files > 0 && isset($Last_BU[1])) {
$tpl->assign_block_vars('LAST_BACKUP', [
'LAST_BACKUP_INFO' => $Last_BU[1],
'LAST_BACKUP_LINK' => $config['paths']['backup'].urlencode($Last_BU[0]),
'LAST_BACKUP_NAME' => $Last_BU[0], ]);
}
$tpl->pparse('show');

View File

@ -0,0 +1,118 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
$var = (isset($_GET['var'])) ? $_GET['var'] : 'prozesse';
$Titelausgabe = [
'variables' => $lang['L_VARIABELN'], 'status' => $lang['L_STATUS'], 'prozesse' => $lang['L_PROZESSE'], ];
echo '<h5>'.$lang['L_MYSQLVARS'].'</h5><strong>'.$Titelausgabe[$var].'</strong>&nbsp;&nbsp;&nbsp;&nbsp;';
echo '<a href="main.php?action=vars&amp;var=prozesse">'.$lang['L_PROZESSE'].'</a>&nbsp;&nbsp;&nbsp;';
echo '<a href="main.php?action=vars&amp;var=status">'.$lang['L_STATUS'].'</a>&nbsp;&nbsp;&nbsp;';
echo '<a href="main.php?action=vars&amp;var=variables">'.$lang['L_VARIABELN'].'</a>&nbsp;&nbsp;&nbsp;';
echo '<p>&nbsp;</p>';
//Variabeln
switch ($var) {
case 'variables':
$res = mysqli_query($config['dbconnection'], 'SHOW variables');
if ($res) {
$numrows = mysqli_num_rows($res);
}
if (0 == $numrows) {
echo $lang['L_INFO_NOVARS'];
} else {
echo '<table class="bdr"><tr class="thead"><th><strong>Name</strong></th><th><strong>'.$lang['L_INHALT'].'</strong></th></tr>';
for ($i = 0; $i < $numrows; ++$i) {
$row = mysqli_fetch_array($res);
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
echo '<tr class="'.$cl.'"><td align="left">'.$row[0].'</td><td align="left">'.$row[1].'</td></tr>';
}
}
echo '</table>';
break;
case 'status':
$res = mysqli_query($config['dbconnection'], 'SHOW STATUS');
if ($res) {
$numrows = mysqli_num_rows($res);
}
if (0 == $numrows) {
echo $lang['L_INFO_NOSTATUS'];
} else {
echo '<table class="bdr"><tr class="thead"><th>Name</th><th>'.$lang['L_INHALT'].'</th></tr>';
for ($i = 0; $i < $numrows; ++$i) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
$row = mysqli_fetch_array($res);
echo '<tr class="'.$cl.'"><td align="left" valign="top">'.$row[0].'</td><td align="left" valign="top">'.$row[1].'</td></tr>';
}
}
echo '</table>';
break;
case 'prozesse':
if ($config['processlist_refresh'] < 1000) {
$config['processlist_refresh'] = 2000;
}
if (isset($_GET['killid']) && $_GET['killid'] > 0) {
$killid = (isset($_GET['killid'])) ? $_GET['killid'] : 0;
$wait = (isset($_GET['wait'])) ? $_GET['wait'] : 0;
if (0 == $wait) {
$ret = mysqli_query($config['dbconnection'], 'KILL '.$_GET['killid']);
$wait = 2;
} else {
$wait += 2;
}
if (0 == $wait) {
echo '<p class="success">'.$lang['L_PROCESSKILL1'].$_GET['killid'].' '.$lang['L_PROCESSKILL2'].'</p>';
} else {
echo '<p class="success">'.$lang['L_PROCESSKILL3'].$wait.$lang['L_PROCESSKILL4'].$_GET['killid'].' '.$lang['L_PROCESSKILL2'].'</p>';
}
}
$killid = $wait = 0;
$res = mysqli_query($config['dbconnection'], 'SHOW FULL PROCESSLIST ');
if ($res) {
$numrows = mysqli_num_rows($res);
}
if (0 == $numrows) {
echo $lang['L_INFO_NOPROCESSES'];
} else {
echo '<table class="bdr" style="width:100%"><tr class="thead"><th>ID</th><th>User</th><th>Host</th><th>DB</th><th>Command</th><th>Time</th><th>State</th><th width="800">Info</th><th nowrap="nowrap">RT: '.round($config['processlist_refresh'] / 1000).' sec</th></tr>';
for ($i = 0; $i < $numrows; ++$i) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
$row = mysqli_fetch_array($res);
echo '<tr><td>'.$row[0].'</td><td>'.$row[1].'</td>
<td>'.$row[2].'</td><td>'.$row[3].'</td><td>'.$row[4].'</td><td>'.$row[5].'</td>
<td>'.$row[6].'</td><td>'.$row[7].'</td>
<td><a href="main.php?action=vars&amp;var=prozesse&amp;killid='.$row[0].'">kill</a></td></tr>';
if ($row[0] == $killid && 'Killed' == $row[4]) {
$wait = $killid = 0;
}
}
}
echo '</table>';
echo '<form name="f" method="get" action="main.php">
<input type="hidden" name="wait" value="'.$wait.'">
<input type="hidden" name="killid" value="'.$killid.'">
<input type="hidden" name="action" value="vars">
<input type="hidden" name="var" value="prozesse"></form>';
echo '<script>window.setTimeout("document.f.submit();","'.$config['processlist_refresh'].'");</script>';
break;
}

View File

@ -0,0 +1,167 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
include './language/'.$config['language'].'/lang_sql.php';
include './inc/home/apr1_md5/apr1_md5.php';
use WhiteHat101\Crypt\APR1_MD5;
$dba = $hta_dir = $Overwrite = $msg = '';
$error = [];
$is_htaccess = (file_exists('./.htaccess'));
if ($is_htaccess) {
$Overwrite = '<p class="error">'.$lang['L_HTACCESS8'].'</p>';
$htaccess_exist = file('.htaccess'); // read .htaccess
}
$step = (isset($_POST['step'])) ? intval($_POST['step']) : 0;
$type = 1; // default encryption type set to MD5(APR)
if ('WIN' == strtoupper(substr(MOD_OS, 0, 3))) {
$type = 2;
} // we are on a Win-System; pre-select encryption type
if (isset($_POST['type'])) {
$type = intval($_POST['type']);
}
$username = (isset($_POST['username'])) ? $_POST['username'] : '';
$userpass1 = (isset($_POST['userpass1'])) ? $_POST['userpass1'] : '';
$userpass2 = (isset($_POST['userpass2'])) ? $_POST['userpass2'] : '';
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: -1');
header('Content-Type: text/html; charset=UTF-8');
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => './tpl/home/protection_create.tpl', ]);
$tpl->assign_vars([
'THEME' => $config['theme'],
'HEADLINE' => headline($lang['L_HTACC_CREATE']), ]);
if (isset($_POST['username'])) {
// Form submitted
if ('' == $username) {
$error[] = $lang['L_HTACC_NO_USERNAME'];
}
if (($userpass1 != $userpass2) || ('' == $userpass1)) {
$error[] = $lang['L_PASSWORDS_UNEQUAL'];
}
if (0 == sizeof($error)) {
$realm = 'MyOOS-Dumper';
$htaccess =
"<IfModule mod_rewrite.c>\n".
" RewriteEngine off\n".
"</IfModule>\n".
'AuthName "'.$realm."\"\n".
"AuthType Basic\n".
'AuthUserFile "'.$config['paths']['root'].".htpasswd\"\n".
'Require valid-user';
switch ($type) {
// CRYPT
case 0:
$userpass = crypt($userpass1, 'rl');
break;
// MD5(APR)
case 1:
$userpass = APR1_MD5::hash($userpass1);
break;
// PLAIN TEXT
case 2:
$userpass = $userpass1;
break;
// SHA1
case 3:
$userpass = '{SHA}'.base64_encode(sha1($userpass1, true));
break;
// BCRYPT
case 4:
$userpass = password_hash($userpass1, PASSWORD_BCRYPT);
break;
}
$htpasswd = $username.':'.$userpass;
@chmod($config['paths']['root'], 0777);
// save .htpasswd
if ($file_htpasswd = @fopen('.htpasswd', 'w')) {
$saved = fputs($file_htpasswd, $htpasswd);
fclose($file_htpasswd);
} else {
$saved = false;
}
// save .htaccess
if (false !== $saved) {
$file_htaccess = @fopen('.htaccess', 'w');
if ($file_htaccess) {
$saved = fputs($file_htaccess, $htaccess);
fclose($file_htaccess);
} else {
$saved = false;
}
}
if (false !== $saved) {
$msg = '<span class="success">'.$lang['L_HTACC_CREATED'].'</span>';
$tpl->assign_block_vars('CREATE_SUCCESS', [
'HTACCESS' => htmlspecialchars($htaccess),
'HTPASSWD' => htmlspecialchars($htpasswd),
]);
@chmod($config['paths']['root'], 0755);
} else {
$tpl->assign_block_vars('CREATE_ERROR', [
'HTACCESS' => htmlspecialchars($htaccess),
'HTPASSWD' => htmlspecialchars($htpasswd),
]);
}
}
}
if (sizeof($error) > 0 || !isset($_POST['username'])) {
$tpl->assign_vars([
'PASSWORDS_UNEQUAL' => my_addslashes($lang['L_PASSWORDS_UNEQUAL']),
'HTACC_CONFIRM_CREATE' => my_addslashes($lang['L_HTACC_CONFIRM_CREATE']),
]);
$tpl->assign_block_vars('INPUT', [
'USERNAME' => htmlspecialchars($username),
'USERPASS1' => htmlspecialchars($userpass1),
'USERPASS2' => htmlspecialchars($userpass2),
'TYPE0_CHECKED' => 0 == $type ? ' checked="checked"' : '',
'TYPE1_CHECKED' => 1 == $type ? ' checked="checked"' : '',
'TYPE2_CHECKED' => 2 == $type ? ' checked="checked"' : '',
'TYPE3_CHECKED' => 3 == $type ? ' checked="checked"' : '',
'TYPE4_CHECKED' => 4 == $type ? ' checked="checked"' : '',
]);
}
if (sizeof($error) > 0) {
$msg = '<span class="error">'.implode('<br>', $error).'</span>';
}
if ($msg > '') {
$tpl->assign_block_vars('MSG', [
'TEXT' => $msg, ]);
}
$tpl->pparse('show');
echo MODFooter();
ob_end_flush();
exit();

View File

@ -0,0 +1,26 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
@unlink($config['paths']['root'].'.htaccess');
@unlink($config['paths']['root'].'.htpasswd');
$action = 'status';
// todo -> give user info about success or failure of deleting action

View File

@ -0,0 +1,93 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
include './language/'.$config['language'].'/lang_sql.php';
echo MODHeader();
echo headline($lang['L_HTACC_EDIT']);
$htaccessdontexist = 0;
if (isset($_POST['hta_dir']) && isset($_POST['hta_file']) && is_dir($_POST['hta_dir'])) {
$hta_dir = $_POST['hta_dir'];
$hta_file = $_POST['hta_file'];
} else {
$hta_dir = $config['paths']['root'];
$hta_file = '.htaccess';
}
if ('' != $hta_dir & '/' != substr($hta_dir, -1)) {
$hta_dir .= '/';
}
$hta_complete = $hta_dir.$hta_file;
if ((isset($_GET['create']) && 1 == $_GET['create']) || (isset($_POST['create']) && 1 == $_POST['create'])) {
$fp = fopen($hta_complete, 'w');
fwrite($fp, '# created by MySQLDumper '.MOD_VERSION."\n");
fclose($fp);
}
if (isset($_POST['submit']) && isset($_POST['thta'])) {
$fp = fopen($hta_complete, 'w');
fwrite($fp, $_POST['thta']);
fclose($fp);
}
if (file_exists($hta_complete)) {
$htaccess_exist = file($hta_complete);
} else {
$htaccessdontexist = 1;
}
echo $lang['L_HTACCESS32'];
echo '<br><br><form name="ehta" action="main.php?action=edithtaccess" method="post">';
echo '<table>';
echo '<tr><td>'.$lang['L_DIR'].':</td><td><input type="text" name="hta_dir" value="'.$hta_dir.'" size="60"></td></tr>';
echo '<tr><td>'.$lang['L_FILE'].':</td><td><input type="text" name="hta_file" value="'.$hta_file.'"></td></tr>';
echo '</table>';
if (1 != $htaccessdontexist) {
echo '<table class="bdr"><tr><td style="width:70%;"><textarea rows="25" cols="40" name="thta" id="thta">'.htmlspecialchars(implode('', $htaccess_exist)).'</textarea><br><br>';
echo '</td><td valign="top">';
//Presets
echo '<h6>Presets</h6><p><strong>'.$lang['L_HTACCESS30'].'</strong><p>
<a href="javascript:insertHTA(1,document.ehta.thta)">all-inkl</a><br>
<br><p><strong>'.$lang['L_HTACCESS31'].'</strong></p>
<a href="javascript:insertHTA(101,document.ehta.thta)">'.$lang['L_HTACCESS20'].'</a><br>
<a href="javascript:insertHTA(102,document.ehta.thta)">'.$lang['L_HTACCESS21'].'</a><br>
<a href="javascript:insertHTA(103,document.ehta.thta)">'.$lang['L_HTACCESS22'].'</a><br>
<a href="javascript:insertHTA(104,document.ehta.thta)">'.$lang['L_HTACCESS23'].'</a><br>
<a href="javascript:insertHTA(105,document.ehta.thta)">'.$lang['L_HTACCESS24'].'</a><br>
<a href="javascript:insertHTA(106,document.ehta.thta)">'.$lang['L_HTACCESS25'].'</a><br>
<a href="javascript:insertHTA(107,document.ehta.thta)">'.$lang['L_HTACCESS26'].'</a><br>
<a href="javascript:insertHTA(108,document.ehta.thta)">'.$lang['L_HTACCESS27'].'</a><br>
<a href="javascript:insertHTA(109,document.ehta.thta)">'.$lang['L_HTACCESS28'].'</a><br>
<br><a href="http://httpd.apache.org/docs/2.0/mod/directives.html" target="_blank">'.$lang['L_HTACCESS29'].'</a>';
echo '</td></tr>';
echo '<tr><td colspan="2">';
echo '<input type="submit" name="submit" value=" '.$lang['L_SAVE'].' " class="Formbutton">&nbsp;&nbsp;&nbsp;';
echo '<input type="reset" name="reset" value=" '.$lang['L_RESET'].' " class="Formbutton">&nbsp;&nbsp;&nbsp;';
echo '<input type="submit" name="newload" value=" '.$lang['L_HTACCESS19'].' " class="Formbutton">';
echo '</td></tr></table></form>';
} else {
echo '<br>'.$lang['L_FILE_MISSING'].': '.$hta_complete.'<br><br>';
echo '<form action="" method="post"><input type="hidden" name="hta_dir" value="'.$hta_dir.'"><input type="hidden" name="hta_file" value="'.$hta_file.'"><input type="hidden" name="create" value="1"><input type="submit" name="createhtaccess" value="'.$lang['L_CREATE'].'" class="Formbutton"></form>';
}
echo '</div>';
ob_end_flush();
exit();

101
msd/inc/home/system.php Normal file
View File

@ -0,0 +1,101 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
$sysaction = (isset($_GET['dosys'])) ? $_GET['dosys'] : 0;
$msg = '';
$res = mysqli_query($config['dbconnection'], "SHOW VARIABLES LIKE 'datadir'");
if ($res) {
$row = mysqli_fetch_array($res);
$data_dir = $row[1];
}
switch ($sysaction) {
case 1: //FLUSH PRIVILEGES
$msg = '&gt; operating FLUSH PRIVILEGES<br>';
$res = mysqli_query($config['dbconnection'], 'FLUSH PRIVILEGES');
$meldung = mysqli_error($config['dbconnection']);
if ('' != $meldung) {
$msg .= '&gt; MySQL-Error: '.$meldung;
} else {
$msg .= '&gt; Privileges were reloaded.';
}
break;
case 2: //FLUSH STATUS
$msg = '&gt; operating FLUSH STATUS<br>';
$res = mysqli_query($config['dbconnection'], 'FLUSH STATUS');
$meldung = mysqli_error($config['dbconnection']);
if ('' != $meldung) {
$msg .= '&gt; MySQL-Error: '.$meldung;
} else {
$msg .= '&gt; Status was reset.';
}
break;
case 3: //FLUSH HOSTS
$msg = '&gt; operating FLUSH HOSTS<br>';
$res = mysqli_query($config['dbconnection'], 'FLUSH HOSTS');
$meldung = mysqli_error($config['dbconnection']);
if ('' != $meldung) {
$msg .= '&gt; MySQL-Error: '.$meldung;
} else {
$msg .= '&gt; Hosts were reloaded.';
}
break;
case 4: //SHOW MASTER LOGS
$msg = '> operating SHOW MASTER LOGS<br>';
$res = mysqli_query($config['dbconnection'], 'SHOW MASTER LOGS');
$meldung = mysqli_error($config['dbconnection']);
if ('' != $meldung) {
$msg .= '&gt; MySQL-Error: '.$meldung;
} else {
$numrows = mysqli_num_rows($res);
if (0 == $numrows || false === $numrows) {
$msg .= '&gt; there are no master log-files';
} else {
$msg .= '&gt; there are '.$numrows.' logfiles<br>';
for ($i = 0; $i < $numrows; ++$i) {
$row = mysqli_fetch_row($res);
$msg .= '&gt; '.$row[0].'&nbsp;&nbsp;&nbsp;'.(($data_dir) ? byte_output(@filesize($data_dir.$row[0])) : '').'<br>';
}
}
}
break;
case 5: //RESET MASTER
$msg = '&gt; operating RESET MASTER<br>';
$res = mysqli_query($config['dbconnection'], 'RESET MASTER');
$meldung = mysqli_error($config['dbconnection']);
if ('' != $meldung) {
$msg .= '&gt; MySQL-Error: '.$meldung;
} else {
$msg .= '&gt; All Masterlogs were deleted.';
}
break;
}
echo '<h5>'.$lang['L_MYSQLSYS'].'</h5>';
echo '<div id="hormenu"><ul>
<li><a href="main.php?action=sys&amp;dosys=1">Reload Privileges</a></li>
<li><a href="main.php?action=sys&amp;dosys=2">Reset Status</a></li>
<li><a href="main.php?action=sys&amp;dosys=3">Reload Hosts</a></li>
<li><a href="main.php?action=sys&amp;dosys=4">Show Log-Files</a></li>
<li><a href="main.php?action=sys&amp;dosys=5">Reset Master-Log</a></li>
</ul></div>';
echo '<div align="center" class="MySQLbox">';
echo '&gt; MySQL Dumper v'.MOD_VERSION.' - Output Console<br><br>';
echo ('' != $msg) ? $msg : '> waiting for operation ...<br>';
echo '</div>';

87
msd/inc/home/update.php Normal file
View File

@ -0,0 +1,87 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
if ($update->newVersionAvailable() && $check_update === true) {
// Install new update
echo '<p align="center"><a href="main.php">&lt;&lt; Home</a></p>';
echo $lang['L_NEW_MOD_VERSION'] . ': ' . $update->getLatestVersion() . '<br>';
echo $lang['L_INSTALLING_UPDATES'] . ': <br>';
/*
echo '<pre>';
var_dump(array_map(function ($version) {
return (string) $version;
}, $update->getVersionsToUpdate()));
echo '</pre>';
*/
// Optional - empty log file
$f = fopen($config['paths']['log'] . 'update.log', 'rb+');
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
/*
// Optional Callback function - on each version update
function eachUpdateFinishCallback($updatedVersion)
{
echo '<h3>CALLBACK for version ' . $updatedVersion . '</h3>';
}
$update->onEachUpdateFinish('eachUpdateFinishCallback');
// Optional Callback function - on each version update
function onAllUpdateFinishCallbacks($updatedVersions)
{
echo '<h3>CALLBACK for all updated versions:</h3>';
echo '<ul>';
foreach ($updatedVersions as $v) {
echo '<li>' . $v . '</li>';
}
echo '</ul>';
}
$update->setOnAllUpdateFinishCallbacks('onAllUpdateFinishCallbacks');
*/
// This call will only simulate an update.
// Set the first argument (simulate) to "false" to install the update
// i.e. $update->update(false);
$result = $update->update(false);
if ($result === true) {
echo $lang['L_UPDATE_SUCCESSFUL'] . '<br>';
} else {
echo $lang['L_UPDATE_FAILED'] . ': ' . $result . '!<br>';
if ($result = AutoUpdate::ERROR_SIMULATE) {
echo '<pre>';
var_dump($update->getSimulationResults());
echo '</pre>';
}
}
} else {
echo $lang['L_UP_TO_DATE']. '<br>';
}
echo 'Log:<br>';
echo nl2br(file_get_contents($config['paths']['log'] . '/update.log'));
echo '<p align="center"><a href="main.php">&lt;&lt; Home</a></p>';

543
msd/inc/mysqli.php Normal file
View File

@ -0,0 +1,543 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
//Feldspezifikationen
$feldtypen = [
'VARCHAR',
'TINYINT',
'TEXT',
'DATE',
'SMALLINT',
'MEDIUMINT',
'INT',
'BIGINT',
'FLOAT',
'DOUBLE',
'DECIMAL',
'DATETIME',
'TIMESTAMP',
'TIME',
'YEAR',
'CHAR',
'TINYBLOB',
'TINYTEXT',
'BLOB',
'MEDIUMBLOB',
'MEDIUMTEXT',
'LONGBLOB',
'LONGTEXT',
'ENUM',
'SET',
];
$feldattribute = [
'',
'BINARY',
'UNSIGNED',
'UNSIGNED ZEROFILL',
];
$feldnulls = [
'NOT NULL',
'NULL',
];
$feldextras = [
'',
'AUTO_INCREMENT',
];
$feldkeys = [
'',
'PRIMARY KEY',
'UNIQUE KEY',
'FULLTEXT',
];
$feldrowformat = [
'',
'FIXED',
'DYNAMIC',
'COMPRESSED',
];
$rechte_daten = [
'SELECT',
'INSERT',
'UPDATE',
'DELETE',
'FILE',
];
$rechte_struktur = [
'CREATE',
'ALTER',
'INDEX',
'DROP',
'CREATE TEMPORARY TABLES',
];
$rechte_admin = [
'GRANT',
'SUPER',
'PROCESS',
'RELOAD',
'SHUTDOWN',
'SHOW DATABASES',
'LOCK TABLES',
'REFERENCES',
'EXECUTE',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
];
$rechte_resourcen = [
'MAX QUERIES PER HOUR',
'MAX UPDATES PER HOUR',
'MAX CONNECTIONS PER HOUR',
];
$sql_keywords = [
'ALTER',
'AND',
'ADD',
'AUTO_INCREMENT',
'BETWEEN',
'BINARY',
'BOTH',
'BY',
'BOOLEAN',
'CHANGE',
'CHARSET',
'CHECK',
'COLLATE',
'COLUMNS',
'COLUMN',
'CROSS',
'CREATE',
'DATABASES',
'DATABASE',
'DATA',
'DELAYED',
'DESCRIBE',
'DESC',
'DISTINCT',
'DELETE',
'DROP',
'DEFAULT',
'ENCLOSED',
'ENGINE',
'ESCAPED',
'EXISTS',
'EXPLAIN',
'FIELDS',
'FIELD',
'FLUSH',
'FOR',
'FOREIGN',
'FUNCTION',
'FROM',
'GROUP',
'GRANT',
'HAVING',
'IGNORE',
'INDEX',
'INFILE',
'INSERT',
'INNER',
'INTO',
'IDENTIFIED',
'JOIN',
'KEYS',
'KILL',
'KEY',
'LEADING',
'LIKE',
'LIMIT',
'LINES',
'LOAD',
'LOCAL',
'LOCK',
'LOW_PRIORITY',
'LEFT',
'LANGUAGE',
'MEDIUMINT',
'MODIFY',
'MyISAM',
'NATURAL',
'NOT',
'NULL',
'NEXTVAL',
'OPTIMIZE',
'OPTION',
'OPTIONALLY',
'ORDER',
'OUTFILE',
'OR',
'OUTER',
'ON',
'PROCEEDURE',
'PROCEDURAL',
'PRIMARY',
'READ',
'REFERENCES',
'REGEXP',
'RENAME',
'REPLACE',
'RETURN',
'REVOKE',
'RLIKE',
'RIGHT',
'SHOW',
'SONAME',
'STATUS',
'STRAIGHT_JOIN',
'SELECT',
'SETVAL',
'TABLES',
'TEMINATED',
'TO',
'TRAILING',
'TRUNCATE',
'TABLE',
'TEMPORARY',
'TRIGGER',
'TRUSTED',
'UNIQUE',
'UNLOCK',
'USE',
'USING',
'UPDATE',
'UNSIGNED',
'VALUES',
'VARIABLES',
'VIEW',
'WITH',
'WRITE',
'WHERE',
'ZEROFILL',
'XOR',
'ALL',
'ASC',
'AS',
'SET',
'IN',
'IS',
'IF',
];
$mysql_doc = [
'Feldtypen' => 'http://dev.mysql.com/doc/mysql/de/Column_types.html',
];
$mysql_string_types = [
'char',
'varchar',
'tinytext',
'text',
'mediumtext',
'longtext',
'binary',
'varbinary',
'tinyblob',
'mediumblob',
'blob',
'longblob',
'enum',
'set',
];
$mysql_SQLhasRecords = [
'SELECT',
'SHOW',
'EXPLAIN',
'DESCRIBE',
'DESC',
];
function mod_mysqli_connect($encoding = 'utf8mb4', $keycheck_off = false, $actual_table = '')
{
global $config, $databases;
if (isset($config['dbconnection']) && is_resource($config['dbconnection'])) {
return $config['dbconnection'];
}
$port = (isset($config['dbport']) && !empty($config['dbport'])) ? ':'.$config['dbport'] : '';
$socket = (isset($config['dbsocket']) && !empty($config['dbsocket'])) ? ':'.$config['dbsocket'] : '';
// Forcing error reporting mode to OFF, which is no longer the default
// starting with PHP 8.1
@mysqli_report(MYSQLI_REPORT_OFF);
$config['dbconnection'] = @mysqli_connect($config['dbhost'].$port.$socket, $config['dbuser'], $config['dbpass']);
if (!$config['dbconnection']) {
exit(SQLError('Error establishing a database connection!', mysqli_connect_error()));
}
if (!defined('MOD_MYSQL_VERSION')) {
GetMySQLVersion();
}
if (!isset($config['mysql_standard_character_set']) || '' == $config['mysql_standard_character_set']) {
get_sql_encodings();
}
if ($config['mysql_standard_character_set'] != $encoding) {
$set_encoding = mysqli_query($config['dbconnection'], 'SET NAMES \''.$encoding.'\'');
if (false === $set_encoding) {
$config['mysql_can_change_encoding'] = false;
} else {
$config['mysql_can_change_encoding'] = true;
}
}
if ($keycheck_off) {
// only called with this param when restoring
mysqli_query($config['dbconnection'], 'SET FOREIGN_KEY_CHECKS=0');
// also set SQL-Mode NO_AUTO_VALUE_ON_ZERO for magento users
mysqli_query($config['dbconnection'], 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
}
return $config['dbconnection'];
}
function GetMySQLVersion()
{
global $config;
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
$res = mod_query('SELECT VERSION()');
$row = mysqli_fetch_array($res);
$str = $row[0];
$version = str_replace(':', '--', $str);
if (!defined('MOD_MYSQL_VERSION')) {
define('MOD_MYSQL_VERSION', $version);
}
$versions = explode('.', $version);
$new = false;
if (4 == $versions[0] && $versions[1] >= 1) {
$new = true;
}
if ($versions[0] > 4) {
$new = true;
}
if (!defined('MOD_NEW_VERSION')) {
define('MOD_NEW_VERSION', $new);
}
return $version;
}
function mod_query($query, $error_output = true)
{
global $config;
// print_mem();
if (!isset($config['dbconnection'])) {
mod_mysqli_connect();
}
// echo "<br>Query: ".htmlspecialchars($query).'<br>';
$res = mysqli_query($config['dbconnection'], $query);
// print_mem();
if (false === $res && $error_output) {
SQLError($query, mysqli_error($config['dbconnection']));
}
return $res;
}
function print_mem()
{
/* Currently used memory */
$mem_usage = memory_get_usage();
/* Peak memory usage */
$mem_peak = memory_get_peak_usage();
echo 'The script is now using: <strong>'.round($mem_usage / 1024).' KB</strong> of memory.<br>';
echo 'Peak usage: <strong>'.round($mem_peak / 1024).' KB</strong> of memory.<br><br>';
}
function SQLError($sql, $error, $return_output = false)
{
global $lang;
$ret = '<div align="center"><table style="border:1px solid #ff0000" cellspacing="0">
<tr bgcolor="#ff0000"><td style="color:white;font-size:16px;"><strong>MySQL-ERROR</strong></td></tr>
<tr><td style="width:80%;overflow: auto;">'.$lang['L_SQL_ERROR2'].'<br><span style="color:red;">'.$error.'</span></td></tr>
<tr><td width="600"><br>'.$lang['L_SQL_ERROR1'].'<br>'.Highlight_SQL($sql).'</td></tr>
</table></div><br />';
if ($return_output) {
return $ret;
} else {
echo $ret;
}
}
function Highlight_SQL($sql)
{
global $sql_keywords;
$end = '';
$tickstart = false;
if (function_exists('token_get_all')) {
$a = @token_get_all("<?php $sql?>");
} else {
return $sql;
}
foreach ($a as $token) {
if (!is_array($token)) {
if ('`' == $token) {
$tickstart = !$tickstart;
}
$end .= $token;
} else {
if ($tickstart) {
$end .= $token[1];
} else {
switch (token_name($token[0])) {
case 'T_STRING':
case 'T_AS':
case 'T_FOR':
$end .= (in_array(strtoupper($token[1]), $sql_keywords)) ? '<span style="color:#990099;font-weight:bold;">'.$token[1].'</span>' : $token[1];
break;
case 'T_IF':
case 'T_LOGICAL_AND':
case 'T_LOGICAL_OR':
case 'T_LOGICAL_XOR':
$end .= (in_array(strtoupper($token[1]), $sql_keywords)) ? '<span style="color:#0000ff;font-weight:bold;">'.$token[1].'</span>' : $token[1];
break;
case 'T_CLOSE_TAG':
case 'T_OPEN_TAG':
break;
default:
$end .= $token[1];
}
}
}
}
$end = preg_replace('/`(.*?)`/si', '<span style="color:red;">`$1`</span>', $end);
return $end;
}
function Fieldlist($db, $tbl)
{
$fl = '';
$res = mod_query("SHOW FIELDS FROM `$db`.`$tbl`;");
if ($res) {
$fl = '(';
for ($i = 0; $i < mysqli_num_rows($res); ++$i) {
$row = mysqli_fetch_row($res);
$fl .= '`'.$row[0].'`,';
}
$fl = substr($fl, 0, strlen($fl) - 1).')';
}
return $fl;
}
// reads all Tableinfos and place them in $dump-Array
function getDBInfos()
{
global $databases, $dump, $config, $tbl_sel, $flipped;
for ($ii = 0; $ii < count($databases['multi']); ++$ii) {
$dump['dbindex'] = $flipped[$databases['multi'][$ii]];
$tabellen = mysqli_query($config['dbconnection'], 'SHOW TABLE STATUS FROM `'.$databases['Name'][$dump['dbindex']].'`') or exit('getDBInfos: '.mysqli_error($config['dbconnection']));
$num_tables = mysqli_num_rows($tabellen);
// Array mit den gewünschten Tabellen zusammenstellen... wenn Präfix angegeben, werden die anderen einfach nicht übernommen
if ($num_tables > 0) {
for ($i = 0; $i < $num_tables; ++$i) {
$row = mysqli_fetch_array($tabellen);
if (isset($row['Type'])) {
$row['Engine'] = $row['Type'];
}
if (isset($row['Comment']) && 'VIEW' == substr(strtoupper($row['Comment']), 0, 4)) {
$dump['table_types'][] = 'VIEW';
} else {
$dump['table_types'][] = strtoupper($row['Engine']);
}
// check if data needs to be backed up
if ('VIEW' == strtoupper($row['Comment']) || (isset($row['Engine']) && in_array(strtoupper($row['Engine']), [
'MEMORY',
]))) {
$dump['skip_data'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Name'];
}
if ((isset($config['optimize_tables_beforedump']) && (1 == $config['optimize_tables_beforedump'])) && -1 == $dump['table_offset']
&& 'information_schema' != $databases['Name'][$dump['dbindex']]) {
mysqli_select_db($config['dbconnection'], $databases['Name'][$dump['dbindex']]);
$opt = 'OPTIMIZE TABLE `'.$row['Name'].'`';
$res = mysqli_query($config['dbconnection'], 'OPTIMIZE TABLE `'.$row['Name'].'`');
if (false === $res) {
exit('Error in '.$opt.' -> '.mysqli_error($config['dbconnection']));
}
}
if (isset($tbl_sel)) {
if (in_array($row['Name'], $dump['tblArray'])) {
$dump['tables'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Name'];
$dump['records'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Rows'];
$dump['totalrecords'] += $row['Rows'];
}
} elseif ('' != $databases['praefix'][$dump['dbindex']] && !isset($tbl_sel)) {
if (substr($row['Name'], 0, strlen($databases['praefix'][$dump['dbindex']])) == $databases['praefix'][$dump['dbindex']]) {
$dump['tables'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Name'];
$dump['records'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Rows'];
$dump['totalrecords'] += $row['Rows'];
}
} else {
$dump['tables'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Name'];
$dump['records'][] = $databases['Name'][$dump['dbindex']].'|'.$row['Rows'];
// Get nr of records -> need to do it this way because of incorrect returns when using InnoDBs
$sql_2 = 'SELECT count(*) as `count_records` FROM `'.$databases['Name'][$dump['dbindex']].'`.`'.$row['Name'].'`';
$res2 = mysqli_query($config['dbconnection'], $sql_2);
if (false === $res2) {
$read_error = mysqli_error($config['dbconnection']);
SQLError($read_error, $sql_2);
WriteLog($read_error);
if ($config['stop_with_error'] > 0) {
exit($read_error);
}
} else {
$row2 = mysqli_fetch_array($res2);
$row['Rows'] = $row2['count_records'];
$dump['totalrecords'] += $row['Rows'];
}
}
}
// Correct total number of records; substract skipped data
foreach ($dump['skip_data'] as $skip_data) {
$index = false;
$records_to_skip = 0;
//find index of table to get the nr of records
$count = sizeof($dump['tables']);
for ($a = 0; $a < $count; ++$a) {
if ($dump['tables'][$a] == $skip_data) {
$index = $a;
$t = explode('|', $dump['records'][$a]);
$rekords_to_skip = $t[1];
break;
}
}
if ($index) {
$dump['totalrecords'] -= intval($rekords_to_skip);
}
}
}
}
}
// gets the numeric index in dump-array and returns it
function getDBIndex($db, $table)
{
global $dump;
$index = array_keys($dump['tables'], $db.'|'.$table);
return $index[0];
}

150
msd/inc/runtime.php Normal file
View File

@ -0,0 +1,150 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
error_reporting(E_ALL);
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set(@date_default_timezone_get());
}
//Konstanten
if (!defined('MOD_VERSION')) {
define('MOD_VERSION', '5.0.20');
}
if (!defined('MOD_OS')) {
define('MOD_OS', PHP_OS);
}
if (!defined('MOD_OS_EXT')) {
define('MOD_OS_EXT', @php_uname());
}
if (!defined('config') || !is_array($config)) {
$config = [];
}
if (!defined('databases') || !is_array($databases)) {
$databases = [];
}
//Pfade und Files
$config['paths']['root'] = Realpfad('./');
$config['paths']['work'] = 'work/';
$config['paths']['backup'] = $config['paths']['work'].'backup/';
$config['paths']['log'] = $config['paths']['work'].'log/';
$config['paths']['config'] = $config['paths']['work'].'config/';
$config['paths']['temp'] = $config['paths']['root'].$config['paths']['work'].'temp/';
$config['paths']['cache'] = $config['paths']['root'].$config['paths']['work'].'cache/';
$config['paths']['perlexec'] = 'mod_cron/';
if (isset($_SESSION['config_file'])) {
$config['config_file'] = $_SESSION['config_file'];
$config['cron_configurationfile'] = $_SESSION['config_file'];
} else {
$config['config_file'] = 'myoosdumper';
$_SESSION['config_file'] = 'myoosdumper';
$config['cron_configurationfile'] = 'myoosdumper.conf.php';
}
$config['files']['log'] = $config['paths']['log'].'myoosdumper.log';
$config['files']['perllog'] = $config['paths']['log'].'myoosdumper_perl.log';
$config['files']['perllogcomplete'] = $config['paths']['log'].'myoosdumper_perl.complete.log';
$config['files']['parameter'] = $config['paths']['config'].$config['config_file'].'.php';
// inti MySQL-Setting-Vars
$config['mysql_standard_character_set'] = '';
$config['mysql_possible_character_sets'] = [];
//Ini-Parameter
$config['max_execution_time'] = get_cfg_var('max_execution_time');
$config['max_execution_time'] = ($config['max_execution_time'] <= 0) ? 30 : $config['max_execution_time'];
if ($config['max_execution_time'] > 30) {
$config['max_execution_time'] = 30;
}
$config['upload_max_filesize'] = get_cfg_var('upload_max_filesize');
$config['disabled'] = get_cfg_var('disable_functions');
$config['phpextensions'] = implode(', ', get_loaded_extensions());
$m = trim(str_replace('M', '', ini_get('memory_limit')));
// fallback if ini_get doesn't work
if (0 == intval($m)) {
$m = trim(str_replace('M', '', get_cfg_var('memory_limit')));
}
$config['php_ram'] = $m;
//Ist zlib moeglich?
$p1 = explode(', ', $config['phpextensions']);
$p2 = explode(',', str_replace(' ', '', $config['disabled']));
$config['zlib'] = (in_array('zlib', $p1) && (!in_array('gzopen', $p2) || !in_array('gzwrite', $p2) || !in_array('gzgets', $p2) || !in_array('gzseek', $p2) || !in_array('gztell', $p2)));
//Tuning-Ecke
$config['tuning_add'] = 1.1;
$config['tuning_sub'] = 0.9;
$config['time_buffer'] = 0.75; //max_zeit= $config['max_execution_time']*$config['time_buffer']
$config['perlspeed'] = 10000; //Anzahl der Datensaetze, die in einem Rutsch gelesen werden
$config['ignore_enable_keys'] = 0;
//Bausteine
$config['homepage'] = 'http://foren.myoos.de/viewforum.php?f=40';
$nl = "\n";
$mysql_commentstring = '--';
//config-Variablen, die nicht gesichert werden sollen
$config_dontsave = [
'homepage',
'max_execution_time',
'disabled',
'phpextensions',
'php_ram',
'zlib',
'tuning_add',
'tuning_sub',
'time_buffer',
'perlspeed',
'cron_configurationfile',
'dbconnection',
'version',
'mysql_possible_character_sets',
'mysql_standard_character_set',
'config_file',
'upload_max_filesize',
'mysql_can_change_encoding',
'cron_samedb',
'paths',
'files',
];
$dontBackupDatabases = ['mysql', 'information_schema'];
// Automatisches entfernen von Slashes und Leerzeichen vorn und hinten abschneiden
$_POST = trim_deep($_POST);
$_GET = trim_deep($_GET);
function v($t)
{
echo '<br>';
if (is_array($t) || is_object($t)) {
echo '<pre>';
print_r($t);
echo '</pre>';
} else {
echo $t;
}
}
function getServerProtocol()
{
return (isset($_SERVER['HTTPS']) && 'on' == strtolower($_SERVER['HTTPS'])) ? 'https://' : 'http://';
}

View File

@ -0,0 +1,290 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
include './inc/functions_imexport.php';
//Im-/Export
$import = (isset($_GET['import'])) ? 1 : 0;
if (1 == $import) {
//IMPORT
CheckcsvOptions();
if (isset($_POST['f_import_csvtrenn'])) {
$sql['import']['trenn'] = $_POST['f_import_csvtrenn'];
}
if (isset($_POST['f_import_csvenc'])) {
$sql['import']['enc'] = $_POST['f_import_csvenc'];
}
if (isset($_POST['f_import_csvesc'])) {
$sql['import']['esc'] = $_POST['f_import_csvesc'];
}
if (empty($sql['import']['endline'])) {
$sql['import']['endline'] = $nl;
} else {
$sql['import']['endline'] = str_replace('\\r', "\015", $sql['import']['endline']);
$sql['import']['endline'] = str_replace('\\n', "\012", $sql['import']['endline']);
$sql['import']['endline'] = str_replace('\\t', "\011", $sql['import']['endline']);
}
$sql['import']['endline'] = str_replace('\\t', "\011", $sql['import']['endline']);
if (isset($_POST['f_import_csvnull'])) {
$sql['import']['null'] = $_POST['f_import_csvnull'];
}
$sql['import']['namefirstline'] = (isset($_POST['f_import_namefirstline'])) ? $_POST['f_import_namefirstline'] : 0;
$sql['import']['emptydb'] = (isset($_POST['import_emptydb'])) ? 1 : 0;
$sql['import']['createindex'] = (isset($_POST['import_createindex'])) ? 1 : 0;
$sql['import']['table'] = (isset($_POST['import_table'])) ? $_POST['import_table'] : '';
$sql['import']['import_source'] = isset($_POST['import_source']) ? $_POST['import_source'] : 0;
$sql['import']['text'] = isset($_POST['import_text']) ? $_POST['import_text'] : '';
$sql['import']['csv'] = '';
if (isset($_POST['do_import'])) {
$sql['import']['tablecreate'] = 0;
if ('new' == $sql['import']['table']) {
$sql['import']['table'] = 'import_';
$sql['import']['tablecreate'] = 1;
}
if ('' == $sql['import']['table']) {
$aus .= '<span class="error">'.$lang['L_IMPORT_NOTABLE'].'</span>';
} else {
if (0 == $_POST['import_source']) {
//Import aus textbox
$sql['import']['csv'] = explode($sql['import']['endline'], $sql['import']['text']);
} else {
if (!isset($_FILES['upfile']['name']) || empty($_FILES['upfile']['name'])) {
$aus .= '<span class="error">'.$lang['L_FM_UPLOADFILEREQUEST'].'</span>';
} else {
$fn = $_FILES['upfile']['tmp_name'];
$sql['import']['csv'] = ('.gz' == substr($_FILES['upfile']['name'], -3)) ? gzfile($fn) : file($fn);
$sql['import']['text'] = implode('', $sql['import']['csv']);
$aus .= '<span>'.$lang['L_SQL_UPLOADEDFILE'].'<strong>'.$_FILES['upfile']['name'].'</strong>&nbsp;&nbsp;&nbsp;'.byte_output(filesize($_FILES['upfile']['tmp_name'])).'</span>';
}
}
if (is_array($sql['import']['csv'])) {
$aus .= DoImport();
} else {
$aus .= '<br><span class="error">'.$lang['L_CSV_NODATA'].'</span>';
}
}
}
$impaus = $aus;
$impaus .= '<form action="sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;context=4&amp;import=1" method="post" enctype="multipart/form-data">'.$nl;
$impaus .= '';
$impaus .= '<a href="sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;context=4">'.$lang['L_EXPORT'].'</a>';
$impaus .= '<h6>'.sprintf($lang['L_SQL_IMPORT'], $databases['Name'][$dbid]).'</h6>';
$impaus .= '<table class="bordersmall"><tr class="thead"><th>'.$nl;
$impaus .= $lang['L_IMPORTOPTIONS'].'</th><th>'.$lang['L_CSVOPTIONS'].'</th></tr>'.$nl;
$impaus .= '<tr><td valign="top">'.$nl;
$impaus .= '<table cellpadding="0" cellspacing="0">'.$nl;
$impaus .= '<tr><td>'.$lang['L_IMPORTTABLE'].'</td><td><select name="import_table">'.TableComboBox($sql['import']['table']).'<option value="new" '.(('import_' == $sql['import']['table']) ? ' selected="selected"' : '').'>== '.$lang['L_NEWTABLE'].' ==</option></select></td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_IMPORTSOURCE'].'</td>'.$nl;
$impaus .= '<td><input type="radio" class="radio" name="import_source" value="0" '.((0 == $sql['import']['import_source']) ? 'checked' : '').' onclick="check_csvdivs(1); return true">'.$lang['L_FROMTEXTBOX'].'<br>'.$nl;
$impaus .= '<input type="radio" class="radio" id="radio_csv0" name="import_source" value="1" '.((1 == $sql['import']['import_source']) ? 'checked' : '').' onclick="check_csvdivs(1); return true">'.$lang['L_FROMFILE'].'</td></tr>'.$nl;
$impaus .= '<tr><td colspan="2"><input type="checkbox" class="checkbox" name="import_emptydb" value="1" '.((1 == $sql['import']['emptydb']) ? 'checked' : '').'>'.$lang['L_EMPTYTABLEBEFORE'].'</td></tr>'.$nl;
$impaus .= '<tr><td colspan="2"><input type="checkbox" class="checkbox" name="import_createindex" value="1" '.((1 == $sql['import']['createindex']) ? 'checked' : '').'>'.$lang['L_CREATEAUTOINDEX'].'</td></tr>'.$nl;
$impaus .= '</table>'.$nl;
$impaus .= '</td><td valign="top">'.$nl;
$impaus .= '<table cellpadding="0" cellspacing="0">'.$nl;
$impaus .= '<tr><td colspan="2"><input type="checkbox" class="checkbox" name="f_import_namefirstline0" value="1" '.((1 == $sql['import']['namefirstline']) ? 'checked' : '').'>'.$lang['L_CSV_NAMEFIRSTLINE'].'</td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_CSV_FIELDSEPERATE'].'</td><td><input type="text" class="text" name="f_import_csvtrenn" size="4" maxlength="12" value="'.$sql['import']['trenn'].'"></td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_CSV_FIELDSENCLOSED'].'</td><td><input type="text" class="text" name="f_import_csvenc" size="4" maxlength="12" value="'.htmlspecialchars($sql['import']['enc']).'"></td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_CSV_FIELDSESCAPE'].'</td><td><input type="text" class="text" name="f_import_csvesc" size="4" maxlength="12" value="'.$sql['import']['esc'].'"></td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_CSV_EOL'].'</td><td><input type="text" class="text" name="f_import_csvztrenn" size="4" maxlength="12" value="'.$sql['import']['ztrenn'].'"></td></tr>'.$nl;
$impaus .= '<tr><td>'.$lang['L_CSV_NULL'].'</td><td><input type="text" class="text" name="f_import_csvnull" size="4" maxlength="12" value="'.$sql['import']['null'].'"></td></tr>'.$nl;
$impaus .= '</table>'.$nl;
$impaus .= '</td></tr>';
$impaus .= '<tr><td colspan="2"><div id="csv0">'.$lang['L_CSV_FILEOPEN'].':&nbsp;&nbsp;
<input type="file" name="upfile" accept="application/gzip">';
$impaus .= '<input type="hidden" name="MAX_FILE_SIZE" VALUE="2500000"></div></td></tr>';
$impaus .= '<tr><td colspan="2" align="right"><input class="Formbutton" type="submit" name="do_import" value=" '.$lang['L_IMPORTIEREN'].' "></td></tr>';
$impaus .= '</table>'.$nl;
$impaus .= '<p>&nbsp;</p>'.$lang['L_IMPORT'].':<br><textarea name="import_text" wrap="OFF" style="width:760px;height:400px;font-size=11px;">';
//$impaus.= $sql['import']['text'];
$impaus .= '</textarea></form>'.$nl;
$impaus .= '<script>check_csvdivs(1);</script>'.$nl;
echo $impaus.$nl;
} else {
//EXPORT
$tables = 0;
$tblstr = '';
$sql['export']['db'] = $db;
if (isset($_POST['f_export_submit'])) {
//echo '<pre>'.print_r($_POST,true).'</pre><hr>';
$sql['export']['header_sent'] = '';
$sql['export']['lines'] = 0;
$sql['export']['format'] = $_POST['f_export_format'];
$sql['export']['ztrenn'] = $_POST['f_export_csvztrenn'];
$sql['endline']['ztrenn'] = $sql['export']['ztrenn'];
if (0 == $sql['export']['format']) {
//CSV
$format = 0;
$sql['export']['trenn'] = $_POST['f_export_csvtrenn'];
$sql['export']['enc'] = $_POST['f_export_csvenc'];
$sql['export']['esc'] = $_POST['f_export_csvesc'];
if (empty($sql['export']['endline'])) {
$sql['export']['endline'] = $nl;
} else {
$sql['export']['endline'] = str_replace('\\r', "\015", $sql['export']['endline']);
$sql['export']['endline'] = str_replace('\\n', "\012", $sql['export']['endline']);
$sql['export']['endline'] = str_replace('\\t', "\011", $sql['export']['endline']);
}
$sql['export']['endline'] = str_replace('\\t', "\011", $sql['export']['endline']);
} elseif (1 == $sql['export']['format']) {
//EXCEL
$format = 1;
$sql['export']['trenn'] = ',';
$sql['export']['enc'] = '"';
$sql['export']['esc'] = '"';
$sql['export']['endline'] = "\015\012";
} elseif (3 == $sql['export']['format']) {
//EXCEL 2003
$format = 1;
$sql['export']['trenn'] = ';';
$sql['export']['enc'] = '"';
$sql['export']['esc'] = '"';
$sql['export']['endline'] = "\015\012";
} elseif (4 == $sql['export']['format']) {
//XML
$format = 4;
CheckcsvOptions();
} elseif (5 == $sql['export']['format']) {
//HTML
$format = 5;
CheckcsvOptions();
}
if ($format < 3) {
$sql['export']['null'] = $_POST['f_export_csvnull'.$format];
}
$sql['export']['namefirstline'] = (isset($_POST['f_export_namefirstline'.$format])) ? $_POST['f_export_namefirstline'.$format] : 0;
$sql['export']['sendfile'] = $_POST['f_export_sendresult'];
$sql['export']['compressed'] = (isset($_POST['f_export_compressed'])) ? $_POST['f_export_compressed'] : 0;
$sql['export']['exportfile'] = '';
$sql['export']['xmlstructure'] = (isset($_POST['f_export_xmlstructure'])) ? $_POST['f_export_xmlstructure'] : 0;
$sql['export']['htmlstructure'] = (isset($_POST['f_export_htmlstructure'])) ? $_POST['f_export_htmlstructure'] : 0;
//ausgewählte Tabellen
if (isset($_POST['f_export_tables'])) {
$sql['export']['tables'] = $_POST['f_export_tables'];
}
} else {
CheckcsvOptions();
}
//Tabellenliste
$sqlt = "SHOW TABLE STATUS FROM `$db`";
$res = mod_query($sqlt);
if ($res) {
$sql['export']['tablecount'] = mysqli_num_rows($res);
$sql['export']['recordcount'] = 0;
for ($i = 0; $i < $sql['export']['tablecount']; ++$i) {
$row = mysqli_fetch_array($res);
$tblstr .= '<option value="'.$row['Name'].'" '.((isset($sql['export']['tables']) && in_array($row['Name'], $sql['export']['tables'])) ? ' selected="selected"' : '').'>'.$row['Name'].' ('.$row['Rows'].')</option>'."\n";
$sql['export']['recordcount'] += $row['Rows'];
}
}
$exaus = $aus.'<h4>'.sprintf($lang['L_SQL_EXPORT'], $databases['Name'][$dbid]).'</h4>';
$exaus .= '<form action="sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;context=4" method="post">'.$nl;
$exaus .= '<a href="sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;context=4&amp;import=1">'.$lang['L_IMPORT'].'</a>';
$exaus .= '<h6>'.sprintf($lang['L_SQL_EXPORT'], $databases['Name'][$dbid]).'</h6>';
$exaus .= '<table class="bdr"><tr class="thead"><th>'.$lang['L_TABLES'].'</th>'.$nl;
$exaus .= '<th>'.$lang['L_EXPORTOPTIONS'].'</th>';
$exaus .= '<th>'.$lang['L_EXPORT'].'</th></tr><tr>';
$exaus .= '';
$exaus .= '<td><span class="ssmall"><strong>'.$sql['export']['tablecount'].'</strong> '.$lang['L_TABLES'].', <strong>'.$sql['export']['recordcount'].'</strong> '.$lang['L_RECORDS'].'</span>';
$exaus .= '&nbsp;&nbsp;&nbsp;<a class="ssmall" href="#" onclick="SelectTableList(true);">'.$lang['L_ALL'].'</a>&nbsp;&nbsp;<a class="ssmall" href="#" onclick="SelectTableList(false);">'.$lang['L_NONE'].'</a>'.$nl;
$exaus .= '<br><select name="f_export_tables[]" size="12" multiple>'.$tblstr.'</select><br>'.$nl;
$exaus .= '</td><td>'.$nl;
$exaus .= ''.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_format" id="radio_csv0" value="0" '.((0 == $sql['export']['format']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.'CSV'.'&nbsp;&nbsp;&nbsp;'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_format" id="radio_csv1" value="1" '.((1 == $sql['export']['format']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.'Excel'.'&nbsp;&nbsp;&nbsp;'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_format" id="radio_csv2" value="3" '.((3 == $sql['export']['format']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.$lang['L_EXCEL2003'].'<br>'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_format" id="radio_csv4" value="4" '.((4 == $sql['export']['format']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.'XML'.'&nbsp;&nbsp;&nbsp;'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_format" id="radio_csv5" value="5" '.((5 == $sql['export']['format']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.'HTML'.'<br><br>'.$nl;
$exaus .= '<div id="csv0"><fieldset><legend>CSV-Optionen</legend><table cellpadding="0" cellspacing="0"><tr><td colspan="2">'.$nl;
$exaus .= '<input type="checkbox" class="checkbox" name="f_export_namefirstline0" value="1" '.((1 == $sql['export']['namefirstline']) ? 'checked' : '').'>'.$lang['L_CSV_NAMEFIRSTLINE'].'</td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_FIELDSEPERATE'].'</td><td><input type="text" class="text" name="f_export_csvtrenn" size="4" maxlength="12" value="'.$sql['export']['trenn'].'"></td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_FIELDSENCLOSED'].'</td><td><input type="text" class="text" name="f_export_csvenc" size="4" maxlength="12" value="'.htmlspecialchars($sql['export']['enc']).'"></td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_FIELDSESCAPE'].'</td><td><input type="text" class="text" name="f_export_csvesc" size="4" maxlength="12" value="'.$sql['export']['esc'].'"></td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_EOL'].'</td><td><input type="text" class="text" name="f_export_csvztrenn" size="4" maxlength="12" value="'.$sql['export']['ztrenn'].'"></td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_NULL'].'</td><td><input type="text" class="text" name="f_export_csvnull0" size="4" maxlength="12" value="'.$sql['export']['null'].'"></td></tr>'.$nl;
$exaus .= '</table></fieldset></div>'.$nl;
$exaus .= '<div id="csv1"><fieldset><legend>Excel-Optionen</legend><table cellpadding="0" cellspacing="0"><tr><td colspan="2">';
$exaus .= '<input type="checkbox" class="checkbox" name="f_export_namefirstline1" value="1"'.((1 == $sql['export']['namefirstline']) ? 'checked' : '').'>'.$lang['L_CSV_NAMEFIRSTLINE'].'</td></tr>'.$nl;
$exaus .= '<tr><td>'.$lang['L_CSV_NULL'].'</td><td><input type="text" class="text" name="f_export_csvnull1" size="4" maxlength="12" value="'.$sql['export']['null'].'"></td></tr>'.$nl;
$exaus .= '</table></fieldset></div>'.$nl;
$exaus .= '<div id="csv4"><fieldset><legend>XML-Optionen</legend><table>';
$exaus .= '<tr><td><input type="checkbox" name="f_export_xmlstructure" value="1" class="checkbox" '.((1 == $sql['export']['xmlstructure']) ? 'checked' : '').'> mit Struktur</td></tr>';
$exaus .= '</table></fieldset></div>'.$nl;
$exaus .= '<div id="csv5"><fieldset><legend>HTML-Optionen</legend><table>';
$exaus .= '<tr><td><input type="checkbox" name="f_export_htmlstructure" value="1" class="checkbox" '.((1 == $sql['export']['htmlstructure']) ? 'checked' : '').'> mit Struktur</td></tr>';
$exaus .= '</table></fieldset></div>'.$nl;
$exaus .= '</td><td>'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_sendresult" value="0" '.((0 == $sql['export']['sendfile']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.$lang['L_SHOWRESULT'].'<br>'.$nl;
$exaus .= '<input type="radio" class="radio" name="f_export_sendresult" id="radio_csv3" value="1" '.((1 == $sql['export']['sendfile']) ? 'checked' : '').' onclick="check_csvdivs(0); return true">'.$lang['L_SENDRESULTASFILE'].'<br>'.$nl;
$exaus .= '<div id="csv3"><input type="checkbox" class="checkbox" name="f_export_compressed" value="1" '.((1 == $sql['export']['compressed']) ? 'checked' : '').'>'.$lang['L_COMPRESSED'].'</div><br>'.$nl;
$exaus .= '<img src="'.$icon['blank'].'" width="60" height="130" border="0"><br><input class="Formbutton" type="submit" name="f_export_submit" value="'.$lang['L_EXPORT'].'" onclick="if(SelectedTableCount()==0) {alert(msg1);return false;}">'.$nl;
$exaus .= '</td></tr></table></form>'.$nl;
$exaus .= '<script>check_csvdivs(0);</script>'.$nl;
if (!$download) {
echo $exaus.$nl;
}
if (isset($_POST['f_export_submit']) && isset($sql['export']['tables'])) {
if (!$download) {
echo '<br><br><table width="90%"><tr><td>'.$lang['L_EXPORT'].':</td><td align="right"><a href="javascript:BrowseInput(\'imexta\');">zeige in neuem Fenster</a></td></tr></table><textarea id="imexta" wrap="OFF" style="width:760px;height:400px;font-size=11px;">'.$nl;
}
if ($format < 3) {
ExportCSV();
} elseif (4 == $format) {
ExportXML();
} elseif (5 == $format) {
ExportHTML();
}
if (!$download) {
echo '</textarea><br>'.$nl;
echo '<span style="color:blue;">'.$lang['L_EXPORTFINISHED'].'</span>&nbsp;&nbsp;'.sprintf($lang['L_EXPORTLINES'], $sql['export']['lines']).$nl;
} else {
exit();
}
}
}

197
msd/inc/sql_tools.php Normal file
View File

@ -0,0 +1,197 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
get_sql_encodings();
//Datenbanken
if (isset($_GET['dbrefresh'])) {
SetDefault();
}
echo $aus.'<h4>'.$lang['L_TOOLS'].'</h4>';
if (isset($_POST['dbdosubmit'])) {
$newname = $_POST['newname'];
$db_index = $_POST['db_index'];
$db_action = $_POST['db_action'];
$changed = false;
$ausgabe = $out = '';
switch ($db_action) {
case 'drop':
if (MOD_DoSQL('DROP DATABASE `'.$databases['Name'][$db_index].'`')) {
echo SQLOutput($out, '<p class="success">'.$lang['L_DB'].' `'.$databases['Name'][$db_index].'` '.$lang['L_SQL_DELETED'].'</p>');
$changed = true;
}
break;
case 'empty':
EmptyDB($databases['Name'][$db_index]);
echo SQLOutput($out, '<p class="success">'.$lang['L_DB'].' `'.$databases['Name'][$db_index].'` '.$lang['L_SQL_WASEMPTIED'].'.</p>');
break;
case 'rename':
$dbold = $databases['Name'][$db_index];
if (DB_Copy($dbold, $newname, 1)) {
echo SQLOutput($out, '<p class="success">'.$lang['L_DB'].' `'.$dbold.'` '.$lang['L_SQL_RENAMEDTO'].' `'.$newname.'`.</p>');
$changed = true;
}
break;
case 'copy':
$dbold = $databases['Name'][$db_index];
if (DB_Copy($dbold, $newname)) {
$changed = true;
echo SQLOutput($out, '<p class="success">'.sprintf($lang['L_SQL_DBCOPY'], $dbold, $newname).'</p>');
}
break;
case 'structure':
if (DB_Copy($databases['Name'][$db_index], $newname, 0, 0)) {
$changed = true;
echo SQLOutput($out, '<p class="success">'.sprintf($lang['L_SQL_DBSCOPY'], $databases['Name'][$db_index], $newname).'</p>');
}
break;
case 'rights':
break;
}
if (true == $changed) {
SetDefault();
include $config['files']['parameter'];
echo '<script>parent.MyOOS_Dumper_menu.location.href="menu.php?action=dbrefresh";</script>';
}
}
if (isset($_POST['dbwantaction'])) {
if (isset($_POST['db_createnew'])) {
$newname = trim($_POST['db_create']);
if (!empty($newname)) {
$sqlc = "CREATE DATABASE `$newname`";
$col = (MOD_NEW_VERSION) ? $_POST['db_collate'] : '';
if (isset($_POST['db_default_charset']) && intval(substr(MOD_NEW_VERSION, 0, 1)) > 3) {
$db_default_charset_string = $config['mysql_possible_character_sets'][$_POST['db_default_charset']];
$db_default_charset = explode(' ', $db_default_charset_string);
if (isset($db_default_charset[0])) {
$sqlc .= ' DEFAULT CHARACTER SET `'.$db_default_charset[0].'`';
}
}
$db_default_collation = @explode('|', $col);
if (isset($db_default_collation[1])) {
$sqlc .= ' COLLATE `'.$db_default_collation[1].'`';
}
if (mod_query($sqlc)) {
echo $lang['L_DB']." `$newname` ".$lang['L_SQL_WASCREATED'].'.<br>';
SetDefault();
include $config['files']['parameter'];
echo '<script>parent.MyOOS_Dumper_menu.location.href="menu.php?action=dbrefresh";</script>';
}
}
}
$db_action = $newname = '';
$db_index = -1;
for ($i = 0; $i < count($databases['Name']); ++$i) {
if (isset($_POST['db_do_'.$i])) {
$newname = $_POST['db_rename'.$i];
$db_index = $i;
$db_action = $_POST['db_do_action_'.$i];
break;
}
}
if ('' != $db_action) {
echo '<div><div align="left" id="sqleditbox">';
echo '<form action="sql.php?context=3" method="post">
<input type="hidden" name="db_action" value="'.$db_action.'">
<input type="hidden" name="newname" value="'.$newname.'">
<input type="hidden" name="db_index" value="'.$db_index.'">';
switch ($db_action) {
case 'drop':
echo '<strong>'.sprintf($lang['L_ASKDBDELETE'], $databases['Name'][$i]).'</strong><br><br>';
echo '<input type="submit" name="dbdosubmit" value="'.$lang['L_DO_NOW'].'" class="Formbutton">';
break;
case 'empty':
echo '<strong>'.sprintf($lang['L_ASKDBEMPTY'], $databases['Name'][$i]).'</strong><br><br>';
echo '<input type="submit" name="dbdosubmit" value="'.$lang['L_DO_NOW'].'" class="Formbutton">';
break;
case 'rename':
echo '<strong>'.$lang['L_SQL_RENAMEDB'].' `'.$databases['Name'][$db_index].'` '.$lang['L_IN'].' `'.$newname.'`</strong><br><br>';
if ('' == $newname) {
echo '<p class="error">'.$lang['L_SQL_NAMEDEST_MISSING'].'</p>';
} else {
echo '<input type="submit" name="dbdosubmit" value="'.$lang['L_DO_NOW'].'" class="Formbutton">';
}
break;
case 'copy':
echo '<strong>'.sprintf($lang['L_ASKDBCOPY'], $databases['Name'][$db_index], $newname).'</strong><br><br>';
if ('' == $newname) {
echo '<p class="error">'.$lang['L_SQL_NAMEDEST_MISSING'].'</p>';
} else {
echo '<input type="submit" name="dbdosubmit" value="'.$lang['L_DO_NOW'].'" class="Formbutton">';
}
break;
case 'structure':
echo '<strong>'.$lang['L_FM_ASKDBCOPY1'].'`'.$databases['Name'][$db_index].'`'.$lang['L_FM_ASKDBCOPY2'].'`'.$newname.'`'.$lang['L_FM_ASKDBCOPY3'].'</strong><br><br>';
if ('' == $newname) {
echo '<p class="error">'.$lang['L_SQL_NAMEDEST_MISSING'].'</p>';
} else {
echo '<input type="submit" name="dbdosubmit" value="'.$lang['L_DO_NOW'].'" class="Formbutton">';
}
break;
case 'rights':
break;
}
echo '</form></div></div><br>';
}
}
echo '<br><form action="sql.php?context=3" method="post"><input type="hidden" name="dbwantaction" value="1">';
echo '<div><table class="bdr">';
echo '<tr><td colspan="2" align="center"><strong>'.$lang['L_CREATE_DATABASE'].'</strong></td></tr>';
echo '<tr><td>Name:</td><td><input type="text" class="text" name="db_create" size="20"></td></tr>';
echo '<tr><td>'.$lang['L_DEFAULT_CHARSET'].':</td><td><select name="db_default_charset">';
echo make_options($config['mysql_possible_character_sets'], get_index($config['mysql_possible_character_sets'], $config['mysql_standard_character_set']));
echo '</select></td></tr>';
echo '<tr><td>'.$lang['L_COLLATION'].'</td><td><select name="db_collate">'.CollationCombo('', 1).'</select></td></tr>';
echo '<tr><td colspan="2"><input type="submit" name="db_createnew" value="'.$lang['L_CREATE'].'" class="Formbutton"></td></tr>';
echo '</table>';
echo '<br><table class="bdr">';
echo '<tr class="thead"><th>'.$lang['L_DBS'].'</th><th>'.$lang['L_SQL_ACTIONS'].'</th></tr>';
for ($i = 0; $i < count($databases['Name']); ++$i) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
echo ($i == $databases['db_selected_index']) ? '<tr class="dbrowsel">' : '<tr class="'.$cl.'">';
echo '<td><a href="sql.php?db='.$databases['Name'][$i].'&amp;dbid='.$i.'">'.$databases['Name'][$i].'</a></td>';
echo '<td nowrap="nowrap"><input type="text" class="text" name="db_rename'.$i.'" size="20">';
echo '&nbsp;&nbsp;<select name="db_do_action_'.$i.'" onchange="db_do_'.$i.'.disabled=false;">';
echo '<option value="">-- '.$lang['L_SQL_CHOOSEACTION'].' --</option>';
echo '<option value="drop">'.$lang['L_SQL_DELETEDB'].'</option>';
echo '<option value="empty">'.$lang['L_SQL_EMPTYDB'].'</option>';
if (MOD_NEW_VERSION) {
echo '<option value="rename">'.$lang['L_SQL_RENAMEDB'].'</option>';
}
if (MOD_NEW_VERSION) {
echo '<option value="copy">'.$lang['L_SQL_COPYDATADB'].'</option>';
}
echo '<option value="structure">'.$lang['L_SQL_COPYSDB'].'</option>';
echo '</select>';
echo "\n\n".'&nbsp;&nbsp;<input type="submit" name="db_do_'.$i.'" value="'.$lang['L_DO'].'" disabled="disabled" class="Formbutton">';
echo '&nbsp;&nbsp;<input type="Button" value="'.$lang['L_SQL_IMEXPORT'].'" onclick="location.href=\'sql.php?db='.$databases['Name'][$i].'&amp;dbid='.$i.'&amp;context=4\'" class="Formbutton"></td></tr>';
}
echo '</table></div></form>';

View File

@ -0,0 +1,387 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
// get all tables of the current database and build access array
$sql = 'SHOW TABLES FROM `'.$db.'`';
$tables = [];
$link = mod_mysqli_connect();
$res = mysqli_query($link, $sql);
if (false === !$res) {
while ($row = mysqli_fetch_array($res, MYSQLI_NUM)) {
$tables[] = $row[0];
}
} else {
exit('No Tables in Database!');
}
// get search criteria from session or from POST environment
// this way the search criteria are preserved even if you click somewhere else in between
if (isset($_POST['suchbegriffe'])) {
$_SESSION['mysql_search']['suchbegriffe'] = $_POST['suchbegriffe'];
}
if (!isset($_SESSION['mysql_search']['suchbegriffe'])) {
$_SESSION['mysql_search']['suchbegriffe'] = '';
}
$suchbegriffe = $_SESSION['mysql_search']['suchbegriffe'];
if (isset($_POST['suchart'])) {
$_SESSION['mysql_search']['suchart'] = $_POST['suchart'];
}
if (!isset($_SESSION['mysql_search']['suchart']) || strlen($_SESSION['mysql_search']['suchart']) < 2) {
$_SESSION['mysql_search']['suchart'] = 'AND';
}
$suchart = $_SESSION['mysql_search']['suchart'];
if (isset($_POST['table_selected'])) {
$_SESSION['mysql_search']['table_selected'] = $_POST['table_selected'];
}
if (!isset($_SESSION['mysql_search']['table_selected'])) {
$_SESSION['mysql_search']['table_selected'] = 0;
}
$table_selected = $_SESSION['mysql_search']['table_selected'];
// If tables were deleted in the meantime and the index does not exist anymore, reset it
if ($table_selected > count($tables) - 1) {
$table_selected = 0;
}
$offset = (isset($_POST['offset'])) ? intval($_POST['offset']) : 0;
$tablename = isset($_GET['tablename']) ? urldecode($_GET['tablename']) : '';
// Delete
if (isset($_GET['mode']) && 'kill' == $_GET['mode'] && $rk > '') {
// echo "<br> RK ist: ".$rk."<br><br>";
$sqlk = "DELETE FROM `$tablename` WHERE ".$rk.' LIMIT 1';
// echo $sqlk;
$res = mod_query($sqlk);
// echo "<br>".$res;
$aus .= '<p class="success">'.$lang['L_SQL_RECORDDELETED'].'</p>';
}
function mysqli_search($db, $tabelle, $suchbegriffe, $suchart, $offset = 0, $anzahl_ergebnisse = 20, $auszuschliessende_tabellen = '')
{
global $tables, $config, $lang;
$ret = false;
$link = mod_mysqli_connect();
if (sizeof($tables) > 0) {
$suchbegriffe = trim(str_replace('*', '', $suchbegriffe));
$suchworte = explode(' ', $suchbegriffe);
if (($suchbegriffe > '') && (is_array($suchworte))) {
// Remove empty entries (due to double spaces)
$anzahl_suchworte = sizeof($suchworte);
for ($i = 0; $i < $anzahl_suchworte; ++$i) {
if ('' == trim($suchworte[$i])) {
unset($suchworte[$i]);
}
}
$bedingung = [];
$where = '';
$felder = [];
// Determine fields
$sql = 'SHOW COLUMNS FROM `'.$db.'`.`'.$tables[$tabelle].'`';
$res = mysqli_query($link, $sql);
if (false === !$res) {
// Determine fields of the table
while ($row = mysqli_fetch_object($res)) {
$felder[] = $row->Field;
}
}
$feldbedingung = '';
if ('CONCAT' == $suchart) {
if (count($felder) > 0) {
// Build Concat-String
$concat = implode('`),LOWER(`', $felder);
$concat = 'CONCAT_WS(\'\',LOWER(`'.$concat.'`))';
$where = '';
foreach ($suchworte as $suchbegriff) {
$where .= $concat.' LIKE \'%'.strtolower($suchbegriff).'%\' AND ';
}
$where = substr($where, 0, -4); // Remove last AND
$sql = 'SELECT * FROM `'.$db.'`.`'.$tables[$tabelle].'` WHERE '.$where.' LIMIT '.$offset.','.$anzahl_ergebnisse;
} else {
$_SESSION['mysql_search']['suchbegriffe'] = '';
exit(sprintf($lang['L_ERROR_NO_FIELDS'], $tabelle));
}
} else {
$pattern = '`{FELD}` LIKE \'%{SUCHBEGRIFF}%\'';
if (count($felder) > 0) {
foreach ($felder as $feld) {
unset($feldbedingung);
foreach ($suchworte as $suchbegriff) {
$suchen = [
'{FELD}',
'{SUCHBEGRIFF}',
];
$ersetzen = [
$feld,
$suchbegriff,
];
$feldbedingung[] = str_replace($suchen, $ersetzen, $pattern);
}
$bedingung[] = '('.implode(' '.$suchart.' ', $feldbedingung).') ';
}
} else {
$_SESSION['mysql_search']['suchbegriffe'] = '';
exit(sprintf($lang['L_ERROR_NO_FIELDS'], $tabelle));
}
$where = implode(' OR ', $bedingung);
$sql = 'SELECT * FROM `'.$db.'`.`'.$tables[$tabelle].'` WHERE ('.$where.') LIMIT '.$offset.','.$anzahl_ergebnisse;
}
} else {
$sql = 'SELECT * FROM `'.$db.'`.`'.$tables[$tabelle].'` LIMIT '.$offset.','.$anzahl_ergebnisse;
}
$res = mysqli_query($link, $sql);
if (false === !$res) {
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
// Mark hits
foreach ($row as $key => $val) {
foreach ($suchworte as $suchbegriff) {
$row[$key] = markiere_suchtreffer($suchbegriff, $row[$key]);
}
$row[$key] = ersetze_suchtreffer($row[$key]);
}
$ret[] = $row;
}
}
}
return $ret;
}
// Marks the search string with a code (ASCII 01/02)
// - if not found : returns the original string
function markiere_suchtreffer($suchbegriff, $suchstring)
{
$str = strtolower($suchstring);
$suchbegriff = strtolower($suchbegriff);
if ((strlen($str) > 0) && (strlen($suchbegriff) > 0)) {
// Determine hit position
$offset = 0;
$trefferpos = 0;
while (($offset <= strlen($str))) {
// If only the first hit is to be marked, the line must read as follow
// while ( ($offset<=strlen($str)) || ($in_html==false) )
for ($offset = $trefferpos; $offset <= strlen($str); ++$offset) {
$start = strpos($str, $suchbegriff, $offset);
if (false === $start) {
$offset = strlen($str) + 1;
} else {
if ($offset <= strlen($str)) {
//Treffer überprüfen
$in_html = false;
// Steht die Fundstelle zwischen < und > (also im HTML-Tag) ?
for ($position = $start; $position >= 0; --$position) {
if ('>' == substr($str, $position, 1)) {
$in_html = false;
$position = -1; // Schleife verlassen
}
if ('<' == substr($str, $position, 1)) {
$in_html = true;
$position = -1; // Schleife verlassen
}
}
if ($in_html) {
for ($position2 = $start; $position2 < strlen($str); ++$position2) {
if ('<' == substr($str, $position2, 1)) {
$position2 = strlen($str) + 1;
}
if ('>' == substr($str, $position2, 1)) {
$in_html = true;
$position2 = strlen($str) + 1;
$offset = strlen($str) + 1;
}
}
}
if (!$in_html) {
$ersetzen = substr($suchstring, $start, strlen($suchbegriff));
$str = substr($suchstring, 0, $start);
$str .= chr(1).$ersetzen.chr(2);
$str .= substr($suchstring, ($start + strlen($ersetzen)), (strlen($suchstring) - strlen($ersetzen)));
$suchstring = $str;
}
if ($in_html) {
$trefferpos = $start + 1;
$offset = $trefferpos;
}
}
$offset = $start + 1;
}
}
}
}
return $suchstring;
}
// Ersetzt die Codes letztlich durch die Fontangabe
function ersetze_suchtreffer($text)
{
$such = [
chr(1),
chr(2), ];
$ersetzen = [
'<span class="treffer">',
'</span>', ];
return str_replace($such, $ersetzen, htmlspecialchars($text));
}
$suchbegriffe = trim($suchbegriffe); // Leerzeichen vorne und hinten wegschneiden
if (isset($_POST['reset'])) {
$suchbegriffe = '';
$_SESSION['mysql_search']['suchbegriffe'] = '';
$suchart = 'AND';
$_SESSION['mysql_search']['suchart'] = 'AND';
$table_selected = 0;
$_SESSION['mysql_search']['table_selected'] = 0;
}
$showtables = 0; // Anzeige der Tabellendaten im restlichen SQL-Browser ausschalten
// Fix bis zur kompletten Umstellung auf Templates
echo $aus;
$aus = '';
$anzahl_tabellen = sizeof($tables);
$table_options = '';
if ($anzahl_tabellen > 0) {
for ($i = 0; $i < $anzahl_tabellen; ++$i) {
if (isset($tables[$i])) {
$table_options .= '<option value="'.$i.'"';
if (($i == $table_selected) || ($tables[$i] == $tablename)) {
$table_options .= ' selected';
$table_selected = $i;
}
$table_options .= '>'.$tables[$i].'</option>'."\n";
}
}
}
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => './tpl/sqlbrowser/mysql_search.tpl', ]);
$tpl->assign_vars([
'DB_NAME_URLENCODED' => urlencode($db),
'LANG_SQLSEARCH' => $lang['L_SQL_SEARCH'],
'LANG_SQL_SEARCHWORDS' => $lang['L_SQL_SEARCHWORDS'],
'SUCHBEGRIFFE' => $suchbegriffe,
'LANG_START_SQLSEARCH' => $lang['L_START_SQL_SEARCH'],
'LANG_RESET_SEARCHWORDS' => $lang['L_RESET_SEARCHWORDS'],
'LANG_SEARCH_OPTIONS' => $lang['L_SEARCH_OPTIONS'],
'AND_SEARCH' => 'AND' == $suchart ? ' checked' : '',
'OR_SEARCH' => 'OR' == $suchart ? ' checked' : '',
'CONCAT_SEARCH' => 'CONCAT' == $suchart ? ' checked' : '',
'TABLE_OPTIONS' => $table_options,
'LANG_SEARCH_OPTIONS_AND' => $lang['L_SEARCH_OPTIONS_AND'],
'LANG_SEARCH_OPTIONS_OR' => $lang['L_SEARCH_OPTIONS_OR'],
'LANG_SEARCH_OPTIONS_CONCAT' => $lang['L_SEARCH_OPTIONS_CONCAT'],
'LANG_SEARCH_IN_TABLE' => $lang['L_SEARCH_IN_TABLE'], ]);
$max_treffer = 20;
$treffer = mysqli_search($db, $table_selected, $suchbegriffe, $suchart, $offset, $max_treffer + 1);
if (is_array($treffer) && isset($treffer[0])) {
$search_message = sprintf($lang['L_SEARCH_RESULTS'], $suchbegriffe, $tables[$table_selected]);
$anzahl_treffer = count($treffer);
// Blaettern-Buttons
$tpl->assign_block_vars('HITS', [
'LANG_SEARCH_RESULTS' => $search_message,
'LAST_OFFSET' => $offset - $max_treffer,
'BACK_BUTTON_DISABLED' => $offset > 0 ? '' : ' disabled',
'NEXT_OFFSET' => $offset + $max_treffer,
'NEXT_BUTTON_DISABLED' => ($anzahl_treffer != $max_treffer + 1) ? ' disabled' : '',
'LANG_ACCESS_KEYS' => $lang['L_SEARCH_ACCESS_KEYS'], ]);
// Ausgabe der Treffertabelle
$anzahl_felder = sizeof($treffer[0]);
// Ausgabe der Tabellenueberschrift/ Feldnamen
foreach ($treffer[0] as $key => $val) {
$tpl->assign_block_vars('HITS.TABLEHEAD', [
'KEY' => $key, ]);
}
// Ausgabe der Daten
$zeige_treffer = sizeof($treffer);
if ($zeige_treffer == $max_treffer + 1) {
$zeige_treffer = $max_treffer;
}
// built key - does a primary key exist?
$fieldinfos = getExtendedFieldinfo($db, $tables[$table_selected]);
//v($fieldinfos);
// auf zusammengesetzte Schlüssel untersuchen
$table_keys = isset($fieldinfos['primary_keys']) ? $fieldinfos['primary_keys'] : '';
for ($a = 0; $a < $zeige_treffer; ++$a) {
$tablename = array_keys($treffer[$a]);
if (is_array($table_keys) && sizeof($table_keys) > 0) {
// a primary key exitst
$keystring = '';
foreach ($table_keys as $k) {
// remove hit marker from value
$x = str_replace('<span class="treffer">', '', $treffer[$a][$k]);
$x = str_replace('</span>', '', $x);
$keystring .= '`'.$k.'`="'.addslashes($x).'" AND ';
}
$keystring = substr($keystring, 0, -5);
$rk = build_recordkey($keystring);
} else {
$rk = urlencode(build_where_from_record($treffer[$a])); // no keys
}
$delete_link = 'sql.php?search=1&mode=kill&db='.urlencode($db).'&tablename='.urlencode($tables[$table_selected]).'&rk='.$rk;
$edit_link = 'sql.php?mode=searchedit&db='.urlencode($db).'&tablename='.urlencode($tables[$table_selected]).'&recordkey='.$rk;
$tpl->assign_block_vars('HITS.TABLEROW', [
'CLASS' => ($a % 2) ? 'dbrow' : 'dbrow1',
'NR' => $a + $offset + 1,
'TABLENAME' => $tables[$table_selected],
'LINK_EDIT' => $edit_link,
'ICON_EDIT' => $icon['edit'],
'LINK_DELETE' => $delete_link,
'ICON_DELETE' => $icon['delete'], ]);
foreach ($treffer[$a] as $key => $val) {
if ('' == $val) {
$val = '&nbsp;';
}
$tpl->assign_block_vars('HITS.TABLEROW.TABLEDATA', [
'VAL' => $val, ]);
}
}
} else {
if (!isset($tables[$table_selected])) {
$tables[$table_selected] = '';
}
if ('' == $suchbegriffe) {
$tpl->assign_block_vars('NO_ENTRIES', [
'LANG_NO_ENTRIES' => sprintf($lang['L_NO_ENTRIES'], $tables[$table_selected]), ]);
} else {
$tpl->assign_block_vars('NO_RESULTS', [
'LANG_SEARCH_NO_RESULTS' => sprintf($lang['L_SEARCH_NO_RESULTS'], $suchbegriffe, $tables[$table_selected]), ]);
}
}
$tpl->pparse('show');

View File

@ -0,0 +1,114 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
function nl2null($string)
{
$search = ["\r", "\n"];
$replace = ['', ''];
return trim(str_replace($search, $replace, $string));
}
//SQL-Strings
if (!is_array($SQL_ARRAY)) {
$SQL_ARRAY = [];
}
echo $aus .= '<h4>'.$lang['L_SQL_BEFEHLE'].' ('.count($SQL_ARRAY).')</h4>';
echo '<a href="'.$params.'&amp;sqlconfig=1&amp;new=1">'.$lang['L_SQL_BEFEHLNEU'].'</a><br><br>';
if (isset($_POST['sqlnewupdate'])) {
$ind = count($SQL_ARRAY);
if (count($SQL_ARRAY) > 0) {
array_push($SQL_ARRAY, $_POST['sqlname'.$ind].'|'.$_POST['sqlstring'.$ind]);
} else {
$SQL_ARRAY[0] = htmlspecialchars($_POST['sqlname0'], ENT_COMPAT, 'UTF-8').'|'.$_POST['sqlstring0'];
}
WriteSQL();
echo '<p>'.$lang['L_SQL_BEFEHLSAVED1'].' \''.$_POST['sqlname'.$ind].'\' '.$lang['L_SQL_BEFEHLSAVED2'].'</p>';
}
echo '<form name="sqlform" action="sql.php" method="post">
<input type="hidden" name="context" value="1">
<input type="hidden" name="sqlconfig" value="1">
<input type="hidden" name="tablename" value="'.$tablename.'">
<input type="hidden" name="dbid" value="'.$dbid.'">';
echo '<table class="bdr" style="width:100%"><tr class="thead"><th>#</th><th>'.$lang['L_NAME'].'</th><th>SQL</th><th>'.$lang['L_COMMAND'].'</th></tr>';
$i = 0;
if (count($SQL_ARRAY) > 0) {
for ($i = 0; $i < count($SQL_ARRAY); ++$i) {
if (isset($_POST['sqlupdate'.$i])) {
echo '<tr><td colspan="4"><p class="success">'.$lang['L_SQL_BEFEHLSAVED1']
.' \''.htmlspecialchars($_POST['sqlname'.$i], ENT_COMPAT, 'UTF-8').'\' '.$lang['L_SQL_BEFEHLSAVED3'].'</p></td></tr>';
$SQL_ARRAY[$i] = $_POST['sqlname'.$i].'|'.nl2null($_POST['sqlstring'.$i]);
WriteSQL();
}
if (isset($_POST['sqlmove'.$i])) {
echo '<tr><td colspan="4"><p class="success">'.$lang['L_SQL_BEFEHLSAVED1'].' \''.$_POST['sqlname'.$i].'\' '.$lang['L_SQL_BEFEHLSAVED4'].'</p></td></tr>';
$a[] = $SQL_ARRAY[$i];
array_splice($SQL_ARRAY, $i, 1);
$SQL_ARRAY = array_merge($a, $SQL_ARRAY);
WriteSQL();
}
if (isset($_POST['sqldelete'.$i])) {
echo '<tr><td colspan="4"><p class="success">'.$lang['L_SQL_BEFEHLSAVED1'].' \''.$_POST['sqlname'.$i].'\' '.$lang['L_SQL_BEFEHLSAVED5'].'</p></td></tr>';
array_splice($SQL_ARRAY, $i, 1);
WriteSQL();
}
}
for ($i = 0; $i < count($SQL_ARRAY); ++$i) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
echo '<tr class="'.$cl.'"><td>'.($i + 1).'.</td><td>';
echo '<input type="text" class="text" name="sqlname'.$i.'" value="'.htmlspecialchars(SQL_Name($i), ENT_COMPAT, 'UTF-8').'"></td>';
echo '<td><textarea rows="4" cols="80" style="width:100%;" name="sqlstring'.$i.'">'.stripslashes(SQL_String($i)).'</textarea></td>';
echo '<td><input class="Formbutton" style="width:80px;" type="submit" name="sqlupdate'.$i.'" value="save"><br>
<input class="Formbutton" style="width:80px;" type="submit" name="sqlmove'.$i.'" value="move up"><br>
<input class="Formbutton" style="width:80px;" type="submit" name="sqldelete'.$i.'" value="delete"></td></tr>';
}
}
if (isset($_GET['new'])) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
echo '<tr class="'.$cl.'"><td>'.($i + 1).'</td><td>';
echo '<input type="text" class="text" name="sqlname'.$i.'" id="sqlname'.$i.'" value="SQL '.($i + 1).'"><br><div class="small" align="center">'.$lang['L_SQL_LIBRARY'].'<br>';
echo '<select id="sqllib" name="sqllib" onChange="InsertLib('.$i.');" class="small">';
echo '<option value=""></option>';
$og = false;
for ($j = 0; $j < count($sqllib); ++$j) {
if ('trenn' == $sqllib[$j]['sql']) {
if ($og) {
echo '</optgroup>';
}
echo '<optgroup label="'.$sqllib[$j]['name'].'">';
$og = true;
} else {
echo '<option value="'.$sqllib[$j]['sql'].'">'.$sqllib[$j]['name'].'</option>';
}
}
if ($og) {
echo '</optgroup>';
}
echo '</select></div></td>
<td><textarea rows="3" cols="40" name="sqlstring'.$i.'" id="sqlstring'.$i.'">SELECT * FROM</textarea></td>
<td><input class="Formbutton" style="width:80px;" type="submit" name="sqlnewupdate" value="save"></td></tr>';
}
echo '</table></form>';

View File

@ -0,0 +1,406 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
// fuegt eine Sortierungsnummer hinzu, um die Ausgabereihenfolge der Daten steuern zu koennen
// (das Feld ENGINE interessiert mich nicht so sehr und muss nicht vorne stehen)
$keysort = [
'Name' => 0,
'Rows' => 1,
'Data_length' => 2,
'Auto_increment' => 3,
'Avg_row_length' => 4,
'Max_data_length' => 5,
'Comment' => 6,
'Row_format' => 7,
'Index_length' => 8,
'Data_free' => 9,
'Collation' => 10,
'Create_time' => 11,
'Update_time' => 12,
'Check_time' => 13,
'Create_options' => 14,
'Version' => 15,
'Engine' => 16,
'Checksum' => 17,
];
$byte_output = [
'Data_length',
'Avg_row_length',
'Max_data_length',
'Index_length',
'Data_free',
];
function add_sortkey($name)
{
global $keysort;
//echo "<br>Uebergeben: ".$name;
if (array_key_exists($name, $keysort)) {
$ret = $keysort[$name];
} else {
$ret = 0;
}
return $ret;
}
//Data-View
echo $aus.'<h4>'.((1 == $showtables) ? $lang['L_SQL_TABLEVIEW'] : $lang['L_SQL_DATAVIEW']).'</h4><p>';
if (0 == $showtables) {
$p = 'sql.php?sql_statement='.urlencode($sql['sql_statement']).'&amp;db='.$db.'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;limitstart='.$limitstart.'&amp;order='.urlencode($order).'&amp;orderdir='.$orderdir.'&amp;tdc='.$tdcompact;
echo '<a href="'.$p.'&amp;mode=new">'.$lang['L_SQL_RECORDNEW'].'</a>&nbsp;&nbsp;&nbsp;&nbsp;';
echo '<a href="sql.php?db='.$databases['db_actual'].'&amp;dbid='.$dbid.'&amp;tablename='.$tablename.'&amp;context=2">'.$lang['L_SQL_EDIT_TABLESTRUCTURE'].'</a>';
} else {
$p = 'sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;context=2';
echo '<a href="'.$p.'">'.$lang['L_SQL_TABLENEW'].'</a>';
}
//Statuszeile
$tn = ExtractTablenameFromSQL($sql['sql_statement']);
if ($databases['Name'][$dbid] != $databases['db_actual']) {
// Table is located in a different databasse
// switch the actual database
$databases['db_actual'] = $databases['Name'][$dbid];
// refresh menu to switch to actual database
echo '<script>'
.'parent.MyOOS_Dumper_menu.location.href=\'menu.php?dbindex='.$dbid.'\';</script>';
}
echo '</p><p class="tablename">'.('' != $tn ? $lang['L_TABLE'].' <strong>`'.$databases['db_actual'].'`.`'.$tn.'`</strong><br>' : '');
if (isset($msg)) {
echo $msg;
}
$numrowsabs = -1;
$numrows = 0;
// Vorgehensweise - es soll die Summe der Datensaetze ermittelt werden, wenn es kein LIMIT gibt,
// um die Blaettern-Links korrekt anzuzeigen
$skip_mysql_execution = false;
if (0 == $sql_to_display_data) {
//mehrere SQL-Statements
$numrowsabs = $numrows = 0;
MOD_DoSQL($sql['sql_statement']);
echo SQLOutput($out);
$skip_mysql_execution = true;
} else {
// auch alle Tabellen-Namen werden lowercase -> das kann zu Problemen fuehren
// siehe https://dev.mysql.com/doc/refman/5.7/en/identifier-case-sensitivity.html
$sql_temp = strtolower($sql['sql_statement']);
if ('select ' == substr($sql_temp, 0, 7)) {
if (false !== strpos($sql_temp, ' limit ')) {
// es wurde ein eigenes Limit im Query angegeben - eigene Berechnung abbrechen
$numrowsabs = -1;
} else {
// anstatt sql_temp in lowerase hier das 'original' sql_statement verwenden
$sql_temp = "SELECT count(*) as anzahl FROM (".$sql['sql_statement'].") as query;";
$res = @mod_query($sql_temp, false);
if ($res) {
if ($row = mysqli_fetch_object($res)) {
$numrowsabs = $row->anzahl;
}
} else {
// Query ergab Fehler - Anzahl unbekannt; -1 übernimmt dann die Groesse des Resultsets
$numrowsabs = -1;
}
}
}
}
$sqltmp = $sql['sql_statement'].$sql['order_statement'].(strpos(strtolower($sql['sql_statement'].$sql['order_statement']), ' limit ') ? '' : $limit);
if (!$skip_mysql_execution) {
$res = mod_query($sqltmp);
}
$numrows = mysqli_num_rows($res);
if (-1 == $numrowsabs) {
$numrowsabs = $numrows;
}
if ($limitende > $numrowsabs) {
$limitende = $numrowsabs;
}
if ($numrowsabs > 0 && $Anzahl_SQLs <= 1) {
if (0 == $showtables) {
$command_line = $lang['L_INFO_RECORDS'].' '.($limitstart + 1).' - ';
if ($limitstart + $limitende > $numrowsabs) {
$command_line .= $numrowsabs;
} else {
$command_line .= $limitstart + $limitende;
}
$command_line .= ' '.$lang['L_SQL_VONINS']." $numrowsabs &nbsp;&nbsp;&nbsp;";
$command_line .= ($limitstart > 0) ? '<a href="'.$params.'&amp;limitstart=0">&lt;&lt;</a>&nbsp;&nbsp;&nbsp;&nbsp;' : '&lt;&lt;&nbsp;&nbsp;&nbsp;&nbsp;';
$command_line .= ($limitstart > 0) ? '<a href="'.$params.'&amp;limitstart='.(($limitstart - $config['sql_limit'] < 0) ? 0 : $limitstart - $config['sql_limit']).'">&lt;</a>&nbsp;&nbsp;&nbsp;&nbsp;' : '&lt;&nbsp;&nbsp;&nbsp;&nbsp;';
$command_line .= ($limitstart + $limitende < $numrowsabs) ? '<a href="'.$params.'&amp;limitstart='.($limitstart + $config['sql_limit']).'">&gt;</a>&nbsp;&nbsp;&nbsp;&nbsp;' : '&gt;&nbsp;&nbsp;&nbsp;&nbsp;';
$command_line .= ($limitstart + $limitende < ($numrowsabs - $config['sql_limit'])) ? '<a href="'.$params.'&amp;limitstart='.($numrowsabs - $config['sql_limit']).'">&gt;&gt;</a>' : '&gt;&gt;';
echo $command_line;
} else {
echo $numrowsabs.' '.($numrowsabs > 1 ? $lang['L_TABLES'] : $lang['L_TABLE']);
}
echo '</p>';
//Datentabelle
echo '<table class="bdr" id="dataTable">';
$t = $d = '';
$fdesc = [];
$key = -1;
if ($numrows > 0) {
//Infos und Header holen
//1.Datensatz fuer Feldinfos
$row = mysqli_fetch_row($res);
//Kompaktmodus-Switcher
$t = '<td colspan="'.(count($row) + 1).'" align="left"><a href="sql.php?db='.$db.'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;order='.urlencode($order).'&amp;orderdir='.$orderdir.'&amp;limitstart='.$limitstart.'&amp;sql_statement='.urlencode($sql['sql_statement']).'&amp;tdc='.((0 == $tdcompact) ? '1' : '0').'">'.((1 == $tdcompact) ? $lang['L_SQL_VIEW_STANDARD'] : $lang['L_SQL_VIEW_COMPACT']).'</a>';
$t .= '&nbsp;&nbsp;&nbsp;'.$lang['L_SQL_QUERYENTRY'].' '.count($row).' '.$lang['L_SQL_COLUMNS'];
$t .= '</td></tr><tr class="thead">';
$t .= '<th>&nbsp;</th><th>#</th>';
$temp = [];
for ($x = 0; $x < count($row); ++$x) {
// $temp[$x]['data'] =mysqli_fetch_field($res, $x);
$temp[$x]['data'] = mysqli_fetch_field($res);
$temp[$x]['sort'] = add_sortkey($temp[$x]['data']->name);
}
if (1 == $showtables) {
$temp = mu_sort($temp, 'sort');
}
for ($x = 0; $x < count($temp); ++$x) {
$str = $temp[$x]['data'];
$t .= '<th align="left" nowrap="nowrap">';
$pic = '';
$fdesc[$temp[$x]['data']->name]['name'] = isset($str->name) ? $str->name : '';
$fdesc[$temp[$x]['data']->name]['table'] = isset($str->table) ? $str->table : '';
$fdesc[$temp[$x]['data']->name]['max_length'] = isset($str->max_length) ? $str->max_length : '';
$fdesc[$temp[$x]['data']->name]['not_null'] = isset($str->not_null) ? $str->not_null : '';
$fdesc[$temp[$x]['data']->name]['primary_key'] = isset($str->primary_key) ? $str->primary_key : '';
$fdesc[$temp[$x]['data']->name]['unique_key'] = isset($str->unique_key) ? $str->unique_key : '';
$fdesc[$temp[$x]['data']->name]['multiple_key'] = isset($str->multiple_key) ? $str->multiple_key : '';
$fdesc[$temp[$x]['data']->name]['numeric'] = isset($str->numeric) ? $str->numeric : '';
$fdesc[$temp[$x]['data']->name]['blob'] = isset($str->blob) ? $str->blob : '';
$fdesc[$temp[$x]['data']->name]['type'] = isset($str->type) ? $str->type : '';
$fdesc[$temp[$x]['data']->name]['unsigned'] = isset($str->unsigned) ? $str->unsigned : '';
$fdesc[$temp[$x]['data']->name]['zerofill'] = isset($str->zerofill) ? $str->zerofill : '';
$fdesc[$temp[$x]['data']->name]['Check_time'] = isset($str->Check_time) ? $str->Check_time : '';
$fdesc[$temp[$x]['data']->name]['Checksum'] = isset($str->Checksum) ? $str->Checksum : '';
$fdesc[$temp[$x]['data']->name]['Engine'] = isset($str->Engine) ? $str->Engine : '';
if (isset($str->Comment) && 'VIEW' == substr($str->Comment, 0, 4)) {
$fdesc[$temp[$x]['data']->name]['Engine'] = 'View';
}
$fdesc[$temp[$x]['data']->name]['Version'] = isset($str->Version) ? $str->Version : '';
$tt = $lang['L_NAME'].': '.$fdesc[$temp[$x]['data']->name]['name'].' Type: '.$fdesc[$temp[$x]['data']->name]['type'].' Max Length: '.$fdesc[$temp[$x]['data']->name]['max_length'].' Unsigned: '.$fdesc[$temp[$x]['data']->name]['unsigned'].' zerofill: '.$fdesc[$temp[$x]['data']->name]['zerofill'];
$pic = '<img src="'.$icon['blank'].'" alt="" width="1" height="1" border="0">';
if ((isset($str->primary_key) && (1 == $str->primary_key)) || (isset($str->unique_key) && (1 == $str->unique_key))) {
if (-1 == $key) {
$key = $temp[$x]['data']->name;
} else {
$key .= '|'.$temp[$x]['data']->name;
}
if (1 == $str->primary_key) {
$pic = $icon['key_primary'];
} elseif (1 == $str->unique_key) {
$pic = $icon['index'];
}
}
// show sorting icon
$arname = ('ASC' == $orderdir) ? $icon['arrow_down'] : $icon['arrow_up'];
if ($str->name == $order) {
$t .= $arname;
}
if (-1 == $bb) {
$bb_link = ('blob' == $str->type) ? '&nbsp;&nbsp;&nbsp;<a style="font-size:10px;color:blue;" title="use BB-Code for this field" href="sql.php?db='.$db.'&amp;bb='.$x.'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;order='.$order.'&amp;orderdir='.$orderdir.'&amp;limitstart='.$limitstart.'&amp;sql_statement='.urlencode($sql['sql_statement']).'&amp;tdc='.$tdcompact.'">[BB]</a>' : '';
} else {
$bb_link = ('blob' == $str->type) ? '&nbsp;&nbsp;&nbsp;<a title="use BB-Code for this field" href="sql.php?db='.$db.'&amp;bb=-1&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;order='.urlencode($order).'&amp;orderdir='.$orderdir.'&amp;limitstart='.$limitstart.'&amp;sql_statement='.urlencode($sql['sql_statement']).'&amp;tdc='.$tdcompact.'">[no BB]</a>' : '';
}
if (false == $no_order && 0 == $showtables) {
$t .= $pic.'&nbsp;<a title="'.$tt.'" href="sql.php?db='.$db.'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;order='.urlencode($str->name).'&amp;orderdir='.$norder.'&amp;sql_statement='.urlencode($sql['sql_statement']).'&amp;tdc='.$tdcompact.'">'.$str->name.'</a>'.$bb_link;
} else {
$t .= $pic.'&nbsp;<span title="'.$tt.'" >'.$str->name.'</span>'.$bb_link;
}
$t .= '</th>';
}
unset($temp);
$temp = [];
//und jetzt Daten holen
mysqli_data_seek($res, 0);
$s = $keysort;
$s = array_flip($keysort);
ksort($s);
for ($i = 0; $i < $numrows; ++$i) {
$data[0] = mysqli_fetch_array($res, MYSQLI_ASSOC);
if (1 == $showtables && 1 == $tabellenansicht) {
// Spalten sortieren, wenn wir uns in einer Tabellenuebersicht befinden
$xx = mu_sort($data, "$s[0], $s[1], $s[2], $s[3], $s[4], $s[5], $s[6], $s[7], $s[8], $s[9], $s[10], $s[11], $s[12], $s[13], $s[14], $s[15], $s[16]");
$temp[$i] = $xx[0];
/***********************
Ergänzung www.betanet-web.ch - 30.04.2019
Anz. Einträge in der Tabelle wird in Ausgabe Array überschrieben, damit alle Daten exportiert werden.
************************/
$tabellenname = $data[0]['Name'];
$numrows12 = 0;
$select12 = "select * from $tabellenname";
$res12 = mod_query($select12, false);
if (!empty($res12)) {
$numrows12 = mysqli_num_rows($res12);
}
// Überschreiben mit neuem Wert
$temp[$i]['Rows'] = $numrows12;
} else {
$temp[$i] = $data[0];
}
}
$rownr = $limitstart + 1;
for ($i = 0; $i < $numrows; ++$i) {
$row = $temp[$i]; // mysqli_fetch_row($res);
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
$erste_spalte = 1;
// bei Tabellenuebersicht soll nach vorgefertigter Reihenfolge sortiert werden, ansonsten einfach Daten anzeigen
if (1 == $showtables) {
$sortkey = $keysort;
} else {
$sortkey = $row;
}
$spalte = 0;
// get primary key link for editing
if ($key > -1) {
$primary_key = '';
$keys = explode('|', $key);
foreach ($sortkey as $rowkey => $rowval) {
if (in_array($rowkey, $keys)) {
if (strlen($primary_key) > 0) {
$primary_key .= ' AND ';
}
$primary_key .= '`'.urlencode($rowkey).'`=\''.urlencode($rowval).'\'';
}
}
//echo "<br><br>Primaerschluessel erkannt: ".$primary_key;
}
foreach ($sortkey as $rowkey => $rowval) {
if (('Name' == $rowkey) && 1 == $tabellenansicht && isset($row['Name'])) {
$tablename = $row['Name'];
}
if (1 == $erste_spalte) {
//edit-pics
$d .= $nl.'<td valign="top" nowrap="nowrap" class="small">&nbsp;'.$nl;
$p = 'sql.php?sql_statement='.urlencode($sql['sql_statement']).'&amp;db='.$databases['db_actual'].'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'&amp;limitstart='.$limitstart.'&amp;order='.urlencode($order).'&amp;orderdir='.$orderdir.'&amp;tdc='.$tdcompact;
if (-1 == $key) {
$rk = build_where_from_record($temp[$i]);
$p .= '&amp;recordkey='.urlencode($rk);
} else {
//Key vorhanden
$p .= '&amp;recordkey='.urlencode($primary_key); //urlencode("`".$fdesc[$key]['name']."`='".$rowval."'");
}
if (1 == $showtables) {
$p .= '&amp;recordkey='.urlencode($tablename);
}
if (!isset($no_edit) || !$no_edit) {
if (0 == $showtables) {
$d .= '<a href="'.$p.'&amp;mode=edit">'.$icon['edit'].'</a>&nbsp;';
}
}
if (0 == $showtables && 0 == $tabellenansicht) {
$d .= '<a href="'.$p.'&amp;mode=kill" onclick="if(!confirm(\''.$lang['L_ASKDELETERECORD'].'\')) return false;">'.$icon['delete'].'</a>';
} else {
if (1 == $tabellenansicht && 1 == $showtables) {
$d .= '<a href="sql.php?db='.$db.'&amp;dbid='.$dbid.'&amp;tablename='.$tablename.'&amp;context=2">'.$icon['edit'].'</a>&nbsp;'.$nl.$nl;
if (!(isset($row['Comment']) && ('VIEW' == substr(strtoupper($row['Comment']), 0, 4)))) {
$d .= '<a href="'.$p.'&amp;mode=empty" onclick="if(!confirm(\''.sprintf($lang['L_ASKTABLEEMPTY'], $tablename).'\')) return false;">'.$icon['table_truncate'].'</a>&nbsp;'.$nl.$nl;
$d .= '<a href="'.$p.'&amp;mode=emptyk" onclick="if(!confirm(\''.sprintf($lang['L_ASKTABLEEMPTYKEYS'], $tablename).'\')) return false;">'.$icon['table_truncate_reset'].'</a>&nbsp;'.$nl.$nl;
$d .= '<a href="'.$p.'&amp;mode=kill" onclick="if(!confirm(\''.sprintf($lang['L_ASKDELETETABLE'], $tablename).'\')) return false;">'.$icon['delete'].'</a>&nbsp;'.$nl.$nl;
} else {
$d .= '<a href="'.$p.'&amp;mode=kill_view" onclick="if(!confirm(\''.sprintf($lang['L_ASKDELETETABLE'], $tablename).'\')) return false;">'.$icon['delete'].'</a>&nbsp;'.$nl.$nl;
}
}
}
$d .= '</td><td valign="top" class="small" style="text-align:right">'.$rownr.'.&nbsp;</td>';
++$rownr;
$erste_spalte = 0;
}
$d .= '<td valign="top" class="small" nowrap="nowrap">';
$divstart = '<div'.((1 == $tdcompact) ? ' class="tdcompact" ' : ' class="tdnormal"').'>';
$divend = '</div>';
if ($bb == $spalte) {
$data = convert_to_utf8(simple_bbcode_conversion($rowval));
} else {
if (0 == $showtables) {
if (isset($fdesc[$rowkey]['type'])) {
$data = ('string' == $fdesc[$rowkey]['type'] || 'blob' == $fdesc[$rowkey]['type']) ? convert_to_utf8($rowval) : $rowval;
}
} else {
if (isset($temp[$i][$rowkey])) {
$data = ('string' == $fdesc[$rowkey]['type'] || 'blob' == $fdesc[$rowkey]['type']) ? convert_to_utf8($temp[$i][$rowkey]) : $temp[$i][$rowkey];
} else {
$data = '';
}
if (in_array($rowkey, $byte_output)) {
$data = byte_output($data);
}
}
}
//v($fdesc[$rowkey]);
if (0 == $showtables) {
if (is_null($rowval)) {
$data = '<i>NULL</i>';
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
}
++$spalte;
$browse_link = '<a href="sql.php?db='.$db.'&amp;tablename='.$tablename.'&amp;dbid='.$dbid.'" title="'.$data.'">';
$d .= (1 == $tabellenansicht && 'Name' == $rowkey) ? $divstart.$browse_link.$icon['browse'].'</a>&nbsp;'.$browse_link.$data."</a>$divend" : $divstart.$data.$divend;
$d .= '</td>';
}
// Tabellenueberschrift en ausgeben
if (0 == $i) {
echo '<tr>'.$t.'</tr>';
}
// Daten anzeigen
echo "\n\n".'<tr class="'.$cl.'">'.$d.'</tr>'."\n\n";
$d = '';
}
}
echo '</table>';
if (0 == $showtables) {
echo '<br>'.$command_line;
}
} else {
echo '<p class="success">'.$lang['L_SQL_NODATA'].'</p>';
}

View File

@ -0,0 +1,60 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
// insert a new record
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => './tpl/sqlbrowser/sql_record_insert_inputmask.tpl', ]);
$sqledit = "SHOW FIELDS FROM `$tablename`";
$res = mod_query($sqledit);
if ($res) {
$num = mysqli_num_rows($res);
$feldnamen = '';
for ($x = 0; $x < $num; ++$x) {
$row = mysqli_fetch_object($res);
$feldnamen .= $row->Field.'|';
$tpl->assign_block_vars('ROW', [
'CLASS' => ($x % 2) ? 1 : 2,
'FIELD_NAME' => $row->Field,
'FIELD_ID' => correct_post_index($row->Field), ]);
$type = strtoupper($row->Type);
if ('YES' == strtoupper($row->Null)) {
//field is nullable
$tpl->assign_block_vars('ROW.IS_NULLABLE', []);
}
if (in_array($type, [
'BLOB',
'TEXT', ])) {
$tpl->assign_block_vars('ROW.IS_TEXTAREA', []);
} else {
$tpl->assign_block_vars('ROW.IS_TEXTINPUT', []);
}
}
}
$tpl->assign_vars([
'HIDDEN_FIELDS' => FormHiddenParams(),
'FIELDNAMES' => substr($feldnamen, 0, strlen($feldnamen) - 1),
'SQL_STATEMENT' => my_quotes($sql['sql_statement']), ]);
$tpl->pparse('show');

View File

@ -0,0 +1,66 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
// Edit record -> built Edit-Form
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => './tpl/sqlbrowser/sql_record_update_inputmask.tpl', ]);
$target = ('searchedit' == $mode) ? '?mode=searchedit' : '?mode=update'; // jump back to search hit list after saving
$fields = getExtendedFieldInfo($db, $tablename);
$sqledit = "SELECT * FROM `$tablename` WHERE ".$recordkey;
$res = mod_query($sqledit);
$record = mysqli_fetch_array($res, MYSQLI_ASSOC); // get the record
$num = sizeof($record); // get the nr of fields of the record
// iterate fields
$x = 0;
$fieldnames = '';
foreach ($record as $field => $fieldvalue) {
$fieldnames .= $field.'|';
$tpl->assign_block_vars('ROW', [
'CLASS' => ($x % 2) ? 1 : 2,
'FIELD_NAME' => $field,
'FIELD_VALUE' => my_quotes($fieldvalue),
'FIELD_ID' => correct_post_index($field), ]);
if ('YES' == $fields[$field]['null']) {
//field is nullable - precheck checkbox if value is null
$tpl->assign_block_vars('ROW.IS_NULLABLE', [
'NULL_CHECKED' => is_null($fieldvalue) ? ' checked="checked"' : '', ]);
}
$type = strtoupper($fields[$field]['type']);
if (in_array($type, [
'BLOB',
'TEXT', ])) {
$tpl->assign_block_vars('ROW.IS_TEXTAREA', []);
} else {
$tpl->assign_block_vars('ROW.IS_TEXTINPUT', []);
}
++$x;
}
$tpl->assign_vars([
'HIDDEN_FIELDS' => FormHiddenParams(),
'FIELDNAMES' => substr($fieldnames, 0, strlen($fieldnames) - 1),
'SQL_STATEMENT' => my_quotes($sql['sql_statement']),
'RECORDKEY' => my_quotes($recordkey),
'TARGET' => $target, ]);
$tpl->pparse('show');

View File

@ -0,0 +1,583 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
//Tabellen
echo $aus.'<h6>'.$lang['L_SQL_TABLESOFDB'].' `'.$databases['Name'][$dbid].'` '.$lang['L_SQL_EDIT'].'</h6>';
//Primaerschluessel loeschen
if (isset($_GET['killPrimaryKey'])) {
$keys = getPrimaryKeys($databases['Name'][$dbid], $_GET['tablename']);
//Zu loeschenden Schluessel aus dem Array entfernen
$keyPos = array_search($_GET['killPrimaryKey'], $keys['name']);
if (!(false === $keyPos)) {
unset($keys['name'][$keyPos]);
unset($keys['size'][$keyPos]);
$keys['name'] = array_values($keys['name']);
$keys['size'] = array_values($keys['size']);
$res = setNewPrimaryKeys($databases['Name'][$dbid], $_GET['tablename'], $keys['name'], $keys['size']);
if ($res) {
echo '<script>
alert("'.$lang['L_PRIMARYKEY_DELETED'].': '.$_GET['killPrimaryKey'].'");
</script>';
} else {
echo '<script>
alert("'.$lang['L_PRIMARYKEYS_CHANGINGERROR'].': '.$_GET['killPrimaryKey'].'");
</script>';
}
} else {
echo '<script>
alert("'.$lang['L_PRIMARYKEY_NOTFOUND'].': '.$_GET['killPrimaryKey'].'");
</script>';
}
}
//Primärschlüssel löschen ende
//Neue Schlüssel setzen
if (isset($_POST['setNewKeys'])) {
$fields = getAllFields($databases['Name'][$dbid], $_GET['tablename']);
$newKeysArray = [];
$newKeySizesArray = [];
foreach ($fields as $index => $field) {
if ((isset($_POST['setNewKey'.$index])) && ('' != $_POST['setNewKey'.$index])) {
$newKeysArray[] = $_POST['setNewKey'.$index];
$newKeySizesArray[] = isset($_POST['indexSize'.$index]) ? (int) $_POST['indexSize'.$index] : '';
}
}
//doppelte Elemente entfernen
$newKeysArray = array_unique($newKeysArray);
$newKeySizesArray = array_intersect_key($newKeySizesArray, $newKeysArray);
if ('primary' == $_POST['indexType']) {
$res = setNewPrimaryKeys($databases['Name'][$dbid], $_GET['tablename'], $newKeysArray, $newKeySizesArray);
if ($res) {
echo '<script>
alert("'.$lang['L_PRIMARYKEYS_CHANGED'].'");
</script>';
} else {
echo '<script>
alert("'.$lang['L_PRIMARYKEYS_CHANGINGERROR'].'");
</script>';
}
} else {
if ('unique' == $_POST['indexType']) {
$newIndexType = 'UNIQUE';
} elseif ('fulltext' == $_POST['indexType']) {
$newIndexType = 'FULLTEXT';
} else {
$newIndexType = 'INDEX';
}
$res = setNewKeys($databases['Name'][$dbid], $_GET['tablename'], $newKeysArray, $newIndexType, $_POST['indexName'], $newKeySizesArray);
if ($res) {
echo '<script>
alert("'.$lang['L_KEY_ADDED'].'");
</script>';
} else {
echo '<script>
alert("'.$lang['L_KEY_ADDERROR'].'");
</script>';
}
}
}
//Andere Indizes löschen
if (isset($_GET['killIndex'])) {
$res = killKey($databases['Name'][$dbid], $_GET['tablename'], $_GET['killIndex']);
if ($res) {
echo '<script>
alert("'.$lang['L_KEY_DELETED'].': '.$_GET['killIndex'].'");
</script>';
} else {
echo '<script>
alert("'.$lang['L_KEY_DELETEERROR'].': '.$_GET['killIndex'].'");
</script>';
}
}
if (isset($_GET['kill'])) {
if (1 == $_GET['anz']) {
echo '<p class="error">'.$lang['L_SQL_NOFIELDDELETE'].'</p>';
} else {
$sql_alter = 'ALTER TABLE `'.$databases['Name'][$dbid].'`.`'.$_GET['tablename'].'` DROP COLUMN `'.$_GET['kill'].'`';
$res = MOD_DoSQL($sql_alter);
if ($res) {
echo '<div align="left" id="sqleditbox" style="font-size: 11px;width:90%;padding=6px;">';
echo '<p class="success">'.$lang['L_SQL_FIELDDELETE1'].' `'.$_GET['kill'].'` '.$lang['L_SQL_DELETED'].'.</p>'.highlight_sql($out).'</div>';
}
}
}
if (isset($_POST['tablecopysubmit'])) {
$table_edit_name = $_GET['tablename'];
if ('' == $_POST['tablecopyname']) {
echo '<p class="error">'.$lang['L_SQL_NODEST_COPY'].'</p>';
} elseif (Table_Exists($databases['Name'][$dbid], $_POST['tablecopyname'])) {
echo '<p class="error">'.$lang['L_SQL_DESTTABLE_EXISTS'].'</p>';
} else {
Table_Copy('`'.$databases['Name'][$dbid].'`.`'.$table_edit_name.'`', $_POST['tablecopyname'], $_POST['copyatt']);
echo '<div align="left" id="sqleditbox">';
echo (0 == $_POST['copyatt']) ? '<p class="success">'.sprintf($lang['L_SQL_SCOPY'], $table_edit_name, $_POST['tablecopyname']).'</p>' : sprintf($lang['L_SQL_TCOPY'], $table_edit_name, $_POST['tablecopyname']).'</p>';
echo highlight_sql($out).'</div>';
$tablename = $_POST['tablecopyname'];
}
}
if (isset($_POST['newtablesubmit'])) {
if ('' == $_POST['newtablename']) {
echo '<p class="error">'.$lang['L_SQL_TABLENONAME'].'</p>';
} else {
$sql_alter = 'CREATE TABLE `'.$databases['Name'][$dbid].'`.`'.$_POST['newtablename'].'` (`id` int(11) unsigned not null AUTO_INCREMENT PRIMARY KEY ) '.((MOD_NEW_VERSION) ? 'ENGINE' : 'TYPE').'=MyISAM;';
$res = MOD_DoSQL($sql_alter);
if ($res) {
echo SQLOutput($out, $lang['L_TABLE'].' `'.$_POST['newtablename'].'` '.$lang['L_SQL_CREATED']);
}
}
}
if (isset($_POST['t_edit_submit'])) {
$sql_alter = 'ALTER TABLE `'.$databases['Name'][$dbid].'`.`'.$_POST['table_edit_name'].'` ';
if ('' == $_POST['t_edit_name']) {
echo '<p class="error">'.$lang['L_SQL_TBLNAMEEMPTY'].'</p>';
} elseif (MOD_NEW_VERSION && '' != $_POST['t_edit_collate'] && substr($_POST['t_edit_collate'], 0, strlen($_POST['t_edit_charset'])) != $_POST['t_edit_charset']) {
echo '<p class="error">'.$lang['L_SQL_COLLATENOTMATCH'].'</p>';
} else {
if ($_POST['table_edit_name'] != $_POST['t_edit_name']) {
$sql_alter .= 'RENAME TO `'.$_POST['t_edit_name'].'`, ';
$table_edit_name = $_POST['t_edit_name'];
} else {
$table_edit_name = $_POST['table_edit_name'];
}
if ('' != $_POST['t_edit_engine']) {
$sql_alter .= ((MOD_NEW_VERSION) ? 'ENGINE=' : 'TYPE=').$_POST['t_edit_engine'].', ';
}
if ('' != $_POST['t_edit_rowformat']) {
$sql_alter .= 'ROW_FORMAT='.$_POST['t_edit_rowformat'].', ';
}
if (MOD_NEW_VERSION && '' != $_POST['t_edit_charset']) {
$sql_alter .= 'DEFAULT CHARSET='.$_POST['t_edit_charset'].', ';
}
if (MOD_NEW_VERSION && '' != $_POST['t_edit_collate']) {
$sql_alter .= 'COLLATE '.$_POST['t_edit_collate'].', ';
}
$sql_alter .= "COMMENT='".$_POST['t_edit_comment']."' ";
$res = MOD_DoSQL($sql_alter);
if ($res) {
echo SQLOutput($out, $lang['L_TABLE'].' `'.$_POST['table_edit_name'].'` '.$lang['L_SQL_CHANGED']);
}
}
} else {
if (!isset($table_edit_name) || '' == $table_edit_name) {
$table_edit_name = (isset($_GET['tablename'])) ? $_GET['tablename'] : '';
if (isset($_POST['tableselect'])) {
$table_edit_name = $_POST['tableselect'];
}
if (isset($_POST['newtablesubmit'])) {
$table_edit_name = $_POST['newtablename'];
}
}
}
if (isset($_POST['newfield_posted'])) {
//build sql for alter
if ('' == $_POST['f_name']) {
echo '<p class="error">'.$lang['L_SQL_FIELDNAMENOTVALID'].' ('.$_POST['f_name'].')</p>';
$field_fehler = 1;
} else {
//alter Key
$oldkeys[0] = $_POST['f_primary'];
$oldkeys[1] = $_POST['f_unique'];
$oldkeys[2] = $_POST['f_index'];
$oldkeys[3] = $_POST['f_fulltext'];
//neuer Key
$newkeys[0] = ('primary' == $_POST['f_index_new']) ? 1 : 0;
$newkeys[1] = ('unique' == $_POST['f_index_new']) ? 1 : 0;
$newkeys[2] = ('index' == $_POST['f_index_new']) ? 1 : 0;
$newkeys[3] = (isset($_POST['f_indexfull'])) ? 1 : 0;
$add_sql .= ChangeKeys($oldkeys, $newkeys, $_POST['f_name'], $_POST['f_size'], 'drop_only');
$sql_stamm = 'ALTER TABLE `'.$databases['Name'][$dbid]."`.`$table_edit_name` ";
$sql_alter = $sql_stamm.((isset($_POST['editfield'])) ? 'CHANGE COLUMN `'.$_POST['fieldname'].'` `'.$_POST['f_name'].'` ' : 'ADD COLUMN `'.$_POST['f_name'].'` ');
$sql_alter .= $_POST['f_type'];
$wl = stripslashes($_POST['f_size']);
if ('' != $wl && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $_POST['f_type'])) {
$sql_alter .= "($wl) ";
} elseif ('' == $_POST['f_size'] && preg_match('@^(VARCHAR)$@i', $_POST['f_type'])) {
$sql_alter .= '('.'255'.') ';
} else {
$sql_alter .= ' ';
}
$sql_alter .= $_POST['f_attribut'].' ';
$sql_alter .= $_POST['f_null'].' ';
$sql_alter .= ('' != $_POST['f_default']) ? "DEFAULT '".addslashes($_POST['f_default'])."' " : '';
if (MOD_NEW_VERSION && '' != $_POST['f_collate']) {
$sql_alter .= 'COLLATE '.$_POST['f_collate'].' ';
}
if ('AUTO_INCREMENT' == $_POST['f_extra']) {
$sql_alter .= ' AUTO_INCREMENT ';
}
$sql_alter .= $_POST['f_position'];
if (1 == $newkeys[0]) {
$sql_alter .= ', ADD PRIMARY KEY (`'.$_POST['f_name'].'`)';
}
if (1 == $newkeys[1]) {
$sql_alter .= ', ADD UNIQUE (`'.$_POST['f_name'].'`)';
}
if (1 == $newkeys[2]) {
$sql_alter .= ', ADD INDEX (`'.$_POST['f_name'].'`)';
}
if (1 == $newkeys[3]) {
$sql_alter .= ', ADD FULLTEXT INDEX (`'.$_POST['f_name'].'`)';
}
$sql_alter .= ';';
if ('' != $add_sql) {
$add_sql = $sql_stamm.$add_sql;
$sql_alter = "$sql_alter\n$add_sql;";
}
$res = MOD_DoSQL($sql_alter);
if ($res) {
echo '<div align="left" id="sqleditbox" style="font-size: 11px;width:90%;padding=6px;">';
echo '<p class="success"> `'.$_POST['f_name'].'` '.((isset($_POST['editfield'])) ? $lang['L_SQL_CHANGED'] : $lang['L_SQL_CREATED']).'</p>';
echo highlight_sql($out).'</div>';
}
$fields_infos = getFieldinfos($databases['Name'][$dbid], $table_edit_name);
}
}
mysqli_select_db($config['dbconnection'], $databases['Name'][$dbid]);
$sqlt = 'SHOW TABLE STATUS FROM `'.$databases['Name'][$dbid].'` ;';
$res = mod_query($sqlt);
$anz_tabellen = mysqli_num_rows($res);
$p = 'sql.php?db='.$databases['Name'][$dbid]."&amp;dbid= $dbid&amp;tablename= $table_edit_name&amp;context=2";
echo '<form action="sql.php?db='.$databases['Name'][$dbid].'&amp;dbid='.$dbid.'&amp;tablename='.$table_edit_name.'&amp;context=2" method="post">';
echo '<table class="bdr"><tr class="dbrow"><td>'.$lang['L_SQL_CREATETABLE'].': </td><td colspan="2"><input type="text" class="text" name="newtablename" size="30" maxlength="150"></td><td><input type="submit" name="newtablesubmit" value="'.$lang['L_SQL_CREATETABLE'].'" class="Formbutton"></td></tr>';
echo '<tr class="dbrow1"><td>'.$lang['L_SQL_COPYTABLE'].': </td><td><input type="text" class="text" name="tablecopyname" size="20" maxlength="150"></td><td><select name="copyatt"><option value="0">'.$lang['L_SQL_STRUCTUREONLY'].'</option>'.((MOD_NEW_VERSION) ? '<option value="1">'.$lang['L_SQL_STRUCTUREDATA'].'</option>' : '').'</select></td><td><input type="submit" class="Formbutton" name="tablecopysubmit" value="'.$lang['L_SQL_COPYTABLE'].'" '.(('' == $table_edit_name) ? 'disabled="disabled"' : '').'></td></tr>';
if (0 == $anz_tabellen) {
echo '<tr><td>'.$lang['L_SQL_NOTABLESINDB'].' `'.$databases['Name'][$dbid].'`</td></tr>';
} else {
echo '<tr><td>'.$lang['L_SQL_SELECTTABLE'].':&nbsp;&nbsp;&nbsp;</td>';
echo '<td colspan="2"><select name="tableselect" onchange="this.form.submit()"><option value="1" SELECTED></option>';
for ($i = 0; $i < $anz_tabellen; ++$i) {
$row = mysqli_fetch_array($res);
echo '<option value="'.$row['Name'].'">'.$row['Name'].'</option>';
}
echo '</select>&nbsp;&nbsp;</td>';
echo '<td><input type="button" class="Formbutton" value="'.$lang['L_SQL_SHOWDATATABLE'].'" onclick="location.href=\'sql.php?db='.$databases['Name'][$dbid].'&amp;dbid='.$dbid.'&amp;tablename='.$tablename.'\'"></td></tr>';
}
echo '</table></form><p>&nbsp;</p>';
if ('' != $table_edit_name) {
$sqlf = 'SHOW FULL FIELDS FROM `'.$databases['Name'][$dbid]."`.`$table_edit_name` ;";
$res = mod_query($sqlf);
$anz_fields = mysqli_num_rows($res);
$fields_infos = getFieldinfos($databases['Name'][$dbid], $table_edit_name);
if (MOD_NEW_VERSION) {
$t_engine = (isset($fields_infos['_tableinfo_']['ENGINE'])) ? $fields_infos['_tableinfo_']['ENGINE'] : 'MyISAM';
} else {
$t_engine = (isset($fields_infos['_tableinfo_']['TYPE'])) ? $fields_infos['_tableinfo_']['TYPE'] : 'MyISAM';
}
$t_charset = (isset($fields_infos['_tableinfo_']['DEFAULT CHARSET'])) ? $fields_infos['_tableinfo_']['DEFAULT CHARSET'] : '';
$t_collation = isset($row['Collation']) ? $row['Collation'] : ''; //(isset($fields_infos['_tableinfo_']['COLLATE'])) ? $fields_infos['_tableinfo_']['COLLATE'] : '';
$t_comment = (isset($fields_infos['_tableinfo_']['COMMENT'])) ? substr($fields_infos['_tableinfo_']['COMMENT'], 1, strlen($fields_infos['_tableinfo_']['COMMENT']) - 2) : '';
$t_rowformat = (isset($fields_infos['_tableinfo_']['ROW_FORMAT'])) ? $fields_infos['_tableinfo_']['ROW_FORMAT'] : '';
echo '<h6>'.$lang['L_TABLE']." `$table_edit_name`</h6>";
$td = '<td valign="top" nowrap="nowrap" class="small">';
//Tabelleneigenschaften
echo '<form action="'.$p.'" method="post"><input type="hidden" name="table_edit_name" value="'.$table_edit_name.'"><table class="bdr">';
echo '<tr class="sqlNew"><td colspan="4" style="font-size:10pt;font-weight:bold;">'.$lang['L_SQL_TBLPROPSOF'].' `'.$table_edit_name.'` ('.$anz_fields.' '.$lang['L_FIELDS'].')</td>';
echo '<td class="small" colspan="2" align="center">Name<br><input type="text" class="text" name="t_edit_name" value="'.$table_edit_name.'" size="30" maxlength="150" style="font-size:11px;"></td></tr>';
echo '<tr class="sqlNew">';
echo '<td class="small" align="center">Engine<br><select name="t_edit_engine" style="font-size:11px;">'.EngineCombo($t_engine).'</select></td>';
echo '<td class="small" align="center">Row Format<br><select name="t_edit_rowformat" style="font-size:11px;">'.GetOptionsCombo($feldrowformat, $t_rowformat).'</select></td>';
echo '<td class="small" align="center">'.$lang['L_CHARSET'].'<br><select name="t_edit_charset" style="font-size:11px;">'.CharsetCombo($t_charset).'</select></td>';
echo '<td class="small" align="center">'.$lang['L_COLLATION'].'<br><select name="t_edit_collate" style="font-size:11px;">'.CollationCombo($t_collation).'</select></td>';
echo '<td class="small" align="center">'.$lang['L_COMMENT'].'<br><input type="text" class="text" name="t_edit_comment" value="'.$t_comment.'" size="30" maxlength="100" style="font-size:11px;"></td>';
echo '<td class="small" align="center">&nbsp;<br><input type="submit" name="t_edit_submit" value="'.$lang['L_CHANGE'].'" class="Formbutton"></td></tr>';
echo '</table></form><p>&nbsp;</p>';
$field_fehler = 0;
echo '<h6>'.$lang['L_FIELDS_OF_TABLE'].' `'.$table_edit_name.'`</h6>';
$d_collate = '';
$d_comment = '';
if (isset($_GET['newfield']) || isset($_GET['editfield']) || $field_fehler > 0 || isset($_POST['newfield_posted'])) {
if (isset($_GET['editfield'])) {
$id = $_GET['editfield'];
}
$d_name = (isset($_GET['editfield'])) ? $fields_infos[$id]['name'] : '';
$d_type = (isset($_GET['editfield'])) ? $fields_infos[$id]['type'] : '';
$d_size = (isset($_GET['editfield'])) ? $fields_infos[$id]['size'] : '';
$d_null = (isset($_GET['editfield'])) ? $fields_infos[$id]['null'] : '';
$d_attribute = (isset($_GET['editfield'])) ? $fields_infos[$id]['attributes'] : '';
$d_default = '';
if (isset($id) && isset($fields_infos[$id]) && isset($fields_infos[$id]['default'])) {
if ('NULL' == $fields_infos[$id]['default']) {
$d_default = 'NULL';
} else {
$d_default = substr($fields_infos[$id]['default'], 1, strlen($fields_infos[$id]['default']) - 2);
}
}
$d_extra = (isset($_GET['editfield'])) ? $fields_infos[$id]['extra'] : '';
$d_primary = $d_unique = $d_index = $d_fulltext = 0;
if (isset($id)) {
if (isset($fields_infos[$id]['collate'])) {
$d_collate = (isset($_GET['editfield'])) ? $fields_infos[$id]['collate'] : '';
}
if (isset($fields_infos[$id]['comment'])) {
$d_comment = (isset($_GET['editfield'])) ? $fields_infos[$id]['comment'] : '';
}
}
$d_privileges = (isset($_GET['editfield'])) ? $fields_infos[$id]['privileges'] : '';
if (isset($_GET['editfield'])) {
$d_primary = (in_array($fields_infos[$id]['name'], $fields_infos['_primarykeys_'])) ? 1 : 0;
$d_index = (in_array($fields_infos[$id]['name'], $fields_infos['_key_'])) ? 1 : 0;
$d_fulltext = (in_array($fields_infos[$id]['name'], $fields_infos['_fulltextkey_'])) ? 1 : 0;
$d_unique = (in_array($fields_infos[$id]['name'], $fields_infos['_uniquekey_'])) ? 1 : 0;
}
echo '<form action="'.$p.'" method="post" id="smallform"><input type="hidden" name="newfield_posted" value="1">';
if (isset($_GET['editfield'])) {
echo '<input type="hidden" name="editfield" value="'.$id.'"><input type="hidden" name="fieldname" value="'.$d_name.'">';
}
if (isset($_POST['newtablesubmit'])) {
echo '<input type="hidden" name="newtablename" value="'.$_POST['newtablename'].'">';
}
echo '<input type="hidden" name="f_primary" value="'.$d_primary.'"><input type="hidden" name="f_unique" value="'.$d_unique.'">';
echo '<input type="hidden" name="f_index" value="'.$d_index.'"><input type="hidden" name="f_fulltext" value="'.$d_fulltext.'">';
echo '<table class="bdr"><tr class="thead"><th colspan="6" align="center">'.((isset($_GET['editfield'])) ? $lang['L_SQL_EDITFIELD'].' `'.$d_name.'`' : $lang['L_SQL_NEWFIELD']).'</th></tr>';
echo '<tr><td class="small">Name<br><input type="text" class="text" value="'.$d_name.'" name="f_name" size="30"></td>';
echo '<td>Type<br><select name="f_type">'.GetOptionsCombo($feldtypen, $d_type).'</select></td>';
echo '<td>Size&nbsp;<br><input type="text" class="text" value="'.$d_size.'" name="f_size" size="3" maxlength="80"></td>';
echo '<td>NULL<br><select name="f_null">'.GetOptionsCombo($feldnulls, $d_null).'</select></td>';
echo '<td align="center">Default<br><input type="text" class="text" name="f_default" value="'.$d_default.'" size="10"></td>';
echo '<td align="center">Extra<br><select name="f_extra">'.GetOptionsCombo($feldextras, $d_extra).'</select></td>';
echo '</tr><tr><td align="center">'.$lang['L_SQL_INDEXES'].'<br>';
echo '<input type="radio" class="radio" name="f_index_new" id="k_no_index" value="no" '.((0 == $d_primary + $d_unique + $d_index + $d_fulltext) ? 'checked="checked"' : '').'>';
echo '<label for="k_no_index">'.$icon['key_nokey'].'</label>&nbsp;&nbsp;';
echo '<input type="radio" class="radio" name="f_index_new" id="k_primary" value="primary" '.((1 == $d_primary) ? 'checked' : '').'>';
echo '<label for="k_primary">'.$icon['key_primary'].'</label>&nbsp;&nbsp;';
echo '<input type="radio" class="radio" name="f_index_new" id="k_unique" value="unique" '.((1 == $d_unique) ? 'checked' : '').'>';
echo '<label for="k_unique">'.$icon['key_unique'].'</label>&nbsp;&nbsp;';
echo '<input type="radio" class="radio" name="f_index_new" id="k_index" value="index" '.((1 == $d_index) ? 'checked' : '').'>&nbsp;';
echo '<label for="k_index">'.$icon['index'].'</label>&nbsp;&nbsp;';
echo '<input type="checkbox" class="checkbox" name="f_indexfull" id="k_fulltext" value="1" '.((1 == $d_fulltext) ? 'checked' : '').'>';
echo '<label for="k_fulltext">'.$icon['key_fulltext'].'</label>&nbsp;&nbsp;</td>';
echo '<td align="center" colspan="2" >'.$lang['L_COLLATION'].'<br><select name="f_collate">'.CollationCombo($d_collate).'</select></td>';
echo '<td align="center">'.$lang['L_SQL_ATTRIBUTES'].'<br><select name="f_attribut">'.AttributeCombo($d_attribute).'</select></td>';
echo '<td align="center">'.$lang['L_SQL_ATPOSITION'].':<br><select name="f_position"><option value=""></option><option value="FIRST">'.$lang['L_SQL_FIRST'].'</option>';
if ($anz_fields > 0) {
for ($i = 0; $i < $anz_fields; ++$i) {
echo '<option value="AFTER `'.$fields_infos[$i]['name'].'`">'.$lang['L_SQL_AFTER'].' `'.$fields_infos[$i]['name'].'`</option>';
}
}
echo '</select></td><td align="center"><br><input type="submit" name="newfieldsubmit" value="'.((isset($_GET['editfield'])) ? $lang['L_SQL_CHANGEFIELD'] : $lang['L_SQL_INSERTFIELD']).'" class="Formbutton"></td></tr></table></form><p>&nbsp;</p>';
} else {
echo '<a style="font-size:8pt;padding-bottom:8px;" href="'.$p.'&amp;newfield=1">'.$lang['L_SQL_INSERTNEWFIELD'].'</a><br><br>';
}
//Felder ausgeben
echo '<table class="bdr">';
for ($i = 0; $i < $anz_fields; ++$i) {
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
if (0 == $i) {
echo '<tr class="thead"><th colspan="2">&nbsp;</th><th>Field</th><th>Type</th><th>Size</th><th>NULL</th><th>Key</th><th>Attribute</th><th>Default</th><th>Extra</th><th>'.
$lang['L_COLLATION'].'</th><th>'.$lang['L_COMMENT'].'</th></tr>';
}
echo '<tr class="'.$cl.'">';
echo '<td nowrap="nowrap">';
echo '<a href="'.$p.'&amp;editfield='.$i.'"><img src="'.$config['files']['iconpath'].'edit.gif" title="edit field" alt="edit field" border="0"></a>&nbsp;&nbsp;';
echo '<a href="'.$p.'&amp;kill='.$fields_infos[$i]['name'].'&amp;anz='.$anz_fields.'" onclick="if(!confirm(\''.$lang['L_ASKDELETEFIELD'].'\')) return false;"><img src="'.$config['files']['iconpath'].'delete.gif" alt="delete field" border="0"></a>&nbsp;&nbsp;';
echo '</td>';
echo '<td style="text-align:right">'.($i + 1).'.</td>';
echo '<td><strong>'.$fields_infos[$i]['name'].'</strong></td><td>'.$fields_infos[$i]['type'].'</td><td>'.$fields_infos[$i]['size'].'</td>';
echo '<td>'.get_output_attribut_null($fields_infos[$i]['null']).'</td><td>';
//key
if (in_array($fields_infos[$i]['name'], $fields_infos['_primarykeys_'])) {
echo $icon['key_primary'];
}
if (in_array($fields_infos[$i]['name'], $fields_infos['_fulltextkey_'])) {
echo $icon['key_fulltext'];
}
if (in_array($fields_infos[$i]['name'], $fields_infos['_uniquekey_'])) {
echo $icon['key_unique'];
}
if (in_array($fields_infos[$i]['name'], $fields_infos['_key_'])) {
echo $icon['index'];
}
echo '</td><td>'.$fields_infos[$i]['attributes'].'</td>';
echo '<td>'.$fields_infos[$i]['default'].'</td>'.$td.$fields_infos[$i]['extra'].'</td>';
echo '<td>'.((MOD_NEW_VERSION) ? $fields_infos[$i]['collate'] : '&nbsp;').'</td>';
echo '<td>'.((isset($fields_infos[$i]['comment'])) ? $fields_infos[$i]['comment'] : '&nbsp;').'</td>';
echo '</tr>';
}
echo '</table><br>';
echo '<h6>'.$lang['L_SQL_TABLEINDEXES'].' `'.$table_edit_name.'`</h6>';
echo '<table class="bdr">
<tr class="thead">
<th colspan="2">&nbsp;</th>
<th>'.$lang['L_NAME'].'</th>
<th>'.$lang['L_SQL_COLUMNS'].'</th>
<th>'.$lang['L_INFO_SIZE'].'</th>
'.((MOD_NEW_VERSION) ? '<th>'.$lang['L_TABLE_TYPE'].'</th>' : '').'
<th>'.$lang['L_SQL_ALLOWDUPS'].'</th>
<th>'.$lang['L_SQL_CARDINALITY'].'</th>
<th>'.$lang['L_COMMENT'].'</th>
</tr>';
$sqlk = 'SHOW KEYS FROM `'.$databases['Name'][$dbid]."`.`$table_edit_name`;";
$res = mod_query($sqlk);
$num = mysqli_num_rows($res);
if (0 == $num) {
echo '<tr><td colspan="6">'.$lang['L_SQL_TABLENOINDEXES'].'</td></tr>';
} else {
for ($i = 0; $i < $num; ++$i) {
$row = mysqli_fetch_array($res, MYSQLI_ASSOC);
if (!isset($row['Comment'])) {
$row['Comment'] = '';
}
$cl = ($i % 2) ? 'dbrow' : 'dbrow1';
//Images
echo '<tr class="'.$cl.'">';
echo '<td>';
if ('PRIMARY' == $row['Key_name']) {
echo '<a href="'.$p.'&amp;killPrimaryKey='.$row['Column_name'].'" onclick="if(!confirm(\''.$lang['L_PRIMARYKEY_CONFIRMDELETE'].'\')) return false;">';
echo '<img src="'.$config['files']['iconpath'].'delete.gif" alt="" border="0">';
echo '</a>';
} else {
echo '<a href="'.$p.'&amp;killIndex='.$row['Key_name'].'" onclick="if(!confirm(\''.$lang['L_KEY_CONFIRMDELETE'].'\')) return false;">';
echo '<img src="'.$config['files']['iconpath'].'delete.gif" alt="" border="0">';
echo '</a>';
}
echo '</td>';
echo '<td style="text-align:right">'.($i + 1).'.</td>';
echo '<td>'.$row['Key_name'].'</td>';
echo '<td>'.$row['Column_name'].'</td>';
echo '<td class="right">';
if (isset($row['Sub_part']) && $row['Sub_part'] > 0) {
echo $row['Sub_part'];
}
echo '</td>';
if (MOD_NEW_VERSION) {
echo '<td>'.$row['Index_type'].'</td>';
}
echo '<td align="center">'.((1 == $row['Non_unique']) ? $lang['L_YES'] : $lang['L_NO']).'</td>';
echo '<td>'.(($row['Cardinality'] >= 0) ? $row['Cardinality'] : $lang['L_NO']).'</td>';
echo '<td>'.$row['Comment'].'</td>';
echo '</tr>';
}
}
echo '</table><br><input type="Button" value="'.$lang['L_SQL_CREATEINDEX'].'" onclick="location.href=\''.$p.'&amp;sql_createindex=1#setnewkeys\'" class="Formbutton">';
if ((isset($_GET['sql_createindex'])) && ('1' == $_GET['sql_createindex'])) { ?>
<script>
function toggleIndexLength(id)
{
var mysqlStrings = ['<?php echo implode("','", $mysql_string_types); ?>'];
var field = 'setNewKey'+id;
var sel = document.getElementById(field).selectedIndex;
var val = document.getElementById(field).options[sel].innerHTML;
document.getElementById('indexSize'+id).disabled = true;
for (i=0;i<mysqlStrings.length;i++)
{
if (val.indexOf("["+mysqlStrings[i]) != -1)
{
document.getElementById('indexSize'+id).disabled = false;
}
}
}
</script>
<?php
echo '<br><a name="setnewkeys"></a>';
echo '<form action="'.$p.'" method="POST">';
echo '<h6>'.$lang['L_SETKEYSFOR'].' `'.$table_edit_name.'`</h6>';
//kopf
echo '<table class="bdr">';
//body
$sqlFelder = 'DESCRIBE `'.$databases['Name'][$dbid].'`.`'.$_GET['tablename'].'`;';
$res = mod_query($sqlFelder);
$num = mysqli_num_rows($res);
if (0 == $num) {
echo '<tr><td>'.$lang['L_SQL_TABLENOINDEXES'].'</td></tr>';
} else {
echo '<tr class="thead"><th>'.$lang['L_NAME'].'</th><th>'.$lang['L_TABLE_TYPE'].'</th></tr>';
echo '<tr>';
echo '<td><input type="text" name="indexName" value="" class="text">';
echo '<td><select name="indexType"><option value="primary">'.$lang['L_TITLE_KEY_PRIMARY'].'</option><option value="unique">'.$lang['L_TITLE_KEY_UNIQUE'].'</option><option value="index" selected="selected">'.$lang['L_TITLE_INDEX'].'</option><option value="fulltext">'.$lang['L_TITLE_KEY_FULLTEXT'].'</option></select></td>';
echo '</tr>';
echo '</table><br>';
//alle Felder holen
$feldArray = [];
echo '<table class="bdr">';
echo '<tr class="thead"><th>#</th><th>'.$lang['L_PRIMARYKEY_FIELD'].'</th><th>'.$lang['L_INFO_SIZE'].'</th>';
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$feldArray[$row['Field']] = $row['Type'];
}
//Primaerschluessel holen, um automatisch vorzuselektieren
$primaryKeys = getPrimaryKeys($databases['Name'][$dbid], $_GET['tablename']);
//eine Select-Box pro Feld anzeigen, Felder für Name und Typ nur in der ersten Zeile
for ($i = 0; $i < $num; ++$i) {
echo '<tr><td class="right">'.($i + 1).'.</td><td>';
$options = "\n\n".'<option value="">---</option>';
$selectedFeldTyp = false;
foreach ($feldArray as $feldName => $feldTyp) {
$options .= "\n".'<option value="'.$feldName.'"';
//alle Primaerschluessel vorselektieren
if (isset($primaryKeys['name'][$i]) && $primaryKeys['name'][$i] == $feldName) {
$options .= ' selected="selected"';
$selectedFeldTyp = $feldTyp;
}
$options .= '>'.$feldName.' ['.$feldTyp.']</option>';
}
echo '<select id="setNewKey'.$i.'" name="setNewKey'.$i.'" onchange="toggleIndexLength('.$i.');">';
echo $options."\n".'</select></td>';
echo '<td>';
$type = explode('(', $selectedFeldTyp);
echo '<input type="text" id="indexSize'.$i.'" name="indexSize'.$i.'" value="" size="10" class="text"';
if (!isset($type[0]) || !in_array($type[0], $mysql_string_types)) {
echo ' disabled="disabled"';
}
echo '></td>';
echo '</tr>';
}
++$i;
}
echo '</table>';
//Speichern Knopf
echo '<br><input name="setNewKeys" type="submit" value="'.$lang['L_SAVE'].'" class="Formbutton">';
echo '</form>';
}
}

View File

@ -0,0 +1,88 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
//Start SQL-Box
$tpl = new MODTemplate();
$tpl->set_filenames([
'show' => $config['paths']['root'].'./tpl/sqlbrowser/sqlbox.tpl', ]);
if (isset($_GET['readfile']) && 1 == $_GET['readfile']) {
$tpl->assign_block_vars('SQLUPLOAD', [
'POSTTARGET' => $params,
'LANG_OPENSQLFILE' => $lang['L_SQL_OPENFILE'],
'LANG_OPENSQLFILE_BUTTON' => $lang['L_SQL_OPENFILE_BUTTON'],
'LANG_SQL_MAXSIZE' => $lang['L_MAX_UPLOAD_SIZE'],
'MAX_FILESIZE' => $config['upload_max_filesize'], ]);
}
if (isset($_POST['submit_openfile'])) {
//open file
if (!isset($_FILES['upfile']['name']) || empty($_FILES['upfile']['name'])) {
$aus .= '<span class="error">'.$lang['L_FM_UPLOADFILEREQUEST'].'</span>';
} else {
$fn = $_FILES['upfile']['tmp_name'];
if ('.gz' == strtolower(substr($_FILES['upfile']['name'], -3))) {
$read__user_sqlfile = gzfile($fn);
} else {
$read__user_sqlfile = file($fn);
}
$aus .= '<span>geladenes File: <strong>'.$_FILES['upfile']['name'].'</strong>&nbsp;&nbsp;&nbsp;'.byte_output(filesize($_FILES['upfile']['tmp_name'])).'</span>';
$sql_loaded = implode('', $read__user_sqlfile);
}
}
// Sind SQL-Befehle in der SQLLib vorhanden?
$sqlcombo = SQL_ComboBox();
if ($sqlcombo > '') {
$tpl->assign_block_vars('SQLCOMBO', [
'SQL_COMBOBOX' => $sqlcombo, ]);
}
$tpl->assign_vars([
'LANG_SQL_WARNING' => $lang['L_SQL_WARNING'],
'ICONPATH' => $config['files']['iconpath'],
'MYSQL_REF' => $mysql_help_ref,
'BOXSIZE' => ((isset($config['interface_sqlboxsize'])) ? $config['interface_sqlboxsize'] : ''),
'BOXCONTENT' => ((isset($sql_loaded)) ? $sql_loaded : $sql['sql_statement'].$sql['order_statement']),
'LANG_SQL_BEFEHLE' => $lang['L_SQL_BEFEHLE'],
'TABLE_COMBOBOX' => Table_ComboBox(),
'LANG_SQL_EXEC' => $lang['L_SQL_EXEC'],
'LANG_RESET' => $lang['L_RESET'],
'PARAMS' => $params,
'DB' => $databases['Name'][$dbid],
'DBID' => $dbid,
'TABLENAME' => $tablename,
'ICON_SEARCH' => $icon['search'],
'ICON_UPLOAD' => $icon['upload'],
'ICON_MYSQL_HELP' => $icon['mysql_help'],
'MYSQL_HELP' => $lang['L_TITLE_MYSQL_HELP'],
'DBID' => $databases['db_selected_index'],
'LANG_TOOLBOX' => $lang['L_TOOLS_TOOLBOX'],
'LANG_TOOLS' => $lang['L_TOOLS'],
'LANG_DB' => $lang['L_DB'],
'LANG_TABLE' => $lang['L_TABLE'],
'LANG_SQL_TABLEVIEW' => $lang['L_SQL_TABLEVIEW'],
'LANG_BACK_TO_DB_OVERVIEW' => $lang['L_SQL_BACKDBOVERVIEW'], ]);
if ($tablename > '') {
$tpl->assign_block_vars('TABLE_SELECTED', []);
}
$tpl->pparse('show');

69
msd/inc/sqllib.php Normal file
View File

@ -0,0 +1,69 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
//SQL-Library
include './language/'.$config['language'].'/lang_sql.php';
/*
Template
if $sqllib[$i]['sql'] =trenn, Then it is a Heading
$sqllib[$i]['name'] = '';
$sqllib[$i]['sql'] = '';
$i++;
*/
$i = 0;
$sqllib = [];
$sqllib[$i]['name'] = $lang['L_SQLLIB_GENERALFUNCTIONS'];
$sqllib[$i]['sql'] = 'trenn';
++$i;
$sqllib[$i]['name'] = $lang['L_SQLLIB_RESETAUTO'];
$sqllib[$i]['sql'] = 'ALTER TABLE `table` AUTO_INCREMENT=1;';
++$i;
/********* phpBB-Boards *********************************/
$sqllib[$i]['name'] = 'phpBB-'.$lang['L_SQLLIB_BOARDS'];
$sqllib[$i]['sql'] = 'trenn';
++$i;
// Bord de-/aktivieren
$sqllib[$i]['name'] = $lang['L_SQLLIB_DEACTIVATEBOARD'].' [phpBB]';
$sqllib[$i]['sql'] = "UPDATE `phpbb_config` set config_value=1 where config_name='board_disable'";
++$i;
$sqllib[$i]['name'] = $lang['L_SQLLIB_ACTIVATEBOARD'].' [phpBB]';
$sqllib[$i]['sql'] = "UPDATE `phpbb_config` set config_value=0 where config_name='board_disable'";
++$i;
// Bord de-/aktivieren
$sqllib[$i]['name'] = 'vBulletin-'.$lang['L_SQLLIB_BOARDS'];
$sqllib[$i]['sql'] = 'trenn';
++$i;
// Bord de-/aktivieren
$sqllib[$i]['name'] = $lang['L_SQLLIB_DEACTIVATEBOARD'].' [vBulletin]';
$sqllib[$i]['sql'] = 'UPDATE forum SET options = options - 1 WHERE options & 1';
++$i;
$sqllib[$i]['name'] = $lang['L_SQLLIB_ACTIVATEBOARD'].' [vBulletin]';
$sqllib[$i]['sql'] = 'UPDATE forum SET options = options + 1 WHERE NOT (options & 1)';
++$i;

181
msd/inc/table_query.php Normal file
View File

@ -0,0 +1,181 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
include './language/'.$config['language'].'/lang.php';
include './language/'.$config['language'].'/lang_dump.php';
include './inc/template.php';
$tblr = ('dump' == $tblfrage_refer) ? 'Backup' : 'Restore';
$filename = (isset($_GET['filename'])) ? $_GET['filename'] : '';
if (isset($_POST['file'][0])) {
$filename = $_POST['file'][0];
}
ob_start();
$tpl = new MODTemplate();
$sel_dump_encoding = isset($_POST['sel_dump_encoding']) ? $_POST['sel_dump_encoding'] : '';
$tpl = new MODtemplate();
//Informationen zusammenstellen
if ('Backup' == $tblr) {
$tpl->set_filenames([
'show' => './tpl/dump_select_tables.tpl',
]);
$button_name = 'dump_tbl';
//Info aus der Datenbank lesen
mod_mysqli_connect();
$res = mysqli_query($config['dbconnection'], 'SHOW TABLE STATUS FROM `'.$databases['db_actual'].'`');
$numrows = mysqli_num_rows($res);
$tbl_zeile = '';
for ($i = 0; $i < $numrows; ++$i) {
$row = mysqli_fetch_array($res, MYSQLI_ASSOC);
//v($row);
// Get nr of records -> need to do it this way because of incorrect returns when using InnoDBs
$sql_2 = 'SELECT count(*) as `count_records` FROM `'.$databases['db_actual'].'`.`'.$row['Name'].'`';
$res2 = mysqli_query($config['dbconnection'], $sql_2);
if (false === $res2) {
$read_error = mysqli_error($config['dbconnection']);
$row['Rows'] = '<span class="error">'.$lang['L_ERROR'].': '.$read_error.'</span>';
} else {
$row2 = mysqli_fetch_array($res2);
$row['Rows'] = $row2['count_records'];
}
$klasse = ($i % 2) ? 1 : '';
$table_size = $row['Data_length'] + $row['Index_length'];
$table_type = $row['Engine'];
if ('VIEW' == substr($row['Comment'], 0, 4)) {
$table_type = 'View';
$table_size = '-';
}
$tpl->assign_block_vars('ROW', [
'CLASS' => 'dbrow'.$klasse,
'ID' => $i,
'NR' => $i + 1,
'TABLENAME' => $row['Name'],
'TABLETYPE' => $table_type,
'RECORDS' => 'View' == $table_type ? '<i>'.$row['Rows'].'</i>' : '<strong>'.$row['Rows'].'</strong>',
'SIZE' => is_int($table_size) ? byte_output($table_size) : $table_size,
'LAST_UPDATE' => $row['Update_time'],
]);
}
} else {
$tpl->set_filenames([
'show' => './tpl/restore_select_tables.tpl',
]);
//Restore - Header aus Backupfile lesen
$button_name = 'restore_tbl';
$gz = (substr($filename, -3)) == '.gz' ? 1 : 0;
if ($gz) {
$fp = gzopen($fpath.$filename, 'r');
$statusline = gzgets($fp, 40960);
$offset = gztell($fp);
} else {
$fp = fopen($fpath.$filename, 'r');
$statusline = fgets($fp, 5000);
$offset = ftell($fp);
}
//Header auslesen
$sline = ReadStatusline($statusline);
$anzahl_tabellen = $sline['tables'];
$anzahl_eintraege = $sline['records'];
$tbl_zeile = '';
$part = ('' == $sline['part']) ? 0 : substr($sline['part'], 3);
if (-1 == $anzahl_eintraege) {
// not a backup of MySQLDumper
$tpl->assign_block_vars('NO_MOD_BACKUP', []);
} else {
$tabledata = [];
$i = 0;
//Tabellenfinos lesen
gzseek($fp, $offset);
$eof = false;
while (!$eof) {
$line = $gz ? gzgets($fp, 40960) : fgets($fp, 40960);
if ('-- TABLE|' == substr($line, 0, 9)) {
$d = explode('|', $line);
$tabledata[$i]['name'] = $d[1];
$tabledata[$i]['records'] = $d[2];
$tabledata[$i]['size'] = $d[3];
$tabledata[$i]['update'] = $d[4];
$tabledata[$i]['engine'] = isset($d[5]) ? $d[5] : '';
++$i;
}
if ('-- EOF' == substr($line, 0, 6)) {
$eof = true;
}
if ('create' == substr(strtolower($line), 0, 6)) {
$eof = true;
}
}
for ($i = 0; $i < sizeof($tabledata); ++$i) {
$klasse = ($i % 2) ? 1 : '';
$tpl->assign_block_vars('ROW', [
'CLASS' => 'dbrow'.$klasse,
'ID' => $i,
'NR' => $i + 1,
'TABLENAME' => $tabledata[$i]['name'],
'RECORDS' => $tabledata[$i]['records'],
'SIZE' => byte_output($tabledata[$i]['size']),
'LAST_UPDATE' => $tabledata[$i]['update'],
'TABLETYPE' => $tabledata[$i]['engine'],
]);
}
}
if ($gz) {
gzclose($fp);
} else {
fclose($fp);
}
}
if (!isset($dk)) {
$dk = '';
}
$confirm_restore = $lang['L_FM_ALERTRESTORE1'].' `'.$databases['db_actual'].'` '.$lang['L_FM_ALERTRESTORE2'].' '.$filename.' '.$lang['L_FM_ALERTRESTORE3'];
$tpl->assign_vars([
'PAGETITLE' => $tblr.' -'.$lang['L_TABLESELECTION'],
'L_NAME' => $lang['L_NAME'],
'L_DATABASE' => $lang['L_DB'],
'DATABASE' => $databases['db_actual'],
'L_LAST_UPDATE' => $lang['L_LASTBUFROM'],
'SEL_DUMP_ENCODING' => $sel_dump_encoding,
'FILENAME' => $filename,
'DUMP_COMMENT' => $dk,
'BUTTON_NAME' => $button_name,
'L_START_BACKUP' => $lang['L_STARTDUMP'],
'L_START_RESTORE' => $lang['L_FM_RESTORE'],
'L_ROWS' => $lang['L_INFO_RECORDS'],
'L_SIZE' => $lang['L_INFO_SIZE'],
'L_TABLE_TYPE' => $lang['L_TABLE_TYPE'],
'L_SELECT_ALL' => $lang['L_SELECTALL'],
'L_DESELECT_ALL' => $lang['L_DESELECTALL'],
'L_RESTORE' => $lang['L_RESTORE'],
'L_NO_MOD_BACKUP' => $lang['L_NOT_SUPPORTED'],
'L_CONFIRM_RESTORE' => $confirm_restore,
]);
$tpl->pparse('show');
ob_end_flush();
exit();

456
msd/inc/template.php Normal file
View File

@ -0,0 +1,456 @@
<?php
/* ----------------------------------------------------------------------
MyOOS [Dumper]
http://www.oos-shop.de/
Copyright (c) 2013 - 2022 by the MyOOS Development Team.
----------------------------------------------------------------------
Based on:
MySqlDumper
http://www.mysqldumper.de
Copyright (C)2004-2011 Daniel Schlichtholz (admin@mysqldumper.de)
----------------------------------------------------------------------
Released under the GNU General Public License
---------------------------------------------------------------------- */
if (!defined('MOD_VERSION')) {
exit('No direct access.');
}
define('TPL_DEBUG', 0); // used if evaluationg of template fails
/***************************************************************************
* template.php
* -------------------
* begin : Saturday, Feb 13, 2001
* copyright : (C) 2001 The phpBB Group
* email : support@phpbb.com
*
* $Id: template.php 1330 2011-01-07 17:51:25Z dsb1971 $
*
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
/**
* Template class. By Nathan Codding of the phpBB group.
* The interface was originally inspired by PHPLib templates,
* and the template file formats are quite similar.
*/
class MODTemplate
{
public $classname = 'MODTemplate';
// variable that holds all the data we'll be substituting into
// the compiled templates.
// ...
// This will end up being a multi-dimensional array like this:
// $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value
// if it's a root-level variable, it'll be like this:
// $this->_tpldata[.][0][varname] == value
public $_tpldata = [];
// Hash of filenames for each template handle.
public $files = [];
// Root template directory.
public $root = '';
// this will hash handle names to the compiled code for that handle.
public $compiled_code = [];
// This will hold the uncompiled code for that handle.
public $uncompiled_code = [];
/**
* Constructor. Simply sets the root dir.
*/
public function __construct($root = '.')
{
$this->set_rootdir($root);
}
/**
* Destroys this template object. Should be called when you're done with it, in order
* to clear out the template data so you can load/parse a new template set.
*/
public function destroy()
{
$this->_tpldata = [];
}
/**
* Sets the template root directory for this Template object.
*/
public function set_rootdir($dir)
{
if (!is_dir($dir)) {
return false;
}
$this->root = $dir;
return true;
}
/**
* Sets the template filenames for handles. $filename_array
* should be a hash of handle => filename pairs.
*/
public function set_filenames($filename_array)
{
if (!is_array($filename_array)) {
return false;
}
reset($filename_array);
foreach ($filename_array as $handle => $filename) {
$this->files[$handle] = $this->make_filename($filename);
}
return true;
}
/**
* Load the file for the handle, compile the file,
* and run the compiled code. This will print out
* the results of executing the template.
*/
public function pparse($handle)
{
// Edit DSB: autimatically assign language vars
global $lang;
$this->assign_vars($lang);
if (!$this->loadfile($handle)) {
exit("Template->pparse(): Couldn't load template file for handle $handle");
}
// actually compile the template now.
if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle])) {
// Actually compile the code now.
$this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
}
// Run the compiled code.
if (defined(TPL_DEBUG) && TPL_DEBUG > 0) {
echo '<pre>'.htmlspecialchars($this->compiled_code[$handle]).'</pre>';
}
eval($this->compiled_code[$handle]);
return true;
}
/**
* Inserts the uncompiled code for $handle as the
* value of $varname in the root-level. This can be used
* to effectively include a template in the middle of another
* template.
* Note that all desired assignments to the variables in $handle should be done
* BEFORE calling this function.
*/
public function assign_var_from_handle($varname, $handle)
{
if (!$this->loadfile($handle)) {
exit("Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
}
// Compile it, with the "no echo statements" option on.
$_str = '';
$code = $this->compile($this->uncompiled_code[$handle], true, '_str');
// evaluate the variable assignment.
eval($code);
// assign the value of the generated variable to the given varname.
$this->assign_var($varname, $_str);
return true;
}
/**
* Block-level variable assignment. Adds a new block iteration with the given
* variable assignments. Note that this should only be called once per block
* iteration.
*/
public function assign_block_vars($blockname, $vararray)
{
if (strstr($blockname, '.')) {
// Nested block.
$blocks = explode('.', $blockname);
$blockcount = sizeof($blocks) - 1;
$str = '$this->_tpldata';
for ($i = 0; $i < $blockcount; ++$i) {
$str .= '[\''.$blocks[$i].'.\']';
eval('$lastiteration = sizeof('.$str.') - 1;');
$str .= '['.$lastiteration.']';
}
// Now we add the block that we're actually assigning to.
// We're adding a new iteration to this block with the given
// variable assignments.
$str .= '[\''.$blocks[$blockcount].'.\'][] = $vararray;';
// Now we evaluate this assignment we've built up.
eval($str);
} else {
// Top-level block.
// Add a new iteration to this block with the variable assignments
// we were given.
$this->_tpldata[$blockname.'.'][] = $vararray;
}
return true;
}
/**
* Root-level variable assignment. Adds to current assignments, overriding
* any existing variable assignment with the same name.
*/
public function assign_vars($vararray)
{
global $lang;
foreach ($vararray as $key => $val) {
$this->_tpldata['.'][0][$key] = $val;
}
return true;
}
/**
* Root-level variable assignment. Adds to current assignments, overriding
* any existing variable assignment with the same name.
*/
public function assign_var($varname, $varval)
{
$this->_tpldata['.'][0][$varname] = $varval;
return true;
}
/**
* Generates a full path+filename for the given filename, which can either
* be an absolute name, or a name relative to the rootdir for this Template
* object.
*/
public function make_filename($filename)
{
// Check if it's an absolute or relative path.
/*
if (substr($filename, 0, 1) != '/')
{
$filename = $this->root.'/'.$filename;
}
*/
if (!file_exists($filename)) {
exit("Template->make_filename(): Error - file $filename does not exist");
}
return $filename;
}
/**
* If not already done, load the file for the given handle and populate
* the uncompiled_code[] hash with its code. Do not compile.
*/
public function loadfile($handle)
{
// If the file for this handle is already loaded and compiled, do nothing.
if (isset($this->uncompiled_code[$handle]) && !empty($this->uncompiled_code[$handle])) {
return true;
}
// If we don't have a file assigned to this handle, die.
if (!isset($this->files[$handle])) {
exit("Template->loadfile(): No file specified for handle $handle");
}
$filename = $this->files[$handle];
$str = implode('', @file($filename));
if (empty($str)) {
exit("Template->loadfile(): File $filename for handle $handle is empty");
}
$this->uncompiled_code[$handle] = $str;
return true;
}
/**
* Compiles the given string of code, and returns
* the result in a string.
* If "do_not_echo" is true, the returned code will not be directly
* executable, but can be used as part of a variable assignment
* for use in assign_code_from_handle().
*/
public function compile($code, $do_not_echo = false, $retvar = '')
{
// replace \ with \\ and then ' with \'.
$code = str_replace('\\', '\\\\', $code);
$code = str_replace('\'', '\\\'', $code);
// change template varrefs into PHP varrefs
// This one will handle varrefs WITH namespaces
$varrefs = [];
preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
$varcount = sizeof($varrefs[1]);
for ($i = 0; $i < $varcount; ++$i) {
$namespace = $varrefs[1][$i];
$varname = $varrefs[3][$i];
$new = $this->generate_block_varref($namespace, $varname);
$code = str_replace($varrefs[0][$i], $new, $code);
}
// This will handle the remaining root-level varrefs
$code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\'.( ( isset($this->_tpldata[\'.\'][0][\'\1\']) ) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\' ) . \'', $code);
// Break it up into lines.
$code_lines = explode("\n", $code);
$block_nesting_level = 0;
$block_names = [];
$block_names[0] = '.';
// Second: prepend echo ', append '."\n"; to each line.
$line_count = sizeof($code_lines);
for ($i = 0; $i < $line_count; ++$i) {
$code_lines[$i] = chop($code_lines[$i]);
if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m)) {
$n[0] = $m[0];
$n[1] = $m[1];
// Added: dougk_ff7-Keeps templates from bombing if begin is on the same line as end.. I think. :)
if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n)) {
++$block_nesting_level;
$block_names[$block_nesting_level] = $m[1];
if ($block_nesting_level < 2) {
// Block is not nested.
$code_lines[$i] = '$_'.$n[1].'_count = ( isset($this->_tpldata[\''.$n[1].'.\']) ) ? sizeof($this->_tpldata[\''.$n[1].'.\']) : 0;';
$code_lines[$i] .= "\n".'for ($_'.$n[1].'_i = 0; $_'.$n[1].'_i < $_'.$n[1].'_count; $_'.$n[1].'_i++)';
$code_lines[$i] .= "\n".'{';
} else {
// This block is nested.
// Generate a namespace string for this block.
$namespace = implode('.', $block_names);
// strip leading period from root level..
$namespace = substr($namespace, 2);
// Get a reference to the data array for this block that depends on the
// current indices of all parent blocks.
$varref = $this->generate_block_data_ref($namespace, false);
// Create the for loop code to iterate over this block.
$code_lines[$i] = '$_'.$n[1].'_count = ( isset('.$varref.') ) ? sizeof('.$varref.') : 0;';
$code_lines[$i] .= "\n".'for ($_'.$n[1].'_i = 0; $_'.$n[1].'_i < $_'.$n[1].'_count; $_'.$n[1].'_i++)';
$code_lines[$i] .= "\n".'{';
}
// We have the end of a block.
unset($block_names[$block_nesting_level]);
--$block_nesting_level;
$code_lines[$i] .= '} // END '.$n[1];
$m[0] = $n[0];
$m[1] = $n[1];
} else {
// We have the start of a block.
++$block_nesting_level;
$block_names[$block_nesting_level] = $m[1];
if ($block_nesting_level < 2) {
// Block is not nested.
$code_lines[$i] = '$_'.$m[1].'_count = ( isset($this->_tpldata[\''.$m[1].'.\']) ) ? sizeof($this->_tpldata[\''.$m[1].'.\']) : 0;';
$code_lines[$i] .= "\n".'for ($_'.$m[1].'_i = 0; $_'.$m[1].'_i < $_'.$m[1].'_count; $_'.$m[1].'_i++)';
$code_lines[$i] .= "\n".'{';
} else {
// This block is nested.
// Generate a namespace string for this block.
$namespace = implode('.', $block_names);
// strip leading period from root level..
$namespace = substr($namespace, 2);
// Get a reference to the data array for this block that depends on the
// current indices of all parent blocks.
$varref = $this->generate_block_data_ref($namespace, false);
// Create the for loop code to iterate over this block.
$code_lines[$i] = '$_'.$m[1].'_count = ( isset('.$varref.') ) ? sizeof('.$varref.') : 0;';
$code_lines[$i] .= "\n".'for ($_'.$m[1].'_i = 0; $_'.$m[1].'_i < $_'.$m[1].'_count; $_'.$m[1].'_i++)';
$code_lines[$i] .= "\n".'{';
}
}
} elseif (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m)) {
// We have the end of a block.
unset($block_names[$block_nesting_level]);
--$block_nesting_level;
$code_lines[$i] = '} // END '.$m[1];
} else {
// We have an ordinary line of code.
if (!$do_not_echo) {
$code_lines[$i] = 'echo \''.$code_lines[$i].'\'."\\n";';
} else {
$code_lines[$i] = '$'.$retvar.'.= \''.$code_lines[$i].'\'."\\n";';
}
}
}
// Bring it back into a single string of lines of code.
$code = implode("\n", $code_lines);
return $code;
}
/**
* Generates a reference to the given variable inside the given (possibly nested)
* block namespace. This is a string of the form:
* '.$this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname'].'
* It's ready to be inserted into an "echo" line in one of the templates.
* NOTE: expects a trailing "." on the namespace.
*/
public function generate_block_varref($namespace, $varname)
{
// Strip the trailing period.
$namespace = substr($namespace, 0, strlen($namespace) - 1);
// Get a reference to the data block for this namespace.
$varref = $this->generate_block_data_ref($namespace, true);
// Prepend the necessary code to stick this in an echo line.
// Append the variable reference.
$varref .= '[\''.$varname.'\']';
$varref = '\'.( ( isset('.$varref.') ) ? '.$varref.' : \'\' ) . \'';
return $varref;
}
/**
* Generates a reference to the array of data values for the given
* (possibly nested) block namespace. This is a string of the form:
* $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN'].
*
* If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above.
* NOTE: does not expect a trailing "." on the blockname.
*/
public function generate_block_data_ref($blockname, $include_last_iterator)
{
// Get an array of the blocks involved.
$blocks = explode('.', $blockname);
$blockcount = sizeof($blocks) - 1;
$varref = '$this->_tpldata';
// Build up the string with everything but the last child.
for ($i = 0; $i < $blockcount; ++$i) {
$varref .= '[\''.$blocks[$i].'.\'][$_'.$blocks[$i].'_i]';
}
// Add the block reference for the last child.
$varref .= '[\''.$blocks[$blockcount].'.\']';
// Add the iterator for the last child if requried.
if ($include_last_iterator) {
$varref .= '[$_'.$blocks[$blockcount].'_i]';
}
return $varref;
}
}