Author: Michael J. Calkins (clouddueling@github.com)
Author: Diego Torres (ifsnop@github.com)
Example #1
0
function database_backup($config)
{
    info(__FUNCTION__ . ' start...<br />');
    $file = $config['database']['target'] . '/' . $config['database']['filename'];
    if (is_dir(dirname($file)) === false) {
        mkdir(dirname($file), 0777, true);
    }
    try {
        $compress = Mysqldump::NONE;
        switch ($config['database']['compress']) {
            case 'gzip':
            case Mysqldump::GZIP:
                $file .= '.gz';
                $compress = Mysqldump::GZIP;
                break;
        }
        $dump = new Mysqldump($config['database']['dsn'], $config['database']['username'], $config['database']['password'], ['single-transaction' => false, 'compress' => $compress]);
        $dump->start($file);
    } catch (\Exception $e) {
        info('mysqldump-php error: ' . $e->getMessage());
    }
    info(__FUNCTION__ . ' finished...<br />');
    $remote = $config['database']['remoteFolder'] . '/' . basename($file);
    return [$remote => $file];
}
 /**
  * This action will FULLY(!!) drop all tables of the current configuration, create a zip from the
  * provided $remoteDsn Database and import the remote database:
  *
  * ```
  * ./vendor/bin/luya exporter/database/remote-replace-local "mysql:host=localhost;dbname=REMOTE_DB_NAME" "USERNAME" "PASSWORD"
  * ```
  *
  * @param string $fromDsn
  * @param string $fromUsername
  * @param string $fromPassword
  */
 public function actionRemoteReplaceLocal($remoteDsn, $remoteUsername, $remotePassword)
 {
     if (YII_ENV_PROD || YII_ENV == 'prod') {
         throw new Exception("Its not possible to use remote-replace-local method in prod environment as it would remove the prod database env.");
     }
     $temp = tempnam(sys_get_temp_dir(), uniqid());
     $dump = new Mysqldump($remoteDsn, $remoteUsername, $remotePassword);
     $dump->start($temp);
     $tempBackup = tempnam(sys_get_temp_dir(), uniqid() . '-BACKUP-' . time());
     $dump = new Mysqldump(Yii::$app->db->dsn, Yii::$app->db->username, Yii::$app->db->password);
     $dump->start($tempBackup);
     $this->outputInfo("Temporary Backup File has been created: " . $tempBackup);
     if ($this->interactive) {
         if ($this->confirm('Are you sure you want to drop all local tables and replace them with the Remote Databse?')) {
             if ($this->confirm('Last Time: Really?')) {
                 foreach (Yii::$app->db->schema->getTableNames() as $name) {
                     Yii::$app->db->createCommand()->dropTable($name)->execute();
                 }
                 Yii::$app->db->createCommand()->setSql(file_get_contents($temp))->execute();
                 unlink($temp);
                 return $this->outputSuccess("The local database has been replace with the remote database.");
             }
         }
         unlink($temp);
         unlink($tempBackup);
         return $this->outputError('Abort by user input.');
     } else {
         foreach (Yii::$app->db->schema->getTableNames() as $name) {
             Yii::$app->db->createCommand()->dropTable($name)->execute();
         }
         Yii::$app->db->createCommand()->setSql(file_get_contents($temp))->execute();
         unlink($temp);
         return $this->outputSuccess("The local database has been replace with the remote database.");
     }
 }
Example #3
0
 public function upgradeAction()
 {
     $dump = new IMysqldump\Mysqldump('mysql:host=localhost;dbname=' . $this->container->getParameter('database_name'), $this->getParameter('database_user'), $this->getParameter('database_password'));
     $dump->start($this->get('kernel')->getRootDir() . '/dump-' . date('d-m-Y_h-i-s') . '.sql');
     $path = realpath($this->get('kernel')->getRootDir() . '/../');
     $result = array($this->runCommand($path, 'curl -sS https://getcomposer.org/installer | php'), $this->runCommand($path, 'php app/console doctrine:schema:update --dump-sql'), $this->runCommand($path, 'php app/console doctrine:schema:update --force'), $this->runCommand($path, 'COMPOSER_HOME="' . $path . '" php composer.phar update --ansi'), $this->runCommand($path, 'COMPOSER_HOME="' . $path . '" php composer.phar dump-autoload --optimize'), $this->runCommand($path, 'php app/console cache:clear'), $this->runCommand($path, 'php app/console cache:clear --env=prod --no-debug'));
     $response = new Response(json_encode($result));
     $response->headers->set('Content-Type', 'application/json; charset=UTF-8');
     return $response;
 }
 /**
  * Perform the database backupwordpress
  *
  * @return bool True if the backup completed successfully, else false.
  */
 public function backup()
 {
     try {
         $dump = new IMysqldump\Mysqldump($this->get_dsn(), $this->get_user(), $this->get_password(), $this->get_dump_settings());
         $dump->start($this->get_backup_filepath());
     } catch (\Exception $e) {
         $this->error(__CLASS__, $e->getMessage());
     }
     return $this->verify_backup();
 }
Example #5
0
 public function actionIndex()
 {
     $hash = time();
     $cacheFolder = Yii::getAlias('@runtime/exporter/' . $hash);
     FileHelper::createDirectory($cacheFolder);
     $dump = new Mysqldump\Mysqldump(Yii::$app->db->dsn, Yii::$app->db->username, Yii::$app->db->password);
     $dump->start($cacheFolder . '/mysql.sql');
     FileHelper::copyDirectory(Yii::getAlias('@web/public_html/storage'), $cacheFolder . '/storage');
     $save = Yii::getAlias($this->module->downloadFile);
     @unlink($save);
     ZipHelper::dir($cacheFolder . '/', $save);
 }
Example #6
0
 /**
  * Execute the command.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Ask the user for database credentials
     $output->writeln('');
     $output->writeln($this->messages->translator->trans('db.list.db.credentials'));
     $output->writeln('');
     $this->askCredentials($input, $output);
     // Get arguments and options
     $name = $input->getArgument('name');
     $compress = $input->getOption('compress');
     $dir = $input->getOption('dump-dir');
     // Create dumps dir if not exists
     if (!$dir) {
         $dir = getcwd() . '/dumps';
         if (!is_dir($dir)) {
             if (!mkdir($dir, 01775)) {
                 $output->writeln($this->messages->translator->trans('db.dump.option.location.error'));
                 $output->writeln('');
                 exit(-1);
             }
         }
     }
     $fileName = $dir . '/' . $name . '-' . date('Y-m-d') . '-' . time() . '.sql';
     // Dump settings
     $dumpSettings = ['compress' => IMysqldump\Mysqldump::NONE];
     $dumpSettings = ['skip-comments' => false];
     if ('gzip' === $compress) {
         $dumpSettings = ['compress' => IMysqldump\Mysqldump::GZIP];
         $fileName .= '.gz';
     } elseif ('bzip2' === $compress) {
         $dumpSettings = ['compress' => IMysqldump\Mysqldump::BZIP2];
         $fileName .= '.bz2';
     }
     // Try to create the database dump
     try {
         $output->writeln('');
         $output->writeln($this->messages->translator->trans('db.dump.message.dumping.db', ['%fileName%' => $fileName]));
         $dump = new IMysqldump\Mysqldump('mysql:host=localhost;dbname=' . $name, $this->username, $this->password, $dumpSettings);
         $dump->start($fileName);
         $output->writeln('');
     } catch (\Exception $e) {
         $output->writeln('');
         $output->writeln($this->messages->translator->trans('db.dump.message.dumping.error', ['errorMessage' => $e->getMessage()]));
         $output->writeln('');
         exit(-1);
     }
     $output->writeln($this->messages->translator->trans('app.all.done'));
     $output->writeln('');
 }
 /**
  * @AfterScenario
  */
 public function takeDatabaseDumpAfterFailedStep(AfterScenarioScope $scope)
 {
     if ($this->screenshot_dir && TestResult::FAILED === $scope->getTestResult()->getResultCode()) {
         $feature = $scope->getFeature();
         $scenario = $scope->getScenario();
         $filename = basename($feature->getFile(), '.feature') . '-' . $scenario->getLine();
         $filepath = $this->screenshot_dir . $filename . '.sql';
         try {
             $dump = new Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
             $dump->start($filepath);
         } catch (\Exception $e) {
             echo 'mysqldump-php error: ' . $e->getMessage();
         }
     }
 }
 /**
  * Prepare export.
  */
 protected function export()
 {
     try {
         // Database connection info.
         $connection = $this->connectionOptions['driver'] . ':' . 'host=';
         $connection .= $this->connectionOptions['host'] . ';dbname=';
         $connection .= $this->connectionOptions['database'];
         $dump = new IMysqldump\Mysqldump($connection, $this->connectionOptions['username'], $this->connectionOptions['password'], $this->settings);
         $dump->start($this->file_location);
         $this->complete();
     } catch (\Exception $e) {
         $this->error = TRUE;
         \Drupal::logger('backup_db')->error('Could not perform backup, @error.', array('@error' => $e->getMessage()));
     }
 }
Example #9
0
 public function dump($directory, array $options = [])
 {
     $directory = rtrim($directory, '/') . '/';
     $compress = array_get($options, 'compress', Mysqldump::GZIP);
     if (function_exists('gzopen') === false && $compress === Mysqldump::GZIP) {
         $compress = Mysqldump::NONE;
     }
     $filename = sprintf('sqldump-%s.sql', Carbon::now()->format('YmdHis'));
     switch ($compress) {
         case Mysqldump::GZIP:
             $filename .= '.gz';
             break;
         case Mysqldump::BZIP2:
             $filename .= '.bz2';
             break;
     }
     $dumpper = new Mysqldump($this->dsn, $this->username, $this->password, ['compress' => $compress, 'single-transaction' => false]);
     $dumpper->start($directory . $filename);
     return new Fluent($directory . $filename);
 }
Example #10
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (parent::execute($input, $output)) {
         $file_system_helper = new FileSystem();
         $this->loadOCConfig();
         $this->backup_folder = $this->getOCDirectory() . DIRECTORY_SEPARATOR . ".backup_tmp/";
         $za = new \ZipArchive();
         if ($za->open("ocok_backup_" . date("Y_m_d_H_i") . ".zip", \ZipArchive::OVERWRITE)) {
             if (is_dir($this->backup_folder)) {
                 $file_system_helper->rmdir($this->backup_folder);
             }
             mkdir($this->backup_folder);
             $image_path = DIR_IMAGE;
             if ($this->isVersion('2')) {
                 $image_path .= 'catalog/';
             } elseif ($this->isVersion('1')) {
                 $image_path .= 'data/';
             }
             if ($input->getOption("images")) {
                 $files = $file_system_helper->getFilesRecursively($image_path);
                 foreach ($files as $file) {
                     if ($file->isFile() && $file->isReadable() && $file_system_helper->isImage($file->getPathname())) {
                         // remove basefolder prefix from path
                         if (substr($file->getPathname(), 0, strlen($this->getOCDirectory())) == $this->getOCDirectory()) {
                             $path = substr($file->getPathname(), strlen($this->getOCDirectory()));
                         }
                         $za->addFile($file->getPathname(), substr($path, 1));
                     }
                 }
             }
             if ($input->getOption("database")) {
                 $dumper = new Mysqldump(DB_DATABASE, DB_USERNAME, DB_PASSWORD, DB_HOSTNAME, 'mysql', array('add-drop-table' => true, 'add-drop-database' => true, 'databases' => true));
                 $dumper->start($this->backup_folder . $this->backup_db);
                 $za->addFile($this->backup_folder . $this->backup_db, $this->backup_db);
             }
             $za->close();
             $file_system_helper->rmdir($this->backup_folder);
         }
     }
 }
 /**
  * @return mixed
  */
 public function doBackup()
 {
     $date = date('YmdHisO');
     $dumpName = trim($this->options->getPath() . $date . '.sql', '/');
     switch ($this->dumperOptions->getCompress()) {
         case Mysqldump::GZIP:
             $dumpName = $dumpName . '.gz';
             break;
         case Mysqldump::BZIP2:
             $dumpName = $dumpName . '.bz2';
             break;
     }
     $tmpFile = tempnam(sys_get_temp_dir(), 'bsb-flysystem-mysql-backup-');
     $fileStream = fopen($tmpFile, 'rb');
     try {
         if (false === $fileStream) {
             throw new \RuntimeException("A temp file could not be created");
         }
         // start dump and backup
         $this->dumper->start($tmpFile);
         $this->filesystem->writeStream($dumpName, $fileStream);
         // write a latest file
         if ($this->options->getWriteLatest()) {
             $this->filesystem->put($this->options->getPath() . $this->options->getWriteLatest(), pathinfo($dumpName, PATHINFO_BASENAME));
         }
         if ($this->options->getAutoPrune()) {
             $this->pruneStorage();
         }
     } catch (\Exception $e) {
         throw new \RuntimeException($e->getMessage());
     } finally {
         if (is_resource($fileStream)) {
             fclose($fileStream);
         }
         if (file_exists($tmpFile)) {
             unlink($tmpFile);
         }
     }
     return $dumpName;
 }
 /**
  * @param SS_HTTPRequest $request
  */
 public function run($request)
 {
     increase_time_limit_to();
     DB::alteration_message("Pass ?folder=myfolder to specify the output folder. By default, it's going to be one level outside the web root to protected your dumps.");
     $host = SS_DATABASE_SERVER;
     $dbname = SS_DATABASE_NAME;
     $username = SS_DATABASE_USERNAME;
     $password = SS_DATABASE_PASSWORD;
     $folder = dirname(Director::baseFolder());
     if ($request->getVar('folder')) {
         $folder = Director::baseFolder() . '/' . trim($folder, '/');
     }
     $filename = date('Ymd') . '-' . $dbname . '.sql';
     try {
         $dumpSettings = array();
         $dump = new IMysqldump\Mysqldump('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password, $dumpSettings);
         $dump->start($folder . '/' . $filename);
         DB::alteration_message($folder . '/' . $filename . ' has been created successfully', 'created');
     } catch (\Exception $e) {
         DB::alteration_message('mysqldump-php error: ' . $e->getMessage(), 'error');
     }
 }
 /**
  * Create a zip file with database dump and storage files/images and stores the zip in
  * the runtime folder.
  *
  * @return void
  */
 public function actionIndex()
 {
     $hash = time();
     $cacheFolder = Yii::getAlias('@runtime/exporter/' . $hash);
     $this->verbosePrint("cache folder {$cacheFolder}");
     FileHelper::createDirectory($cacheFolder, 0777);
     $dump = new Mysqldump\Mysqldump(Yii::$app->db->dsn, Yii::$app->db->username, Yii::$app->db->password);
     $dump->start($cacheFolder . '/mysql.sql');
     $source = Yii::getAlias('@web/public_html/storage');
     $this->verbosePrint("storage source folder {$source}");
     if (is_link($source)) {
         $source = readlink($source);
         $this->verbosePrint("source is a symlink, readlink output: " . $source);
     }
     FileHelper::copyDirectory($source, $cacheFolder . '/storage', ['dirMode' => 0777, 'fileMode' => 0775]);
     $save = Yii::getAlias($this->module->downloadFile);
     if (file_exists($save)) {
         $this->verbosePrint("a exporter file does already exists, unlink file: " . $save);
         @unlink($save);
     }
     ZipHelper::dir($cacheFolder . '/', $save);
 }
Example #14
0
 /**
  * PHP alternative to dump database without exec
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws \Exception
  */
 private function createBackupWithoutExec(InputInterface $input, OutputInterface $output)
 {
     $magerun = $this->getMagerun();
     $filePath = $this->getFilePath($input);
     $stripOptions = $input->getOption('strip') ?: '@development';
     // Exec must be unavailable so use PHP alternative (match output)
     $dbHelper = new DatabaseHelper();
     $dbHelper->setHelperSet($magerun->getHelperSet());
     $dbHelper->detectDbSettings(new NullOutput());
     $magerunConfig = $magerun->getConfig();
     $stripTables = $dbHelper->resolveTables(explode(' ', $stripOptions), $dbHelper->getTableDefinitions($magerunConfig['commands']['N98\\Magento\\Command\\Database\\DumpCommand']));
     $output->writeln(array('', $magerun->getHelperSet()->get('formatter')->formatBlock('Dump MySQL Database (without exec)', 'bg=blue;fg=white', true), ''));
     $dbSettings = $dbHelper->getDbSettings();
     $username = (string) $dbSettings['username'];
     $password = (string) $dbSettings['password'];
     $dbName = (string) $dbSettings['dbname'];
     try {
         $output->writeln('<comment>No-data export for: <info>' . implode(' ', $stripTables) . '</info></comment>');
         $output->writeln('<comment>Start dumping database <info>' . $dbSettings['dbname'] . '</info> to file <info>' . $filePath . '</info>');
         // Dump Structure for tables that we are not to receive data from
         $dumpStructure = new Mysqldump(sprintf('%s;dbname=%s', $dbHelper->dsn(), $dbName), $username, $password, array('include-tables' => $stripTables, 'no-data' => true));
         $dumpStructure->start($filePath . '.structure');
         $dump = new Mysqldump(sprintf('%s;dbname=%s', $dbHelper->dsn(), $dbName), $username, $password, array('exclude-tables' => $stripTables));
         $dump->start($filePath . '.data');
         // Now merge two files
         $fhData = fopen($filePath . '.data', 'a+');
         $fhStructure = fopen($filePath . '.structure', 'r');
         if ($fhData && $fhStructure) {
             while (!feof($fhStructure)) {
                 fwrite($fhData, fgets($fhStructure, 4096));
             }
         }
         fclose($fhStructure);
         // Gzip
         rewind($fhData);
         $zfh = gzopen($filePath, 'wb');
         while (!feof($fhData)) {
             gzwrite($zfh, fgets($fhData, 4096));
         }
         gzclose($zfh);
         fclose($fhData);
     } catch (\Exception $e) {
         throw new \Exception("Unable to export database.");
     }
 }
Example #15
0
 public function exportDB($xDestDir = '')
 {
     if (!$this->getUser()->has_cap('export')) {
         throw new UserCapabilityException('You have no sufficient rights to export the database');
     }
     if (!array_key_exists('import_sql_file', $this->data)) {
         throw new \RuntimeException('Insufficient data.');
     }
     $dest = ($xDestDir ? $xDestDir : $this->path) . '/' . $this->data['import_sql_file'];
     $memLim = ini_get('memory_limit');
     @ini_set('memory_limit', '2048M');
     $timeLim = ini_get('max_execution_time');
     @ini_set('max_execution_time', 0);
     try {
         $dump = new Mysqldump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, 'mysql', array('add-drop-table' => true, 'single-transaction' => false, 'lock-tables' => true));
         // @formatter:on
         $dump->start($dest);
     } catch (\Exception $e) {
         throw $e;
     }
     @ini_set('memory_limit', $memLim);
     @ini_set('max_execution_time', $timeLim);
     return $dest;
 }
Example #16
0
<?php

/*
for($i=0;$i<128;$i++) {
    echo "$i>" . bin2hex(chr($i)) . "<" . PHP_EOL;
}
*/
error_reporting(E_ALL);
include_once dirname(__FILE__) . "/../src/Ifsnop/Mysqldump/Mysqldump.php";
use Ifsnop\Mysqldump as IMysqldump;
$dumpSettings = array('compress' => IMysqldump\Mysqldump::NONE, 'no-data' => false, 'add-drop-table' => true, 'single-transaction' => true, 'lock-tables' => true, 'add-locks' => true, 'extended-insert' => false, 'disable-keys' => true, 'skip-triggers' => false, 'add-drop-trigger' => true, 'databases' => false, 'add-drop-database' => false, 'hex-blob' => true, 'no-create-info' => false, 'where' => '');
$dump = new IMysqldump\Mysqldump("test001", "travis", "", "localhost:3306", "mysql", $dumpSettings);
$dump->start("mysqldump-php_test001.sql");
$dumpSettings['default-character-set'] = IMysqldump\Mysqldump::UTF8MB4;
$dump = new IMysqldump\Mysqldump("test002", "travis", "", "localhost", "mysql", $dumpSettings);
$dump->start("mysqldump-php_test002.sql");
exit;
 /**
  * MysqlDumperService constructor.
  *
  * @param string             $dsn
  * @param string             $user
  * @param string             $pass
  * @param MysqlDumperOptions $dumpSettings
  * @param array              $pdoSettings
  */
 public function __construct($dsn = '', $user = '', $pass = '', MysqlDumperOptions $dumpSettings, $pdoSettings = [])
 {
     parent::__construct($dsn, $user, $pass, $dumpSettings->toDumperArray(), $pdoSettings);
 }
Example #18
0
<?php

/*
for($i=0;$i<128;$i++) {
    echo "$i>" . bin2hex(chr($i)) . "<" . PHP_EOL;
}
*/
error_reporting(E_ALL);
include_once dirname(__FILE__) . "/../src/Ifsnop/Mysqldump/Mysqldump.php";
use Ifsnop\Mysqldump as IMysqldump;
$dumpSettings = array('compress' => IMysqldump\Mysqldump::NONE, 'no-data' => false, 'add-drop-table' => true, 'single-transaction' => false, 'lock-tables' => true, 'add-locks' => true, 'extended-insert' => false, 'disable-keys' => true, 'skip-triggers' => false, 'add-drop-trigger' => true, 'databases' => false, 'add-drop-database' => false, 'hex-blob' => true, 'no-create-info' => false, 'where' => '');
$dump = new IMysqldump\Mysqldump("test001", "travis", "", "localhost", "mysql", $dumpSettings);
$dump->start("mysqldump-php.sql");
exit;
Example #19
0
 /**
  * Create database backup in tmp directory.
  * Use magerun db:dump if available. Otherwise use php alternative if exec not available.
  *
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @throws \Exception
  */
 private function createBackup(InputInterface $input, OutputInterface $output)
 {
     $magerun = $this->getMagerun();
     $filePath = $this->getFilePath($input);
     try {
         /** @var \N98\Magento\Command\Database\DumpCommand $dumpCommand */
         $dumpCommand = $magerun->find("db:dump");
         $dumpInput = new ArrayInput(array('filename' => $filePath, '--strip' => '@development', '--compression' => 'gzip'));
         if ($dumpCommand->run($dumpInput, $output)) {
             throw new \Exception("magerun db:dump failed to create backup..");
         }
     } catch (\InvalidArgumentException $e) {
         // Exec must be unavailable so use PHP alternative (match output)
         $dbHelper = new DatabaseHelper();
         $dbHelper->setHelperSet($magerun->getHelperSet());
         $dbHelper->detectDbSettings(new NullOutput());
         $stripTables = $dbHelper->resolveTables(explode(' ', '@development'), $dbHelper->getTableDefinitions($magerun->getConfig()['commands']['N98\\Magento\\Command\\Database\\DumpCommand']));
         $output->writeln(array('', $magerun->getHelperSet()->get('formatter')->formatBlock('Dump MySQL Database (without exec)', 'bg=blue;fg=white', true), ''));
         $dbSettings = $dbHelper->getDbSettings();
         $username = (string) $dbSettings['username'];
         $password = (string) $dbSettings['password'];
         $dbName = (string) $dbSettings['dbname'];
         try {
             $dump = new Mysqldump(sprintf('%s;dbname=%s', $dbHelper->dsn(), $dbName), $username, $password, array('compress' => Mysqldump::GZIP, 'exclude-tables' => $stripTables));
             $output->writeln('<comment>No-data export for: <info>' . implode(' ', $stripTables) . '</info></comment>');
             $output->writeln('<comment>Start dumping database <info>' . $dbSettings['dbname'] . '</info> to file <info>' . $filePath . '</info>');
             $dump->start($filePath);
         } catch (\Exception $e) {
             throw new \Exception("Unable to export database.");
         }
         $output->writeln('<info>Finished</info>');
     }
 }
Example #20
0
 /**
  * PHP mysqldump fallback functions, exports the database to a .sql file
  *
  */
 public function mysqldump_fallback()
 {
     $this->errors_to_warnings($this->get_mysqldump_method());
     $this->mysqldump_method = 'mysqldump_fallback';
     $this->do_action('hmbkp_mysqldump_started');
     // Guess port or socket connection type
     $port_or_socket = strstr(DB_HOST, ':');
     $host = DB_HOST;
     if (!empty($port_or_socket)) {
         $host = substr(DB_HOST, 0, strpos(DB_HOST, ':'));
         $port_or_socket = substr($port_or_socket, 1);
         if (0 !== strpos($port_or_socket, '/')) {
             $port = intval($port_or_socket);
             $maybe_socket = strstr($port_or_socket, ':');
             if (!empty($maybe_socket)) {
                 $socket = substr($maybe_socket, 1);
             }
         } else {
             $socket = $port_or_socket;
         }
     }
     // PDO connection string formats:
     // mysql:host=localhost;port=3307;dbname=testdb
     // mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
     if ($port_or_socket) {
         if (isset($port)) {
             $dsn = 'mysql:host=' . DB_HOST . ';port=' . $port . ';dbname=' . DB_NAME;
         } elseif (isset($socket)) {
             $dsn = 'mysql:unix_socket=' . $socket . ';dbname=' . DB_NAME;
         }
     } else {
         $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME;
     }
     // Get character set from constant if it is declared.
     if (defined('DB_CHARSET') && DB_CHARSET) {
         $charset = DB_CHARSET;
     } else {
         $charset = 'utf8';
     }
     if (defined('DB_PASSWORD') && DB_PASSWORD) {
         $pwd = DB_PASSWORD;
     } else {
         $pwd = '';
     }
     if (!defined('HMBKP_MYSQLDUMP_SINGLE_TRANSACTION') || false !== HMBKP_MYSQLDUMP_SINGLE_TRANSACTION) {
         $single_transaction = true;
     } else {
         $single_transaction = false;
     }
     $dump_settings = array('default-character-set' => $charset, 'hex-blob' => true, 'single-transaction' => $single_transaction);
     try {
         // Allow passing custom options to dump process.
         $dump_settings = apply_filters('hmbkp_mysqldump_fallback_dump_settings', $dump_settings);
         $dump = new IMysqldump\Mysqldump($dsn, DB_USER, $pwd, $dump_settings);
         $dump->start($this->get_database_dump_filepath());
     } catch (\Exception $e) {
         return new \WP_Error('mysql-fallback-error', sprintf(__('mysqldump fallback error %s', 'backupwordpress'), $e->getMessage()));
     }
 }
Example #21
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $pathparam = $this->option('path');
     $dbconnect = $this->option('dbconnect');
     $force = $this->option('force');
     $method = strtolower($this->option('method'));
     $refresh = strtolower($this->option('refresh'));
     $type = strtolower($this->option('type'));
     $dumpOptions = $this->option('opts');
     $dumpOptions = $dumpOptions ? $dumpOptions : [];
     if ($type && !in_array($type, ['sql', 'gzip', 'bzip2'])) {
         $this->error('The type "' . $type . '" does not support');
         return;
     }
     if (!$dbconnect) {
         $dbconnect = 'mysql';
     }
     $username = Config::get('database.connections.' . $dbconnect . '.username');
     $password = Config::get('database.connections.' . $dbconnect . '.password');
     $host = Config::get('database.connections.' . $dbconnect . '.host');
     $database = Config::get('database.connections.' . $dbconnect . '.database');
     $filename = 'schema';
     switch ($type) {
         case 'gzip':
             $filetype = '.sql.gz';
             break;
         case 'bzip2':
             $filetype = '.sql.bz2';
             break;
         default:
             $filetype = '.sql';
             break;
     }
     $filename .= $filetype;
     if (!$pathparam) {
         $path = database_path();
         $pathparam = 'database';
     } else {
         $path = base_path() . '/' . $pathparam;
         if (!is_dir($path)) {
             $this->error('The path does not exist');
             return;
         }
     }
     try {
         $dbh = new PDO("mysql:host={$host};dbname={$database}", $username, $password);
     } catch (Exception $e) {
         $this->error($e->getMessage());
         //@codeCoverageIgnore
         return;
         //@codeCoverageIgnore
     }
     if ($refresh != 'no') {
         if ($force == 'true' || $this->confirm('Your database will refresh! Do you wish to continue?')) {
             Artisan::call('vendor:publish');
             Artisan::call('clear-compiled');
             Artisan::call('optimize');
             Artisan::call('migrate:refresh', ['--database' => $dbconnect, '--force' => true]);
         } else {
             return;
         }
     }
     if (!$method || $method == 'mysqldump') {
         try {
             if ($type == 'gzip') {
                 exec("mysqldump --user={$username} --password={$password} --host={$host} {$database} | gzip > " . $path . '/' . $filename);
             } elseif ($type == 'bzip2') {
                 exec("mysqldump --user={$username} --password={$password} --host={$host} {$database} | bzip2 > " . $path . '/' . $filename);
             } else {
                 exec("mysqldump --user={$username} --password={$password} --host={$host} {$database} > " . $path . '/' . $filename);
             }
             $this->info('Generate successed, the file saved to: ' . $path . '/' . $filename);
         } catch (Exception $e) {
             $this->error($e->getMessage());
             //@codeCoverageIgnore
             $this->info('You can select `php` method by add `--method=php` to command.');
         }
     } elseif ($method == 'php') {
         try {
             if ($type == 'gzip') {
                 $dumpOptions[] = 'compress=' . IMysqldump::GZIP;
             } elseif ($type == 'bzip2') {
                 $dumpOptions[] = 'compress=' . IMysqldump::BZIP2;
             }
             $options = [];
             foreach ($dumpOptions as $key => $opt) {
                 list($k, $v) = explode('=', $opt);
                 $options[$k] = $v === 'false' ? false : $v;
             }
             $dump = new IMysqldump("mysql:host={$host};dbname={$database}", $username, $password, $options);
             $dump->start($path . '/' . $filename);
             $this->info('Generate successed, the file saved to: ' . $path . '/' . $filename);
         } catch (\Exception $e) {
             $this->error('Mysqldump-php error: ' . $e->getMessage());
             //@codeCoverageIgnore
         }
     } else {
         $this->error('The method you selected does not support. You can select below methods: `mysqldump` or `php`');
     }
 }
Example #22
0
 /**
  * @param  string $project
  * @return array  $return
  */
 public function backupDatabase($project)
 {
     // Exception if not defined
     if (!isset($this->config[$project]['database'])) {
         throw new \Exception('No "Database config" for this project', 1);
     }
     // Data required to backup Database
     $path = $this->getBackupPath($project, 'database');
     // Get database settings
     $settings = $this->getDatabaseSettings($project);
     $dumpSettings = $this->getDatabaseDumpSettings($project);
     // Get backup file prefix
     $backupDbPrefix = '';
     if (!empty($settings['backup_file_prefix'])) {
         $backupDbPrefix = $settings['backup_file_prefix'];
     }
     // Set filename
     $filename = $backupDbPrefix . date('Ymd_His') . '.sql';
     if ($dumpSettings['compress'] == 'GZIP') {
         $filename .= '.gz';
     }
     // Dump action
     $dump = new Mysqldump($settings['name'], $settings['user'], $settings['password'], $settings['host'], $settings['driver'], $dumpSettings);
     $dump->start($path . '/' . $filename);
     return $this->getBackupInfo($path, $filename);
 }
 public function getInstallSql($config)
 {
     $this->init($config);
     try {
         // Run migrations
         $this->w->Migration->installInitialMigration();
         $this->w->Migration->runMigrations("all");
     } catch (\Exception $e) {
         echo 'migrations error: ' . $e->getMessage();
     }
     try {
         // create admin user
         $contact = "INSERT INTO `contact` (`id`, `firstname`, `lastname`, `othername`, `title`, `homephone`, `workphone`, `mobile`, `priv_mobile`, `fax`, `email`, `notes`, `dt_created`, `dt_modified`, `is_deleted`, `private_to_user_id`, `creator_id`) VALUES\n\t(1, 'Administrator', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '*****@*****.**', NULL, '2012-04-27 06:31:52', '0000-00-00 00:00:00', 0, NULL, NULL);";
         $user = "******";
         $role = "INSERT INTO user_role (`id`, `user_id`, `role`) VALUES (NULL, 1, 'user');";
         $output[] = $contact;
         $output[] = $user;
         $output[] = $role;
         self::runSql($this->pdo, $contact);
         self::runSql($this->pdo, $user);
         self::runSql($this->pdo, $role);
     } catch (\Exception $e) {
         echo 'mysql user patch error: ' . $e->getMessage();
     }
     try {
         // now dump database
         $dump = new IMysqldump\Mysqldump('mysql:host=' . $config['hostname'] . ';dbname=' . $config['database'], $config['username'], $config['password'], ['add-drop-table' => 'true']);
         $dump->start('cache/install.sql');
         #$exec='mysql -u '.$config['username'].' -p'.$config['password'].' -h '.$config['hostname'].' --add-drop-table '.$config['database'].' > '.$config['cmFivePath'].'/cache/install.sql';
         //echo "CONNECTsss";
         #echo $exec;
         #exec($exec);
     } catch (\Exception $e) {
         echo 'mysqldump-php error: ' . $e->getMessage();
     }
     return file_get_contents('cache/install.sql');
 }
Example #24
0
$folder = DUMP_FOLDER . "/" . $date;
// If this folder don't exist, it has to be create
if (!file_exists($folder)) {
    mkdir($folder, 0755, true);
}
// For all databases
foreach ($databases as $database) {
    // Get the name
    $database_name = $database->Database;
    // if the database is not exclude
    if (!in_array($database_name, $exclude)) {
        try {
            // the filename is database_name.sql
            $sqlname = $database_name . '.sql';
            // init dump for this base
            $dump = new IMysqldump\Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . $database_name, DB_ROOT_USER, DB_ROOT_PASS);
            // store the dump file in the folder
            $dump->start($folder . '/' . $sqlname);
        } catch (\Exception $e) {
            // Show error
            echo 'mysqldump-php error: ' . $e->getMessage();
        }
    }
}
// Delete old dump according to the constant
if (DUMP_DURATION > 0) {
    // init arrays of dumps directory
    $dirs = [];
    // get all dump folder
    foreach (glob(DUMP_FOLDER . '/*', GLOB_ONLYDIR) as $fold) {
        $date_folder = DateTime::createFromFormat('Ymd_His', basename($fold));