-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsyncd.php
More file actions
3140 lines (2962 loc) · 120 KB
/
syncd.php
File metadata and controls
3140 lines (2962 loc) · 120 KB
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* TODO: make a real is writeable test in test modus
* TODO: make ftp client
* TODO: follow symbolic links
* TODO: ssh user on shared server must not have full path in all action in target path. define xml node to use target root path or not
* TODO: copy file must be a stream write procedure since copy/fopen are asyncron operations and there is no way of determining the eof event to set chmod after file has been copied
*/
/**
* @desc
* linux/unix directory staging/sync script for php cli
*
* this script will copy contents of a source directory to a target directory as defined in a config xml file emulating a (s)ftp client.
* the script will only run in cli modus from shell/command line and can be called like:
*
* - bash:~$ php -f /path/to/syncd.php
*
* in order for the script to run 2 mandatory parameter/argument must be passed in the shell/command line, e.g.:
*
* - bash:~$ php -f /path/to/syncd.php "config.xml" "test-logged"
* - bash:~$ php -f /path/to/syncd.php "/var/www/tmp/config.xml" "live"
* - bash:~$ php -f /path/to/syncd.php "/var/www/tmp/config.xml" "live-logged" -option1
* - bash:~$ php -f /path/to/syncd.php "/var/www/tmp/config.xml" "test" -option1 -option2=1
*
* the first mandatory argument expects the path to the config xml file. path must be absolute or filename only if config.xml resides in same
* directory as the script. the second mandatory argument expects the run modus as explained here:
*
* - "test" = simulates sync testing the basic requirements for a successful sync echoing everything in the shell
* - "test-logged" = does the same as "test" with logging everything to a log report file
* - "live" = executes the jobs defined in the config xml
* - "live-logged" = does the same as "live" with logging everything to log report file
*
* the > third argument or all arguments after the run modus argument are considered to be optional options which are lined up linux style with a trailing "-"
* to signify that the argument is an option like: "-option1" but also "-option2=yes" which are options with key => value pairs. the following options are supported
* - "-force" = will force the job to be executed regardless of any scheduled values for type "once|daily"
* - "-silent" = suppress all log message output in shell and allow only logging to log file
*
* NOTE: the directory in which this script resides must be writeable in order to write the log report if the config.logdir value is not set
* NOTE: the script currently supports only sftp with ssh2 and normal user/pass authentification!
* NOTE: when defining job type and date attributes a history log file in the same directory or the config.logdir as the script named "jobs.log" will be created to log when jobs are executed
*
* The following displays are complete config xml file:
*
<?xml version="1.0" encoding="utf-8"?>
<root>
<config>
<ini>
<memory_limit>512mb</memory_limit>
</ini>
(<target>
<host>xx.xx.xx.xx</host>
<port>22</port>
<user>root</user>
<pass></pass>
<options>
<pubkey>/path/to/public.key</pubkey> //full path to public ssh-rsa key
<privkey>/path/to/private.key</privkey> //full path to private ssh-rsa key
</options>
<class includes="/var/www/syncd/seclib:Net/SFTP.php">Phpseclib_SFTP</class>
</target>)
<sourcebase></sourcebase>
<targetbase></targetbase>
<compare>date</compare>
<resync>1</resync>
<skip>*.svn*,*.git*,*.log</skip>
<modified_since>10.11.09 15:20:21</modified_since>
<chmod>0755</chmod>
<chown>www-data</chown> //numeric value for Phpseclib_Sftp
<chgrp>www-data</chgrp> //numeric value for Phpseclib_Sftp
<logdir>/logs</logdir>
<logclean>30</logclean>
<profile>1</profile>
</config>
<jobs>
<job id="job1" compare="size" resync="1" type="daily" date="00:00">
<target><![CDATA[/backup]]></target>
<source><![CDATA[/var/www/website/private]]></source>
<excludes>
<exclude><![CDATA[/var/www/website/private/tpls/*]]></exclude>
<exclude><![CDATA[/backup]]></exclude>
<exclude><![CDATA[/config/config.inc.php]]></exclude>
<exclude><![CDATA[functions.php]]></exclude>
</excludes>
<actions>
<action type="delete"><![CDATA[/.htaccess]]></action>
<action type="delete"><![CDATA[/var/www/website/temp/]]></action>
</actions>
</job>
</jobs>
</root>
* The optional ini node can be used to set ini key => values for php
*
* The config parameters are the following:
*
* NOTE: Use target node only when dealing with (S)FTP sync else omit target node and child nodes!!!
*
* config.target (optional!)
*
* 1) config.target.host (mandatory)
* expects the host name or ip for the remote target
*
* 2) config.target.port (mandatory)
* expects the port (crucial to decide which protocol to use)
*
* 3) config.target.user (mandatory)
* expects the user for normal user/pass authentification
*
* 4) config.target.pass (optional)
* expects the ssh user password (if not set will asked for in shell)
*
* 5) config.target.options (optional)
* expects key => value pair currently implemented:
* - pubkey = full path to public .pub openssh ssh-rsa key
* - privkey = full path to private openssh ssh-rsa key
*
* 6) config.target.class (optional)
* expects the optional class to force use, e.g. Sftp. the class node can also have attributes for using external classes:
* - includes - for a ":" separated string of include paths or include files
*
* 7) config.sourcebase (optional)
* expects the source root/base path. if set the job source path must be relative because basepath + jobpath
*
* 8) config.targetbase (optional)
* expects the target root/base path. if set the job target path must be relative because basepath + jobpath
* the targetbase path also set the current working directory on the target server. if not set the app will look for the cwd
* automatically using the unix pwd command.
* NOTE: on shared hosts the pwd command still will return the correct path from root but ftp/sftp can only write to relative path.
* in this case the targetbase path should be set like "/" forcing the cwd to the path of the logged in user (relative)
*
* 9) config.compare (optional)
* if set expects a compare modus (size|date) which will compare files and sync only if rule does not apply
*
* 10) config.resync (optional)
* expects a value (0 = off|1 = on) if the process should also delete orphaned files on target remote server
*
* 11) config.skip (optional)
* expects optional skip rules which is a comma separated list of file extensions or paths. file extensions will be identified
* by dot e.g. .svn values. path by either *, /, \ as last chars. a skip rule for everything that contains .svn in either extension
* or path will be e.g. *.svn*, a file extension only check e.g. *.svn
*
* 12) config.modified_since (optional)
* if set syncs only files which are newer then modification date
*
* 13) config.chmod (optional)
* expects a chmod value to set to remote file once syncd to remote server. if the value is "copy" will try to copy source permission to target file/dir
* NOTE! using "copy" as value should only be used when copied folder/files on target dont inherit permissions via setgid and co
*
* 14) config.chown (optional)
* expects a username as string to set after copy of file/dir has been successful. the username will be tested before sync to check if username does exist on target server.
* the new username will only be set if the to be copied source file/dir does have a different user as owner
*
* 15) config.chgrp (optional)
* expects a group name as string to set after copy of file/dir has been successful. the group will be tested before sync to check if group does exist on target server.
* the new group name will only be set if the to be copied source file/dir does have a different user as owner
*
* 16) config.logdir (optional)
* expects absolute or relative path to log file directory, the directory where log files are written to. relative must be from the location of base syncd.php file.
*
* 17) config.logclean (optional)
* if set and an integer value of x days will delete all report log files older then that value in days
*
* 18) config.profile (optional)
* if set to 1 will use profiling (time, cpu, ram) and write profiling values to log file
*
*
* The following parameters must/can be defined in job nodes as attribute:
*
* 1) id
* 2) type
* 3) date
*
* 1) job.id (optional)
* defines a job id for cron automated syncing as well as defining a job as reference for future implementation. if not set will be filled with numeric index starting for 0 for first job.
* NOTE: that if changing the id and when automating scripts the reference to the job history will be lost resulting in wrong cron/automatization behaviour. delete jobs.log file after changing!
*
* 2) job.type (optional)
* defines the type of job when running under automated scripts. the values can be (once, daily). in "once" modus the job will be executed only once (see job.date for date attribute) since its job timestamp will be logged to
* prevent calling of job more then once. in "daily" modus the job will be executed only once daily at a defined hour (see job.date attribute)
*
* 3) job.date (mandatory if job.type is set)
* defines the date on when the job is supposed to be executed according to attribute job.type.
* "once" = accepts a valid php strtotime value, see http://php.net/manual/en/datetime.formats.php like "2013-05-03 10:55:00"
* "daily" = expects a hourly value like "14:00", "09:30"
*
* The following parameters can be defined in job nodes as attribute to overwrite global values:
*
* 1) compare
* 2) resync
* 3) skip
* 4) chmod
* 5) chown
* 6) chgrp
* 7) modified_since
*
* (see descriptions for global parameters)
*
* Each job can be defined with the following parameter:
*
* 1) job.source (mandatory)
* defines the source path to sync files from -> to remote target path. The path must be absolute if source basepath is not set.
*
* 2) job.target (mandatory)
* defines the target path on remote server where to sync files from source -> target. The path must be absolute if target basepath is not set.
*
* 3) job.excludes (optional)
* defines the exclude rules which can be:
* - absolute path in source or target
* - relative path to job source or target dir
* - filename + extension (will exclude all files of the same name in all directories of job source/target path!)
* - path + filename # extension will exclude a specific file from job source/target path (defined relative or absolute)
* excluded can be files/dir from source AND target - syncd will autodetect according to dir where to exclude.
* it is advised to always use absolute paths to avoid possible conflicts! in case of target excludes rules use always
* absolute path without targetbase. always test your rules before running syncd live
*
* 4) job.actions (optional)
* defines a list of actions applied after sync on target server - currently only type "delete" supported. this option is mend to perform actions
* on the target server after the sync providing for more flexibility. the action will work on:
* - absolute path/folder in target
* - relative path/folder in target
* - absolute file pointer in target
* - relative file pointer in target
*
* @author setcookie <set@cooki.me>
* @link set.cooki.me
* @copyright Copyright © 2011-2012 setcookie
* @license http://www.gnu.org/copyleft/gpl.html
* @package syncd
* @version 0.1.2
* @desc base class for sync
* @throws Exception
*/
class Syncd
{
const MODE_LIVE = "live";
const MODE_LIVE_LOGGED = "live-logged";
const MODE_TEST = "test";
const MODE_TEST_LOGGED = "test-logged";
const LOG_NOTICE = "notice";
const LOG_SUCCESS = "success";
const LOG_ERROR = "error";
const LOG_EXCEPTION = "exception";
protected $_start = null;
protected $_xml = null;
protected $_dir = null;
protected $_mode = null;
protected $_profile = false;
protected $_options = array();
protected $_xmlArray = null;
protected $_conn = null;
protected $_log = array();
protected $_err = 0;
protected $_logDir = null;
protected $_logFile = null;
protected $_jobFile = null;
protected $_jobPool = null;
protected static $_instance = null;
/**
* @desc validates parameter and checks for valid environment
* @throws Exception
* @param string $xml expects absolute or relative path to config xml
* @param string $mode expects the run mode
* @param array $options expects optional options array
*/
public function __construct($xml, $mode, Array $options = null)
{
$this->_start = microtime(true);
@set_time_limit(0);
@error_reporting(E_ALL);
@ini_set("display_errors", 1);
@ini_set('memory_limit', '512M');
if(!defined("DIRECTORY_SEPARATOR"))
{
define('DIRECTORY_SEPARATOR', ((isset($_ENV["OS"]) && stristr('win',$_ENV["OS"]) !== false) ? '\\' : '/'));
}
$xml = DIRECTORY_SEPARATOR . ltrim(trim($xml), DIRECTORY_SEPARATOR);
$mode = strtolower(trim((string)$mode));
if(in_array($mode, array(self::MODE_LIVE, self::MODE_LIVE_LOGGED, self::MODE_TEST, self::MODE_TEST_LOGGED)))
{
$this->_mode = $mode;
}else{
throw new Exception("syncd run mode: $mode is not a valid run mode");
}
if($options !== null)
{
foreach($options as $o)
{
if(substr($o, 0, 1) === '-')
{
$o = trim($o, " -");
if(strpos($o, '=') !== false)
{
$this->_options[strtolower(substr($o, 0, strpos($o, '=')))] = substr($o, strpos($o, '=') + 1, strlen($o));
}else{
$this->_options[strtolower($o)] = null;
}
}
}
}
if(array_key_exists('silent', $this->_options))
{
@ini_set("display_errors", 0);
}
if(strtolower(trim(php_sapi_name())) !== 'cli')
{
throw new Exception("script can only be called from command line (cli)");
}
if(!(bool)ini_get('allow_url_fopen'))
{
throw new Exception("system does not support open (s)ftp protocol wrapper");
}
if(!class_exists('RecursiveDirectoryIterator', false))
{
throw new Exception("system does not support recursive iterators");
}
if(!class_exists('DOMDocument'))
{
throw new Exception('system does not support dom document functions');
}
if(stristr($xml, realpath(dirname(__FILE__))) === false)
{
$this->_xml = $xml = rtrim(realpath(dirname(__FILE__)), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($xml, DIRECTORY_SEPARATOR);
}else{
$this->_xml = $xml;
}
$dom = new DOMDocument();
if($dom->load($this->_xml, LIBXML_NOBLANKS | LIBXML_NOCDATA))
{
$this->_xmlArray = $this->xmlToArray($dom);
$this->_xmlArray = array_shift($this->_xmlArray);
$this->init();
$this->exec();
}else{
throw new Exception("xml config file: $xml not found or invalid");
}
}
/**
* @desc singleton run method to shortcut run syncd
* @static
* @param string $xml expects absolute or relative path to config xml
* @param string $mode expects the run mode
* @param array $options expects optional options array
* @return null|Syncd
*/
public static function run($xml, $mode, Array $options = null)
{
if(self::$_instance === null)
{
self::$_instance = new self($xml, $mode, $options);
}
return self::$_instance;
}
/**
* @desc init global config settings and check for job log file
* @access protected
* @throws Exception
*/
protected function init()
{
$tmp = array();
$xml =& $this->_xmlArray;
if(isset($xml['ini']))
{
foreach((array)$xml['ini'] as $k => $v)
{
@ini_set($k, $v);
}
}
if(isset($xml['config']['profile']) && (int)$xml['config']['profile'] === 1)
{
$this->_profile = true;
}
if(isset($xml['config']['logdir']))
{
if(stristr($xml['config']['logdir'], DIRECTORY_SEPARATOR) === false || (substr($xml['config']['logdir'], 0, 1) === DIRECTORY_SEPARATOR && substr_count($xml['config']['logdir'], DIRECTORY_SEPARATOR) === 1))
{
$this->_logDir = $xml['config']['logdir'] = rtrim(realpath(dirname(__FILE__)), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($xml['config']['logdir'], DIRECTORY_SEPARATOR);
}else{
$this->_logDir = $xml['config']['logdir'];
}
$this->_logDir = $this->_logDir . DIRECTORY_SEPARATOR;
if(!is_dir($this->_logDir) || !is_writable($this->_logDir))
{
throw new Exception("config.logdir log directory does not exist or is not writeable");
}
}else{
$this->_logDir = rtrim(realpath(dirname($this->_xml)), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if(!is_dir($this->_logDir) || !is_writable($this->_logDir))
{
throw new Exception("config.logdir log directory does not exist or is not writeable");
}
}
$this->_jobFile = $this->_logDir . 'jobs.log';
$this->_logFile = $this->_logDir . basename($this->_xml, ".xml") . "-". strftime("%Y%m%d-%H%M%S", time()) . ".report.log";
if(isset($xml['config']['logclean']) && (int)$xml['config']['logclean'] > 0)
{
if(($dir = glob($this->_logDir . '*.log')) !== false)
{
foreach($dir as $d)
{
if(preg_match('/([0-9]{8})\-([0-9]{6})\.report\.log$/i', $d, $match))
{
if(mktime(0, 0, 0, (int)substr($match[0], 4, 2), (int)substr($match[0], 6, 2), (int)substr($match[0], 0, 4)) < time() - ((int)$xml['config']['logclean'] * 86400))
{
@unlink($d);
}
}
}
}
}
if(is_file($this->_jobFile))
{
if(($this->_jobPool = file($this->_jobFile, FILE_SKIP_EMPTY_LINES)) !== false)
{
foreach($this->_jobPool as $k => $v)
{
$t = explode(",", $v);
if(!empty($t))
{
if(array_key_exists(0, $t) && !array_key_exists($t[0], $tmp))
{
$tmp[$t[0]] = array();
}
if(array_key_exists(1, $t) && !array_key_exists($t[1], $tmp[$t[0]]))
{
$tmp[$t[0]][$t[1]] = array();
}
if(array_key_exists(0, $t) && array_key_exists(1, $t))
{
$tmp[$t[0]][$t[1]][] = $t[2];
}
}
}
$this->_jobPool = $tmp;
}else{
throw new Exception("job.log file could not be opened");
}
}
$this->log("starting syncd with the following arguments: " . implode(" ", $GLOBALS['argv']), self::LOG_NOTICE);
$this->initJobs();
$this->initConfig();
}
/**
* @desc validates and inits the job entries
* @throws Exception
* @return void
*/
protected function initJobs()
{
try
{
$tmp = array();
$xml =& $this->_xmlArray;
if(isset($xml['jobs']) && !empty($xml['jobs']))
{
if(!isset($xml['jobs']['job'][0]))
{
$xml['jobs']['job'] = array($xml['jobs']['job']);
}
$j = 0;
foreach($xml['jobs']['job'] as $k => &$v)
{
if(isset($v['actions']['action']) && !isset($v['actions']['action'][0]))
{
$v['actions']['action'] = array($v['actions']['action']);
}
if(!$this->is("jobs.job.$j.@attributes.id"))
{
$v['@attributes']['id'] = $j;
}
$id = $v['@attributes']['id'];
$this->log(".validating job: $j with id: $id", self::LOG_NOTICE);
//validate actions
if(isset($v['actions']))
{
foreach($v['actions']['action'] as $r)
{
if(!array_key_exists('@attributes', $r) || !array_key_exists('type', $r['@attributes']))
{
throw new Exception("job entry must contain a valid attribute for jobs.job.actions.action.@attribute.type");
}
if(!in_array($r['@attributes']['type'], array('delete')))
{
throw new Exception("job entry must contain a valid attribute for jobs.job.actions.action.@attribute.type");
}
}
}
//validate date
if($this->is("jobs.job.$j.@attributes.date"))
{
if(!array_key_exists('force', $this->_options))
{
if($this->is("jobs.job.$j.@attributes.type"))
{
$type = strtolower(trim($this->get("jobs.job.$j.@attributes.type")));
}else{
$type = $v['@attributes']['type'] = 'once';
}
$date = trim($this->get("jobs.job.$j.@attributes.date"));
$id = trim($this->get("jobs.job.$j.@attributes.id"));
if(!in_array($type, array('once', 'daily')))
{
throw new Exception("job entry must contain a valid attribute for jobs.job.@attributes.type");
}
if(empty($date))
{
throw new Exception("job entry must contain a valid attribute for jobs.job.@attributes.date");
}
if(strlen($id) < 1)
{
throw new Exception("job entry must contain a valid attribute for jobs.job.@attributes.id");
}
switch($type)
{
case 'once':
if(($date = strtotime($date)) !== false)
{
if(time() >= $date)
{
if($this->_jobPool !== null && isset($this->_jobPool[basename($this->_xml)][$id]))
{
$v = null;
$this->log("..job has been scheduled to run once and has already been executed", self::LOG_NOTICE);
}
}else{
$v = null;
$this->log("..job has been scheduled to run once but can not be executed before schedule date", self::LOG_NOTICE);
}
}else{
throw new Exception("job attribute value for jobs.job.@attributes.date is not a valid date value");
}
break;
case 'daily':
if((bool)preg_match('/([0-9]{1,2})\:([0-9]{1,2})$/i', $date, $m) !== false)
{
if(time() < mktime((int)$m[1], (int)$m[2], (int)strftime('%S', time()), (int)strftime('%m', time()), (int)strftime('%d', time()), (int)strftime('%Y', time())))
{
$v = null;
$this->log("..job has been scheduled to run daily but can not be executed before schedule date", self::LOG_NOTICE);
}
if($this->_jobPool !== null && isset($this->_jobPool[basename($this->_xml)][$id]))
{
$time = (int)trim($this->_jobPool[basename($this->_xml)][$id][sizeof($this->_jobPool[basename($this->_xml)][$id]) - 1]);
if(time() > mktime((int)strftime('%H', $time), (int)strftime('%M', $time), (int)strftime('%S', $time), (int)strftime('%m', time()), (int)strftime('%d', time()), (int)strftime('%Y', time())))
{
$v = null;
$this->log("..job has been scheduled to run daily and has already been executed", self::LOG_NOTICE);
}
}
}else{
throw new Exception("job attribute value for jobs.job.@attributes.date is not a valid hourly value");
}
break;
default:
throw new Exception("job schedule type is not supported");
}
}
}
$j++;
}
}else{
throw new Exception("config file must have at least one valid job entry", self::LOG_EXCEPTION);
}
}
catch(Exception $e)
{
$this->log($e->getMessage(), self::LOG_EXCEPTION);
}
}
/**
* @desc init method validates xml config and inits remote connection
* @throws Exception
* @return void
*/
protected function initConfig()
{
try
{
if($this->_xmlArray !== null)
{
$xml =& $this->_xmlArray;
if(isset($xml['config']['target']))
{
if(!isset($xml['config']['target']['host']))
{
$this->log("config file must define config.target.host", self::LOG_EXCEPTION);
}
if(!isset($xml['config']['target']['port']))
{
$this->log("config file must define config.target.port", self::LOG_EXCEPTION);
}
if(!isset($xml['config']['target']['user']))
{
$this->log("config file must define config.target.user", self::LOG_EXCEPTION);
}
if(
(!isset($xml['config']['target']['pass']) || empty($xml['config']['target']['pass']))
&&
(!isset($xml['config']['target']['options']['pubkey']))
)
{
echo "Password for target: ";
$pass = preg_replace('/\r?\n$/', '', `stty -echo; head -n1 ; stty echo`);
if(!empty($pass))
{
$xml['config']['target']['pass'] = $pass;
}else{
echo "Please run script again an enter correct password";
exit(0);
}
}
}
if(isset($xml['config']['target']))
{
if(isset($xml['config']['target']['class']) && !empty($xml['config']['target']['class']))
{
if(is_array($xml['config']['target']['class']))
{
if(isset($xml['config']['target']['class']['@attributes']) && isset($xml['config']['target']['class']['@attributes']['includes']))
{
$includes = explode(':', trim($xml['config']['target']['class']['@attributes']['includes']));
foreach($includes as $i)
{
if(strpos($i, '.') !== false)
{
include_once(trim($i));
}else{
if(!set_include_path(get_include_path() . PATH_SEPARATOR . trim($i)))
{
echo "unable to set include path: $i";
exit(0);
}
}
}
}
$class = strtolower(trim($xml['config']['target']['class']['@value']));
}else{
$class = strtolower(trim($xml['config']['target']['class']));
}
}else{
$class = ((int)$xml['config']['target']['port'] === 21 || strtolower(trim($xml['config']['target']['port'])) === "ftp") ? "Ftp" : "Sftp";
}
$this->_conn = new $class($this);
$this->_conn->init
(
$xml['config']['target']['host'],
$xml['config']['target']['port'],
((!empty($xml['config']['target']['user'])) ? $xml['config']['target']['user'] : null),
((!empty($xml['config']['target']['pass'])) ? $xml['config']['target']['pass'] : null),
((!empty($xml['config']['target']['options'])) ? $xml['config']['target']['options'] : null)
);
$this->_conn->connect();
}else{
$this->_conn = new Fs($this);
}
}
}
catch(Exception $e)
{
$this->log($e->getMessage(), self::LOG_EXCEPTION);
}
}
/**
* @desc executes the sync with all config settings
* @throws Exception
* @return void
*/
protected function exec()
{
$tmp = array();
$xml =& $this->_xmlArray['jobs'];
$j = 0;
foreach($xml['job'] as $k => $v)
{
try
{
if($v !== null)
{
$id = $v['@attributes']['id'];
$this->log(".executing job: $j with id: $id", self::LOG_NOTICE);
$resync = (bool)$this->get("config.resync", false);
if($this->is("jobs.job.$j.@attributes.resync"))
{
$resync = (bool)$this->get("jobs.job.$j.@attributes.resync", false);
}
$skip = trim($this->get("config.skip"));
if($this->is("jobs.job.$j.@attributes.skip"))
{
$skip = trim($this->get("jobs.job.$j.@attributes.skip"));
}
$chmod = trim($this->get("config.chmod"));
if($this->is("jobs.job.$j.@attributes.chmod"))
{
$chmod = trim($this->get("jobs.job.$j.@attributes.chmod"));
}
$chown = trim($this->get("config.chown"));
if($this->is("jobs.job.$j.@attributes.chown"))
{
$chown = trim($this->get("jobs.job.$j.@attributes.chown"));
}
$chgrp = trim($this->get("config.chgrp"));
if($this->is("jobs.job.$j.@attributes.chgrp"))
{
$chgrp = trim($this->get("jobs.job.$j.@attributes.chgrp"));
}
$compare = strtolower($this->get("config.compare"));
if($this->is("jobs.job.$j.@attributes.compare"))
{
$compare = strtolower($this->get("jobs.job.$j.@attributes.compare"));
}
$modified_since = trim($this->get("config.modified_since"));
if($this->is("jobs.job.$j.@attributes.modified_since"))
{
$modified_since = (bool)$this->get("jobs.job.$j.@attributes.modified_since");
}
$time_offset = $this->get("config.time_offset", 0);
$exclude = null;
if($this->is("jobs.job.$j.excludes.exclude"))
{
$exclude = $this->get("jobs.job.$j.excludes.exclude");
if(!is_array($exclude))
{
$exclude = array($exclude);
}
}
$this->log("..using class: " . get_class($this->_conn), self::LOG_NOTICE);
$this->log("..using compare mode: $compare", self::LOG_NOTICE);
$this->log("..using resync option: " . (($resync) ? "yes" : "no"), self::LOG_NOTICE);
$this->log("..using skip rules: $skip", self::LOG_NOTICE);
$this->log("..using chmod value: $chmod", self::LOG_NOTICE);
$this->log("..using chown value: $chown", self::LOG_NOTICE);
$this->log("..using chgrp value: $chgrp", self::LOG_NOTICE);
$this->log("..using modified since value: ".((!empty($modified_since)) ? $modified_since : ""), self::LOG_NOTICE);
$this->log("..using time offset value: ".$time_offset, self::LOG_NOTICE);
//testing source dir
$source = rtrim($this->get("config.sourcebase"), DIRECTORY_SEPARATOR."*") . DIRECTORY_SEPARATOR . trim($v['source'], DIRECTORY_SEPARATOR."*") . DIRECTORY_SEPARATOR;
$source = DIRECTORY_SEPARATOR . ltrim($source, DIRECTORY_SEPARATOR);
$this->log("...validating source dir: $source", self::LOG_NOTICE);
if(!is_dir($source) && is_readable($source))
{
$this->log("....dir: $source FAILED (not found or not readable)", self::LOG_ERROR, true);
}
//testing target dir and setting current working directory
if($this->is("config.targetbase"))
{
$cwd = $this->get("config.targetbase");
if($cwd === DIRECTORY_SEPARATOR)
{
$this->_conn->setCwd("/");
}else{
$this->_conn->setCwd(DIRECTORY_SEPARATOR . trim($this->get("config.targetbase"), DIRECTORY_SEPARATOR."*") . DIRECTORY_SEPARATOR);
}
}else{
$this->_conn->setCwd();
}
$target = DIRECTORY_SEPARATOR . trim($v['target'], DIRECTORY_SEPARATOR."*") . DIRECTORY_SEPARATOR;
$this->log("...validating target dir: $target", self::LOG_NOTICE);
//testing target dir
if(!$this->_conn->testDir($target))
{
$this->log("....dir: $target FAILED (not found or not writeable)", self::LOG_ERROR, true);
}
//testing for user
if(!empty($chown))
{
if(!$this->_conn->isOwn($chown, $target))
{
$this->log("....user: $chown does not exist on target server or permissions for chown denied", self::LOG_ERROR, true);
}
}
//testing for group
if(!empty($chgrp))
{
if(!$this->_conn->isGrp($chgrp, $target))
{
$this->log("....group: $chgrp does not exist on target server or permissions for chgrp denied", self::LOG_ERROR, true);
}
}
$skip_dir = array();
$skip_ext = preg_split('/\,+/', str_replace(array(";", ".", "*"), array(",", "", ""), $skip));
foreach(preg_split('/\,+/', $skip) as $s)
{
if(in_array(substr($s, -1), array('*', '/', '\\')))
{
$skip_dir[] = preg_quote(trim($s, '*/\\'));
}
}
//prepare actions
$actions = false;
if($this->is("jobs.job.$j.actions.action"))
{
$actions = array();
foreach($v['actions']['action'] as &$a)
{
$a['@value'] = trim($a['@value'], ' *');
if(preg_match('/\.([a-z0-9]{2,})$/i', $a['@value']))
{
if(stristr($a['@value'], $target))
{
$p = DIRECTORY_SEPARATOR . ltrim($a['@value'], DIRECTORY_SEPARATOR);
$r = "#^" . addslashes(DIRECTORY_SEPARATOR . ltrim($a['@value'], DIRECTORY_SEPARATOR)) . "$#i";
}else{
$p = $target . ltrim($a['@value'], DIRECTORY_SEPARATOR);
$r = "#^" . addslashes($target . ltrim($a['@value'], DIRECTORY_SEPARATOR)) . "$#i";
}
}else{
if(stristr($a['@value'], $target))
{
$p = DIRECTORY_SEPARATOR . trim($a['@value'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$r = "#^" . addslashes(DIRECTORY_SEPARATOR . trim($a['@value'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) . ".*#i";
}else{
$p = $target . trim($a['@value'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$r = "#^" . addslashes($target . trim($a['@value'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) . ".*#i";
}
}
$actions[md5($p)] = array($a['@attributes']['type'], $r, $p);
}
}
//prepare modified since value
if(!empty($modified_since))
{
$modified_since = trim($modified_since);
//assume timestamp
if(is_numeric($modified_since) && (int)$modified_since == $modified_since){
$modified_since = (int)$modified_since;
//assume date/time
}else if((bool)preg_match("/^([\d]{1,2})(?:\-|\/|\.)([\d]{1,2})(?:\-|\/|\.)([\d]{2,4})\s+([\d]{2})(?:\:)([\d]{2})(?:\:)([\d]{2})$/i", $modified_since, $m)){
$modified_since = mktime((int)$m[4], (int)$m[5], (int)$m[6], (int)$m[1], (int)$m[2], (int)$m[3]);
//assume date
}else if((bool)preg_match("/^([\d]{1,2})(?:\-|\/.)([\d]{1,2})(?:\-|\/.)([\d]{2,4})$/i", $modified_since, $m)){
$modified_since = mktime(0, 0, 0, (int)$m[1], (int)$m[2], (int)$m[3]);
}else{
throw new Exception("modified since date: $modified_since is not a valid date/time");
}
}
//prepare offset value
if(!empty($time_offset))
{
if(is_numeric($time_offset)){
$time_offset = (int)$time_offset;
}else{
throw new Exception("server time offset: $time_offset is not a valid value");
}
}
//prepare exclude values
if($exclude !== null)
{
foreach($exclude as &$ex)
{
$ex = DIRECTORY_SEPARATOR . ltrim(trim($ex, " *"), DIRECTORY_SEPARATOR);
//the exclude rule is a absolute path to a source directory
if(@is_dir($ex)){
$ex = "#^" . preg_quote(DIRECTORY_SEPARATOR . trim($ex, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) . ".*#i";
//the exclude rule is a relative path to directory
}else if(@is_dir($source . ltrim($ex, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)){
$ex = "#^" . preg_quote($source . trim($ex, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR). ".*#i";
//the exclude rule is a absolute path to a source file
}else if(is_file($ex)){
$ex = "#^" . preg_quote($ex) . "$#i";
//the exclude rule is a relative path to a source file
}else if(is_file($source . ltrim($ex, DIRECTORY_SEPARATOR))){
$ex = "#^" . preg_quote($source . ltrim($ex, DIRECTORY_SEPARATOR)) . "$#i";
//the exclude rule is a dir
}else if(stristr($ex, ((strpos($ex, $source) !== false) ? $source : $target)) !== false && !preg_match('/\.([\w]{2,})$/i', $ex)){
$ex = "#^" . preg_quote($ex). ".*#i";
//the exclude rule is a file
}else{
$ex = "#(.*)" . preg_quote($ex) . "$#i";
}
}
unset($ex);
}
//iterate to source directories and sync
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $i)
{
$source_absolute_path = ($i->isDir()) ? rtrim($i->__toString(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $i->__toString();
$source_relative_path = DIRECTORY_SEPARATOR . trim(str_replace($source, "", $source_absolute_path), DIRECTORY_SEPARATOR);
$target_absolute_path = $target . trim($source_relative_path, DIRECTORY_SEPARATOR);
$tmp[] = $source_relative_path;
//get permissions and convert accordingly
$source_permission_num = null;
$source_permission_str = null;
if(!empty($chmod))
{
if(strtolower(trim($chmod) === 'copy'))
{
$source_permission_num = octdec((string)(int)$chmod);
$source_permission_str = str_pad(trim($chmod), 4, 0, STR_PAD_LEFT);
}else{
if(($source_permission = @fileperms($source_absolute_path)) !== false)
{
$source_permission_num = $this->getMod($source_permission);
$source_permission_str = substr(decoct($source_permission), -4);
}else{
$this->log("...file/dir: $source_absolute_path is skipped because unable to get file permission from source file/dir", self::LOG_ERROR);
continue 1;
}
}
}
//get chown user
$owner = fileowner($source_absolute_path);
if($owner !== false && ($owner = posix_getpwuid((int)$owner)) !== false)
{
if(!empty($chown))
{
if($this->_conn instanceof Phpseclib_Sftp)
{
if((int)$owner['uid'] === (int)$chown)
{
$chown = "";
}
}else{
if(strtolower(trim($owner['name'])) === strtolower(trim((string)$chown)))
{
$chown = "";
}
}
}
}else{
$this->log("...file/dir: $source_absolute_path is skipped because unable to get owner from source file/dir", self::LOG_ERROR);
continue 1;
}
//get chgrp group
$group = filegroup($source_absolute_path);
if($group !== false && ($group = posix_getgrgid((int)$group)) !== false)
{
if(!empty($chgrp))
{
if($this->_conn instanceof Phpseclib_Sftp)
{
if((int)$group['gid'] === (int)$chgrp)
{
$chgrp = "";
}
}else{
if(strtolower(trim($group['name'])) === strtolower(trim((string)$chgrp)))
{
$chgrp = "";
}
}
}
}else{
$this->log("...file/dir: $source_absolute_path is skipped because unable to get group from source file/dir", self::LOG_ERROR);
continue 1;
}
if($exclude !== null)
{
foreach($exclude as $ex)
{
if((bool)preg_match($ex, $source_absolute_path))