-
Notifications
You must be signed in to change notification settings - Fork 19
/
dbbackup.class.php
727 lines (618 loc) · 22 KB
/
dbbackup.class.php
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
<?php
/**
* Geeklog Database Backup Class.
* Based on the Wordpress wp-db-backup plugin by Austin Matzko
* http://www.ilfilosofo.com/
*
* @author Lee Garner <lee@leegarner.com>
* @copyright Copyright (c) 2010-2014 Lee Garner <lee@leegarner.com>
* @package lglib
* @version 0.0.1
* @license http://opensource.org/licenses/gpl-2.0.php
* GNU Public License v2 or later
* @filesource
*/
/**
* Class for backup
* @package lglib
*/
class dbBackup
{
/** Backup filename, resulting from backup fucntion. May be false.
* @var mixed */
private $backup_file = '';
/** Backup filename. Static, created from configured values.
* @var string */
private $backup_filename;
/** Flag to indicate whether GZip is to be used.
* @var boolean */
private $gzip = false;
/** Flag to indicate if the backup is running from cron.
* @var boolean */
private $fromCron = false;
/** File pointer to backup file
* @var mixed */
private $fp;
private $tablenames;
private $exclusions;
/**
* Constructor.
* Normally just instantiated. If it's used from cron, then call
* $DB = new dbBackup(true);
*/
public function __construct($fromCron = false)
{
global $_CONF, $_TABLES;
$this->setGZip(true);
$this->fromCron = $fromCron ? true : false;
$this->backup_dir = $_CONF['backup_path'];
} // dbBackup()
/**
* Set the backup filename
* Intended to be used when running via ajax - the current backup filename
* generated with getBackupFilename is stored by the JS and passed to
* subsequent calls.
*
* @return none
*/
public function setBackupFilename($filename)
{
$this->backup_filename = $filename;
}
/**
* Get the backup filename
* Generates appropriate filename based on configurations settings
*
* @return string - the filename (no path).
*/
public function getBackupFilename()
{
global $_CONF;
// Create the backup filename
$table_prefix = empty($_CONF['dbdump_filename_prefix']) ?
'geeklog_db_backup_' : $_CONF['dbdump_filename_prefix'] . '_';
$datum = date("Y_m_d_H_i_s");
$this->backup_filename = $table_prefix . $datum . '.sql';
if ($this->gzip) $this->backup_filename .= '.gz';
return $this->backup_filename;
}
/**
* Builds the list of tables to backup
* Generates the internal array of tables to backup, including only
* tables defined in the $_TABLES array and excluding any tables listed
* in the exclusion array
*
* @return array - array of table names
*/
public function getTableList()
{
global $_TABLES, $_VARS;
// Get all tables in the database
$mysql_tables = array();
$res = DB_query('SHOW TABLES');
while ($A = DB_fetchArray($res)) {
$mysql_tables[] = $A[0];
}
// Get only tables that exist and are listed in $_TABLES
$this->tablenames = array_intersect($mysql_tables, $_TABLES);
// Get exclusions and remove from backup list
$this->exclusions = @unserialize($_VARS['_dbback_exclude']);
if (!is_array($this->exclusions))
$this->exclusions = array($this->exclusions);
$this->tablenames = array_diff($this->tablenames, $this->exclusions);
return $this->tablenames;
}
/**
* Execute a database backup
* Intended to be called from the constructor when requested via url
*
* @return boolean True on success, False on failure
*/
public function perform_backup()
{
$this->getBackupFilename();
$this->getTableList();
$this->backup_file = $this->backupDB();
if (false !== $this->backup_file) {
$this->Purge();
return true;
} else {
return false;
}
}
/**
* Save the time of this backup, if running from cron
*/
public function save_backup_time()
{
global $_TABLES;
$backup_time = time();
DB_query("INSERT INTO {$_TABLES['vars']}
(name, value) VALUES ('db_backup_lastrun', '$backup_time')
ON DUPLICATE KEY
UPDATE value='$backup_time'");
}
/**
* Add backquotes to tables and db-names in
* SQL queries. Taken from phpMyAdmin.
*/
private function backquote($a_name)
{
if (!empty($a_name) && $a_name != '*') {
if (is_array($a_name)) {
$result = array();
reset($a_name);
while(list($key, $val) = each($a_name))
$result[$key] = '`' . $val . '`';
return $result;
} else {
return '`' . $a_name . '`';
}
} else {
return $a_name;
}
}
/**
* Open the backup file for writing, using gzip if appropriate
*
* Note: This function will prepend the backup directory, so only pass
* the filename.
*
* @param string $filename Filename to open
* @param string $mode File mode, default = write
*/
public function open($filename, $mode='w')
{
if (is_writable($this->backup_dir)) {
if ($this->gzip)
$this->fp = @gzopen($this->backup_dir.$filename, $mode);
else
$this->fp = @fopen($this->backup_dir.$filename, $mode);
if(!$this->fp) {
COM_errorLog('Could not open the backup file for writing! (' .
$this->backup_dir . $this->backup_filename . ')');
return false;
}
} else {
$this->error('The backup directory is not writeable ('.$this->backup_dir.')');
return false;
}
return true;
}
/**
* Close the backup file
*/
public function close()
{
if ($this->gzip) {
gzclose($this->fp);
} else {
fclose($this->fp);
}
}
/**
* Write to the backup file
* @param string $query_line the line to write
* @return null
*/
private function stow($query_line)
{
if ($this->gzip) {
if (!@gzwrite($this->fp, $query_line))
$this->error('There was an error writing a line to the backup script:' . ' ' . $query_line);
} else {
if (false === @fwrite($this->fp, $query_line))
$this->error('There was an error writing a line to the backup script:' . ' ' . $query_line);
}
}
/**
* Logs any error messages
* @param array $args
* @return bool
*/
private function error($msg)
{
$backtrace = debug_backtrace();
$method = $backtrace[1]['class'].'::'.$backtrace[1]['function'];
COM_errorLog($method . ' - ' . $msg);
}
/**
* Taken partially from phpMyAdmin and partially from
* Alain Wolf, Zurich - Switzerland
* Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
* Modified by Scott Merrill (http://www.skippy.net/)
* to use the WordPress $wpdb object
* @param string $table
* @return void
*/
public function backupTable($table, $structonly=false, $start = 0)
{
global $_TABLES;
$recordCounter = $start;
$timerStart = time();
$sessionCounter = 0;
$timeout = 30;
$maxExecutionTime = @ini_get("max_execution_time");
$timeout = min($maxExecutionTime,30);
$timeout -= -10; // buffer
if ( $timeout < 0 ) {
$timeout = min($maxExecutionTime,30);
}
if ( $timeout > 10 ) $timeout = 10;
// open the backup file in append mode
if ( $this->open($this->backup_filename,'a') === false ) {
return array(-2,$sessionCounter, $recordCounter);
}
// Save the backquoted table name, gets used a lot
$db_tablename = $this->backquote($table);
// Get the table structure
$res = DB_query("DESCRIBE $table");
$table_structure = array();
while ($A =DB_fetchArray($res, false)) {
$table_structure[] = $A;
}
if (empty($table_structure)) {
$this->error('Error getting table details: ' . $table);
return array(-2,$sessionCounter, $recordCounter);
}
if ( $start == 0 ) {
// Create the SQL statements
$this->stow("# --------------------------------------------------------\n");
$this->stow("# Table: $table\n");
$this->stow("# --------------------------------------------------------\n");
// Add SQL statement to drop existing table
$this->stow("\n\n");
$this->stow("#\n");
$this->stow("# Delete any existing table $db_tablename\n");
$this->stow("#\n");
$this->stow("\n");
$this->stow("DROP TABLE IF EXISTS $db_tablename;\n");
// Table structure
// Comment in SQL-file
$this->stow("\n\n");
$this->stow("#\n");
$this->stow("# Table structure of table $db_tablename\n");
$this->stow("#\n");
$this->stow("\n");
$res = DB_query("SHOW CREATE TABLE $table");
if (!$res) {
$err_msg = 'Error with SHOW CREATE TABLE for ' . $table;
$this->error($err_msg);
$this->stow("#\n# $err_msg\n#\n");
}
$create_table = DB_fetchArray($res);
$create_table = str_replace('0000-00-00 00:00:00','1000-01-01 00:00:00.000000',$create_table);
$this->stow($create_table[1] . ' ;');
// If only backing up the structure, return now
if ($structonly) {
$this->stow("\n");
$this->stow("\n");
$this->close();
return array(0,0,0);
}
// Comment in SQL-file
$this->stow("\n\n");
$this->stow("#\n");
$this->stow("# Data contents of table $db_tablename\n");
$this->stow("#\n");
}
$defs = array();
$ints = array();
foreach ($table_structure as $struct) {
if ( (0 === strpos($struct['Type'], 'tinyint')) ||
(0 === strpos(strtolower($struct['Type']), 'smallint')) ||
(0 === strpos(strtolower($struct['Type']), 'mediumint')) ||
(0 === strpos(strtolower($struct['Type']), 'int')) ||
(0 === strpos(strtolower($struct['Type']), 'timestamp')) ||
(0 === strpos(strtolower($struct['Type']), 'time')) ||
(0 === strpos(strtolower($struct['Type']), 'bigint')) ) {
$defs[strtolower($struct['Field'])] = (null === $struct['Default']) ? 'NULL' : $struct['Default'];
$ints[strtolower($struct['Field'])] = "1";
}
}
$sql = "SELECT * FROM $table LIMIT 18446744073709551610 OFFSET " . $start;
$res = DB_query($sql);
$table_data = array();
$insert = "INSERT INTO {$db_tablename} VALUES (";
while ($A = DB_fetchArray($res, false)) {
// \x08\\x09, not required
$search = array("\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\0', '\n', '\r', '\Z');
$values = array();
foreach ($A as $key => $value) {
if (isset($ints[strtolower($key)]) && $ints[strtolower($key)]) {
// make sure there are no blank spots in the insert syntax,
// yet try to avoid quotation marks around integers
$value = (null === $value || '' === $value) ?
$defs[strtolower($key)] : $value;
$values[] = ( '' === $value ) ? "''" : $value;
} else {
$values[] = "'" . str_replace($search, $replace, DB_escapeString($value)) . "'";
}
}
$this->stow(" \n" . $insert . implode(', ', $values) . ');');
$recordCounter++;
$checkTimer = time();
$elapsedTime = $checkTimer - $timerStart;
if ( $elapsedTime > $timeout || $sessionCounter > 10000 ) {
$this->close();
return array(1,$sessionCounter, $recordCounter);
}
$sessionCounter++;
}
// Create footer/closing comment in SQL-file
$this->stow("\n");
$this->stow("#\n");
$this->stow("# End of data contents of table $db_tablename\n");
$this->stow("# --------------------------------------------------------\n");
$this->stow("\n");
$this->close();
return array(-1,$sessionCounter, $recordCounter);
} // end backupTable()
public function initBackup()
{
global $_TABLES, $_CONF, $_DB_host, $_DB_name;
if ( $this->open($this->backup_filename) === false ) {
return false;
}
//Begin new backup of MySql
$this->stow("# Geeklog MySQL database backup\n");
$this->stow("#\n");
$this->stow('# Generated: ' . date('l j. F Y H:i T') . "\n");
$this->stow("# Hostname: $_DB_host\n");
$this->stow("# Database: $_DB_name\n");
$this->stow("# --------------------------------------------------------\n");
$this->close();
return true;
}
/**
* Actually performs the backup.
* Creates the backup file, saves the file pointer, then cycles
* through all the tables and calls backupTable() for each.
*
* @return mixed False on failure, name of backup file on success.
*/
private function backupDB()
{
global $_TABLES, $_CONF;
if ( $this->initBackup() === false ) {
return false;
}
foreach ($this->tablenames as $key=>$table) {
if (isset($_CONF['dbdump_tables_only']) && $_CONF['dbdump_tables_only']) {
$this->backupTable($table,true);
} else {
$this->backupTable($table);
}
}
$this->completeBackup();
return $this->backup_filename;
} // backupDB()
public function completeBackup()
{
if ( $this->open($this->backup_filename,'a') === false ) {
return false;
}
$this->stow("#\n");
$this->stow("# Database Backup Finished.\n");
$this->stow("#\n");
$this->close();
return true;
}
/**
* Send an email with attachments.
* This is a verbatim copy of COM_mail(), but with the $attachments
* paramater added and 3 extra lines of code near the end.
*
* @param string $to Receiver's email address
* @param string $from Sender's email address
* @param string $subject Message Subject
* @param string $message Message Body
* @param boolean $html True for HTML message, False for Text
* @param integer $priority Message priority value
* @param string $cc Other recipients
* @param string $altBody Alt. body (text)
* @param array $attachments Array of attachments
* @return boolean True on success, False on Failure
*/
private function SendMail(
$to,
$subject,
$message,
$from = '',
$html = false,
$priority = 0,
$cc = '',
$altBody = '',
$attachments = array()
) {
global $_CONF;
$subject = substr($subject, 0, strcspn($subject, "\r\n"));
$subject = COM_emailEscape($subject);
require_once $_CONF['path'] . 'lib/phpmailer/class.phpmailer.php';
$mail = new PHPMailer();
$mail->SetLanguage('en',$_CONF['path'].'lib/phpmailer/language/');
$mail->CharSet = COM_getCharset();
if ($_CONF['mail_backend'] == 'smtp') {
$mail->IsSMTP();
$mail->Host = $_CONF['mail_smtp_host'];
$mail->Port = $_CONF['mail_smtp_port'];
if ($_CONF['mail_smtp_secure'] != 'none') {
$mail->SMTPSecure = $_CONF['mail_smtp_secure'];
}
if ($_CONF['mail_smtp_auth']) {
$mail->SMTPAuth = true;
$mail->Username = $_CONF['mail_smtp_username'];
$mail->Password = $_CONF['mail_smtp_password'];
}
$mail->Mailer = "smtp";
} elseif ($_CONF['mail_backend'] == 'sendmail') {
$mail->Mailer = "sendmail";
$mail->Sendmail = $_CONF['mail_sendmail_path'];
} else {
$mail->Mailer = "mail";
}
$mail->WordWrap = 76;
$mail->IsHTML($html);
if ($html) {
$mail->Body = COM_filterHTML($message);
} else {
$mail->Body = $message;
}
if ($altBody != '') {
$mail->AltBody = $altBody;
}
$mail->Subject = $subject;
if (is_array($from) && isset($from[0]) && $from[0] != '') {
if ($_CONF['use_from_site_mail'] == 1) {
$mail->From = $_CONF['site_mail'];
$mail->AddReplyTo($from[0]);
} else {
$mail->From = $from[0];
}
} else {
$mail->From = $_CONF['site_mail'];
}
if (is_array($from) && isset($from[1]) && $from[1] != '') {
$mail->FromName = $from[1];
} else {
$mail->FromName = $_CONF['site_name'];
}
if (is_array($to) && isset($to[0]) && $to[0] != '') {
if (isset($to[1]) && $to[1] != '') {
$mail->AddAddress($to[0],$to[1]);
} else {
$mail->AddAddress($to[0]);
}
} else {
// assume old style....
$mail->AddAddress($to);
}
if (isset($cc[0]) && $cc[0] != '') {
if (isset($cc[1]) && $cc[1] != '') {
$mail->AddCC($cc[0],$cc[1]);
} else {
$mail->AddCC($cc[0]);
}
} else {
// assume old style....
if (isset($cc) && $cc != '') {
$mail->AddCC($cc);
}
}
if ($priority) {
$mail->Priority = 1;
}
// Add attachments
foreach($attachments as $key => $value) {
$mail->AddAttachment($value);
}
if(!$mail->Send()) {
COM_errorLog("Email Error: " . $mail->ErrorInfo);
return false;
}
return true;
}
/**
* Deliver a backup file.
* Originally had the option of "http" or "smtp", but for Geeklog
* only "smtp" is needed. Files can be downloaded at any time via
* the backup admin interface.
*/
private function deliver_backup($filename = '')
{
global $_VARS, $_CONF;
if ($filename == '' || !filename) return false;
$diskfile = $this->backup_dir . $filename;
$recipient = $_VARS['_dbback_sendto'];
if (!file_exists($diskfile)) {
COM_errorLog("dbBackup: File $diskfile does not exist");
return false;
}
if (!COM_isEmail($recipient)) {
COM_errorLog("$recipient is not a valid email address");
return false;
}
$message = sprintf("Attached to this email is\n %s\n Size:%s kilobytes\n", $filename, round(filesize($diskfile)/1024));
$status = $this->SendMail(
$recipient,
$_CONF['site_name'] . ' ' . 'Database Backup',
$message, '', false, 0, '', '',
array($diskfile) );
return $status;
}
/**
* Run a backup from cron.
* E-mails the backup file to the configured address, if any.
*
* @return boolean Status from deliver_backup, or false on backup failure.
*/
public function cron_backup()
{
$backup_file = $this->backupDB();
$this->save_backup_time();
if (false !== $backup_file) {
$this->Purge(); // Remove old files
return $this->deliver_backup($backup_file);
} else {
return false;
}
}
/**
* Determine whether gzip is available, and configured.
* Sets $this->gzip to indicate whether gzip should be used.
*
* @param boolean $val False to disable, True to enable if available.
*/
function setGZip($val=true)
{
global $_CONF;
switch ($val) {
case false:
$this->gzip = false;
break;
case true:
if (isset($_CONF['dbdump_gzip']) && $_CONF['dbdump_gzip']) {
$this->gzip = function_exists('gzopen') ? true : false;
} else {
$this->gzip = false;
}
break;
}
}
/**
* Purge old files.
* Removes older files, keeping the requested number.
*
* @param integer $files Number to keep, 0 to use configured value.
*/
public function Purge($files = 0)
{
global $_CONF;
if ( !isset($_CONF['dbdump_max_files'])) $_CONF['dbdump_max_files'] = 5;
if ($files == 0) {
$files = (int)$_CONF['dbdump_max_files'];
}
if ($files == 0) return;
$backups = array();
$fd = opendir($this->backup_dir);
$index = 0;
while ((false !== ($file = @readdir($fd)))) {
if ($file <> '.' && $file <> '..' && $file <> 'CVS' &&
preg_match('/\.sql(\.gz)?$/i', $file)) {
$index++;
clearstatcache();
$backups[] = $file;
}
}
// Sort ascending by filename, which includes timestamp
sort($backups);
$count = count($backups); // How many we have
$topurge = $count - $files; // How many to delete
if ($topurge <= 0) return;
for ($i = 0; $i < $topurge; $i++) {
unlink($this->backup_dir . $backups[$i]);
}
}
} // class dbBackup
?>