IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Vote des utilisateurs
0 
0 
Détails
Éditeur : ramislebob
Licence : GPL
Mise en ligne le 13 août 2014
Plate-formes : Linux, Mac, Windows
Langue : Français
Référencé dans
Navigation

script de backup recursif sur FTP avec upload uniquement des fichiers nouveaux ou modifiés (sans probleme d'affichage?..)

But: Backup automatique d'un dossier sur un site FTP comme l'hébergement mutualisé OVH.
- Afin de minimiser les uploads, seuls les fichiers modifiers seront uploader.
- Comme via ftp on ne peut pas avoir le mtdm (date de derniere modification) pour un dossier, utilisation d'une base de données simple afin de stocker les fichiers avec leur taille et le mtdm local.
- Comme on ne peut pas accéder la base de donnée directement de l'extérieur par mesure de sécurité, utilisation d'un wrapper HTTP simple utilisant la methode POST.


Base de donnée et les 2 tables:
2 tables:
- backup_folder: pour stocker les chemins globaux des répertoires (et utiliser un id pour la table des fichiers)
- backup_file: stocke le nom du fichier, sa taille, la date de derniere modification, un boolean pour savoir si c'est un dossier
[code]
CREATE TABLE IF NOT EXISTS `backup_folder` (
`id` int(24) NOT NULL AUTO_INCREMENT,
`name` varchar(1024) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `backup_file` (
`id` int(24) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
`size` int(32) NOT NULL,
`mtime` int(32) NOT NULL,
`path` int(24) NOT NULL,
`isDir` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `c_inode` (`name`,`path`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;;
[/code]



Interface cgi pour la base de donnée:
Simple interface en post. 4 actions:
- ls: to list a directory:
[codeinline]Data: action=ls&folder=D:/Mat/backupTest[/codeinline]

- put: pour ajouter un fichier ou un dossier
[codeinline]Data: action=put&folder=D:/Mat/backupTest&file=2014-7-13.13.45.backupFTP.txt&size=0&mtime=1407912313&isDir=0[/codeinline]

- update: pour actualiser la date de derniere modification et la taille du fichier (et donc uploader la nouvelle version)
[codeinline]Data: action=update&folder=D:/Mat/backupTest&file=2014-7-13.13.44.backupFTP.txt&size=1733&mtime=1407912282&isDir=0[/codeinline]

- del: pour supprimer un fichier ou un dossier (recursivement on supprime tous les sous dossiers/fichiers)
[codeinline]Data: action=del&folder=D:/Mat/backupTest/txt&file=codecs.txt&isDir=0[/codeinline]


Le code (En haut du fichier, juste les parametres de la base de donnée a changer):
[code]
#!/usr/bin/perl
use strict;
use CGI;
use DBI;

use vars qw/
$cgi $action $folder $file $size $mtime $isDir
%DB $dbh $dsn $sql $sth
/;

%DB = (
dbname => 'backup',
host => 'xxxxxxx',
login => 'xxxxxxxx',
pass => 'xxxxxxx''
);


$cgi=new CGI;
print $cgi->header('text/html');

#print "HELLO\n";

$action = $cgi->param('action');
$folder = $cgi->param('folder');
$file = $cgi->param('file');
$size = $cgi->param('size');
$mtime = $cgi->param('mtime');
$isDir = $cgi->param('isDir');

#warn("action: $action, folder: $folder, file: $file, size: $size, mtime: $mtime, isDir: $isDir");

if (!&db_connect()){
&quit("ERROR connecting DB... $DBI::errstr\n");
}

# List folder
if ($action eq 'ls'){
$sql=execute() || &quit("ERROR ls request: $DBI::errstr, sql: $sql\n");

my $nrows = $sth->rows;
if ($nrows == 0){
print "The directory $folder is not on the server\n";
}
for (my $k=0; $k < $nrows; ++$k){
my $res = $sth->fetchrow_hashref();
my $name = $res->{name};
my $size = $res->{size};
my $mtime = $res->{mtime};
my $isDir = $res->{isDir};
my $folder= $res->{folder_id};

print "$isDir $folder $mtime $size $name\n";
}

# add file
} elsif ($action eq 'put'){
# Check folder exists
$sth = $dbh->prepare("select id from backup_folder where name=\"$folder\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder', $DBI::errstr\n");
if ($sth->rows != 1){
print "ERROR, there are no folder: $folder\n";
} else {
my $res = $sth->fetchrow_hashref();
my $folder_id = $res->{id};
$sql=execute() || &quit("ERROR inserting file '$file', $DBI::errstr\n");
print "File inserted";

if ($isDir) {
$sth = $dbh->prepare("insert into backup_folder (name) values (\"$folder/$file\");");
$sth->execute() || &quit("ERROR inserting new folder '$folder/$file', $DBI::errstr\n");

$sth = $dbh->prepare("select id from backup_folder where name=\"$folder/$file\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder/$file', $DBI::errstr\n");
$res = $sth->fetchrow_hashref();
$folder_id = $res->{id};
print ", folder created, folder_id: $folder_id";
}
}



# update file
} elsif ($action eq 'update'){
# Check folder exists
$sth = $dbh->prepare("select id from backup_folder where name=\"$folder\";");
$sth->execute() || &quit("ERROR getting folder id for '$folder', $DBI::errstr\n");
if ($sth->rows != 1){
print "Error, there are no folder: $folder\n";
} else {
my $res = $sth->fetchrow_hashref();
my $folder_id = $res->{id};
$sql=execute() || &quit("ERROR updating file '$file', $DBI::errstr\n");
print "File Updated";
}

# delete file or folder
} elsif ($action eq 'del'){
$sth = $dbh->prepare("delete from backup_file where name=\"$file\";");
$sth->execute() || &quit("ERROR deleting file '$file', $DBI::errstr\n");

if ($isDir){
# delete its files
$sql=execute() || &quit("ERROR deleting files from folder '$file', $DBI::errstr\n");

# delete its folders
$sth = $dbh->prepare("delete from backup_folder where name like \"$folder/$file%\";");
$sth->execute() || &quit("ERROR deleting files from folder '$file', $DBI::errstr\n");
}

print "File deleted";

} else {
print "ERROR Wrong command\n";
}


$sth->finish() if (defined($sth));
&db_disconnect();

exit 0;

sub quit(){
my $msg = shift;
print "$msg";
$sth->finish() if (defined($sth));
&db_disconnect();
exit -1;
}

sub db_connect {
# Connection to the DB
$dsn = "DBI:mysql:database=$DB{dbname};host=$DB{host}";
$dbh = DBI->connect($dsn, $DB{login}, $DB{pass}) or return 0;

return 1;
}

sub db_disconnect {
# Disconnect from the DB
$dbh->disconnect() if (defined($dbh));
}
[/code]




Script d'upload:
Syntax: backupFTP.pl (-h)? (-v)? (-f DEL_FILES)?
-h: help
-v: verbose (or debug) mode
-f: if followed by DEL_FILES, then force deleting files on server that doesn't exist locally anymore

Interception du Ctrl+C et des erreurs FTP ou HTTP afin de fermer proprement le script et d'afficher le résumé de ce qui a pu etre upload.
En cas d'interuption du script avant la fin, il suffit de le relancer et il finira le boulot.
Un fichier log et créer dans le dossier local qui contient la meme chose que le stdout.


Le code (En haut du fichier, juste les parametres du serveur FTP a changer):
[code]
#!/usr/bin/perl
#########################################################
# * Auteur : Matthieu Bruel #
# * Date : 11/08/2014 #
# * Version : Windows (ActivePerl) #
# * Packages : Net::FTP, Try::Tiny #
# * Objectif : Backup files over FTP #
# Use 2 DB tables to track the modification dates. #
# an HTTP wrapper is used to manage the DB #
#########################################################
use strict;
use Net::FTP;
use Try::Tiny;
use LWP::UserAgent;
use Getopt::Std;

use vars qw/
$folderBackup
%FTP $ftp @dir $nbMaxTry $timeBeforeTryAgain
$HTTP $ua $http $resHTTP
@deletedFiles
$debug @error $DEL_FILES
$nbFileUploaded $sizeUploaded
$startTime $endTime $logFile $logFileName
/;

$folderBackup = 'D:\Mat\backupTest';
$HTTP = 'http://www.aec-lataste.com/dbFtpBackup.cgi';


%FTP = (
host => 'xxxxxxxx',
path => '/Backup',
port => 21,
passive => 1,
login => 'xxxxxxx',
pass => 'xxxxxxxx'
);


$nbMaxTry = 10;
$timeBeforeTryAgain = 1;
$debug = 0;
$DEL_FILES = 0;

$SIG{INT} = \&quit;

&get_options();


$ua = LWP::UserAgent->new;
$ua->agent("FtpBackup/1.0");
$ua->ssl_opts(verify_hostname=>0);


$startTime = time();
$nbFileUploaded = 0;
$sizeUploaded = 0;

# Open log file
my ($sec,$min,$hour,$numday,$month,$year,$weekday,$yearday,$isdst) = localtime($startTime);
$year += 1900;
$logFileName = "$year-$month-$numday.$hour.$min.backupFTP.txt";
open my $logFile, '>>', $logFileName || die "Can't create log file $logFileName\n";


# Connect to the FTP server
my $res = &ftpConnect();
if ( $res =~/^Cannot.*$/){
&quit($res);
}


# Do the job
&backupFolder($folderBackup, $FTP{path}, 0);

&quit("SUCCESS");

exit 0;




sub quit(){
my $msg = shift;

# Sum up the number of files that have been uploaded and the total size
my $endTime = time();
my $duration = $endTime - $startTime;
&log("\n\n==> $msg\n");
&log("SUM UP:\n");
&log("\t- $nbFileUploaded files have been uploaded.\n");
&log("\t- total size: ".&getReadableSize($sizeUploaded)."\n");
&log("\t- duration: ".&getReadableDuration($duration)."\n");

# List files on the server that doesn't exist locally anymore
# (maybe delete them or just list them so possible to do it manually...)
my $nbDeletedFiles = $#deletedFiles + 1;
if ($nbDeletedFiles > 0){
&log("\nThere are $nbDeletedFiles files that were deleted locally but are still on the server:\n");
&log("(We are deleting them now as you choose to. Please wait a moment...)\n") if ($DEL_FILES);
foreach my $deletedFile (@deletedFiles){
&log("\t- $deletedFile->{servDir}/$deletedFile->{name}");
if ($deletedFile->{isDir}){
&log(" (directory)\n");
} else {
&log(" (size: $deletedFile->{size} B)\n");
}

# Force deletion of the files on the server that have been deleted locally
# (option -f DEL_FILES of the script)
if ($DEL_FILES){
my $deletionOK = 1;
try{
$ftp->cwd($deletedFile->{servDir});
if ($deletedFile->{isDir}){
$ftp->rmdir($deletedFile->{name}, 1);
} else {
$ftp->delete($deletedFile->{name});
}
} catch {
$deletionOK = 0;
&log("Issue deleting file on server...\n");
};

# delete from the DB
if ($deletionOK){
&dbDelFile($deletedFile->{name}, $deletedFile->{path}, $deletedFile->{isDir});
}
}
}
}

&log("\nmessage");
my $pwdRemote=$ftp->pwd();
&log("Directory on the server: $pwdRemote\n");

# 3.: Check which files needs to be uploaded
&log("Uploading files:\n");

foreach my $file (@files){
my $needBackup = 1;
my $oldVersionOnServ = 0;
foreach my $servFile (@servFiles){
if ($servFile->{name} eq $file->{name}) {
if ($servFile->{mtime} >= $file->{mtime}){
$needBackup = 0;
} else {
$oldVersionOnServ = 1;
}
last;
}
}

if ($needBackup){
&log("\t- $folderName\\$file->{name}, size: ".$file->{size}.", mtime: ".$file->{mtime}."\n");
my $errorUpload = 0;
try {
$ftp->put("$folderName\\$file->{name}");
} catch {
&log("ERROR during upload...\n");
$errorUpload = 1;
push(@error, { name => $file->{name},
path => $folderName,
size => $file->{size},
isDir => 0

}
);
};

if (!$errorUpload){
++$nbFileUploaded;
$sizeUploaded += $file->{size};
if (! $oldVersionOnServ){
&dbPutFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
} else {
&dbUpdateFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
}
}
}
}
}


# 4.: Check on the server for files that have been deleted locally
foreach my $servFile (@servFiles){
my $fileExistLocally = 0;

# it's a folder
if ($servFile->{isDir}){
foreach my $folder (@folders){
if ($servFile->{name} eq $folder->{name}) {
$fileExistLocally = 1;
last;
}
}
# it's a file
} else {
foreach my $file (@files){
if ($servFile->{name} eq $file->{name}) {
$fileExistLocally = 1;
last;
}
}
}

if (! $fileExistLocally){
push(@deletedFiles, { name => $servFile->{name},
path => $folderName,
servDir => $servDir,
size => $servFile->{size},
isDir => $servFile->{isDir}
}
);
}
}



# 5.: backup folder content recursively
foreach my $folder (@folders){
if ($onlyCheckDeletedFiles){
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
} else {
my $needBackup = 1;
my $oldVersionOnServ = 0;
foreach my $servFile (@servFiles){
# if already on serv
if ($servFile->{isDir} && ($servFile->{name} eq $folder->{name}) ) {
# if serv mtime more recent nothing to do
if ($servFile->{mtime} >= $folder->{mtime}){
$needBackup = 0;
}
$oldVersionOnServ = 1;
# print "dir found, oldVersionOnServ= $oldVersionOnServ\n" if ($debug);
last;
}
}

if ($needBackup){
&log("\t+ Folder $folder->{name}\n");
my $errorCreateFolder = 0;
if (!$oldVersionOnServ){
# print "Create folder\n" if ($debug);
try {
$ftp->mkdir($folder->{name});
} catch {
&log("Error creating folder on the server...\n");
$errorCreateFolder = 1;
};

if (! $errorCreateFolder){
&dbPutFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
}
} else {
# print "Update folder\n" if ($debug);
&dbUpdateFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
}

if (!$errorCreateFolder){
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 0);
$ftp->cwd($servDir) || &quit("ERROR Cannot access server directory '$servDir', $ftp->message");
if ($debug){
my $pwdRemote=$ftp->pwd();
&log("Directory on the server: $pwdRemote\n");
}
}

# No need to backup anything,
# just check if there are files on server that have been deleted locally
} else {
&backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
}
}# onlyCheckDeletedFiles
} # foreach

} # end function


sub log(){
my $txt = shift;
print $txt;
print $logFile $txt;
}


sub ftpConnect(){
my $nbTry = 0;
my $connected = 0;
$ftp = undef;
while ( !$connected && ($nbTry < $nbMaxTry) ){
try{
$ftp=Net::FTP->new($FTP{host}, (Passive =>$FTP{passive},Timeout => 120, Debug => 0));
}
catch {
&log("[Error dans le module FTP] TimeOut sur la connection :s\n");
};
++$nbTry;
if (defined($ftp)){
$connected=1;
}
else{
sleep($timeBeforeTryAgain);
}
}

if ($nbTry < $nbMaxTry){
$nbTry = 0;
while ( !($ftp->login($FTP{login},$FTP{pass})) && ($nbTrycwd($FTP{path}) || return "Cannot go to directory '$FTP{path}', $ftp->message\n";
return 1;
}
else{
return "Cannot go to path $FTP{path}, ".$ftp->message."\n";
}
=cut
}


sub ftpQuit(){
try{
$ftp->quit if (defined($ftp));
}
catch{
&log("[Error dans le module FTP] le Quit a eu un pb... :s\n");
};
}


sub dbListDir(){
my ($folder, $servFilesRef) = @_;
$folder =~ s/\\/\//g;
&http_req("action=ls&folder=$folder");
my @lines = split("\n", $resHTTP->content);

my $nbFiles = 0;

for (my $k=0; $k [$k] = { isDir => $1,
folder => $2,
mtime => $3,
size => $4,
name => $5 };
++$nbFiles;
}
}

return $nbFiles;
}


sub dbUpdateFile(){
my ($name, $size, $mtime, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=update&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbPutFile(){
my ($name, $size, $mtime, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=put&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbDelFile(){
my ($name, $path, $isDir) = @_;
$path =~ s/\\/\//g;
&http_req("action=del&folder=$path&file=$name&isDir=$isDir");
}


sub http_req(){
my $data = shift;

$http = HTTP::Request->new(POST => $HTTP);
$http->content_type('application/x-www-form-urlencoded');

print "Data: $data\n" if ($debug);
$http->content($data);

my $nbTry = 0;
my $respOK = 0;
while ( !$respOK && ($nbTry < $nbMaxTry) ){
$resHTTP = $ua->request($http);
if (!$resHTTP->is_success) {
print "ERROR sending POST HTTP req to $HTTP (data: $data)\n";
} else {
if ($resHTTP->content !~ /^ERROR/) {
$respOK = 1;
}
}
}

if (!$respOK){
&quit("ERROR connecting the webserver $HTTP (data: $data)");
}

print $resHTTP->content."\n" if ($debug);
}


sub getReadableSize{
my $byte = shift;

if ($byte > 1024){
my $kb = int($byte/1024);
$byte -= $kb*1024;

if ($kb > 1024){
my $mb = int($kb/1024);
$kb -= $mb*1024;

if ($mb > 1024){
my $gb = int(100*$mb/1024);
$gb /= 100;
return "$gb Gb";
}

$mb+=int(100*$kb/1024)/100;
return "$mb Mb";
}
return "$kb Kb";
}

return "$byte b";
}


sub getReadableDuration {
my $sec=shift;
my $min;
my $hour;
if ($sec > 60){
$min=int($sec/60);
$sec-=$min*60;
if ($min>60){
$hour=int($min/60);
$min-=$hour*60;
return sprintf("%ih %imn %is",$hour,$min,$sec);
}
return sprintf("%imn %is",$min,$sec);
}
return sprintf("%is",$sec);
}


sub syntax(){
print
Avatar de ramislebob
Membre habitué https://www.developpez.com
Le 13/08/2014 à 9:22
Code : Sélectionner tout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#!/usr/bin/perl
#########################################################
# * Auteur   : ramislebob                           #
# * Date     : 11/08/2014                               #
# * Version  : Windows (ActivePerl)                     #
# * Packages : Net::FTP, Try::Tiny                      #
# * Objectif : Backup files over FTP                    #
#    Use 2 DB tables to track the modification dates.   #
#    an HTTP wrapper is used to manage the DB           #
#########################################################
use strict;
use Net::FTP;
use Try::Tiny;
use LWP::UserAgent;
use Getopt::Std;

use vars qw/
$folderBackup
%FTP $ftp @dir $nbMaxTry $timeBeforeTryAgain
$HTTP $ua $http $resHTTP
@deletedFiles
$debug  @error $DEL_FILES
$nbFileUploaded $sizeUploaded 
$startTime $endTime $logFile $logFileName
/;

$folderBackup = 'D:\Mat\backupTest';
$HTTP = 'http://www.aec-lataste.com/dbFtpBackup.cgi';


%FTP = (
    host    => 'xxxxxxxx',
    path    => '/Backup',
    port    => 21,
    passive => 1,
    login   => 'xxxxxxx',
    pass    => 'xxxxxxxx'
);


$nbMaxTry           = 10;
$timeBeforeTryAgain = 1;
$debug              = 0;
$DEL_FILES          = 0;

$SIG{INT} = \&quit; 

&get_options();


$ua = LWP::UserAgent->new;
$ua->agent("FtpBackup/1.0");
$ua->ssl_opts(verify_hostname=>0);


$startTime      = time();
$nbFileUploaded = 0;
$sizeUploaded   = 0;

# Open log file
my ($sec,$min,$hour,$numday,$month,$year,$weekday,$yearday,$isdst) = localtime($startTime);
$year += 1900;
$logFileName = "$year-$month-$numday.$hour.$min.backupFTP.txt";
open my $logFile, '>>', $logFileName || die "Can't create log file $logFileName\n";


# Connect to the FTP server
my $res = &ftpConnect();
if ( $res =~/^Cannot.*$/){
    &quit($res);
}


# Do the job
&backupFolder($folderBackup, $FTP{path}, 0);

&quit("SUCCESS");

exit 0;




sub quit(){
    my $msg = shift;

    # Sum up the number of files that have been uploaded and the total size
    my $endTime = time();
    my $duration = $endTime - $startTime;
    &log("\n\n==> $msg\n");
    &log("SUM UP:\n");
    &log("\t- $nbFileUploaded files have been uploaded.\n");
    &log("\t- total size: ".&getReadableSize($sizeUploaded)."\n");
    &log("\t- duration: ".&getReadableDuration($duration)."\n");

    # List files on the server that doesn't exist locally anymore
    # (maybe delete them or just list them so possible to do it manually...)
    my $nbDeletedFiles = $#deletedFiles + 1;
    if ($nbDeletedFiles > 0){
	&log("\nThere are $nbDeletedFiles files that were deleted locally but are still on the server:\n");
	&log("(We are deleting them now as you choose to. Please wait a moment...)\n") if ($DEL_FILES);
	foreach my $deletedFile (@deletedFiles){
	    &log("\t- $deletedFile->{servDir}/$deletedFile->{name}");
	    if ($deletedFile->{isDir}){
		&log(" (directory)\n");
	    } else {
		&log(" (size: $deletedFile->{size} B)\n");
	    }

	    # Force deletion of the files on the server that have been deleted locally
	    # (option -f DEL_FILES of the script)
	    if ($DEL_FILES){
		my $deletionOK = 1;
		try{
		    $ftp->cwd($deletedFile->{servDir});
		    if ($deletedFile->{isDir}){
			$ftp->rmdir($deletedFile->{name}, 1);
		    } else {
			$ftp->delete($deletedFile->{name});
		    }
		} catch {
		    $deletionOK = 0;
		    &log("Issue deleting file on server...\n");
		};

		# delete from the DB
		if ($deletionOK){
		    &dbDelFile($deletedFile->{name}, $deletedFile->{path}, $deletedFile->{isDir});
		}
	    }
	}
    }

    &log("\n<== $msg\n");


    # disconnect from the FTP server
    &ftpQuit();


    my $exit_value = 0;
    if ($msg eq 'SUCCESS'){
	my $nbError = $#error+1;
	if ($nbError != 0){
	    &log("\nThere were $nbError files that failed during the upload, please re run it when you can\n");
	    $exit_value = -1;
	}
    } else {
	&log("\nAs the script didn't finish properly, please re run it when you can\n");
	$exit_value = -1;
    }

    # close log file
    close($logFile);


    print "\nYou can see the log file here: $logFileName\n";
    exit $exit_value;
}


sub backupFolder(){
    my ($folderName, $servDir, $onlyCheckDeletedFiles)= @_;
    chop($folderName) if ($folderName =~ /\\$/);

    # 1.: Find the list of files that are on the server
    my $path = $folderName;    
    $path =~ s/\\/\//g;
    my @servFiles;
    my $servNbFiles = &dbListDir($path, \@servFiles);

    if (!$onlyCheckDeletedFiles){
	&log("\n\nBackup folder '$folderName'\n"); 
	&log("Number of files already on the server: $servNbFiles\n");
	if ($debug){
	    foreach (@servFiles){
		&log("\t- $_->{name}\n");
	    }
	}
    } else {
	&log("# Check $servDir on server for files that have been deleted locally\n");
    }


    # 2.: List of local files and folders
    my @folders;
    my @files;
    opendir my $dir, $folderName || return "Couldn't open folder $folderName, $!";
    while (my $file = readdir($dir)){
	# Pass current and parent folder
	next if ($file =~/^\.{1,2}$/);

	my $path = "$folderName\\$file";

	my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
	    $atime,$mtime,$ctime,$blksize,$blocks) = stat($path);
#print "DEBUG: $file, $size, $mtime\n";

	if (-d $path) {
    	    push(@folders, {mtime  => $mtime,
	    		    size   => $size,
    			    name   => $file,
    			    }
	    );
	} else {
    	    push(@files,{   mtime  => $mtime,
	    		    size   => $size,
    			    name   => $file
			}
	    );
	}   
    }
    closedir $dir;


    if (!$onlyCheckDeletedFiles){
    
	$ftp->cwd($servDir) || &quit("ERROR Cannot access server directory '$servDir', $ftp->message");
	my $pwdRemote=$ftp->pwd();
	&log("Directory on the server: $pwdRemote\n");

	# 3.: Check which files needs to be uploaded
	&log("Uploading files:\n");

	foreach my $file (@files){
	    my $needBackup = 1;
	    my $oldVersionOnServ = 0;
	    foreach my $servFile (@servFiles){
		if ($servFile->{name} eq $file->{name}) {
		    if ($servFile->{mtime} >= $file->{mtime}){
			$needBackup = 0;
		    } else {
			$oldVersionOnServ = 1;
		    }
		    last;
		}
	    }

	    if ($needBackup){
		&log("\t- $folderName\\$file->{name}, size: ".$file->{size}.", mtime: ".$file->{mtime}."\n");
		my $errorUpload = 0;
		try {
		    $ftp->put("$folderName\\$file->{name}");
		} catch {
		    &log("ERROR during upload...\n");
		    $errorUpload = 1;
		    push(@error, {  name    => $file->{name},
				    path    => $folderName,
				    size    => $file->{size},
				    isDir   => 0

			}
		    );
		};

		if (!$errorUpload){
		    ++$nbFileUploaded;
		    $sizeUploaded += $file->{size};
		    if (! $oldVersionOnServ){
			&dbPutFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
		    } else {
			&dbUpdateFile($file->{name},$file->{size},$file->{mtime},$folderName,0);
		    }
		}
	    }
	}
    }


    # 4.: Check on the server for files that have been deleted locally
    foreach my $servFile (@servFiles){
	my $fileExistLocally = 0;

	# it's a folder
	if ($servFile->{isDir}){
	    foreach my $folder (@folders){
		if ($servFile->{name} eq $folder->{name}) {
		    $fileExistLocally = 1;
		    last;
		}
	    }
	# it's a file
	} else {
	    foreach my $file (@files){
		if ($servFile->{name} eq $file->{name}) {
		    $fileExistLocally = 1;
		    last;
		}
	    }
	}

	if (! $fileExistLocally){
	    push(@deletedFiles, {   name    => $servFile->{name},
				    path    => $folderName,
				    servDir => $servDir,
				    size    => $servFile->{size},
				    isDir   => $servFile->{isDir}
				}
	    );
	}
    }
    

   
    # 5.: backup folder content recursively
    foreach my $folder (@folders){
	if ($onlyCheckDeletedFiles){
	    &backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
	} else {
    	    my $needBackup       = 1;
    	    my $oldVersionOnServ = 0;
    	    foreach my $servFile (@servFiles){
    		# if already on serv
    		if ($servFile->{isDir} && ($servFile->{name} eq $folder->{name}) ) {
    		    # if serv mtime more recent nothing to do
    		    if ($servFile->{mtime} >= $folder->{mtime}){
    			$needBackup = 0;
    		    }
		    $oldVersionOnServ = 1;
#		    print "dir found, oldVersionOnServ= $oldVersionOnServ\n" if ($debug);
    		    last;
    		}
    	    }

    	    if ($needBackup){
    		&log("\t+ Folder $folder->{name}\n");
    		my $errorCreateFolder = 0;
    		if (!$oldVersionOnServ){
#		    print "Create folder\n" if ($debug);
    		    try {
			$ftp->mkdir($folder->{name});
	    	    } catch {
	    		&log("Error creating folder on the server...\n");
	    		$errorCreateFolder = 1;
	    	    };

		    if (! $errorCreateFolder){
			&dbPutFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
		    }
		} else {
#		    print "Update folder\n" if ($debug);
		    &dbUpdateFile($folder->{name}, 0, $folder->{mtime}, $folderName, 1);
		}

		if (!$errorCreateFolder){		
		    &backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 0);
		    $ftp->cwd($servDir) || &quit("ERROR Cannot access server directory '$servDir', $ftp->message");
		    if ($debug){
			my $pwdRemote=$ftp->pwd();
			&log("Directory on the server: $pwdRemote\n");
		    }
		}

	    # No need to backup anything,
	    # just check if there are files on server that have been deleted locally    
	    } else {
		    &backupFolder($folderName.'\\'.$folder->{name}, $servDir.'/'.$folder->{name}, 1);
	    }
	}# onlyCheckDeletedFiles
    } # foreach

} # end function


sub log(){
    my $txt = shift;
    print $txt;
    print $logFile $txt;
}


sub ftpConnect(){
    my $nbTry     = 0;
    my $connected = 0;
    $ftp          = undef;
    while ( !$connected && ($nbTry < $nbMaxTry) ){
	try{
	    $ftp=Net::FTP->new($FTP{host}, (Passive =>$FTP{passive},Timeout => 120, Debug => 0));
	}
	catch {
	    &log("[Error dans le module FTP] TimeOut sur la connection :s\n");
	};
    	++$nbTry;
	if (defined($ftp)){
	    $connected=1;
	}
	else{
	    sleep($timeBeforeTryAgain);
	}	
    }

    if ($nbTry < $nbMaxTry){
	$nbTry = 0;
	while ( !($ftp->login($FTP{login},$FTP{pass})) && ($nbTry<=$nbMaxTry) ){
	    ++$nbTry;
	    sleep($timeBeforeTryAgain);
	}
    }
    else{
	return "Cannot login to $FTP{host}\n";
    }

=pod
    if ($nbTry < $nbMaxTry){
	$ftp->cwd($FTP{path}) || return "Cannot go to directory '$FTP{path}', $ftp->message\n";
	return 1;
    }
    else{
	return "Cannot go to path $FTP{path}, ".$ftp->message."\n";
    }
=cut
}


sub ftpQuit(){
    try{
    	$ftp->quit if (defined($ftp));
    }
    catch{
	&log("[Error dans le module FTP] le Quit a eu un pb... :s\n");
    };
}


sub dbListDir(){
    my ($folder, $servFilesRef) = @_;
    $folder =~ s/\\/\//g;
    &http_req("action=ls&folder=$folder");
    my @lines = split("\n", $resHTTP->content);
    
    my $nbFiles = 0;

    for (my $k=0; $k <= $#lines; ++$k){
	chomp($lines[$k]);
	if ($lines[$k] =~ /^(\d+) (\d+) (\d+) (\d+) (.*)$/){
	    $servFilesRef->[$k] = { isDir  => $1,
				    folder => $2,
				    mtime  => $3,
				    size   => $4,
				    name   => $5 };
	    ++$nbFiles;
	}
    }

    return $nbFiles;
}


sub dbUpdateFile(){
    my ($name, $size, $mtime, $path, $isDir) = @_;
    $path =~ s/\\/\//g;
    &http_req("action=update&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbPutFile(){
    my ($name, $size, $mtime, $path, $isDir) = @_;
    $path =~ s/\\/\//g;
    &http_req("action=put&folder=$path&file=$name&size=$size&mtime=$mtime&isDir=$isDir");
}


sub dbDelFile(){
    my ($name, $path, $isDir) = @_;
    $path =~ s/\\/\//g;
    &http_req("action=del&folder=$path&file=$name&isDir=$isDir");
}


sub http_req(){
    my $data = shift;

    $http = HTTP::Request->new(POST => $HTTP);
    $http->content_type('application/x-www-form-urlencoded');

    print "Data: $data\n" if ($debug);
    $http->content($data);

    my $nbTry  = 0;
    my $respOK = 0;
    while ( !$respOK && ($nbTry < $nbMaxTry) ){
	$resHTTP = $ua->request($http);
	if (!$resHTTP->is_success) {
	    print "ERROR sending POST HTTP req to $HTTP (data: $data)\n";
	} else {	
	    if ($resHTTP->content !~ /^ERROR/) {
		$respOK = 1;
	    }
	}
    }

    if (!$respOK){
	&quit("ERROR connecting the webserver $HTTP (data: $data)");
    }

    print $resHTTP->content."\n" if ($debug);
}


sub getReadableSize{
    my $byte = shift;

    if ($byte > 1024){
	my $kb = int($byte/1024);
	$byte -= $kb*1024;

	if ($kb > 1024){
	    my $mb = int($kb/1024);
	    $kb   -= $mb*1024;

	    if ($mb > 1024){
		my $gb = int(100*$mb/1024);
		$gb /= 100;
		return "$gb Gb";
	    }

	    $mb+=int(100*$kb/1024)/100;
	    return "$mb Mb";
	}
	return "$kb Kb";
    }

    return "$byte b";
}


sub getReadableDuration {
    my $sec=shift;
    my $min;
    my $hour;
    if ($sec > 60){
	$min=int($sec/60);
	$sec-=$min*60;
	if ($min>60){
	    $hour=int($min/60);
	    $min-=$hour*60;
	    return sprintf("%ih %imn %is",$hour,$min,$sec);	    
	}
	return sprintf("%imn %is",$min,$sec);
    }
    return sprintf("%is",$sec);    
}


sub syntax(){
    print <<__SYNTAX__;

Syntax: $0 (-h)? (-v)? (-f DEL_FILES)?
\t-h: help
\t-v: verbose (or debug) mode
\t-f: if followed by DEL_FILES, then force deleting files on server that doesn't exist locally anymore
__SYNTAX__
}


sub get_options(){
    our ($opt_h, $opt_v, $opt_f);
    getopts('hvf:');

    if ($opt_h){
	&syntax();
	exit 0;
    }
    if ($opt_v){
	print "Debug mode\n";
	$debug = 1;
    }

    if ($opt_f){
	if ($opt_f eq 'DEL_FILES'){
	    print "Are you sure you want to force deletion of files on the server that are missing locally? (yN)\n";
	    my $c;
	    sysread STDIN, $c, 1;
	    if ($c =~/^[yY]$/){
		print "DEL_FILES mode!\n";
		$DEL_FILES = 1;
	    }
	} else {
	    &syntax();
	    exit 0;
	}
    }
}
Developpez.com décline toute responsabilité quant à l'utilisation des différents éléments téléchargés.