コード例 #1
0
ファイル: Snapshot.php プロジェクト: askzap/ultimate
 /**
  * Creates database and imports dump there
  * @param  string  $db_name db name
  * @return boolean true on success, false - otherwise
  */
 public static function createDb($db_name = '')
 {
     $snapshot_dir = Registry::get('config.dir.snapshots');
     $dbdump_filename = empty($db_name) ? 'cmp_current.sql' : 'cmp_release.sql';
     if (!fn_mkdir($snapshot_dir)) {
         fn_set_notification('E', __('error'), __('text_cannot_create_directory', array('[directory]' => fn_get_rel_dir($snapshot_dir))));
         return false;
     }
     $dump_file = $snapshot_dir . $dbdump_filename;
     if (is_file($dump_file)) {
         if (!is_writable($dump_file)) {
             fn_set_notification('E', __('error'), __('dump_file_not_writable'));
             return false;
         }
     }
     $fd = @fopen($snapshot_dir . $dbdump_filename, 'w');
     if (!$fd) {
         fn_set_notification('E', __('error'), __('dump_cant_create_file'));
         return false;
     }
     if (!empty($db_name)) {
         Database::changeDb($db_name);
     }
     // set export format
     db_query("SET @SQL_MODE = 'MYSQL323'");
     fn_start_scroller();
     $create_statements = array();
     $insert_statements = array();
     $status_data = db_get_array("SHOW TABLE STATUS");
     $dbdump_tables = array();
     foreach ($status_data as $k => $v) {
         $dbdump_tables[] = $v['Name'];
     }
     // get status data
     $t_status = db_get_hash_array("SHOW TABLE STATUS", 'Name');
     foreach ($dbdump_tables as $k => $table) {
         fn_echo('<br />' . __('backupping_data') . ': <b>' . $table . '</b>&nbsp;&nbsp;');
         $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
         $index = db_get_array("SHOW INDEX FROM {$table}");
         $order_by = array();
         foreach ($index as $kk => $vv) {
             if ($vv['Key_name'] == 'PRIMARY') {
                 $order_by[] = '`' . $vv['Column_name'] . '`';
             }
         }
         if (!empty($order_by)) {
             $order_by = 'ORDER BY ' . implode(',', $order_by);
         } else {
             $order_by = '';
         }
         // Define iterator
         if (!empty($t_status[$table]) && $t_status[$table]['Avg_row_length'] < DB_MAX_ROW_SIZE) {
             $it = DB_ROWS_PER_PASS;
         } else {
             $it = 1;
         }
         for ($i = 0; $i < $total_rows; $i = $i + $it) {
             $table_data = db_get_array("SELECT * FROM {$table} {$order_by} LIMIT {$i}, {$it}");
             foreach ($table_data as $_tdata) {
                 $_tdata = fn_add_slashes($_tdata, true);
                 $values = array();
                 foreach ($_tdata as $v) {
                     $values[] = $v !== null ? "'{$v}'" : 'NULL';
                 }
                 fwrite($fd, "INSERT INTO {$table} (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES (" . implode(', ', $values) . ");\n");
             }
             fn_echo(' .');
         }
     }
     fn_stop_scroller();
     if (!empty($db_name)) {
         Settings::instance()->reloadSections();
     }
     if (fn_allowed_for('ULTIMATE')) {
         $companies = fn_get_short_companies();
         asort($companies);
         $settings['company_root'] = Settings::instance()->getList();
         foreach ($companies as $k => $v) {
             $settings['company_' . $k] = Settings::instance()->getList(0, 0, false, $k);
         }
     } else {
         $settings['company_root'] = Settings::instance()->getList();
     }
     if (!empty($db_name)) {
         Database::changeDb(Registry::get('config.db_name'));
     }
     $settings = self::processSettings($settings, '');
     $settings = self::formatSettings($settings['data']);
     ksort($settings);
     $data = print_r($settings, true);
     fwrite($fd, $data);
     fclose($fd);
     @chmod($snapshot_dir . $dbdump_filename, DEFAULT_FILE_PERMISSIONS);
     return true;
 }
コード例 #2
0
ファイル: fn.database.php プロジェクト: askzap/ultimate
/**
 * Exports database to file
 *
 * @param string $file_name path to file will be created
 * @param array $dbdump_tables List of tables to be exported
 * @param bool $dbdump_schema Export database schema
 * @param bool $dbdump_data Export tatabase data
 * @param bool $log Log database export action
 * @param bool $show_progress Show or do not show process by printing ' .'
 * @param bool $move_progress_bar Move COMET progress bar or not on show progress
 * @param array $change_table_prefix Array with 2 keys (from, to) to change table prefix
 * @return bool false, if file is not accessible
 */
function db_export_to_file($file_name, $dbdump_tables, $dbdump_schema, $dbdump_data, $log = true, $show_progress = true, $move_progress_bar = true, $change_table_prefix = array())
{
    $fd = @fopen($file_name, 'w');
    if (!$fd) {
        fn_set_notification('E', __('error'), __('dump_cant_create_file'));
        return false;
    }
    if ($log) {
        // Log database backup
        fn_log_event('database', 'backup');
    }
    // set export format
    Database::query("SET @SQL_MODE = 'MYSQL323'");
    $create_statements = array();
    $insert_statements = array();
    if ($show_progress && $move_progress_bar) {
        fn_set_progress('step_scale', sizeof($dbdump_tables) * ((int) $dbdump_schema + (int) $dbdump_data));
    }
    // get status data
    $t_status = Database::getHash("SHOW TABLE STATUS", 'Name');
    foreach ($dbdump_tables as $k => $table) {
        $_table = !empty($change_table_prefix) ? str_replace($change_table_prefix['from'], $change_table_prefix['to'], $table) : $table;
        if ($dbdump_schema) {
            if ($show_progress) {
                fn_set_progress('echo', '<br />' . __('backupping_schema') . ': <b>' . $table . '</b>', $move_progress_bar);
            }
            fwrite($fd, "\nDROP TABLE IF EXISTS " . $_table . ";\n");
            $scheme = Database::getRow("SHOW CREATE TABLE {$table}");
            $_scheme = array_pop($scheme);
            if ($change_table_prefix) {
                $_scheme = str_replace($change_table_prefix['from'], $change_table_prefix['to'], $_scheme);
            }
            fwrite($fd, $_scheme . ";\n\n");
        }
        if ($dbdump_data) {
            if ($show_progress) {
                fn_set_progress('echo', '<br />' . __('backupping_data') . ': <b>' . $table . '</b>&nbsp;&nbsp;', $move_progress_bar);
            }
            $total_rows = Database::getField("SELECT COUNT(*) FROM {$table}");
            // Define iterator
            if (!empty($t_status[$table]) && $t_status[$table]['Avg_row_length'] < DB_MAX_ROW_SIZE) {
                $it = DB_ROWS_PER_PASS;
            } else {
                $it = 1;
            }
            for ($i = 0; $i < $total_rows; $i = $i + $it) {
                $table_data = Database::getArray("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                foreach ($table_data as $_tdata) {
                    $_tdata = fn_add_slashes($_tdata, true);
                    $values = array();
                    foreach ($_tdata as $v) {
                        $values[] = $v !== null ? "'{$v}'" : 'NULL';
                    }
                    fwrite($fd, "INSERT INTO {$_table} (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES (" . implode(', ', $values) . ");\n");
                }
                if ($show_progress) {
                    fn_echo(' .');
                }
            }
        }
    }
    fclose($fd);
    @chmod($file_name, DEFAULT_FILE_PERMISSIONS);
    return true;
}
コード例 #3
0
ファイル: fn.common.php プロジェクト: arpad9/bygmarket
/**
 * Add slashes
 *
 * @param mixed $var variable to add slashes to
 * @param boolean $escape_nls if true, escape "new line" chars with extra slash
 * @return mixed filtered variable
 */
function fn_add_slashes(&$var, $escape_nls = false)
{
    if (!is_array($var)) {
        return $var === null ? null : ($escape_nls == true ? str_replace("\n", "\\n", addslashes($var)) : addslashes($var));
    } else {
        $slashed = array();
        foreach ($var as $k => $v) {
            $sk = addslashes($k);
            if (!is_array($v)) {
                $sv = $v === null ? null : ($escape_nls == true ? str_replace("\n", "\\n", addslashes($v)) : addslashes($v));
            } else {
                $sv = fn_add_slashes($v, $escape_nls);
            }
            $slashed[$sk] = $sv;
        }
        return $slashed;
    }
}
コード例 #4
0
ファイル: database.php プロジェクト: diedsmiling/busenika
             $__scheme = db_get_row("SHOW CREATE TABLE {$table}");
             fwrite($fd, array_pop($__scheme) . ";\n\n");
         }
         if (!empty($_REQUEST['dbdump_data']) && $_REQUEST['dbdump_data'] == 'Y') {
             fn_echo('<br />' . fn_get_lang_var('backupping_data') . ': <b>' . $table . '</b>&nbsp;&nbsp;');
             $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
             // Define iterator
             if (!empty($t_status[$table]) && $t_status[$table]['Avg_row_length'] < DB_MAX_ROW_SIZE) {
                 $it = DB_ROWS_PER_PASS;
             } else {
                 $it = 1;
             }
             for ($i = 0; $i < $total_rows; $i = $i + $it) {
                 $table_data = db_get_array("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                 foreach ($table_data as $_tdata) {
                     $_tdata = fn_add_slashes($_tdata, true);
                     fwrite($fd, "INSERT INTO {$table} (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES ('" . implode('\', \'', array_values($_tdata)) . "');\n");
                 }
                 fn_echo(' .');
             }
         }
     }
     fclose($fd);
     @chmod(DIR_DATABASE . 'backup/' . $dbdump_filename, DEFAULT_FILE_PERMISSIONS);
     if ($_REQUEST['dbdump_compress'] == 'Y') {
         fn_echo('<br />' . fn_get_lang_var('compressing_backup') . '...');
         fn_compress_files($dbdump_filename . '.tgz', $dbdump_filename, dirname($dump_file));
         unlink($dump_file);
     }
     fn_stop_scroller();
 }
コード例 #5
0
/**
 * Functions creates dump of tables in $file.
 *
 * @param mixed $tables Array of tables
 * @param string $dir Directory for saving file with table names
 * @param string $file Dump file name  \
 * @param Logger $log
 * @return bool Boolean False on failure
 */
function fn_uc_backup_tables($tables, $dir, $file, $log)
{
    if (empty($tables)) {
        return array();
    }
    if (!is_array($tables)) {
        $tables = array($tables);
    }
    $new_license_data = fn_uc_get_new_license_data();
    if (!empty($new_license_data['new_license']) && !in_array(Registry::get('config.table_prefix') . 'settings', $tables)) {
        $tables[] = Registry::get('config.table_prefix') . 'settings';
    }
    $file_backuped_tables = "{$dir}/db_backup_tables.txt";
    $backuped_tables = is_file($file_backuped_tables) ? explode("\n", fn_get_contents($file_backuped_tables)) : array();
    foreach ($tables as $key => &$table) {
        $table = fn_check_db_prefix($table, Registry::get('config.table_prefix'));
        if (in_array($table, $backuped_tables)) {
            unset($tables[$key]);
        }
    }
    if (empty($tables)) {
        return $tables;
    }
    if (false === fn_uc_is_enough_disk_space($file, $tables)) {
        fn_set_notification('W', __('warning'), __('text_uc_no_enough_space_to_backup_database'));
        return false;
    }
    if (fn_uc_is_mysqldump_available(Registry::get('config.db_password'))) {
        $log->write('Using mysqldump', __FILE__, __LINE__);
        $command = 'mysqldump --compact --no-create-db --add-drop-table --default-character-set=utf8 --skip-comments --verbose --host=' . Registry::get('config.db_host') . ' --user='******'config.db_user') . ' --password=\'' . Registry::get('config.db_password') . '\' --databases ' . Registry::get('config.db_name') . ' --tables ' . implode(' ', $tables) . ' >> ' . $file;
        system($command, $retval);
        if (0 === $retval) {
            $backuped_tables = array_merge($backuped_tables, $tables);
            fn_put_contents($file_backuped_tables, implode("\n", $backuped_tables));
            return $tables;
        }
        $log->write('mysqldump has reported failure', __FILE__, __LINE__);
    }
    $rows_per_pass = 40;
    $max_row_size = 10000;
    $t_status = db_get_hash_array("SHOW TABLE STATUS", 'Name');
    $f = fopen($file, 'ab');
    if (!empty($f)) {
        foreach ($tables as &$table) {
            $log->write('Backing up table: ' . $table, __FILE__, __LINE__);
            fwrite($f, "\nDROP TABLE IF EXISTS " . str_replace('?:', Registry::get('config.table_prefix'), $table) . ";\n");
            if (empty($t_status[str_replace('?:', Registry::get('config.table_prefix'), $table)])) {
                // new table in upgrade, we need drop statement only
                continue;
            }
            $scheme = db_get_row("SHOW CREATE TABLE {$table}");
            fwrite($f, array_pop($scheme) . ";\n\n");
            $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
            // Define iterator
            if ($t_status[str_replace('?:', Registry::get('config.table_prefix'), $table)]['Avg_row_length'] < $max_row_size) {
                $it = $rows_per_pass;
            } else {
                $it = 1;
            }
            fn_echo(' .');
            for ($i = 0; $i < $total_rows; $i = $i + $it) {
                $table_data = db_get_array("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                foreach ($table_data as $_tdata) {
                    $_tdata = fn_add_slashes($_tdata, true);
                    $values = array();
                    foreach ($_tdata as $v) {
                        $values[] = $v !== null ? "'{$v}'" : 'NULL';
                    }
                    fwrite($f, "INSERT INTO " . str_replace('?:', Registry::get('config.table_prefix'), $table) . " (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES (" . implode(', ', $values) . ");\n");
                }
            }
            $backuped_tables[] = "{$table}";
        }
        fclose($f);
        @chmod($file, DEFAULT_FILE_PERMISSIONS);
        fn_put_contents($file_backuped_tables, implode("\n", $backuped_tables));
        return $tables;
    }
}
コード例 #6
0
/**
 * Functions creates dump of tables in $file.
 *
 * @param mixed $tables Array of tables
 * @param string $file Dump file name
 * @return Boolean False on failure
 */
function fn_uc_backup_tables($tables, $file)
{
    $rows_per_pass = 40;
    $max_row_size = 10000;
    if (!empty($tables)) {
        if (!is_array($tables)) {
            $tables = array($tables);
        }
        $t_status = db_get_hash_array("SHOW TABLE STATUS", 'Name');
        $f = fopen($file, 'ab');
        if (!empty($f)) {
            foreach ($tables as &$table) {
                $table = fn_check_db_prefix($table);
                fwrite($f, "\nDROP TABLE IF EXISTS " . str_replace('?:', TABLE_PREFIX, $table) . ";\n");
                if (empty($t_status[str_replace('?:', TABLE_PREFIX, $table)])) {
                    // new table in upgrade, we need drop statement only
                    continue;
                }
                $scheme = db_get_row("SHOW CREATE TABLE {$table}");
                fwrite($f, array_pop($scheme) . ";\n\n");
                $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
                // Define iterator
                if ($t_status[str_replace('?:', TABLE_PREFIX, $table)]['Avg_row_length'] < $max_row_size) {
                    $it = $rows_per_pass;
                } else {
                    $it = 1;
                }
                fn_echo(' .');
                for ($i = 0; $i < $total_rows; $i = $i + $it) {
                    $table_data = db_get_array("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                    foreach ($table_data as $_tdata) {
                        $_tdata = fn_add_slashes($_tdata, true);
                        fwrite($f, "INSERT INTO " . str_replace('?:', TABLE_PREFIX, $table) . " (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES ('" . implode('\', \'', array_values($_tdata)) . "');\n");
                    }
                }
            }
            fclose($f);
            @chmod($file, DEFAULT_FILE_PERMISSIONS);
            return $tables;
        }
    } else {
        return array();
    }
}