XPressME Integration Kit

Trac

source: trunk/extras/wp_plugin/xpressme-backup/xpressme-backup.php @ 675

Last change on this file since 675 was 675, checked in by toemon, 13 years ago

WordPressME2.0.1x のuser_lole がWordPress3.0では利用できなくなるバグ修正 ref#385
EUC->UTF-8変換時、例として
[s:24:"管理人 - (Administrator)";]
[s:27:"管理人 - (Administrator)";]のところ
[s:27:"管理人 - (Administrator)"](;が抜けている)になっていたため。
get_optionの後のunserializeでエラーとなっていた。

File size: 60.3 KB
Line 
1<?php
2/*
3Plugin Name: XPressME Database Backup
4Plugin URI: http://ja.xpressme.info/
5Description: On-demand backup of your WordPress database.  Navigate to <a href="edit.php?page=xpressme-backup">Tools &rarr; Backup</a> to get started.
6Author: toemon
7Author URI: http://ja.xpressme.info
8Version: 1.2
9
10Originally modified from Austin Matzko's WordPress Database Backup(http://www.ilfilosofo.com/blog/wp-db-backup) plugin.
11
12Copyright 2008  toemon
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 2 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
27*/
28
29/**
30 * Change WP_BACKUP_DIR if you want to
31 * use a different backup location
32 */
33
34$rand = substr( md5( md5( DB_PASSWORD ) ), -5 );
35global $wpdbb_content_dir, $wpdbb_content_url, $wpdbb_plugin_dir;
36$wpdbb_content_dir = ( defined('WP_CONTENT_DIR') ) ? WP_CONTENT_DIR : ABSPATH . 'wp-content';
37$wpdbb_content_url = ( defined('WP_CONTENT_URL') ) ? WP_CONTENT_URL : get_option('siteurl') . '/wp-content';
38$wpdbb_plugin_dir = ( defined('WP_PLUGIN_DIR') ) ? WP_PLUGIN_DIR : $wpdbb_content_dir . '/plugins';
39
40if ( ! defined('WP_BACKUP_DIR') ) {
41        define('WP_BACKUP_DIR', $wpdbb_content_dir . '/backup-' . $rand . '/');
42}
43
44if ( ! defined('WP_BACKUP_URL') ) {
45        define('WP_BACKUP_URL', $wpdbb_content_url . '/backup-' . $rand . '/');
46}
47
48if ( ! defined('ROWS_PER_SEGMENT') ) {
49        define('ROWS_PER_SEGMENT', 100);
50}
51
52/**
53 * Set MOD_EVASIVE_OVERRIDE to true
54 * and increase MOD_EVASIVE_DELAY
55 * if the backup stops prematurely.
56 */
57// define('MOD_EVASIVE_OVERRIDE', false);
58if ( ! defined('MOD_EVASIVE_DELAY') ) {
59        define('MOD_EVASIVE_DELAY', '500');
60}
61load_plugin_textdomain('xpressme-backup', 'wp-content/plugins/xpressme-backup');
62
63class wpdbBackup {
64
65        var $backup_complete = false;
66        var $backup_file = '';
67        var $backup_filename;
68        var $core_table_names = array();
69        var $errors = array();
70        var $basename;
71        var $page_url;
72        var $referer_check_key;
73        var $version = '2.1.5-alpha';
74
75        function gzip() {
76                return function_exists('gzopen');
77        }
78
79        function module_check() {
80                $mod_evasive = false;
81                if ( true === MOD_EVASIVE_OVERRIDE ) return true;
82                if ( false === MOD_EVASIVE_OVERRIDE ) return false;
83                if ( function_exists('apache_get_modules') )
84                        foreach( (array) apache_get_modules() as $mod )
85                                if ( false !== strpos($mod,'mod_evasive') || false !== strpos($mod,'mod_dosevasive') )
86                                        return true;
87                return false;
88        }
89
90        function wpdbBackup() {
91                global $table_prefix, $wpdb;
92                add_action('wp_ajax_save_backup_time', array(&$this, 'save_backup_time'));
93                add_action('init', array(&$this, 'init_textdomain'));
94                add_action('load-update-core.php', array(&$this, 'update_notice_action'));
95                add_action('wp_db_backup_cron', array(&$this, 'cron_backup'));
96                add_action('xpressme_cron_daily', array(&$this, 'xpressme_cron_daily'));
97                add_filter('cron_schedules', array(&$this, 'add_sched_options'));
98                add_filter('wp_db_b_schedule_choices', array(&$this, 'schedule_choices'));
99               
100                $table_prefix = ( isset( $table_prefix ) ) ? $table_prefix : $wpdb->prefix;
101                $datum = date("Ymd_B");
102                $this->backup_filename = DB_NAME . "_$table_prefix$datum.sql";
103                if ($this->gzip()) $this->backup_filename .= '.gz';
104
105                $possible_names = array(
106                        'categories',
107                        'comments',
108                        'link2cat',
109                        'linkcategories',
110                        'links',
111                        'options',
112                        'post2cat',
113                        'postmeta',
114                        'posts',
115                        'terms',
116                        'term_taxonomy',
117                        'term_relationships',
118                        'users',
119                );
120                $xpress_possible_names = array(
121                        'usermeta',
122                        'd3forum_link',
123                        'group_role',
124                        'views',
125                        'notify_reserve',
126                );
127
128                foreach( $possible_names as $name ) {
129                        if ( isset( $wpdb->{$name} ) ) {
130                                $this->core_table_names[] = $wpdb->{$name};
131                        }
132                }
133                foreach( $xpress_possible_names as $name ) {
134                                $this->core_table_names[] = $table_prefix . $name;
135                }
136       
137                $this->backup_dir = trailingslashit(apply_filters('wp_db_b_backup_dir', WP_BACKUP_DIR));
138                $this->basename = 'xpressme-backup';
139       
140                $this->referer_check_key = $this->basename . '-download_' . DB_NAME;
141                $query_args = array( 'page' => $this->basename );
142                if ( function_exists('wp_create_nonce') )
143                        $query_args = array_merge( $query_args, array('_wpnonce' => wp_create_nonce($this->referer_check_key)) );
144                $base = ( function_exists('site_url') ) ? site_url('', 'admin') : get_option('siteurl');
145                $this->page_url = add_query_arg( $query_args, $base . '/wp-admin/edit.php');
146                if (isset($_POST['do_backup'])) {
147                        $this->wp_secure('fatal');
148                        check_admin_referer($this->referer_check_key);
149                        $this->can_user_backup('main');
150                        // save exclude prefs
151
152                        $exc_revisions = (array) $_POST['exclude-revisions'];
153                        $exc_spam = (array) $_POST['exclude-spam'];
154                        update_option('xpressme_backup_excs', array('revisions' => $exc_revisions, 'spam' => $exc_spam));
155                       
156                        $do_euc_to_utf8 = $_POST['euc_to_utf8'];
157                        $do_rename_prefix = $_POST['do_rename_prefix'];
158                        $before_prefix = $_POST['before_prefix'];
159                        $after_prefix = $_POST['after_prefix'];
160                        $do_change_uri = $_POST['do_change_uri'];
161                        $before_uri = $_POST['before_uri'];
162                        $after_uri = $_POST['after_uri'];
163                        $del_active_plugin = $_POST['del_active_plugin'];
164                       
165                        update_option('xpressme_backup_extras_option',
166                                array('do_euc_to_utf8' => $do_euc_to_utf8,
167                                        'do_rename_prefix' => $do_rename_prefix,
168                                        'before_prefix' => $before_prefix,
169                                        'after_prefix' => $after_prefix,
170                                        'do_change_uri' => $do_change_uri,
171                                        'before_uri' => $before_uri,
172                                        'after_uri' => $after_uri,
173                                        'del_active_plugin' => $del_active_plugin
174                                )
175                        );
176                               
177                        switch($_POST['do_backup']) {
178                        case 'backup':
179                                add_action('init', array(&$this, 'perform_backup'));
180                                break;
181                        case 'fragments':
182                                add_action('admin_menu', array(&$this, 'fragment_menu'));
183                                break;                         
184                        }
185                } elseif (isset($_GET['fragment'] )) {
186                        $this->can_user_backup('frame');
187                        add_action('init', array(&$this, 'init'));
188                } elseif (isset($_GET['backup'] )) {
189                        $this->can_user_backup();
190                        add_action('init', array(&$this, 'init'));
191                } else {
192                        add_action('admin_menu', array(&$this, 'admin_menu'));
193                }
194        }
195       
196        function init() {
197                $this->can_user_backup();
198                if (isset($_GET['backup'])) {
199                        $via = isset($_GET['via']) ? $_GET['via'] : 'http';
200                       
201                        $this->backup_file = $_GET['backup'];
202                        $this->validate_file($this->backup_file);
203
204                        switch($via) {
205                        case 'smtp':
206                        case 'email':
207                                $success = $this->deliver_backup($this->backup_file, 'smtp', $_GET['recipient'], 'frame');
208                                $this->error_display( 'frame' );
209                                if ( $success ) {
210                                        echo '
211                                                <!-- ' . $via . ' -->
212                                                <script type="text/javascript"><!--\\
213                                        ';
214                                        echo '
215                                                alert("' . __('Backup Complete!','xpressme-backup') . '");
216                                                window.onbeforeunload = null;
217                                                </script>
218                                        ';
219                                }
220                                break;
221                        default:
222                                $this->deliver_backup($this->backup_file, $via);
223                                $this->error_display( 'frame' );
224                        }
225                        die();
226                }
227                if (isset($_GET['fragment'] )) {
228                        list($table, $segment, $filename) = explode(':', $_GET['fragment']);
229                        $this->validate_file($filename);
230                        $this->backup_fragment($table, $segment, $filename);
231                }
232
233                die();
234        }
235
236        function init_textdomain() {
237                load_plugin_textdomain('xpressme-backup', str_replace(ABSPATH, '', dirname(__FILE__)), dirname(plugin_basename(__FILE__)));
238        }
239
240        /*
241         * Add a link to back up your database when doing a core upgrade
242         */
243        function update_notice_action() {
244                if ( 'upgrade-core' == $_REQUEST['action'] ) :
245                        ob_start(array(&$this, 'update_notice'));
246                        add_action('admin_footer', create_function('', 'ob_end_flush();'));
247                endif;
248        }
249                function update_notice($text = '') {
250                        $pattern = '#(<a href\="' . __('http://codex.wordpress.org/WordPress_Backups') . '">.*?</p>)#';
251                        $replace = '$1' . "\n<p>" . sprintf(__('Click <a href="%s" target="_blank">here</a> to back up your database using the WordPress Database Backup plugin. <strong>Note:</strong> WordPress Database Backup does <em>not</em> back up your files, just your database.', 'xpressme-backup'), 'tools.php?page=xpressme-backup') . "</p>\n";
252                        $text = preg_replace($pattern, $replace, $text);
253                        return $text;
254                }
255
256        function build_backup_script() {
257                global $table_prefix, $wpdb;
258       
259                echo "<div class='wrap'>";
260                echo    '<fieldset class="options"><legend>' . __('Progress','xpressme-backup') . '</legend>
261                        <p><strong>' .
262                                __('DO NOT DO THE FOLLOWING AS IT WILL CAUSE YOUR BACKUP TO FAIL:','xpressme-backup').
263                        '</strong></p>
264                        <ol>
265                                <li>'.__('Close this browser','xpressme-backup').'</li>
266                                <li>'.__('Reload this page','xpressme-backup').'</li>
267                                <li>'.__('Click the Stop or Back buttons in your browser','xpressme-backup').'</li>
268                        </ol>
269                        <p><strong>' . __('Progress:','xpressme-backup') . '</strong></p>
270                        <div id="meterbox" style="height:11px;width:80%;padding:3px;border:1px solid #659fff;"><div id="meter" style="height:11px;background-color:#659fff;width:0%;text-align:center;font-size:6pt;">&nbsp;</div></div>
271                        <div id="progress_message"></div>
272                        <div id="errors"></div>
273                        </fieldset>
274                        <iframe id="backuploader" src="about:blank" style="visibility:hidden;border:none;height:1em;width:1px;"></iframe>
275                        <script type="text/javascript">
276                        //<![CDATA[
277                        window.onbeforeunload = function() {
278                                return "' . __('Navigating away from this page will cause your backup to fail.', 'xpressme-backup') . '";
279                        }
280                        function setMeter(pct) {
281                                var meter = document.getElementById("meter");
282                                meter.style.width = pct + "%";
283                                meter.innerHTML = Math.floor(pct) + "%";
284                        }
285                        function setProgress(str) {
286                                var progress = document.getElementById("progress_message");
287                                progress.innerHTML = str;
288                        }
289                        function addError(str) {
290                                var errors = document.getElementById("errors");
291                                errors.innerHTML = errors.innerHTML + str + "<br />";
292                        }
293
294                        function backup(table, segment) {
295                                var fram = document.getElementById("backuploader");
296                                fram.src = "' . $this->page_url . '&fragment=" + table + ":" + segment + ":' . $this->backup_filename . ':";
297                        }
298                       
299                        var curStep = 0;
300                       
301                        function nextStep() {
302                                backupStep(curStep);
303                                curStep++;
304                        }
305                       
306                        function finishBackup() {
307                                var fram = document.getElementById("backuploader");                             
308                                setMeter(100);
309                ';
310
311                $download_uri = add_query_arg('backup', $this->backup_filename, $this->page_url);
312                switch($_POST['deliver']) {
313                case 'http':
314                        echo '
315                                setProgress("' . sprintf(__("Backup complete, preparing <a href=\\\"%s\\\">backup</a> for download...",'xpressme-backup'), $download_uri) . '");
316                                window.onbeforeunload = null;
317                                fram.src = "' . $download_uri . '";
318                        ';
319                        break;
320                case 'smtp':
321                        echo '
322                                setProgress("' . sprintf(__("Backup complete, sending <a href=\\\"%s\\\">backup</a> via email...",'xpressme-backup'), $download_uri) . '");
323                                window.onbeforeunload = null;
324                                fram.src = "' . $download_uri . '&via=email&recipient=' . $_POST['backup_recipient'] . '";
325                        ';
326                        break;
327                default:
328                        echo '
329                                setProgress("' . sprintf(__("Backup complete, download <a href=\\\"%s\\\">here</a>.",'xpressme-backup'), $download_uri) . '");
330                                window.onbeforeunload = null;
331                        ';
332                }
333               
334                echo '
335                        }
336                       
337                        function backupStep(step) {
338                                switch(step) {
339                                case 0: backup("", 0); break;
340                ';
341               
342                $also_backup = array();
343                if (isset($_POST['other_tables'])) {
344                        $also_backup = $_POST['other_tables'];
345                } else {
346                        $also_backup = array();
347                }
348                $core_tables = $_POST['core_tables'];
349                $tables = array_merge($core_tables, $also_backup);
350                $step_count = 1;
351                foreach ($tables as $table) {
352                        $rec_count = $wpdb->get_var("SELECT count(*) FROM {$table}");
353                        $rec_segments = ceil($rec_count / ROWS_PER_SEGMENT);
354                        $table_count = 0;
355                        if ( $this->module_check() ) {
356                                $delay = "setTimeout('";
357                                $delay_time = "', " . (int) MOD_EVASIVE_DELAY . ")";
358                        }
359                        else { $delay = $delay_time = ''; }
360                        do {
361                                echo "case {$step_count}: {$delay}backup(\"{$table}\", {$table_count}){$delay_time}; break;\n";
362                                $step_count++;
363                                $table_count++;
364                        } while($table_count < $rec_segments);
365                        echo "case {$step_count}: {$delay}backup(\"{$table}\", -1){$delay_time}; break;\n";
366                        $step_count++;
367                }
368                echo "case {$step_count}: finishBackup(); break;";
369               
370                echo '
371                                }
372                                if(step != 0) setMeter(100 * step / ' . $step_count . ');
373                        }
374
375                        nextStep();
376                        // ]]>
377                        </script>
378        </div>
379                ';
380                $this->backup_menu();
381        }
382
383        function backup_fragment($table, $segment, $filename) {
384                global $table_prefix, $wpdb;
385                       
386                echo "$table:$segment:$filename";
387               
388                if($table == '') {
389                        $msg = __('Creating backup file...','xpressme-backup');
390                } else {
391                        if($segment == -1) {
392                                $msg = sprintf(__('Finished backing up table \\"%s\\".','xpressme-backup'), $table);
393                        } else {
394                                $msg = sprintf(__('Backing up table \\"%s\\"...','xpressme-backup'), $table);
395                        }
396                }
397               
398                if (is_writable($this->backup_dir)) {
399                        $this->fp = $this->open($this->backup_dir . $filename, 'a');
400                        if(!$this->fp) {
401                                $this->error(__('Could not open the backup file for writing!','xpressme-backup'));
402                                $this->error(array('loc' => 'frame', 'kind' => 'fatal', 'msg' =>  __('The backup file could not be saved.  Please check the permissions for writing to your backup directory and try again.','xpressme-backup')));
403                        }
404                        else {
405                                if($table == '') {             
406                                        //Begin new backup of MySql
407                                        $this->stow("# " . __('WordPress MySQL database backup','xpressme-backup') . "\n");
408                                        $this->stow("#\n");
409                                        $this->stow("# " . sprintf(__('Generated: %s','xpressme-backup'),date("l j. F Y H:i T")) . "\n");
410                                        $this->stow("# " . sprintf(__('Hostname: %s','xpressme-backup'),DB_HOST) . "\n");
411                                        $this->stow("# " . sprintf(__('Database: %s','xpressme-backup'),$this->backquote(DB_NAME)) . "\n");
412                                        $this->stow("# --------------------------------------------------------\n");
413                                } else {
414                                        if($segment == 0) {
415                                                // Increase script execution time-limit to 15 min for every table.
416                                                if ( !ini_get('safe_mode')) @set_time_limit(15*60);
417                                                // Create the SQL statements
418                                                $this->stow("# --------------------------------------------------------\n");
419                                                $this->stow("# " . sprintf(__('Table: %s','xpressme-backup'),$this->backquote($table)) . "\n");
420                                                $this->stow("# --------------------------------------------------------\n");
421                                        }                       
422                                        $this->backup_table($table, $segment);
423                                }
424                        }
425                } else {
426                        $this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __('The backup directory is not writeable!  Please check the permissions for writing to your backup directory and try again.','xpressme-backup')));
427                }
428
429                if($this->fp) $this->close($this->fp);
430               
431                $this->error_display('frame');
432
433                echo '<script type="text/javascript"><!--//
434                var msg = "' . $msg . '";
435                window.parent.setProgress(msg);
436                window.parent.nextStep();
437                //--></script>
438                ';
439                die();
440        }
441
442        function perform_backup() {
443                // are we backing up any other tables?
444                $also_backup = array();
445                if (isset($_POST['other_tables']))
446                        $also_backup = $_POST['other_tables'];
447                $core_tables = $_POST['core_tables'];
448                $this->backup_file = $this->db_backup($core_tables, $also_backup);
449                if (false !== $this->backup_file) {
450                        if ('smtp' == $_POST['deliver']) {
451                                $this->deliver_backup($this->backup_file, $_POST['deliver'], $_POST['backup_recipient'], 'main');
452                                wp_redirect($this->page_url);
453                        } elseif ('http' == $_POST['deliver']) {
454                                $download_uri = add_query_arg('backup',$this->backup_file,$this->page_url);
455                                wp_redirect($download_uri);
456                                exit;
457                        }
458                        // we do this to say we're done.
459                        $this->backup_complete = true;
460                }
461        }
462
463        function admin_header() {
464                ?>
465                <script type="text/javascript">
466                //<![CDATA[
467                if ( 'undefined' != typeof addLoadEvent ) {
468                        addLoadEvent(function() {
469                                var t = {'extra-tables-list':{name: 'other_tables[]'}, 'include-tables-list':{name: 'xpressme_cron_backup_tables[]'}};
470
471                                for ( var k in t ) {
472                                        t[k].s = null;
473                                        var d = document.getElementById(k);
474                                        if ( ! d )
475                                                continue;
476                                        var ul = d.getElementsByTagName('ul').item(0);
477                                        if ( ul ) {
478                                                var lis = ul.getElementsByTagName('li');
479                                                if ( 3 > lis.length )
480                                                        return;
481                                                var text = document.createElement('p');
482                                                text.className = 'instructions';
483                                                text.innerHTML = '<?php _e('Click and hold down <code>[SHIFT]</code> to toggle multiple checkboxes', 'xpressme-backup'); ?>';
484                                                ul.parentNode.insertBefore(text, ul);
485                                        }
486                                        t[k].p = d.getElementsByTagName("input");
487                                        for(var i=0; i < t[k].p.length; i++)
488                                                if(t[k].name == t[k].p[i].getAttribute('name')) {
489                                                        t[k].p[i].id = k + '-table-' + i;
490                                                        t[k].p[i].onkeyup = t[k].p[i].onclick = function(e) {
491                                                                e = e ? e : event;
492                                                                if ( 16  == e.keyCode )
493                                                                        return;
494                                                                var match = /([\w-]*)-table-(\d*)/.exec(this.id);
495                                                                var listname = match[1];
496                                                                var that = match[2];
497                                                                if ( null === t[listname].s )
498                                                                        t[listname].s = that;
499                                                                else if ( e.shiftKey ) {
500                                                                        var start = Math.min(that, t[listname].s) + 1;
501                                                                        var end = Math.max(that, t[listname].s);
502                                                                        for( var j=start; j < end; j++)
503                                                                                t[listname].p[j].checked = t[listname].p[j].checked ? false : true;
504                                                                        t[listname].s = null;
505                                                                }
506                                                        }
507                                                }
508                                }
509
510                                <?php if ( function_exists('wp_schedule_event') ) : // needs to be at least WP 2.1 for ajax ?>
511                                if ( 'undefined' == typeof XMLHttpRequest )
512                                        var xml = new ActiveXObject( navigator.userAgent.indexOf('MSIE 5') >= 0 ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP' );
513                                else
514                                        var xml = new XMLHttpRequest();
515
516                                var initTimeChange = function() {
517                                        var timeWrap = document.getElementById('backup-time-wrap');
518                                        var backupTime = document.getElementById('next-backup-time');
519                                        if ( !! timeWrap && !! backupTime ) {
520                                                var span = document.createElement('span');
521                                                span.className = 'submit';
522                                                span.id = 'change-wrap';
523                                                span.innerHTML = '<input type="submit" id="change-backup-time" name="change-backup-time" value="<?php _e('Change','xpressme-backup'); ?>" />';
524                                                timeWrap.appendChild(span);
525                                                backupTime.ondblclick = function(e) { span.parentNode.removeChild(span); clickTime(e, backupTime); };
526                                                span.onclick = function(e) { span.parentNode.removeChild(span); clickTime(e, backupTime); };
527                                        }
528                                }
529
530                                var clickTime = function(e, backupTime) {
531                                        var tText = backupTime.innerHTML;
532                                        backupTime.innerHTML = '<input type="text" value="' + tText + '" name="backup-time-text" id="backup-time-text" /> <span class="submit"><input type="submit" name="save-backup-time" id="save-backup-time" value="<?php _e('Save', 'xpressme-backup'); ?>" /></span>';
533                                        backupTime.ondblclick = null;
534                                        var mainText = document.getElementById('backup-time-text');
535                                        mainText.focus();
536                                        var saveTButton = document.getElementById('save-backup-time');
537                                        if ( !! saveTButton )
538                                                saveTButton.onclick = function(e) { saveTime(backupTime, mainText); return false; };
539                                        if ( !! mainText )
540                                                mainText.onkeydown = function(e) {
541                                                        e = e || window.event;
542                                                        if ( 13 == e.keyCode ) {
543                                                                saveTime(backupTime, mainText);
544                                                                return false;
545                                                        }
546                                                }
547                                }
548
549                                var saveTime = function(backupTime, mainText) {
550                                        var tVal = mainText.value;
551
552                                        xml.open('POST', 'admin-ajax.php', true);
553                                        xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
554                                        if ( xml.overrideMimeType )
555                                                xml.setRequestHeader('Connection', 'close');
556                                        xml.send('action=save_backup_time&_wpnonce=<?php echo wp_create_nonce($this->referer_check_key); ?>&backup-time='+tVal);
557                                        xml.onreadystatechange = function() {
558                                                if ( 4 == xml.readyState && '0' != xml.responseText ) {
559                                                        backupTime.innerHTML = xml.responseText;
560                                                        initTimeChange();
561                                                }
562                                        }
563                                }
564
565                                initTimeChange();
566                                <?php endif; // wp_schedule_event exists ?>
567                        });
568                }
569                //]]>
570                </script>
571                <style type="text/css">
572                        .xpressme-backup-updated {
573                                margin-top: 1em;
574                        }
575
576                        fieldset.options {
577                                border: 1px solid;
578                                margin-top: 1em;
579                                padding: 1em;
580                        }
581                                fieldset.options div.tables-list {
582                                        float: left;
583                                        padding: 1em;
584                                }
585
586                                fieldset.options input {
587                                }
588
589                                fieldset.options legend {
590                                        font-size: larger;
591                                        font-weight: bold;
592                                        margin-bottom: .5em;
593                                        padding: 1em;
594                                }
595               
596                                fieldset.options .instructions {
597                                        font-size: smaller;
598                                }
599
600                                fieldset.options ul {
601                                        list-style-type: none;
602                                }
603                                        fieldset.options li {
604                                                text-align: left;
605                                        }
606
607                                fieldset.options .submit {
608                                        border-top: none;
609                                }
610                </style>
611                <?php
612        }
613
614        function admin_load() {
615                add_action('admin_head', array(&$this, 'admin_header'));
616        }
617
618        function admin_menu() {
619                $_page_hook = add_management_page(__('XPressME Backup','xpressme-backup'), __('XPressME Backup','xpressme-backup'), 'import', $this->basename, array(&$this, 'backup_menu'));
620                add_action('load-' . $_page_hook, array(&$this, 'admin_load'));
621                if ( function_exists('add_contextual_help') ) {
622                        $text = $this->help_menu();
623                        add_contextual_help($_page_hook, $text);
624                }
625        }
626
627        function fragment_menu() {
628                $page_hook = add_management_page(__('XPressME Backup','xpressme-backup'), __('XPressME Backup','xpressme-backup'), 'import', $this->basename, array(&$this, 'build_backup_script'));
629                add_action('load-' . $page_hook, array(&$this, 'admin_load'));
630        }
631
632        /**
633         * Add WP-DB-Backup-specific help options to the 2.7 =< WP contextual help menu
634         * return string The text of the help menu.
635         */
636        function help_menu() {
637                $text = '';
638//              $text = "\n<a href=\"http://wordpress.org/extend/plugins/xpressme-backup/faq/\" target=\"_blank\">" . __('FAQ', 'xpressme-backup') . '</a>';
639//              $text .= "\n<br />\n<a href=\"http://www.ilfilosofo.com/forum/forum/2\" target=\"_blank\">" . __('WP-DB-Backup Support Forum', 'xpressme-backup') . '</a>';
640                return $text;
641        }
642
643        function save_backup_time() {
644                if ( $this->can_user_backup() ) {
645                        // try to get a time from the input string
646                        $time = strtotime(strval($_POST['backup-time']));
647                        if ( ! empty( $time ) && time() < $time ) {
648                                wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
649                                $scheds = (array) wp_get_schedules();
650                                $name = get_option('xpressme_cron_backup_schedule');
651                                if ( 0 != $time ) {
652                                        wp_schedule_event($time, $name, 'wp_db_backup_cron');
653                                        echo gmdate(get_option('date_format') . ' ' . get_option('time_format'), $time + (get_option('gmt_offset') * 3600));
654                                        exit;
655                                }
656                        }
657                } else {
658                        die(0);
659                }
660        }
661
662        /**
663         * Better addslashes for SQL queries.
664         * Taken from phpMyAdmin.
665         */
666        function sql_addslashes($a_string = '', $is_like = false) {
667                if ($is_like) $a_string = str_replace('\\', '\\\\\\\\', $a_string);
668                else $a_string = str_replace('\\', '\\\\', $a_string);
669                return str_replace('\'', '\\\'', $a_string);
670        }
671
672        /**
673         * Add backquotes to tables and db-names in
674         * SQL queries. Taken from phpMyAdmin.
675         */
676        function backquote($a_name) {
677                if (!empty($a_name) && $a_name != '*') {
678                        if (is_array($a_name)) {
679                                $result = array();
680                                reset($a_name);
681                                while(list($key, $val) = each($a_name))
682                                        $result[$key] = '`' . $val . '`';
683                                return $result;
684                        } else {
685                                return '`' . $a_name . '`';
686                        }
687                } else {
688                        return $a_name;
689                }
690        }
691
692        function open($filename = '', $mode = 'w') {
693                if ('' == $filename) return false;
694                if ($this->gzip())
695                        $fp = @gzopen($filename, $mode);
696                else
697                        $fp = @fopen($filename, $mode);
698                return $fp;
699        }
700
701        function close($fp) {
702                if ($this->gzip()) gzclose($fp);
703                else fclose($fp);
704        }
705
706        /**
707         * Write to the backup file
708         * @param string $query_line the line to write
709         * @return null
710         */
711        function stow($query_line) {
712                $query_line = $this->extras_filter($query_line);
713                if ($this->gzip()) {
714                        if(! @gzwrite($this->fp, $query_line))
715                                $this->error(__('There was an error writing a line to the backup script:','xpressme-backup') . '  ' . $query_line . '  ' . $php_errormsg);
716                } else {
717                        if(false === @fwrite($this->fp, $query_line))
718                                $this->error(__('There was an error writing a line to the backup script:','xpressme-backup') . '  ' . $query_line . '  ' . $php_errormsg);
719                }
720        }
721       
722        /**
723         * Logs any error messages
724         * @param array $args
725         * @return bool
726         */
727        function error($args = array()) {
728                if ( is_string( $args ) )
729                        $args = array('msg' => $args);
730                $args = array_merge( array('loc' => 'main', 'kind' => 'warn', 'msg' => ''), $args);
731                $this->errors[$args['kind']][] = $args['msg'];
732                if ( 'fatal' == $args['kind'] || 'frame' == $args['loc'])
733                        $this->error_display($args['loc']);
734                return true;
735        }
736
737        /**
738         * Displays error messages
739         * @param array $errs
740         * @param string $loc
741         * @return string
742         */
743        function error_display($loc = 'main', $echo = true) {
744                $errs = $this->errors;
745                unset( $this->errors );
746                if ( ! count($errs) ) return;
747                $msg = '';
748                $err_list = array_slice(array_merge( (array) $errs['fatal'], (array) $errs['warn']), 0, 10);
749                if ( 10 == count( $err_list ) )
750                        $err_list[9] = __('Subsequent errors have been omitted from this log.','xpressme-backup');
751                $wrap = ( 'frame' == $loc ) ? "<script type=\"text/javascript\">\n var msgList = ''; \n %1\$s \n if ( msgList ) alert(msgList); \n </script>" : '%1$s';
752                $line = ( 'frame' == $loc ) ?
753                        "try{ window.parent.addError('%1\$s'); } catch(e) { msgList += ' %1\$s';}\n" :
754                        "%1\$s<br />\n";
755                foreach( (array) $err_list as $err )
756                        $msg .= sprintf($line,str_replace(array("\n","\r"), '', addslashes($err)));
757                $msg = sprintf($wrap,$msg);
758                if ( count($errs['fatal'] ) ) {
759                        if ( function_exists('wp_die') && 'frame' != $loc ) wp_die(stripslashes($msg));
760                        else die($msg);
761                }
762                else {
763                        if ( $echo ) echo $msg;
764                        else return $msg;
765                }
766        }
767
768        /**
769         * Taken partially from phpMyAdmin and partially from
770         * Alain Wolf, Zurich - Switzerland
771         * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
772       
773         * Modified by Scott Merrill (http://www.skippy.net/)
774         * to use the WordPress $wpdb object
775         * @param string $table
776         * @param string $segment
777         * @return void
778         */
779        function backup_table($table, $segment = 'none') {
780                global $wpdb;
781
782                $table_structure = $wpdb->get_results("DESCRIBE $table");
783                if (! $table_structure) {
784                        $this->error(__('Error getting table details','xpressme-backup') . ": $table");
785                        return false;
786                }
787       
788                if(($segment == 'none') || ($segment == 0)) {
789                        // Add SQL statement to drop existing table
790                        $this->stow("\n\n");
791                        $this->stow("#\n");
792                        $this->stow("# " . sprintf(__('Delete any existing table %s','xpressme-backup'),$this->backquote($table)) . "\n");
793                        $this->stow("#\n");
794                        $this->stow("\n");
795                        $this->stow("DROP TABLE IF EXISTS " . $this->backquote($table) . ";\n");
796                       
797                        // Table structure
798                        // Comment in SQL-file
799                        $this->stow("\n\n");
800                        $this->stow("#\n");
801                        $this->stow("# " . sprintf(__('Table structure of table %s','xpressme-backup'),$this->backquote($table)) . "\n");
802                        $this->stow("#\n");
803                        $this->stow("\n");
804                       
805                        $create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
806                        if (false === $create_table) {
807                                $err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','xpressme-backup'), $table);
808                                $this->error($err_msg);
809                                $this->stow("#\n# $err_msg\n#\n");
810                        }
811                        $this->stow($create_table[0][1] . ' ;');
812                       
813                        if (false === $table_structure) {
814                                $err_msg = sprintf(__('Error getting table structure of %s','xpressme-backup'), $table);
815                                $this->error($err_msg);
816                                $this->stow("#\n# $err_msg\n#\n");
817                        }
818               
819                        // Comment in SQL-file
820                        $this->stow("\n\n");
821                        $this->stow("#\n");
822                        $this->stow('# ' . sprintf(__('Data contents of table %s','xpressme-backup'),$this->backquote($table)) . "\n");
823                        $this->stow("#\n");
824                }
825               
826                if(($segment == 'none') || ($segment >= 0)) {
827                        $defs = array();
828                        $ints = array();
829                        foreach ($table_structure as $struct) {
830                                if ( (0 === strpos($struct->Type, 'tinyint')) ||
831                                        (0 === strpos(strtolower($struct->Type), 'smallint')) ||
832                                        (0 === strpos(strtolower($struct->Type), 'mediumint')) ||
833                                        (0 === strpos(strtolower($struct->Type), 'int')) ||
834                                        (0 === strpos(strtolower($struct->Type), 'bigint')) ) {
835                                                $defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
836                                                $ints[strtolower($struct->Field)] = "1";
837                                }
838                        }
839                       
840                       
841                        // Batch by $row_inc
842                       
843                        if($segment == 'none') {
844                                $row_start = 0;
845                                $row_inc = ROWS_PER_SEGMENT;
846                        } else {
847                                $row_start = $segment * ROWS_PER_SEGMENT;
848                                $row_inc = ROWS_PER_SEGMENT;
849                        }
850                       
851                        do {   
852                                // don't include extra stuff, if so requested
853                                $excs = (array) get_option('xpressme_backup_excs');
854
855                                $where = '';
856                                if ( is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) {
857                                        $where = ' WHERE comment_approved != "spam"';
858                                } elseif ( is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) {
859                                        $where = ' WHERE post_type != "revision"';
860                                }
861                               
862                                if ( !ini_get('safe_mode')) @set_time_limit(15*60);
863                                $table_data = $wpdb->get_results("SELECT * FROM $table $where LIMIT {$row_start}, {$row_inc}", ARRAY_A);
864
865                                $entries = 'INSERT INTO ' . $this->backquote($table) . ' VALUES (';     
866                                //    \x08\\x09, not required
867                                $search = array("\x00", "\x0a", "\x0d", "\x1a");
868                                $replace = array('\0', '\n', '\r', '\Z');
869                                if($table_data) {
870                                        foreach ($table_data as $row) {
871                                                $values = array();
872                                                foreach ($row as $key => $value) {
873                                                        if ($ints[strtolower($key)]) {
874                                                                // make sure there are no blank spots in the insert syntax,
875                                                                // yet try to avoid quotation marks around integers
876                                                                $value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
877                                                                $values[] = ( '' === $value ) ? "''" : $value;
878                                                        } else {
879                                                                $values[] = "'" . str_replace($search, $replace, $this->sql_addslashes($value)) . "'";
880                                                        }
881                                                }
882                                                $this->stow(" \n" . $entries . implode(', ', $values) . ');');
883                                        }
884                                        $row_start += $row_inc;
885                                }
886                        } while((count($table_data) > 0) and ($segment=='none'));
887                }
888               
889                if(($segment == 'none') || ($segment < 0)) {
890                        // Create footer/closing comment in SQL-file
891                        $this->stow("\n");
892                        $this->stow("#\n");
893                        $this->stow("# " . sprintf(__('End of data contents of table %s','xpressme-backup'),$this->backquote($table)) . "\n");
894                        $this->stow("# --------------------------------------------------------\n");
895                        $this->stow("\n");
896                }
897        } // end backup_table()
898       
899        function db_backup($core_tables, $other_tables) {
900                global $table_prefix, $wpdb;
901               
902                if (is_writable($this->backup_dir)) {
903                        $this->fp = $this->open($this->backup_dir . $this->backup_filename);
904                        if(!$this->fp) {
905                                $this->error(__('Could not open the backup file for writing!','xpressme-backup'));
906                                return false;
907                        }
908                } else {
909                        $this->error(__('The backup directory is not writeable!','xpressme-backup'));
910                        return false;
911                }
912               
913                //Begin new backup of MySql
914                $this->stow("# " . __('WordPress MySQL database backup','xpressme-backup') . "\n");
915                $this->stow("#\n");
916                $this->stow("# " . sprintf(__('Generated: %s','xpressme-backup'),date("l j. F Y H:i T")) . "\n");
917                $this->stow("# " . sprintf(__('Hostname: %s','xpressme-backup'),DB_HOST) . "\n");
918                $this->stow("# " . sprintf(__('Database: %s','xpressme-backup'),$this->backquote(DB_NAME)) . "\n");
919                $this->stow("# --------------------------------------------------------\n");
920               
921                        if ( (is_array($other_tables)) && (count($other_tables) > 0) )
922                        $tables = array_merge($core_tables, $other_tables);
923                else
924                        $tables = $core_tables;
925               
926                foreach ($tables as $table) {
927                        // Increase script execution time-limit to 15 min for every table.
928                        if ( !ini_get('safe_mode')) @set_time_limit(15*60);
929                        // Create the SQL statements
930                        $this->stow("# --------------------------------------------------------\n");
931                        $this->stow("# " . sprintf(__('Table: %s','xpressme-backup'),$this->backquote($table)) . "\n");
932                        $this->stow("# --------------------------------------------------------\n");
933                        $this->backup_table($table);
934                }
935                               
936                $this->close($this->fp);
937               
938                if (count($this->errors)) {
939                        return false;
940                } else {
941                        return $this->backup_filename;
942                }
943               
944        } //wp_db_backup
945
946        /**
947         * Sends the backed-up file via email
948         * @param string $to
949         * @param string $subject
950         * @param string $message
951         * @return bool
952         */
953        function send_mail( $to, $subject, $message, $diskfile) {
954                global $phpmailer;
955
956                $filename = basename($diskfile);
957
958                extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message' ) ) );
959
960                if ( !is_object( $phpmailer ) || ( strtolower(get_class( $phpmailer )) != 'phpmailer' ) ) {
961                        if ( file_exists( ABSPATH . WPINC . '/class-phpmailer.php' ) )
962                                require_once ABSPATH . WPINC . '/class-phpmailer.php';
963                        if ( file_exists( ABSPATH . WPINC . '/class-smtp.php' ) )
964                                require_once ABSPATH . WPINC . '/class-smtp.php';
965                        if ( class_exists( 'PHPMailer') )
966                                $phpmailer = new PHPMailer();
967                }
968
969                // try to use phpmailer directly (WP 2.2+)
970                if ( is_object( $phpmailer ) && ( strtolower(get_class( $phpmailer )) == 'phpmailer' ) ) {
971                       
972                        // Get the site domain and get rid of www.
973                        $sitename = strtolower( $_SERVER['SERVER_NAME'] );
974                        if ( substr( $sitename, 0, 4 ) == 'www.' ) {
975                                $sitename = substr( $sitename, 4 );
976                        }
977                        $from_email = 'wordpress@' . $sitename;
978                        $from_name = 'WordPress';
979
980                        // Empty out the values that may be set
981                        $phpmailer->ClearAddresses();
982                        $phpmailer->ClearAllRecipients();
983                        $phpmailer->ClearAttachments();
984                        $phpmailer->ClearBCCs();
985                        $phpmailer->ClearCCs();
986                        $phpmailer->ClearCustomHeaders();
987                        $phpmailer->ClearReplyTos();
988
989                        $phpmailer->AddAddress( $to );
990                        $phpmailer->AddAttachment($diskfile, $filename);
991                        $phpmailer->Body = $message;
992                        $phpmailer->CharSet = apply_filters( 'wp_mail_charset', get_bloginfo('charset') );
993                        $phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
994                        $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
995                        $phpmailer->IsMail();
996                        $phpmailer->Subject = $subject;
997
998                        do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
999                       
1000                        $result = @$phpmailer->Send();
1001
1002                // old-style: build the headers directly
1003                } else {
1004                        $randomish = md5(time());
1005                        $boundary = "==WPBACKUP-$randomish";
1006                        $fp = fopen($diskfile,"rb");
1007                        $file = fread($fp,filesize($diskfile));
1008                        $this->close($fp);
1009                       
1010                        $data = chunk_split(base64_encode($file));
1011                       
1012                        $headers .= "MIME-Version: 1.0\n";
1013                        $headers = 'From: wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])) . "\n";
1014                        $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
1015               
1016                        // Add a multipart boundary above the plain message
1017                        $message = "This is a multi-part message in MIME format.\n\n" .
1018                                "--{$boundary}\n" .
1019                                "Content-Type: text/plain; charset=\"" . get_bloginfo('charset') . "\"\n" .
1020                                "Content-Transfer-Encoding: 7bit\n\n" .
1021                                $message . "\n\n";
1022
1023                        // Add file attachment to the message
1024                        $message .= "--{$boundary}\n" .
1025                                "Content-Type: application/octet-stream;\n" .
1026                                " name=\"{$filename}\"\n" .
1027                                "Content-Disposition: attachment;\n" .
1028                                " filename=\"{$filename}\"\n" .
1029                                "Content-Transfer-Encoding: base64\n\n" .
1030                                $data . "\n\n" .
1031                                "--{$boundary}--\n";
1032                       
1033                        $result = @wp_mail($to, $subject, $message, $headers);
1034                }
1035                return $result;
1036
1037        }
1038
1039        function deliver_backup($filename = '', $delivery = 'http', $recipient = '', $location = 'main') {
1040                if ('' == $filename) { return false; }
1041               
1042                $diskfile = $this->backup_dir . $filename;
1043                if ('http' == $delivery) {
1044                        if (! file_exists($diskfile))
1045                                $this->error(array('kind' => 'fatal', 'msg' => sprintf(__('File not found:%s','xpressme-backup'), "&nbsp;<strong>$filename</strong><br />") . '<br /><a href="' . $this->page_url . '">' . __('Return to Backup','xpressme-backup') . '</a>'));
1046                        header('Content-Description: File Transfer');
1047                        header('Content-Type: application/octet-stream');
1048                        header('Content-Length: ' . filesize($diskfile));
1049                        header("Content-Disposition: attachment; filename=$filename");
1050                        $success = readfile($diskfile);
1051                        unlink($diskfile);
1052                } elseif ('smtp' == $delivery) {
1053                        if (! file_exists($diskfile)) {
1054                                $msg = sprintf(__('File %s does not exist!','xpressme-backup'), $diskfile);
1055                                $this->error($msg);
1056                                return false;
1057                        }
1058                        if (! is_email($recipient)) {
1059                                $recipient = get_option('admin_email');
1060                        }
1061                        $message = sprintf(__("Attached to this email is\n   %1s\n   Size:%2s kilobytes\n",'xpressme-backup'), $filename, round(filesize($diskfile)/1024));
1062                        $success = $this->send_mail($recipient, get_bloginfo('name') . ' ' . __('Database Backup','xpressme-backup'), $message, $diskfile);
1063
1064                        if ( false === $success ) {
1065                                $msg = __('The following errors were reported:','xpressme-backup') . "\n ";
1066                                if ( function_exists('error_get_last') ) {
1067                                        $err = error_get_last();
1068                                        $msg .= $err['message'];
1069                                } else {
1070                                        $msg .= __('ERROR: The mail application has failed to deliver the backup.','xpressme-backup');
1071                                }
1072                                $this->error(array('kind' => 'fatal', 'loc' => $location, 'msg' => $msg));
1073                        } else {
1074                                unlink($diskfile);
1075                        }
1076                }
1077                return $success;
1078        }
1079       
1080        function backup_menu() {
1081                global $table_prefix, $wpdb;
1082                $feedback = '';
1083                $whoops = false;
1084               
1085                // did we just do a backup?  If so, let's report the status
1086                if ( $this->backup_complete ) {
1087                        $feedback = '<div class="updated xpressme-backup-updated"><p>' . __('Backup Successful','xpressme-backup') . '!';
1088                        $file = $this->backup_file;
1089                        switch($_POST['deliver']) {
1090                        case 'http':
1091                                $feedback .= '<br />' . sprintf(__('Your backup file: <a href="%1s">%2s</a> should begin downloading shortly.','xpressme-backup'), WP_BACKUP_URL . "{$this->backup_file}", $this->backup_file);
1092                                break;
1093                        case 'smtp':
1094                                if (! is_email($_POST['backup_recipient'])) {
1095                                        $feedback .= get_option('admin_email');
1096                                } else {
1097                                        $feedback .= $_POST['backup_recipient'];
1098                                }
1099                                $feedback = '<br />' . sprintf(__('Your backup has been emailed to %s','xpressme-backup'), $feedback);
1100                                break;
1101                        case 'none':
1102                                $feedback .= '<br />' . __('Your backup file has been saved on the server. If you would like to download it now, right click and select "Save As"','xpressme-backup');
1103                                $feedback .= ':<br /> <a href="' . WP_BACKUP_URL . "$file\">$file</a> : " . sprintf(__('%s bytes','xpressme-backup'), filesize($this->backup_dir . $file));
1104                        }
1105                        $feedback .= '</p></div>';
1106                }
1107       
1108                // security check
1109                $this->wp_secure(); 
1110
1111                if (count($this->errors)) {
1112                        $feedback .= '<div class="updated xpressme-backup-updated error"><p><strong>' . __('The following errors were reported:','xpressme-backup') . '</strong></p>';
1113                        $feedback .= '<p>' . $this->error_display( 'main', false ) . '</p>';
1114                        $feedback .= "</p></div>";
1115                }
1116
1117                // did we just save options for wp-cron?
1118                if ( (function_exists('wp_schedule_event') || function_exists('xpressme_cron_init'))
1119                        && isset($_POST['xpressme_cron_backup_options']) ) :
1120                        do_action('wp_db_b_update_cron_options');
1121                        if ( function_exists('wp_schedule_event') ) {
1122                                wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
1123                                $scheds = (array) wp_get_schedules();
1124                                $name = strval($_POST['xpressme_cron_schedule']);
1125                                $interval = ( isset($scheds[$name]['interval']) ) ?
1126                                        (int) $scheds[$name]['interval'] : 0;
1127                                update_option('xpressme_cron_backup_schedule', $name, false);
1128                                if ( 0 !== $interval ) {
1129                                        wp_schedule_event(time() + $interval, $name, 'wp_db_backup_cron');
1130                                }
1131                        }
1132                        else {
1133                                update_option('xpressme_cron_backup_schedule', intval($_POST['cron_schedule']), false);
1134                        }
1135                        update_option('xpressme_cron_backup_tables', $_POST['xpressme_cron_backup_tables']);
1136                        if (is_email($_POST['cron_backup_recipient'])) {
1137                                update_option('xpressme_cron_backup_recipient', $_POST['cron_backup_recipient'], false);
1138                        }
1139                        $feedback .= '<div class="updated xpressme-backup-updated"><p>' . __('Scheduled Backup Options Saved!','xpressme-backup') . '</p></div>';
1140                endif;
1141               
1142                $other_tables = array();
1143                $also_backup = array();
1144       
1145                // Get complete db table list   
1146                $all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
1147                $all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
1148                // Get list of WP tables that actually exist in this DB (for 1.6 compat!)
1149                $wp_backup_default_tables = array_intersect($all_tables, $this->core_table_names);
1150                // Get list of non-WP tables
1151                $other_tables = array_diff($all_tables, $wp_backup_default_tables);
1152               
1153                if ('' != $feedback)
1154                        echo $feedback;
1155
1156                if ( ! $this->wp_secure() )     
1157                        return;
1158
1159                // Give the new dirs the same perms as wp-content.
1160//              $stat = stat( ABSPATH . 'wp-content' );
1161//              $dir_perms = $stat['mode'] & 0000777; // Get the permission bits.
1162                $dir_perms = '0777';
1163
1164                // the file doesn't exist and can't create it
1165                if ( ! file_exists($this->backup_dir) && ! @mkdir($this->backup_dir) ) {
1166                        ?><div class="updated xpressme-backup-updated error"><p><?php _e('WARNING: Your backup directory does <strong>NOT</strong> exist, and we cannot create it.','xpressme-backup'); ?></p>
1167                        <p><?php printf(__('Using your FTP client, try to create the backup directory yourself: %s', 'xpressme-backup'), '<code>' . $this->backup_dir . '</code>'); ?></p></div><?php
1168                        $whoops = true;
1169                // not writable due to write permissions
1170                } elseif ( !is_writable($this->backup_dir) && ! @chmod($this->backup_dir, $dir_perms) ) {
1171                        ?><div class="updated xpressme-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','xpressme-backup'); ?></p>
1172                        <p><?php printf(__('Using your FTP client, try to set the backup directory&rsquo;s write permission to %1$s or %2$s: %3$s', 'xpressme-backup'), '<code>777</code>', '<code>a+w</code>', '<code>' . $this->backup_dir . '</code>'); ?>
1173                        </p></div><?php
1174                        $whoops = true;
1175                } else {
1176                        $this->fp = $this->open($this->backup_dir . 'test' );
1177                        if( $this->fp ) {
1178                                $this->close($this->fp);
1179                                @unlink($this->backup_dir . 'test' );
1180                        // the directory is not writable probably due to safe mode
1181                        } else {
1182                                ?><div class="updated xpressme-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','xpressme-backup'); ?></p><?php
1183                                if( ini_get('safe_mode') ){
1184                                        ?><p><?php _e('This problem seems to be caused by your server&rsquo;s <code>safe_mode</code> file ownership restrictions, which limit what files web applications like WordPress can create.', 'xpressme-backup'); ?></p><?php
1185                                }
1186                                ?><?php printf(__('You can try to correct this problem by using your FTP client to delete and then re-create the backup directory: %s', 'xpressme-backup'), '<code>' . $this->backup_dir . '</code>');
1187                                ?></div><?php
1188                                $whoops = true;
1189                        }
1190                }
1191
1192               
1193
1194                if ( !file_exists($this->backup_dir . 'index.php') )
1195                        @ touch($this->backup_dir . 'index.php');
1196                ?><div class='wrap'>
1197                <h2><?php _e('Backup','xpressme-backup') ?></h2>
1198                <form method="post" action="">
1199                <?php if ( function_exists('wp_nonce_field') ) wp_nonce_field($this->referer_check_key); ?>
1200                <fieldset class="options"><legend><?php _e('Tables','xpressme-backup') ?></legend>
1201                <table align="center" cellspacing="5" cellpadding="5">
1202                <tr><td width="50%" align="left" class="alternate" valign="top">
1203                <div class="tables-list core-tables alternate">
1204                <h4><?php _e('These core WordPress tables will always be backed up:','xpressme-backup') ?></h4><ul><?php
1205                $excs = (array) get_option('xpressme_backup_excs');
1206
1207                foreach ($wp_backup_default_tables as $table) {
1208                        if ( $table == $wpdb->comments ) {
1209                                $checked = ( isset($excs['spam']) && is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) ? ' checked=\'checked\'' : '';
1210                                echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code> <span class='instructions'> <input type='checkbox' name='exclude-spam[]' value='$table' $checked /> " . __('Exclude spam comments', 'xpressme-backup') . '</span></li>';
1211                        } elseif ( function_exists('wp_get_post_revisions') && $table == $wpdb->posts ) {
1212                                        $checked = ( isset($excs['revisions']) && is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) ? ' checked=\'checked\'' : '';
1213                                echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code> <span class='instructions'> <input type='checkbox' name='exclude-revisions[]' value='$table' $checked /> " . __('Exclude post revisions', 'xpressme-backup') . '</span></li>';
1214                        } else {
1215                                echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code></li>";
1216                        }
1217                }
1218                ?></ul>
1219                </div>
1220                </td><td width="50%" align="left" valign="top">
1221                <div class="tables-list extra-tables" id="extra-tables-list">
1222                <?php
1223                if (count($other_tables) > 0) {
1224                        $select_all = __('Select all','xpressme-backup');
1225                        $select_none = __('Select none','xpressme-backup');
1226                        ?>
1227                        <h4><?php _e('You may choose to include any of the following tables:','xpressme-backup'); ?></h4>
1228                        <ul>
1229                        <script type="text/javascript">
1230                        //<![CDATA[
1231                                var wpdbBackup = function() {};
1232                                (function(b){
1233                                        var n = function(c) {
1234                                                var p = document.getElementsByTagName("input");
1235                                                for(var i=0;i<p.length;i++)
1236                                                        if('other_tables[]' == p[i].getAttribute('name'))
1237                                                                p[i].checked = c;
1238                                        }
1239                                        b.a = function() { n(true) }
1240                                        b.n = function() { n(false) }
1241
1242                                        document.write('<p><a href="javascript:void(0)" onclick="wpdbBackup.a()"><?php echo $select_all ?></a> / <a href="javascript:void(0)" onclick="wpdbBackup.n()"><?php echo $select_none ?></a></p>');
1243                                })(wpdbBackup)
1244                        //]]>
1245                        </script>
1246       
1247                        <?php
1248                        foreach ($other_tables as $table) {
1249                                ?>
1250                                <li><label><input type="checkbox" name="other_tables[]" value="<?php echo $table; ?>" /> <code><?php echo $table; ?></code></label>
1251                                <?php
1252                        }
1253                        ?></ul><?php
1254                }
1255                ?></div>
1256                </td></tr></table>
1257                </fieldset>
1258               
1259                <fieldset class="options">
1260                        <legend><?php _e('Backup Options','xpressme-backup'); ?></legend>
1261                        <p><?php  _e('What to do with the backup file:','xpressme-backup'); ?></p>
1262                        <ul>
1263                        <li><label for="do_save">
1264                                <input type="radio" id="do_save" name="deliver" value="none" style="border:none;" />
1265                                <?php _e('Save to server','xpressme-backup');
1266                                echo " (<code>" . $this->backup_dir . "</code>)"; ?>
1267                        </label></li>
1268                        <li><label for="do_download">
1269                                <input type="radio" checked="checked" id="do_download" name="deliver" value="http" style="border:none;" />
1270                                <?php _e('Download to your computer','xpressme-backup'); ?>
1271                        </label></li>
1272                        <li><label for="do_email">
1273                                <input type="radio" name="deliver" id="do_email" value="smtp" style="border:none;" />
1274                                <?php _e('Email backup to:','xpressme-backup'); ?>
1275                                <input type="text" name="backup_recipient" size="20" value="<?php echo get_option('admin_email'); ?>" />
1276                        </label></li>
1277                        </ul>
1278                        <p><?php  _e('Data conversion option.','xpressme-backup'); ?></p>
1279                        <ul>
1280                        <?php
1281                        if(WPLANG == 'ja_EUC'){
1282                                echo '<li><label for="do_euc_to_utf8">';
1283                                if($this->is_mbstring()){
1284                                        echo    '<input type="checkbox" name="euc_to_utf8" id="euc_to_utf8" value="1" />';
1285                                        echo __('Converte EUC-JP to UTF-8','xpressme-backup');
1286                                } else {
1287                                        echo    '<input type="checkbox" name="euc_to_utf8" id="euc_to_utf8" value="1" disabled="1"/>';
1288                                        echo __('Converte EUC-JP to UTF-8','xpressme-backup');
1289                                        echo ' (<span style="color:#ff0000">' . __('The server used does not support the mb_convert_encoding() function.','xpressme-backup') . '</span>)';
1290                                }
1291                                echo '</label></li>';
1292                        } else {
1293                                echo '<input type="hidden" name="euc_to_utf8" id="euc_to_utf8" value="0" />';
1294                        }
1295                        ?>
1296                        <li><label for="rename_prefix">
1297                                <input type="checkbox" name="do_rename_prefix" id="do_rename_prefix" value="1" />
1298                                <?php _e('Rename DB Prefix','xpressme-backup'); ?>
1299                                <input type="text" name="before_prefix" size="20" value="<?php echo $table_prefix; ?>" />
1300                                <?php _e('to','xpressme-backup'); ?>
1301                                <input type="text" name="after_prefix" size="20" value="<?php echo $table_prefix; ?>" />
1302                        </label></li>
1303                        <li><label for="change_uri">
1304                                <input type="checkbox" name="do_change_uri" id="do_change_uri" value="1" />
1305                                <?php $site_uri = get_option('siteurl');?>
1306                                <?php _e('Change URL','xpressme-backup'); ?>
1307                                <div style="padding-left: 20px;">
1308                                <input type="text" name="before_uri" size="50" value="<?php echo $site_uri; ?>" /><br />
1309                                <?php _e('to','xpressme-backup'); ?><br />
1310                                <input type="text" name="after_uri" size="50" value="<?php echo $site_uri; ?>" />
1311                                </div>
1312                        </label></li>
1313                        <li><label for="set_default_role">
1314                                <input type="checkbox" name="set_default_role" id="set_default_role" value="1" />
1315                                <?php _e('user_role is corrected to upgrade.','xpressme-backup'); ?>
1316                        </label></li>
1317                        <li><label for="del_active_plugin">
1318                                <input type="checkbox" name="del_active_plugin" id="del_active_plugin" value="1" />
1319                                <?php _e('In the backup data,all plug-ins are Deactivate state.','xpressme-backup'); ?>
1320                        </label></li>
1321                        </ul>
1322
1323                        <?php if ( ! $whoops ) : ?>
1324                        <input type="hidden" name="do_backup" id="do_backup" value="backup" />
1325                        <p class="submit">
1326                                <input type="submit" name="submit" onclick="document.getElementById('do_backup').value='fragments';" value="<?php _e('Backup now!','xpressme-backup'); ?>" />
1327                        </p>
1328                        <?php else : ?>
1329                                <div class="updated xpressme-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable!','xpressme-backup'); ?></p></div>
1330                        <?php endif; // ! whoops ?>
1331                </fieldset>
1332                <?php do_action('wp_db_b_backup_opts'); ?>
1333                </form>
1334               
1335                <?php
1336                // this stuff only displays if some sort of wp-cron is available
1337                $cron = ( function_exists('wp_schedule_event') ) ? true : false; // wp-cron in WP 2.1+
1338                $cron_old = ( function_exists('xpressme_cron_init') && ! $cron ) ? true : false; // wp-cron plugin by Skippy
1339                if ( $cron_old || $cron ) :
1340                        echo '<fieldset class="options"><legend>' . __('Scheduled Backup','xpressme-backup') . '</legend>';
1341                        $datetime = get_option('date_format') . ' ' . get_option('time_format');
1342                        if ( $cron ) :
1343                                $next_cron = wp_next_scheduled('wp_db_backup_cron');
1344                                if ( ! empty( $next_cron ) ) :
1345                                        ?>
1346                                        <p id="backup-time-wrap">
1347                                        <?php printf(__('Next Backup: %s','xpressme-backup'), '<span id="next-backup-time">' . gmdate($datetime, $next_cron + (get_option('gmt_offset') * 3600)) . '</span>'); ?>
1348                                        </p>
1349                                        <?php
1350                                endif;
1351                        elseif ( $cron_old ) :
1352                                ?><p><?php printf(__('Last WP-Cron Daily Execution: %s','xpressme-backup'), gmdate($datetime, get_option('xpressme_cron_daily_lastrun') + (get_option('gmt_offset') * 3600))); ?><br /><?php
1353                                printf(__('Next WP-Cron Daily Execution: %s','xpressme-backup'), gmdate($datetime, (get_option('xpressme_cron_daily_lastrun') + (get_option('gmt_offset') * 3600) + 86400))); ?></p><?php
1354                        endif;
1355                        ?><form method="post" action="">
1356                        <?php if ( function_exists('wp_nonce_field') ) wp_nonce_field($this->referer_check_key); ?>
1357                        <div class="tables-list">
1358                        <h4><?php _e('Schedule: ','xpressme-backup'); ?></h4>
1359                        <?php
1360                        if ( $cron_old ) :
1361                                $xpressme_cron_backup_schedule = get_option('xpressme_cron_backup_schedule');
1362                                $schedule = array(0 => __('None','xpressme-backup'), 1 => __('Daily','xpressme-backup'));
1363                                foreach ($schedule as $value => $name) {
1364                                        echo ' <input type="radio" style="border:none;" name="cron_schedule"';
1365                                        if ($xpressme_cron_backup_schedule == $value) {
1366                                                echo ' checked="checked" ';
1367                                        }
1368                                        echo 'value="' . $value . '" /> ' . $name;
1369                                }
1370                        elseif ( $cron ) :
1371                                echo apply_filters('wp_db_b_schedule_choices', wp_get_schedules() );
1372                        endif;
1373                        $cron_recipient = get_option('xpressme_cron_backup_recipient');
1374                        if (! is_email($cron_recipient)) {
1375                                $cron_recipient = get_option('admin_email');
1376                        }
1377                        $cron_recipient_input = '<p><label for="cron_backup_recipient">' . __('Email backup to:','xpressme-backup') . ' <input type="text" name="cron_backup_recipient" id="cron_backup_recipient" size="20" value="' . $cron_recipient . '" /></label></p>';
1378                        echo apply_filters('wp_db_b_cron_recipient_input', $cron_recipient_input);
1379                        echo '<p class="submit"><input type="submit" name="submit" value="' . __('Schedule backup','xpressme-backup') . '" /></p>';
1380                        echo '</div>';
1381                        $cron_tables = get_option('xpressme_cron_backup_tables');
1382                        if (! is_array($cron_tables)) {
1383                                $cron_tables = array();
1384                        }
1385                        if (count($other_tables) > 0) {
1386                                echo '<div class="tables-list alternate" id="include-tables-list">';
1387                                echo '<h4>' . __('Tables to include in the scheduled backup:','xpressme-backup') . '</h4><ul>';
1388                                foreach ($other_tables as $table) {
1389                                        echo '<li><input type="checkbox" ';
1390                                        if (in_array($table, $cron_tables)) {
1391                                                echo 'checked="checked" ';
1392                                        }
1393                                        echo "name='xpressme_cron_backup_tables[]' value='{$table}' /> <code>{$table}</code></li>";
1394                                }
1395                                echo '</ul></div>';
1396                        }
1397                        echo '<input type="hidden" name="xpressme_cron_backup_options" value="SET" /></form>';
1398                        echo '</fieldset>';
1399                endif; // end of wp_cron (legacy) section
1400               
1401                echo '</div><!-- .wrap -->';
1402               
1403        } // end wp_backup_menu()
1404
1405        function get_sched() {
1406                $options = array_keys( (array) wp_get_schedules() );
1407                $freq = get_option('xpressme_cron_backup_schedule');
1408                $freq = ( in_array( $freq , $options ) ) ? $freq : 'never';
1409                return $freq;
1410        }
1411
1412        function schedule_choices($schedule) { // create the cron menu based on the schedule
1413                $xpressme_cron_backup_schedule = $this->get_sched();
1414                $next_cron = wp_next_scheduled('wp_db_backup_cron');
1415                $xpressme_cron_backup_schedule = ( empty( $next_cron ) ) ? 'never' : $xpressme_cron_backup_schedule;
1416                $sort = array();
1417                foreach ( (array) $schedule as $key => $value ) $sort[$key] = $value['interval'];
1418                asort( $sort );
1419                $schedule_sorted = array();
1420                foreach ( (array) $sort as $key => $value ) $schedule_sorted[$key] = $schedule[$key];
1421                $menu = '<ul>';
1422                $schedule = array_merge( array( 'never' => array( 'interval' => 0, 'display' => __('Never','xpressme-backup') ) ),
1423                        (array) $schedule_sorted );
1424                foreach ( $schedule as $name => $settings) {
1425                        $interval = (int) $settings['interval'];
1426                        if ( 0 == $interval && ! 'never' == $name ) continue;
1427                        $display = ( ! '' == $settings['display'] ) ? $settings['display'] : sprintf(__('%s seconds','xpressme-backup'),$interval);
1428                        $menu .= "<li><input type='radio' name='xpressme_cron_schedule' style='border:none;' ";
1429                        if ($xpressme_cron_backup_schedule == $name) {
1430                                $menu .= " checked='checked' ";
1431                        }
1432                        $menu .= "value='$name' /> $display</li>";
1433                }
1434                $menu .= '</ul>';
1435                return $menu;
1436        } // end schedule_choices()
1437       
1438        function wp_cron_daily() { // for legacy cron plugin
1439                $schedule = intval(get_option('xpressme_cron_backup_schedule'));
1440                // If scheduled backup is disabled
1441                if (0 == $schedule)
1442                        return;
1443                else return $this->cron_backup();
1444        }
1445
1446        function cron_backup() {
1447                global $table_prefix, $wpdb;
1448                $all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
1449                $all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
1450                $core_tables = array_intersect($all_tables, $this->core_table_names);
1451                $other_tables = get_option('xpressme_cron_backup_tables');
1452                $recipient = get_option('xpressme_cron_backup_recipient');
1453                $backup_file = $this->db_backup($core_tables, $other_tables);
1454                if (false !== $backup_file)
1455                        return $this->deliver_backup($backup_file, 'smtp', $recipient, 'main');
1456                else return false;
1457        }
1458
1459        function add_sched_options($sched) {
1460                $sched['weekly'] = array('interval' => 604800, 'display' => __('Once Weekly','xpressme-backup'));
1461                return $sched;
1462        }
1463
1464        /**
1465         * Checks that WordPress has sufficient security measures
1466         * @param string $kind
1467         * @return bool
1468         */
1469        function wp_secure($kind = 'warn', $loc = 'main') {
1470                global $wp_version;
1471               
1472                if ( function_exists('wp_verify_nonce') ) return true;
1473                else {
1474                        $this->error(array('kind' => $kind, 'loc' => $loc, 'msg' => sprintf(__('Your WordPress version, %1s, lacks important security features without which it is unsafe to use the WP-DB-Backup plugin.  Hence, this plugin is automatically disabled.  Please consider <a href="%2s">upgrading WordPress</a> to a more recent version.','xpressme-backup'),$wp_version,'http://wordpress.org/download/')));
1475                        return false;
1476                }
1477               
1478        }
1479
1480        /**
1481         * Checks that the user has sufficient permission to backup
1482         * @param string $loc
1483         * @return bool
1484         */
1485        function can_user_backup($loc = 'main') {
1486                $can = false;
1487                // make sure WPMU users are site admins, not ordinary admins
1488                if ( function_exists('is_site_admin') && ! is_site_admin() )
1489                        return false;
1490                if ( ( $this->wp_secure('fatal', $loc) ) && current_user_can('import') )
1491                        $can = $this->verify_nonce($_REQUEST['_wpnonce'], $this->referer_check_key, $loc);
1492                if ( false == $can )
1493                        $this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => __('You are not allowed to perform backups.','xpressme-backup')));
1494                return $can;
1495        }
1496
1497        /**
1498         * Verify that the nonce is legitimate
1499         * @param string $rec   the nonce received
1500         * @param string $nonce what the nonce should be
1501         * @param string $loc   the location of the check
1502         * @return bool
1503         */
1504        function verify_nonce($rec = '', $nonce = 'X', $loc = 'main') {
1505                if ( wp_verify_nonce($rec, $nonce) )
1506                        return true;
1507                else
1508                        $this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => sprintf(__('There appears to be an unauthorized attempt from this site to access your database located at %1s.  The attempt has been halted.','xpressme-backup'),get_option('home'))));
1509        }
1510
1511        /**
1512         * Check whether a file to be downloaded is 
1513         * surreptitiously trying to download a non-backup file
1514         * @param string $file
1515         * @return null
1516         */
1517        function validate_file($file) {
1518                if ( (false !== strpos($file, '..')) || (false !== strpos($file, './')) || (':' == substr($file, 1, 1)) )
1519                        $this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __("Cheatin' uh ?",'xpressme-backup')));
1520        }
1521       
1522        function extras_filter($query_line){
1523                $extras_option = get_option('xpressme_backup_extras_option');
1524                if ($extras_option['do_euc_to_utf8'] && $this->is_mbstring()){
1525                        $query_line = mb_convert_encoding(mb_convert_encoding($query_line,"sjis-win","EUC-JP"),"UTF-8","sjis-win");
1526                        $tmp = preg_replace('/DEFAULT\s*CHARSET\s*=\s*ujis/','DEFAULT CHARSET=utf8',$query_line);
1527                        if (empty($buf)) $query_line = $tmp;
1528                        if (preg_match_all('/s:([0-9]+):"(.*?)";/',$query_line,$matchs)){
1529                                $i_count = count($matchs[0]);
1530                                for($i=0; $i < $i_count ;$i++){
1531                                        $org = $matchs[0][$i];
1532                                        $num = $matchs[1][$i];
1533                                        $str = $matchs[2][$i];
1534                                        $str =  str_replace('\r\n','\n',$str);
1535
1536                                        $volm = strlen(bin2hex($str)) / 2;
1537                                       
1538                                        if ($num != $volm){
1539                                                $org =  str_replace('\\','\\\\',$org);
1540                                                $org =  str_replace('/','\\/',$org);
1541                                                $org =  str_replace('(','\\(',$org);
1542                                                $org =  str_replace(')','\\)',$org);
1543                                                $org =  str_replace('?','\\?',$org);
1544                                                $org =  str_replace('+','\\+',$org);
1545                                                $org =  str_replace('*','\\*',$org);
1546                                                $org =  str_replace('[','\\[',$org);
1547                                                $org =  str_replace(']','\\]',$org);                                   
1548                                                $org =  str_replace('$','\\$',$org);
1549                                                $org =  str_replace('{','\\{',$org);                                   
1550                                                $org =  str_replace('}','\\}',$org);
1551                                                $org =  str_replace('^','\\^',$org);
1552                                                $org =  str_replace('.','\\.',$org);
1553                               
1554                                                $src = '/' . $org . '/';
1555//                                              $dist = '*************************************s:' . $num . '->' . $volm . '"' . $str . '"';
1556                                                $dist = 's:'. $volm . ':"' . $str . '";';
1557                                                if(preg_match($src,$query_line)){
1558                                                        $query_line = preg_replace($src,$dist,$query_line);
1559                                                }
1560                                        }
1561                                }
1562                        }
1563                        $seach = "/'blog_charset'.*'EUC-JP'/";
1564                        $src = "/'EUC-JP'/";
1565                        $dist = "'UTF-8'";
1566                        if(preg_match($seach,$query_line)){
1567                                $query_line = preg_replace($src,$dist,$query_line);
1568                        }
1569                }
1570                if ($extras_option['do_rename_prefix']){
1571                        if (!empty($extras_option['before_prefix']) && !empty($extras_option['after_prefix'])){
1572                                $src = '/' . $extras_option['before_prefix'] . '/';
1573                                $dist = $extras_option['after_prefix'];
1574                                if(preg_match($src,$query_line)){
1575                                        $query_line = preg_replace($src,$dist,$query_line);
1576                                }
1577                        }
1578                }
1579                if ($extras_option['do_change_uri']){
1580                        if (!empty($extras_option['before_uri']) && !empty($extras_option['after_uri'])){
1581                                $org =  $extras_option['before_uri'];
1582                                $org =  str_replace('/','\\/',$org);
1583                                $src = '/' . $org . '/';
1584                                $dist = $extras_option['after_uri'];
1585                                if(preg_match($src,$query_line)){
1586                                        $query_line = preg_replace($src,$dist,$query_line);
1587                                }
1588                        }
1589                }
1590               
1591                if ($extras_option['del_active_plugin']){
1592                                $src = '/' . "(INSERT INTO `.+_options` VALUES \([0-9]+, [0-9]+, 'active_plugins', 'Y', [0-9]+, ')(a:.+})('.+\);)" . '/';
1593                                if(preg_match($src,$query_line,$matches)){
1594                                        if(preg_match('/xpressme\/xpressme.php/',$matches[2])){
1595                                                $query_line = "\n" . $matches[1] . 'a:1:{i:0;s:21:"xpressme/xpressme.php";}' . $matches[3];
1596                                        } else {
1597                                                $query_line = "\n" . $matches[1] . 'a:0:{}' . $matches[3];
1598                                        }
1599                                }                       
1600                }
1601                return $query_line;
1602               
1603        }
1604        function is_mbstring(){
1605                return function_exists('mb_convert_encoding');
1606        }
1607}
1608
1609function wpdbBackup_init() {
1610        global $mywpdbbackup;
1611        $mywpdbbackup = new wpdbBackup();       
1612}
1613
1614add_action('plugins_loaded', 'wpdbBackup_init');
1615?>
Note: See TracBrowser for help on using the repository browser.