Miglioramenti vari backup

This commit is contained in:
Thomas Zilio 2019-02-09 14:44:30 +01:00
parent 025d275ec9
commit 13a4ab3cf9
6 changed files with 200 additions and 111 deletions

View File

@ -72,22 +72,7 @@ function delete($files)
*/
function directory($path)
{
if (is_dir($path) && is_writable($path)) {
return true;
} elseif (!is_dir($path)) {
// Filesystem Symfony
$fs = new Symfony\Component\Filesystem\Filesystem();
// Tentativo di creazione
try {
$fs->mkdir($path);
return true;
} catch (Symfony\Component\Filesystem\Exception\IOException $e) {
}
}
return false;
return Util\FileSystem::directory($path);
}
/**
@ -410,6 +395,7 @@ function operationLog($operation, array $ids = [], array $options = [])
*
* @return string
*/
function clean($string, $permitted = '') {
return preg_replace('/[^A-Za-z0-9'.$permitted.']/', '', $string); // Removes special chars.
function clean($string, $permitted = '')
{
return preg_replace('/[^A-Za-z0-9'.$permitted.']/', '', $string); // Removes special chars.
}

View File

@ -36,6 +36,13 @@ switch (filter('op')) {
flash()->error(tr('Errore durante la creazione del backup!').' '.str_replace('_DIR_', '"'.$backup_dir.'"', tr('Verifica che la cartella _DIR_ abbia i permessi di scrittura!')));
}
break;
case 'size':
$file = filter('file');
echo Util\FileSystem::size($backup_dir.'/'.$file);
break;
}

View File

@ -3,6 +3,7 @@
include_once __DIR__.'/../../core.php';
$backup_dir = Backup::getDirectory();
$backups = Backup::getList();
echo '<p>'.tr('Il backup è <b>molto importante</b> perché permette di creare una copia della propria installazione e relativi dati per poterla poi ripristinare in seguito a errori, cancellazioni accidentali o guasti hardware').'.</p>';
@ -35,26 +36,10 @@ if (!empty($backup_dir)) {
$message = tr('Sembra che tu non abbia ancora specificato un percorso per il backup').'.';
}
echo '
<div class="row">
<div class="col-md-8">
<div class="callout callout-success">
<p>'.$message.'</p>
<p><small>'.tr('Dimensione totale: _SPAZIO_', [
'_SPAZIO_' => format_size(foldersize($backup_dir)),
]).'</small><br
<p><small>'.tr('Numero di backup: _NUM_', [
'_NUM_' => count(Backup::getList()),
]).'</small><br/>
<small>'.tr('Puoi modificare il percorso di backup dal tuo file _FILE_', [
'_FILE_' => '<b>config.inc.php</b>',
]).'</small></p>
</div>
</div>';
// Ripristino backup
// Operazioni JavaScript
echo '
<script>
// Ripristino backup
function restore() {
if ($("#blob").val()) {
swal({
@ -72,8 +57,62 @@ function restore() {
})
}
}
// Creazione backup
function backup(){
swal({
title: "'.tr('Nuovo backup').'",
text: "'.tr('Sei sicuro di voler creare un nuovo backup?').'",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn btn-lg btn-success",
confirmButtonText: "'.tr('Crea').'",
}).then(
function(){
location.href = globals.rootdir + "/editor.php?id_module='.$id_module.'&op=backup";
}, function(){});
}
// Caricamento
function loadSize(name, id){
$("#" + id).html("'.tr('Calcolo in corso').'...");
$.ajax({
url: globals.rootdir + "/actions.php",
type: "get",
data: {
id_module: globals.id_module,
op: "size",
file: name,
},
success: function(data) {
$("#" + id).html(data);
}
});
}
</script>';
echo '
<div class="row">
<div class="col-md-8">
<div class="callout callout-success">
<p>'.$message.'</p>
<p><small>'.tr('Dimensione totale: _SPAZIO_', [
'_SPAZIO_' => '<i id="total_size"></i>',
]).'</small></p>
<p><small>'.tr('Numero di backup: _NUM_', [
'_NUM_' => count($backups),
]).'</small></p>
<p><small>'.tr('Puoi modificare il percorso di backup dal tuo file _FILE_', [
'_FILE_' => '<b>config.inc.php</b>',
]).'</small></p>
</div>
</div>
<script>
loadSize("", "total_size");
</script>';
$upload_max_filesize = ini_get('upload_max_filesize');
$max_execution_time = ini_get('max_execution_time');
echo '
@ -104,7 +143,6 @@ if (file_exists($backup_dir)) {
$backups_zip = [];
$backups_file = [];
$backups = Backup::getList();
foreach ($backups as $backup) {
if (ends_with($backup, '.zip')) {
$backups_zip[] = $backup;
@ -126,7 +164,7 @@ if (file_exists($backup_dir)) {
<h3>'.tr('Backup compressi').'</h3>';
if (!empty($backups_zip)) {
foreach ($backups_zip as $backup) {
foreach ($backups_zip as $id => $backup) {
$name = basename($backup);
$info = Backup::readName($backup);
@ -141,9 +179,13 @@ if (file_exists($backup_dir)) {
]).'</h4>
<p><small>
'.tr('Nome del file').': '.$name.'<br>
'.tr('Dimensione').': '.format_size(filesize($backup)).'
'.tr('Dimensione').': <i id="c-'.$id.'"></i>
</small></p>
<script>
loadSize("'.$name.'", "c-'.$id.'");
</script>
<a class="btn btn-primary" href="'.$rootdir.'/modules/backups/actions.php?op=getfile&file='.$name.'" target="_blank"><i class="fa fa-download"></i> '.tr('Scarica').'</a>
<div class="pull-right">
@ -187,8 +229,12 @@ if (file_exists($backup_dir)) {
]).'</h4>
<p><small>
'.tr('Nome del file').': '.$name.'<br>
'.tr('Dimensione').': '.format_size(filesize($backup)).'
'.tr('Dimensione').': <i id="n-'.$id.'"></i>
</small></p>
<script>
loadSize("'.$name.'", "n-'.$id.'");
</script>
<a class="btn btn-sm btn-warning disabled" href="javascript:;"><i class="fa fa-times"></i> '.tr('Non scaricabile').'</a>
@ -219,26 +265,10 @@ if (file_exists($backup_dir)) {
<div class="alert alert-danger">'.tr('La cartella di backup non esiste!').' '.tr('Non è possibile eseguire i backup!').'</div>';
}
// Creazione backup
if (!empty($backup_dir)) {
// Creazione backup
echo '
<button type="button" class="btn btn-primary pull-right" onclick="continue_backup()"><i class="fa fa-database"></i> '.tr('Crea backup').'...</button>
<button type="button" class="btn btn-primary pull-right" onclick="backup()"><i class="fa fa-database"></i> '.tr('Crea backup').'...</button>
<div class="clearfix"></div>
<script>
function continue_backup(){
swal({
title: "'.tr('Nuovo backup').'",
text: "'.tr('Sei sicuro di voler creare un nuovo backup?').'",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn btn-lg btn-success",
confirmButtonText: "'.tr('Crea').'",
}).then(
function(){
location.href = globals.rootdir + "/editor.php?id_module='.$id_module.'&op=backup";
}, function(){});
}
</script>';
<div class="clearfix"></div>';
}

View File

@ -1,46 +0,0 @@
<?php
include_once __DIR__.'/../../core.php';
/**
* Calculate the full size of a directory
*
* @param string $path
*/
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';
foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size) {
$units = explode(' ', 'B KB MB GB TB PB');
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>

View File

@ -28,10 +28,7 @@ class Backup
$result = App::getConfig()['backup_dir'];
$result = rtrim($result, '/');
if (!directory($result)){
$fileSystem->mkdir($result, 0700);
}
else if (!is_writable($result)) {
if (!directory($result) || !is_writable($result)) {
throw new UnexpectedValueException();
}
@ -59,7 +56,8 @@ class Backup
$backups = Symfony\Component\Finder\Finder::create()
->name('/^'.$pattern.'/')
->sortByName()
->in(self::getDirectory());
->in(self::getDirectory())
->depth('== 0');
$results = [];
foreach ($backups as $backup) {

114
src/Util/FileSystem.php Normal file
View File

@ -0,0 +1,114 @@
<?php
namespace Util;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
/**
* @since 2.4.6
*/
class FileSystem
{
/**
* Controlla l'esistenza e i permessi di scrittura sul percorso indicato.
*
* @param string $path
*
* @return bool
*/
public function directory($path)
{
if (is_dir($path) && is_writable($path)) {
return true;
} elseif (!is_dir($path)) {
// Filesystem Symfony
$fs = new \Symfony\Component\Filesystem\Filesystem();
// Tentativo di creazione
try {
$fs->mkdir($path);
return true;
} catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
}
}
return false;
}
/**
* Individua la dimensione di una cartella indicata.
*
* @param string $path
*
* @return int
*/
public static function folderSize($path)
{
$total = 0;
$path = realpath($path);
if ($path !== false && $path != '' && file_exists($path)) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
$total += $object->getSize();
}
}
return $total;
}
/**
* Individua la dimensione del file indicato.
*
* @param string $path
*
* @return int
*/
public static function fileSize($path)
{
$path = realpath($path);
return filesize($path);
}
/**
* Individua la dimensione del file o cartella indicati, formattati in modo standard.
*
* @param string $path
*
* @return string
*/
public static function size($path)
{
$path = realpath($path);
$result = is_file($path) ? self::fileSize($path) : self::folderSize($path);
return self::formatBytes($result);
}
/**
* Formatta i byte nell'unità di misura relativa.
*
* @param int $bytes
* @param int $precision
*
* @return string
*/
public static function formatBytes($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
$bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));
return round($bytes, $precision).' '.$units[$pow];
}
}