databases/scripts/dbImport.php
2017-03-29 14:14:18 +02:00

121 lines
3.5 KiB
PHP

<?php
/**
* Script auto d'importation de dump sql
* Name of backup dir : TYPE-YYYY.MM.DD.HHMMSS
* Name of file dump : dbname.tablename.sql
*/
// --- Options
$shortopts = '';
$longopts = array(
'name:',
'db:',
'config:',
);
$options = getopt($shortopts, $longopts);
if ($options === false || count($options) == 0) {
echo "Nothing to do...\n";
exit;
}
/**
* Format file size to display
* @param int $size
*/
function format_bytes($size) {
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
return round($size, 2).$units[$i];
}
$configFile = 'dbImportConfig.php';
if (array_key_exists('config', $options)) {
$configFile = $options['config'];
}
if (file_exists(__DIR__.'/'.$configFile)) {
$config = include __DIR__.'/'.$configFile;
} else {
echo "No config."; exit;
}
$path = $config['dir'];
$name = $options['name'];
$excludeDb = array();
$dir = $path.'/'.$name;
if ( ! is_dir($dir) ) {
echo "Directory '$path/$name' not found!"; exit;
}
if (array_key_exists('decompress', $options)) {
// --- Parcourir le répertoire pour la décompression
$pattern = '/([^\s_]+)\.(.*)\.sql\.(gz|bzip2|xz|7z)\Z/';
if ( $dh = opendir($dir) ) {
while ( ($file = readdir($dh)) !== false ) {
if ( !is_file($dir.'/'.$file) && $file == '.' && $file == '..' ) {
continue;
}
if ( preg_match($pattern, $file, $matches) ) {
switch($matches[3]) {
case 'gz':
break;
case '7z':
break;
case 'xz':
break;
default:
break;
}
if (!empty($cmd)) {
echo date('Y-m-d H:i:s')." - Décompression $file";
passthru($cmd);
echo " - Done\n";
}
}
}
closedir($dh);
}
}
// --- Parcourir le répertoire pour l'import
$pattern = '/([^\s_]+)\.(.*)\.sql\Z/';
$import = array();
if ( $dh = opendir($dir) ) {
while ( ($file = readdir($dh)) !== false ) {
if ( !is_file($dir.'/'.$file) && $file == '.' && $file == '..' ) {
continue;
}
if (array_key_exists('db', $options)) {
if (substr($file, 0, strlen($options['db'])) != $options['db']) {
continue;
}
}
if ( preg_match($pattern, $file, $matches) ) {
if ( !in_array($matches[1], $excludeDb) && ( empty($database) || $matches[1]==$database ) ) {
$import[$file] = array(
'database' => $matches[1],
'source' => $dir.'/'.$file,
'size' => format_bytes(filesize($dir.'/'.$file)),
);
}
}
}
closedir($dh);
}
// --- Import
ksort($import);
$nb = count($import);
if ($nb>0) {
$i = 0;
foreach($import as $file => $info) {
$i++;
echo date('Y-m-d H:i:s').' : '.$i.'/'.$nb.' - '.$info['database'].' '.$file.' ('.$info['size'].')', "\n";
$cmdDB = "mysql -h ".$config['host']." -u".$config['user']." -p".$config['pass']." -e \"CREATE DATABASE IF NOT EXISTS ".$info['database']."\"";
$output = shell_exec($cmdDB);
$cmd = "mysql ".$config['options']." -h ".$config['host']." -u".$config['user']." -p".$config['pass']." ".$info['database']." < ".$info['source'];
$output = shell_exec($cmd);
if (!empty($output)) echo $output, "\n";
}
}