XPressME Integration Kit

Trac

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

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

XPressME-BuckupプラグインにWordPressMEのユーザ権限名をWordPressのユーザ権限名に変更するオプション追加 ref#386
また、バックアップデータからXPressME-Buckupプラグイン自身のデータを削除するようにした。

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