first commit

This commit is contained in:
Roman Pyrih
2023-07-24 08:30:51 +02:00
commit c2e100a763
7128 changed files with 1622619 additions and 0 deletions

View File

@@ -0,0 +1,679 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Extension_Backups extends FW_Extension {
/**
* @var _FW_Ext_Backups_Module_Tasks
*/
private $tasks;
/**
* @return _FW_Ext_Backups_Module_Tasks
*/
public function tasks() {
return $this->tasks;
}
/**
* @var _FW_Ext_Backups_Module_Schedule
*/
private $schedule;
/**
* @return _FW_Ext_Backups_Module_Schedule
*/
public function schedule() {
return $this->schedule;
}
private static $wp_ajax_action_status = 'fw:ext:backups:status';
private static $wp_ajax_action_backup = 'fw:ext:backups:backup';
private static $wp_ajax_action_restore = 'fw:ext:backups:restore';
private static $wp_ajax_action_delete = 'fw:ext:backups:delete';
private static $wp_ajax_action_cancel = 'fw:ext:backups:cancel';
private static $wp_ajax_action_test = 'fw:ext:backups:test';
private static $download_GET_parameter = 'download-archive';
/**
* Also can be used as "is current user allowed to make backups?"
* @return string
*/
public function get_capability() {
/**
* https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table
* Should work on both single and multi-site
*/
return 'export';
}
/**
* @param int $sum Since 2.0.16
* @return int
*/
public function get_timeout($sum = 0) {
$timeout = (int)ini_get('max_execution_time');
/**
* Fix timeout value
* For e.g. timeout 0 messes up the tasks execution verification logic
*/
if ($timeout < 1 || $timeout > $this->get_config('max_timeout')) {
$timeout = $this->get_config('max_timeout');
}
return max($timeout + $sum, 1); // Prevent negative or 0 value
}
/**
* If a task step execution takes more that this amount of second, then perhaps it is something wrong.
* @return int
* @since 2.0.14
*/
public function get_task_step_execution_threshold() {
return 30; // http://php.net/manual/en/info.configuration.php#ini.max-execution-time
}
public function get_page_slug() {
return 'fw-backups';
}
public function get_page_url() {
if ($this->is_disabled()) {
return;
}
$rel_path = 'admin.php?page=' . urlencode( $this->get_page_slug() );
if (is_multisite() && is_network_admin()) {
return network_admin_url( $rel_path );
} else {
return admin_url( $rel_path );
}
}
/**
* On some installations the backup actions need to be disabled for security reasons
* (for e.g. public testlabs for clients to test your theme and demo content install)
* @return bool
* @since 2.0.1
*/
public function is_disabled() {
$cache_key = $this->get_cache_key('/disabled');
try {
return FW_Cache::get($cache_key);
} catch (FW_Cache_Not_Found_Exception $e) {
$is_disabled = (
is_multisite() && !current_user_can('manage_network_plugins') &&
apply_filters('fw:ext:backups:multisite_disabled', false)
);
FW_Cache::set($cache_key, $is_disabled);
return $is_disabled;
}
}
/**
* @since 2.0.22
* @return string Error message
*/
public function server_requirements_not_met() {
if (class_exists('ZipArchive')) {
return false;
} else {
return sprintf(
__('Oops, %s requires %s but it is not enabled on your server. If you are not familiar with PHP Zip module, please contact your hosting provider.', 'fw'),
fw_html_tag('a', array(
'href' => function_exists('menu_page_url')
? menu_page_url(fw()->extensions->manager->get_page_slug(), false) .'#ext-backups'
: '#',
), __('Unyson Backup', 'fw')),
fw_html_tag('a', array(
'href' => 'https://www.google.com/search#q=hosting+enable+php+zip',
'target' => '_blank',
), __('PHP Zip module', 'fw'))
);
}
}
protected function _init() {
if ( is_admin() && isset( $_SERVER['SERVER_SOFTWARE'] ) && strpos( $_SERVER['SERVER_SOFTWARE'], 'LiteSpeed' ) !== false ) {
if ( ! is_file( ABSPATH . '.htaccess' ) || ! preg_match( '/noabort/i', file_get_contents( ABSPATH . '.htaccess' ) ) ) {
add_action( 'admin_notices', array( $this, '_action_admin_notices_litespeed' ) );
}
}
{
if (!$this->is_disabled()) {
add_action('admin_menu', array($this, '_action_admin_menu'));
add_action('current_screen', array($this, '_action_download'));
add_action('admin_enqueue_scripts', array($this, '_action_enqueue_scripts'));
add_action('wp_ajax_' . self::$wp_ajax_action_status, array($this, '_action_ajax_status'));
add_action('wp_ajax_' . self::$wp_ajax_action_backup, array($this, '_action_ajax_backup'));
add_action('wp_ajax_' . self::$wp_ajax_action_restore, array($this, '_action_ajax_restore'));
add_action('wp_ajax_' . self::$wp_ajax_action_delete, array($this, '_action_ajax_delete'));
add_action('wp_ajax_' . self::$wp_ajax_action_cancel, array($this, '_action_ajax_cancel'));
}
add_action('network_admin_menu', array($this, '_action_admin_menu'));
add_action('wp_ajax_nopriv_' . self::$wp_ajax_action_test, array($this, '_action_ajax_test'));
}
$dir = dirname(__FILE__);
// load and init modules/parts
{
require_once $dir .'/includes/module/class--fw-ext-backups-module.php';
require_once $dir .'/includes/module/tasks/class--fw-ext-backups-module-tasks.php';
$this->tasks = new _FW_Ext_Backups_Module_Tasks(self::get_access_key());
require_once $dir .'/includes/module/schedule/class--fw-ext-backups-module-schedule.php';
$this->schedule = new _FW_Ext_Backups_Module_Schedule(self::get_access_key());
$this->tasks->_init();
$this->schedule->_init();
}
require_once $dir .'/includes/log/init.php';
}
public function _action_admin_notices_litespeed() {
$screen = get_current_screen();
if ( ! $this->is_backups_page() && 'tools_page_fw-backups-demo-content' !== $screen->id ) {
return;
}
echo
'<div class="notice notice-warning">
<p><strong>Unyson: </strong>' .
sprintf(
esc_html__( 'Your website is hosted using the LiteSpeed web server. Please consult this %sarticle%s if you have problems backing up.', 'fw' ),
'<a href="http://manual.unyson.io/en/latest/extension/backups/index.html#litespeed-webserver" target="_blank">',
'</a>'
) .
'</p>
</div>';
}
/**
* @var FW_Access_Key
*/
private static $access_key;
/**
* @return FW_Access_Key
*/
private static function get_access_key() {
if (empty(self::$access_key)) {
self::$access_key = new FW_Access_Key('fw:ext:backups');
}
return self::$access_key;
}
/**
* @return bool
*/
public function is_backups_page() {
$current_screen = get_current_screen();
if (!$current_screen) {
return false;
}
$cache_key = $this->get_cache_key('/is_backups_page');
try {
return FW_Cache::get($cache_key);
} catch (FW_Cache_Not_Found_Exception $e) {
$is = false;
foreach (array( '_page_'. $this->get_page_slug(), '_page_'. $this->get_page_slug() .'-network' ) as $suffix) {
if (substr($current_screen->id, -strlen($suffix)) === $suffix) {
$is = true;
break;
}
}
FW_Cache::set($cache_key, $is);
return $is;
}
}
public function _action_enqueue_scripts() {
if ($this->is_backups_page()) {
wp_enqueue_style('fw');
wp_enqueue_media(); // needed for modal styles
wp_enqueue_style(
'fw-ext-backups',
$this->get_uri('/static/style.css'),
array('fw'),
$this->manifest->get_version()
);
wp_enqueue_script(
'fw-ext-backups',
$this->get_uri('/static/scripts.js'),
array('fw'),
$this->manifest->get_version()
);
wp_localize_script(
'fw-ext-backups',
'_fw_ext_backups_localized',
array_merge(
apply_filters('fw:ext:backups:script_localized_data', array()),
array(
'ajax_action_status' => self::$wp_ajax_action_status,
'ajax_action_backup' => self::$wp_ajax_action_backup,
'ajax_action_restore' => self::$wp_ajax_action_restore,
'ajax_action_delete' => self::$wp_ajax_action_delete,
'ajax_action_cancel' => self::$wp_ajax_action_cancel,
'l10n' => array(
'abort_confirm' => __('Are you sure?', 'fw'),
),
)
)
);
do_action('fw:ext:backups:enqueue_scripts');
}
}
/**
* @internal
*/
public function _action_ajax_status() {
if (!current_user_can($this->get_capability())) {
wp_send_json_error(new WP_Error('denied', 'Access Denied'));
}
// in case the execution chain stopped and there is a pending task
$this->tasks()->_request_next_step_execution(self::get_access_key());
$is_busy = (bool)$this->tasks()->get_active_task_collection();
$archives = $this->get_archives();
$response = array(
'is_busy' => $is_busy,
'tasks_status' => array(
'html' => $this->render_view('tasks-status', array(
'active_task_collection' => $this->tasks()->get_active_task_collection(),
'executing_task' => $this->tasks()->get_executing_task(),
'pending_tasks' => $this->tasks()->get_pending_task(),
)),
),
'archives' => array(
'count' => count($archives),
'html' => $this->render_view('archives', array(
'archives' => $archives,
'is_busy' => $is_busy,
)),
),
'ajax_steps' => array(
'token' => md5(
defined('NONCE_SALT')
? NONCE_SALT
: $this->manifest->get_version()
),
'active_tasks_hash' => (($collection = $this->tasks()->get_active_task_collection())
? md5(serialize($collection))
: ''
)
),
);
wp_send_json_success(array_merge(
apply_filters('fw_ext_backups_ajax_status_extra_response', array(), array('is_busy' => $is_busy)),
$response
));
}
/**
* @internal
*/
public function _action_ajax_backup() {
if (!current_user_can($this->get_capability())) {
wp_send_json_error(new WP_Error('denied', 'Access Denied'));
}
$this->tasks()->do_backup(
!empty($_POST['full'])
&&
fw_ext_backups_current_user_can_full()
);
wp_send_json_success();
}
/**
* @internal
*/
public function _action_ajax_restore() {
if (!current_user_can($this->get_capability())) {
wp_send_json_error(new WP_Error('denied', 'Access Denied'));
}
$archives = $this->get_archives();
if (
empty($_POST['file'])
||
!isset($archives[ $filename = (string)$_POST['file'] ])
) {
wp_send_json_error(new WP_Error(
'no_file', __('File not specified', 'fw')
));
}
$fs_args = array();
if ($archives[ $filename ]['full'] && !FW_WP_Filesystem::has_direct_access(ABSPATH)) {
if (empty($_POST['filesystem_args'])) {
wp_send_json_error(array(
'message' => esc_html__('Filesystem access required', 'fw'),
'request_fs' => true,
));
} else {
$fs_args = $_POST['filesystem_args'];
if (
is_array($_POST['filesystem_args']) &&
isset($fs_args['hostname']) && is_string($fs_args['hostname']) &&
isset($fs_args['username']) && is_string($fs_args['username']) &&
isset($fs_args['password']) && is_string($fs_args['password']) &&
isset($fs_args['connection_type']) && is_string($fs_args['connection_type'])
) {
$fs_args = array(
'hostname' => $fs_args['hostname'],
'username' => $fs_args['username'],
'password' => $fs_args['password'],
'connection_type' => $fs_args['connection_type'],
);
if (!WP_Filesystem($fs_args, ABSPATH)) {
wp_send_json_error(array(
'message' => esc_html__('Invalid filesystem credentials', 'fw')
));
}
} else {
wp_send_json_error(array(
'message' => esc_html__('Invalid filesystem credentials', 'fw')
));
}
}
}
$this->tasks()->do_restore(
$archives[ $filename ]['full'] && fw_ext_backups_current_user_can_full(),
$archives[ $filename ]['path'],
$fs_args
);
wp_send_json_success();
}
/**
* @internal
*/
public function _action_ajax_delete() {
if (!current_user_can($this->get_capability())) {
wp_send_json_error(new WP_Error('denied', 'Access Denied'));
}
$archives = $this->get_archives();
if (
empty($_POST['file'])
||
!isset($archives[ $filename = (string)$_POST['file'] ])
) {
wp_send_json_error(new WP_Error(
'no_file', __('File not specified', 'fw')
));
}
if (@unlink($archives[ $filename ]['path'])) {
wp_send_json_success();
} else {
wp_send_json_error();
}
}
/**
* @internal
*/
public function _action_ajax_cancel() {
if (!current_user_can($this->get_capability())) {
wp_send_json_error(new WP_Error('denied', 'Access Denied'));
}
if ($this->tasks()->do_cancel()) {
wp_send_json_success();
} else {
wp_send_json_error();
}
}
/**
* @internal
*/
public function _action_admin_menu() {
call_user_func_array(
is_multisite() && is_network_admin() ? 'add_menu_page' : 'add_management_page',
array(
__( 'Backup', 'fw' ),
__( 'Backup', 'fw' ),
$this->get_capability(),
$this->get_page_slug(),
array( $this, '_render_page' )
)
);
}
/**
* @param null|bool Get only full or content backups
* @return array Descending date sorting
*/
public function get_archives($full = null) {
$archives = array();
if ($this->server_requirements_not_met()) {
return $archives;
} elseif ($paths = glob($this->get_backups_dir() .'/*.zip')) {
foreach ( $paths as $path ) {
{
$zip = new ZipArchive();
if ( true === $zip->open( $path ) ) {
$is_full = (bool) (
$zip->locateName( 'f/themes/index.php' ) !== false
||
$zip->locateName( 'f/plugins/index.php' ) !== false
);
$zip->close();
} else {
trigger_error('Cannot open zip: '. $path, E_USER_WARNING);
continue;
}
}
if (
!is_null($full)
&&
$full != $is_full
) {
continue;
}
$archives[ basename( $path ) ] = array(
'path' => $path,
'full' => $is_full,
'time' => filemtime($path),
);
}
}
uasort($archives, array($this, '_archive_sort_callback'));
return $archives;
}
public function _archive_sort_callback($a, $b) {
if ($a['time'] == $b['time']) {
return 0;
} else {
return ($a['time'] > $b['time']) ? -1 : 1;
}
}
/**
* @internal
*/
public function _render_page() {
echo '<div class="wrap">';
if ($error_message = $this->server_requirements_not_met()) {
echo "<div class=\"notice notice-error\"><p>{$error_message}</p></div>";
} else {
$this->render_view( 'page', array(
'archives_html' => $this->render_view( 'archives', array(
'archives' => $this->get_archives(),
'is_busy' => (bool) $this->tasks()->get_active_task_collection(),
) ),
), false );
}
echo '</div>';
echo '<div id="fw-ext-backups-filesystem-form" style="display:none;">';
FW_WP_Filesystem::request_access(ABSPATH);
echo '</div>';
}
/**
* @return string
*/
public function get_tmp_dir() {
return $this->get_backups_dir() . '/tmp';
}
/**
* All backups (zip) will go in this directory
* @return string
*/
public function get_backups_dir() {
return $this->get_config( 'dirs.destination' );
}
/**
* {@inheritdoc}
*/
public function _get_link() {
if (current_user_can($this->get_capability())) {
return $this->get_page_url();
} else {
return null;
}
}
/**
* @internal
*/
public function _get_test_ajax_action() {
return self::$wp_ajax_action_test;
}
/**
* @internal
*/
public function _action_ajax_test() {
wp_send_json_success();
}
public function get_download_link($archive_filename) {
return add_query_arg(self::$download_GET_parameter, urlencode($archive_filename), $this->get_page_url());
}
public function _action_download() {
if (
!isset($_GET[self::$download_GET_parameter])
||
!is_string($archive_filename = $_GET[self::$download_GET_parameter])
||
!$this->is_backups_page()
) {
return;
}
$error = __('Unknown error', 'fw');
do {
if (!current_user_can($this->get_capability())) {
$error = __('Access Denied', 'fw');
break;
}
$archives = $this->get_archives();
if (!isset($archives[$archive_filename])) {
$error = __('Archive not found', 'fw');
break;
}
$archive = $archives[$archive_filename];
if ($archive['full'] && !fw_ext_backups_current_user_can_full()) {
$error = __('Access Denied', 'fw');
break;
}
if ($f = fopen($archive['path'], 'r')) {
// ok
} else {
$error = __('Failed to open file', 'fw');
break;
}
header('Content-Type: application/zip, application/octet-stream');
header('Content-Disposition: attachment; filename="'. esc_attr($archive_filename) .'"');
header('Content-length: '. filesize($archive['path']));
header('Cache-control: private');
/**
* Some files can be huge, do not load entire file in php memory then output, it can cause memory limit error
* Read and output parts
*/
{
$output_buffer_size = max(
// https://github.com/ThemeFuse/Unyson/issues/2070#issuecomment-258427852
(int)ini_get('output_buffering'),
// default to this value in case ini_get() will return 0 (some server restrictions)
// http://php.net/manual/en/outcontrol.configuration.php#ini.output-buffering
4096
);
while (!feof($f)) {
echo fread($f, $output_buffer_size);
if (ob_get_level()) { ob_flush(); }
flush();
}
}
fclose($f);
exit;
} while(false);
wp_die($error, $error);
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace Unyson\Extension\Backups;
/**
* Unyson Backups Extension CLI Commands.
*
* @package wp-cli
*/
class Command extends \Unyson\Extension\Command {
/**
* List all available backups.
*
* ## OPTIONS
*
* ## EXAMPLES
*
* # List all backups files
* $ wp unyson ext backups list
* +--------------------------------------+--------------------+---------+
* | Name | Time | Type |
* +--------------------------------------+--------------------+---------+
* | fw-backup-2017_03_25-05_58_28-2.0.23 | 25 Mar 2017, 05:58 | Content |
* | fw-backup-2017_03_25-05_57_44-2.0.23 | 25 Mar 2017, 05:57 | Content |
* | fw-backup-2017_03_25-05_55_58-2.0.23 | 25 Mar 2017, 05:55 | Content |
* | fw-backup-2017_03_25-05_24_04-2.0.23 | 25 Mar 2017, 05:24 | Content |
* | fw-backup-2017_03_24-18_49_46-2.0.23 | 24 Mar 2017, 18:49 | Content |
* | fw-backup-2017_03_24-11_23_29-2.0.23 | 24 Mar 2017, 11:23 | Full |
* | fw-backup-2017_03_24-11_23_01-2.0.23 | 24 Mar 2017, 11:23 | Full |
* +--------------------------------------+--------------------+---------+
*
*
* @param array $_
* @param array $options
*
* @subcommand list
*/
public function _list( $_, $options = array() ) {
$archives = array_map(
array( $this, 'get_backup_file_data' ),
$this->get_backups()
);
\WP_CLI\Utils\format_items(
'table',
$archives,
array( 'Name', 'Time', 'Type' )
);
}
/**
* Create a backup.
*
* ## OPTIONS
*
* [--full]
* : Specify to create a full backup.
*
* ## EXAMPLES
*
* # Create content backup
* $ wp unyson ext backups create
* Backup successfully created
*
* # Create full backup
* $ wp unyson ext backups create --full
* Backup successfully created
*
*
* @param array $args
* @param array $options
*/
public function create( $args, $options = array() ) {
$this
->get_ext()
->tasks()
->do_backup( isset( $options['full'] ) );
$this->message( "Backup successfully created" );
}
/**
* Restore a backup.
*
* ## OPTIONS
*
* <backup-id>
* : The ID of the backup to restore. The ID is the backup file name without `.zip` extension.
*
*
* ## EXAMPLES
*
* # Restore backup
* $ wp unyson ext backups restore fw-backup-2017_03_25-05_58_28-2.0.23
* Backup fw-backup-2017_03_25-05_58_28-2.0.23 was successfully restored
*
*
* @param array $args
* @param array $options
*/
public function restore( $args, $options = array() ) {
$id = array_shift( $args );
try {
$backup = $this->get( $id );
} catch ( \Exception $e ) {
$this->error( "Backup %g$id%n doesn't seem to exist" );
}
$this->initialize_fs();
$this
->get_ext()
->tasks()
->do_restore( $backup['full'], $backup['path'] );
$this->message( "Backup %g$id%n was successfully restored" );
}
protected function get_backup_file_data( array $backup ) {
return array(
'Name' => basename( $backup['path'], '.zip' ),
'Type' => $backup['full'] ? 'Full' : 'Content',
'Time' => date( 'd M Y, H:i', $backup['time'] ),
);
}
protected function get_backups() {
return $this->get_ext()->get_archives();
}
protected function get( $id ) {
$backups = $this->get_backups();
if ( isset( $backups[ $id . '.zip' ] ) ) {
return $backups[ $id . '.zip' ];
}
throw new \Exception( "Backup $id cannot be found" );
}
}

View File

@@ -0,0 +1,84 @@
<?php if (!defined('FW')) die('Forbidden');
$cfg = array();
/**
* WhiteList hidden files and directories
* By default all hidden files and dirs are skipped (like .git/ .idea/)
*/
$cfg['included_hidden_names'] = array(
'.htaccess' => true,
);
global $wpdb; /** @var WPDB $wpdb */
// Note: Exclude and Keep are for content backup. On Full backup everything is exported and everything is replaced.
$cfg['db.backup.exclude_options'] = array(
$wpdb->prefix .'user_roles' => true,
'admin_email' => true,
'cron' => true,
'mailserver_login' => true,
'mailserver_pass' => true,
'mailserver_port' => true,
'mailserver_url' => true,
'ftp_credentials' => true,
'use_ssl' => true,
'WPLANG' => true,
'recently_edited' => true, // contains full paths
'current_theme' => true,
// 'template' => true, 'stylesheet' => true, // used on restore to replace option names with current child theme
);
$cfg['db.restore.keep_options'] = array_merge(
$cfg['db.backup.exclude_options'],
array(
'home' => true,
'siteurl' => true,
'date_format' => true,
'links_updated_date_format' => true,
'time_format' => true,
'timezone_string' => true,
'gmt_offset' => true,
'start_of_week' => true,
// 'permalink_structure' => true, // imported links with different structure will be 404 if current structure will be kept
'rewrite_rules' => true,
'ping_sites' => true,
'upload_path' => true,
'upload_url_path' => true,
'uploads_use_yearmonth_folders' => true,
'users_can_register' => true,
'use_smilies' => true,
'use_trackback' => true,
'blogname' => true,
'blogdescription' => true,
'blog_charset' => true,
'active_plugins' => true,
'uninstall_plugins' => true,
'recently_activated' => true,
'moderation_notify' => true,
'blacklist_keys' => true,
'comment_registration' => true,
'default_role' => true,
'blog_public' => true,
'can_compress_scripts' => true,
'template' => true, 'stylesheet' => true, // keep current theme active
)
);
/**
* Automatic backups will be scheduled to run at this hour
* Format: 0...23
*/
$cfg['schedule.hour'] = 3;
/**
* The tasks that can't be executed in steps (for e.g. zip)
* will use this value to try to increase php's default timeout
*/
$cfg['max_timeout'] = 60 * 10;
/**
* Destination directory for backups archives
*/
$cfg['dirs.destination'] = fw_callback( 'fw_ext_backups_destination_directory' );

View File

@@ -0,0 +1,522 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Extension_Backups_Demo extends FW_Extension {
/**
* Cache
* @var FW_Ext_Backups_Demo[]
*/
private static $demos;
private static $wp_ajax_install = 'fw:ext:backups-demo:install';
private static $wp_ajax_status = 'fw:ext:backups-demo:status';
private static $wp_ajax_cancel = 'fw:ext:backups-demo:cancel';
private static $task_collection_id = 'demo-content-install';
private static $wp_option_active_demo = 'fw:ext:backups-demo:active-demo';
/**
* @return FW_Extension_Backups
*/
public static function backups() {
return fw_ext('backups');
}
/**
* @var FW_Access_Key
*/
private static $access_key;
/**
* @return FW_Access_Key
*/
private static function get_access_key() {
if (empty(self::$access_key)) {
self::$access_key = new FW_Access_Key('fw:ext:backups-demo');
}
return self::$access_key;
}
public function get_page_slug() {
return 'fw-backups-demo-content';
}
/**
* @internal
*/
protected function _init() {
add_action('admin_menu', array($this, '_admin_action_admin_menu'));
add_action('admin_enqueue_scripts', array($this, '_action_admin_enqueue_scripts'));
add_action(
'fw:ext:backups:tasks:fail:id:'. self::$task_collection_id,
array($this, '_action_tasks_fail')
);
add_action(
'fw:ext:backups:tasks:success:id:'. self::$task_collection_id,
array($this, '_action_tasks_success')
);
add_action(
'fw:ext:backups:tasks:cancel:id:'. self::$task_collection_id,
array($this, '_action_tasks_cancel')
);
add_action(
'wp_ajax_'. self::$wp_ajax_status,
array($this, '_action_ajax_status')
);
add_action(
'wp_ajax_'. self::$wp_ajax_install,
array($this, '_action_ajax_install')
);
add_action(
'wp_ajax_'. self::$wp_ajax_cancel,
array($this, '_action_ajax_cancel')
);
add_filter(
'fw_ext_backups_db_export_exclude_option',
array($this, '_filter_fw_ext_backups_db_export_exclude_option'),
10, 3
);
add_filter(
'fw_ext_backups_db_restore_keep_options',
array($this, '_filter_fw_ext_backups_db_restore_keep_options')
);
spl_autoload_register(array($this, '_spl_autoload'));
}
/**
* @internal
*/
public function _admin_action_admin_menu() {
if (
!current_user_can(self::backups()->get_capability())
||
!$this->get_demos()
) {
return;
}
add_management_page(
__('Demo Content Install', 'fw'),
__('Demo Content Install', 'fw'),
self::backups()->get_capability(),
$this->get_page_slug(),
array($this, '_display_page')
);
}
/**
* @internal
*/
public function _display_page() {
echo '<div class="wrap">';
if (function_exists('is_wpe_snapshot') && !is_wpe_snapshot()) {
echo '<div class="error"><p>',
sprintf(
esc_html__('Demo Content Install works only in %s.', 'fw'),
'<a href="'. esc_attr(admin_url('admin.php?page=wpengine-staging')) .'">'
. esc_html__('Staging', 'fw')
. '</a>'
),
'</p></div>';
} elseif ($error_message = $this->get_parent()->server_requirements_not_met()) {
echo "<div class=\"notice notice-error\"><p>{$error_message}</p></div>";
} else {
$this->render_view('page', array(
'demos' => $this->get_demos(),
), false);
}
echo '</div>';
}
/**
* @return FW_Ext_Backups_Demo[]
* @since 2.0.23
*/
public function get_demos() {
if (is_null(self::$demos)) {
$demos = array();
foreach (apply_filters('fw_ext_backups_demo_dirs', array(
fw_fix_path(get_template_directory()) .'/demo-content'
=>
get_template_directory_uri() .'/demo-content',
)) as $dir_path => $dir_uri) {
if (
!is_dir($dir_path)
||
!($dirs = glob($dir_path .'/*', GLOB_ONLYDIR))
) {
continue;
}
foreach (array_map('fw_fix_path', $dirs) as $demo_dir) {
$demo_dir_name = basename($demo_dir);
{
if (!file_exists($demo_dir .'/manifest.php')) {
continue;
}
$manifest = fw_get_variables_from_file(
$demo_dir .'/manifest.php',
array('manifest' => array()),
array('uri' => $dir_uri .'/'. $demo_dir_name)
);
$manifest = array_merge(array(
'title' => fw_id_to_title($demo_dir_name),
'screenshot' => fw_get_framework_directory_uri('/static/img/no-image.png'),
'preview_link' => '',
'extra' => array(),
), $manifest['manifest']);
}
$demo = new FW_Ext_Backups_Demo(
'local-'. md5($demo_dir),
'local',
array('source' => $demo_dir)
);
$demo->set_title($manifest['title']);
$demo->set_screenshot($manifest['screenshot']);
$demo->set_preview_link($manifest['preview_link']);
$demo->set_extra($manifest['extra']);
$demos[ $demo->get_id() ] = $demo;
unset($demo);
}
}
self::$demos = array_merge(
apply_filters('fw:ext:backups-demo:demos', array()),
$demos
);
}
return self::$demos;
}
/**
* @param string $id
*
* @return FW_Ext_Backups_Demo|null
*/
private function get_demo($id) {
$demos = $this->get_demos();
return isset($demos[$id]) ? $demos[$id] : null;
}
/**
* If currently is displayed the Demo list page
* @return bool
*/
private function is_page() {
return (
($current_screen = get_current_screen())
&&
$current_screen->id === 'tools_page_'. $this->get_page_slug()
);
}
public function _action_admin_enqueue_scripts() {
if ($this->is_page()) {
wp_enqueue_media(); // needed for modals
wp_enqueue_style(
'fw-ext-backups-demo',
$this->get_uri('/static/page.css'),
array('fw'),
$this->manifest->get_version()
);
wp_enqueue_script(
'fw-ext-backups-demo',
$this->get_uri('/static/page.js'),
array('fw'),
$this->manifest->get_version()
);
wp_localize_script(
'fw-ext-backups-demo',
'_fw_ext_backups_demo',
array(
'ajax_action' => array(
'install' => self::$wp_ajax_install,
'status' => self::$wp_ajax_status,
'cancel' => self::$wp_ajax_cancel,
),
'l10n' => array(
'abort_confirm' => __('Are you sure?', 'fw'),
),
)
);
}
}
private function install_is_pending() {
foreach (self::backups()->tasks()->get_pending_task_collections() as $collection) {
if ($collection->get_id() === self::$task_collection_id) {
return true;
}
}
return false;
}
private function install_is_active() {
if ($active_task_collection = self::backups()->tasks()->get_active_task_collection()) {
return $active_task_collection->get_id() === self::$task_collection_id;
} else {
return false;
}
}
private function install_is_busy() {
return $this->install_is_active() || $this->install_is_pending();
}
private function get_active_demo() {
return get_option(self::$wp_option_active_demo, array('id' => '', 'result' => null));
}
private function set_active_demo($data) {
$active_demo = $this->get_active_demo();
update_option(
self::$wp_option_active_demo,
array_merge(array(
'id' => $active_demo['id'],
'result' => null, // 'string' - error message, true - success
), $data),
false
);
}
public function _action_ajax_status() {
if (!current_user_can(self::backups()->get_capability())) {
wp_send_json_error(new WP_Error(
'forbidden',
__('Forbidden', 'fw')
));
}
$install_is_executing = $this->install_is_active();
$install_is_pending = $this->install_is_pending();
$is_busy = $this->install_is_busy();
$active_demo = $this->get_active_demo();
if (
/**
* When the tasks are changed via hook, this code is not relevant and must not be executed
* so it can be disabled using this filter
* @since 2.0.17
*/
apply_filters('fw_ext_backups_demo_has_to_reset_active_demo', true)
) {
if ($active_demo['result']) {
// if result is finished, reset, to prevent same message on next request
$this->set_active_demo(array('id' => '', 'result' => null));
}
}
// in case the execution chain stopped and there is a pending task
self::backups()->tasks()->_request_next_step_execution(self::get_access_key());
wp_send_json_success(array(
'is_busy' => $is_busy,
'active_demo' => $active_demo,
'home_url' => home_url(),
'html' => $is_busy
? $this->render_view('status', array(
'install_is_executing' => $install_is_executing,
'install_is_pending' => $install_is_pending,
'executing_task' => self::backups()->tasks()->get_executing_task(),
'pending_task' => self::backups()->tasks()->get_pending_task(),
))
: '',
'ajax_steps' => array(
'token' => md5(
defined('NONCE_SALT')
? NONCE_SALT
: self::backups()->manifest->get_version()
),
'active_tasks_hash' => (($collection = self::backups()->tasks()->get_active_task_collection())
? md5(serialize($collection))
: ''
)
),
));
}
public function _action_ajax_install() {
if (!current_user_can(self::backups()->get_capability())) {
wp_send_json_error(new WP_Error(
'forbidden',
__('Forbidden', 'fw')
));
}
if (
!isset($_POST['id'])
||
!is_string($_POST['id'])
||
!($demo = $this->get_demo($_POST['id']))
) {
wp_send_json_error(new WP_Error(
'invalid_id',
__('Invalid demo', 'fw')
));
}
if ($this->install_is_busy()) {
wp_send_json_error(new WP_Error(
'already_running',
__('A content install is currently running', 'fw')
));
}
$this->do_install($demo);
wp_send_json_success();
}
public function _action_ajax_cancel() {
if (!current_user_can(self::backups()->get_capability())) {
wp_send_json_error(new WP_Error(
'forbidden',
__('Forbidden', 'fw')
));
}
if (self::backups()->tasks()->do_cancel()) {
wp_send_json_success();
} else {
wp_send_json_error();
}
}
/**
* @param FW_Ext_Backups_Demo $demo
* @since 2.0.23
*/
public function do_install(FW_Ext_Backups_Demo $demo) {
$tmp_dir = self::backups()->get_tmp_dir();
$id_prefix = 'demo:';
$collection = new FW_Ext_Backups_Task_Collection(self::$task_collection_id);
if (!self::backups()->is_disabled()) {
$collection = self::backups()->tasks()->add_backup_tasks($collection);
}
$collection->set_title(__('Demo Content Install', 'fw'));
$collection->add_task(new FW_Ext_Backups_Task(
$id_prefix .'tmp-dir-clean:before',
'dir-clean',
array('dir' => $tmp_dir)
));
$collection->add_task(new FW_Ext_Backups_Task(
$id_prefix .'demo-download',
'download',
array(
'type' => $demo->get_source_type(),
'type_args' => $demo->get_source_args(),
'destination_dir' => $tmp_dir,
// used only for https://github.com/ThemeFuse/Unyson-Backups-Extension/issues/15
'demo_id' => $demo->get_id(),
)
));
self::backups()->tasks()->add_restore_tasks($collection);
/** @since 2.0.16 */
do_action('fw:ext:backups-demo:add-install-tasks', $collection, array(
'demo' => $demo,
'tmp_dir' => $tmp_dir,
));
$this->set_active_demo(array('id' => $demo->get_id(), 'result' => null));
self::backups()->tasks()->execute_task_collection($collection);
}
/**
* @param bool $exclude
* @param string $option_name
* @param bool $is_full_backup
* @return bool
*/
public function _filter_fw_ext_backups_db_export_exclude_option($exclude, $option_name, $is_full_backup) {
if ($option_name === self::$wp_option_active_demo) {
return true;
}
return $exclude;
}
/**
* @param array $options {option_name: true}
* @return array
*/
public function _filter_fw_ext_backups_db_restore_keep_options($options) {
$options[ self::$wp_option_active_demo] = true;
return $options;
}
public function _action_tasks_fail(FW_Ext_Backups_Task_Collection $collection) {
$error = __('Error', 'fw');
foreach ($collection->get_tasks() as $task) {
if ($task->result_is_fail()) {
if (is_wp_error($task->get_result())) {
$error = $task->get_result()->get_error_message();
}
break;
}
}
$this->set_active_demo(array('result' => $error));
}
public function _action_tasks_cancel() {
$this->set_active_demo(array(
'result' => __('Demo Install has been aborted', 'fw')
));
}
public function _action_tasks_success(FW_Ext_Backups_Task_Collection $collection) {
$this->set_active_demo(array('result' => true));
}
/**
* @param FW_Access_Key $access_Key
* @return int
* @internal
* @since 2.0.3
*/
public function _get_demos_count(FW_Access_Key $access_Key) {
if ($access_Key->get_key() !== 'fw:ext:backups-demo:helper:count') {
trigger_error('Method call denied', E_USER_ERROR);
}
return count($this->get_demos());
}
/**
* @param string $class
* @internal
*/
public function _spl_autoload($class) {
if ('FW_Ext_Backups_Demo' === $class) {
require_once dirname(__FILE__) .'/includes/entity/class-fw-ext-backups-demo.php';
}
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Unyson\Extension\BackupsDemo;
/**
* Unyson Backups Demo Extension CLI Commands.
*
* @package wp-cli
*/
class Command extends \Unyson\Extension\Command {
/**
* List all available demos.
*
* ## OPTIONS
*
* ## EXAMPLES
*
* # List all available demos.
* $ wp unyson ext backups-demo list
* +---------------+----------------+------------------------------------------+
* | Id | Name | Preview |
* +---------------+----------------+------------------------------------------+
* | creed | Creed | http://demo.themefuse.com/creed/ |
* | the-core | The Core | http://demo.themefuse.com/the-core/ |
* | hope | Hope | http://demo.themefuse.com/hope/ |
* | gourmet | Gourmet | http://demo.themefuse.com/gourmet/ |
* | keynote | Keynote | http://demo.themefuse.com/keynote/ |
* | wellness | Wellness | http://demo.themefuse.com/wellness/ |
* | cribs | Cribs | http://demo.themefuse.com/cribs/ |
* | the-college | The College | http://demo.themefuse.com/the-college/ |
* +---------------+----------------+------------------------------------------+
*
* @param array $_
* @param array $options
*
* @subcommand list
*/
public function _list( $_, $options = array() ) {
\WP_CLI\Utils\format_items(
'table',
array_map(
array( $this, 'get_demo_data' ),
$this->get_demos()
),
array( 'Id', 'Name', 'Preview' )
);
}
/**
* Install demo.
*
* ## OPTIONS
*
* <demo-id>
* : Demo ID to install.
*
* ## EXAMPLES
*
* # Install demo
* $ wp unyson ext backups-demo install the-core
* Demo the-core successfully installed.
*/
public function install( $args, $options = array() ) {
$id = array_shift( $args );
try {
$demo = $this->get( $id );
} catch ( \Exception $e ) {
$this->error( $e->getMessage() );
}
$this->get_ext()->do_install( $demo );
$this->message( "Demo %g{$demo->get_title()}%n successfully installed." );
}
/**
* @return \FW_Extension_Backups_Demo
*/
protected function get_ext() {
return fw_ext( 'backups-demo' );
}
protected function get( $id ) {
$demos = $this->get_demos();
if ( isset( $demos[ $id ] ) ) {
return $demos[ $id ];
}
throw new \Exception( "Demo '$id' cannot be found" );
}
protected function get_demos() {
return $this->get_ext()->get_demos();
}
protected function get_demo_data( \FW_Ext_Backups_Demo $demo ) {
return array(
'Id' => $demo->get_id(),
'Name' => $demo->get_title(),
'Preview' => $demo->get_preview_link(),
);
}
}

View File

@@ -0,0 +1,20 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @return int
* @since 2.0.3
*/
function fw_ext_backups_demo_count() {
static $access_key = null;
if (is_null($access_key)) {
$access_key = new FW_Access_Key('fw:ext:backups-demo:helper:count');
}
/**
* @var FW_Extension_Backups_Demo $extension
*/
$extension = fw_ext('backups-demo');
return $extension->_get_demos_count($access_key);
}

View File

@@ -0,0 +1,134 @@
<?php if (!defined('FW')) die('Forbidden');
final class FW_Ext_Backups_Demo {
/**
* @var string
*/
private $id;
/**
* @var string
*/
private $screenshot;
/**
* A registered download source
* @see FW_Ext_Backups_Task_Type_Download_Type
* @var string
*/
private $source_type;
/**
* Args sent to download type
* @var array
*/
private $source_args = array();
private $preview_link;
private $title;
/**
* @since 2.0.16
*/
private $extra = array();
public function __construct($id, $source_type = null, $source_args = array()) {
$this->id = $id;
$this->source_type = $source_type;
$this->source_args = $source_args;
}
public function get_id() {
return $this->id;
}
public function get_screenshot() {
return $this->screenshot;
}
public function set_screenshot($screenshot) {
$this->screenshot = $screenshot;
return $this;
}
public function get_source_type() {
return $this->source_type;
}
public function set_source_type($source_type) {
$this->source_type = $source_type;
return $this;
}
public function get_source_args() {
return $this->source_args;
}
public function set_source_args(array $source_args) {
$this->source_args = $source_args;
return $this;
}
public function get_preview_link() {
return $this->preview_link;
}
public function set_preview_link($preview_link) {
$this->preview_link = $preview_link;
return $this;
}
public function get_title() {
return $this->title;
}
public function set_title($title) {
$this->title = $title;
return $this;
}
/**
* @return array
* @since 2.0.16
*/
public function get_extra() {
return $this->extra;
}
/**
* @param array $extra
* @return $this
* @since 2.0.16
*/
public function set_extra(array $extra) {
$this->extra = $extra;
return $this;
}
public static function from_array(array $data) {
$demo = new self($data['id']);
$demo->set_screenshot($data['screenshot']);
$demo->set_source_type($data['source_type']);
$demo->set_source_args($data['source_args']);
$demo->set_extra(isset($data['extra']) ? $data['extra'] : array());
return $demo;
}
public function to_array() {
return array(
'id' => $this->get_id(),
'screenshot' => $this->get_screenshot(),
'source_type' => $this->get_source_type(),
'source_args' => $this->get_source_args(),
'extra' => $this->get_extra(),
);
}
}

View File

@@ -0,0 +1,7 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
$manifest = array();
$manifest['standalone'] = true;

View File

@@ -0,0 +1,30 @@
#fw-ext-backups-demo-list .theme .theme-actions {
opacity: 1;
top: auto;
bottom: 0;
-webkit-transform: translateY(0);
transform: translateY(0);
}
#fw-ext-backups-demo-list .theme a.more-details {
text-decoration: none;
}
#fw-ext-backups-demo-list .fw-ext-backups-demo-item.active .theme-actions {
display: none;
}
/* status modal */
.fw-ext-backups-demo-status-modal .progress-percent {
background: #ddd;
margin: 0 30px;
}
.fw-ext-backups-demo-status-modal .progress-percent > div {
background: #0085ba;
height: 3px;
}
/* end: status modal */

View File

@@ -0,0 +1,337 @@
/**
* Check current status
*/
jQuery(function ($) {
var inst = {
localized: _fw_ext_backups_demo,
getEventName: function(name) {
return 'fw:ext:backups-demo:status:'+ name;
},
timeoutId: 0,
timeoutTime: 3000,
/**
* 0 - (false) not busy
* 1 - (true) busy
* 2 - (true) busy and a pending ajax
*/
isBusy: 0,
doAjax: function() {
if (this.isBusy) {
this.isBusy = 2;
return false;
}
clearTimeout(this.timeoutId);
fwEvents.trigger(this.getEventName('updating'));
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: this.localized.ajax_action.status
}
})
.done(_.bind(function(r){
if (r.success) {
fwEvents.trigger(this.getEventName('update'), r.data);
} else {
fwEvents.trigger(this.getEventName('update-fail'));
}
}, this))
.fail(_.bind(function(jqXHR, textStatus, errorThrown){
console.error('Ajax error', jqXHR, textStatus, errorThrown);
fwEvents.trigger(this.getEventName('update-fail'));
}, this))
.always(_.bind(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fwEvents.trigger(this.getEventName('updated'));
if (this.isBusy === 2) {
this.isBusy = 0;
this.doAjax();
} else {
this.isBusy = 0;
}
this.timeoutId = setTimeout(_.bind(this.doAjax, this), this.timeoutTime);
}, this));
return true;
},
onUpdate: function(data) {
this.timeoutTime = data.is_busy ? 3000 : 10000;
},
init: function(){
this.init = function(){};
fwEvents.on(this.getEventName('do-update'), _.bind(function(){ this.doAjax(); }, this));
fwEvents.on(this.getEventName('update'), _.bind(function(data){ this.onUpdate(data); }, this));
this.doAjax();
}
};
// let other scripts to listen events
setTimeout(function(){ inst.init(); }, 100);
});
/**
* Current status
*/
jQuery(function($){
var inst = {
failCount: 0,
fwSoleModalId: 'fw-ext-backups-demo-status',
onUpdating: function(){},
onUpdate: function(data) {
if (data.is_busy) {
fw.soleModal.show(
this.fwSoleModalId,
data.html,
{
allowClose: false,
updateIfCurrent: true
}
);
} else {
fw.soleModal.hide(this.fwSoleModalId);
}
this.failCount = 0;
},
onUpdateFail: function() {
if (this.failCount > 3) {
fw.soleModal.show(
this.fwSoleModalId,
'<span class="fw-text-danger dashicons dashicons-warning"></span>',
{
allowClose: false,
updateIfCurrent: true
}
);
}
++this.failCount;
},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups-demo:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups-demo:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups-demo:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups-demo:status:updated': _.bind(this.onUpdated, this)
});
}
};
inst.init();
});
/**
* Install button
*/
jQuery(function($) {
var inst = {
localized: _fw_ext_backups_demo,
isBusy: false,
fwLoadingId: 'fw-ext-backups-demo-install',
init: function(){
fwEvents.on('fw:ext:backups-demo:status:update', function(data){
{
$('#fw-ext-backups-demo-list .fw-ext-backups-demo-item').removeClass('active');
if (data.active_demo.id) {
$('#demo-'+ data.active_demo.id).addClass('active');
}
}
if (data.active_demo.result) {
if (data.active_demo.result === true) {
fw.soleModal.hide(inst.fwLoadingId);
setTimeout(function(){
$(document.body).fadeOut();
}, 500); // after modal hide animation end
setTimeout(function(){
window.location.assign(data.home_url);
}, 1000); // after all animations end
} else {
fw.soleModal.show(
inst.fwLoadingId,
'<h3 class="fw-text-danger">'+ data.active_demo.result +'</h3>'
);
}
}
});
$('#fw-ext-backups-demo-list').on('click', '[data-install]', function(){
if (inst.isBusy) {
console.log('Install is busy');
return;
}
var $this = $(this),
demoId = $this.attr('data-install'),
confirm_message = $this.attr('data-confirm');
if (confirm_message) {
if (!confirm(confirm_message)) {
return;
}
}
inst.isBusy = true;
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
data: {
action: inst.localized.ajax_action.install,
id: demoId
},
type: 'POST',
dataType: 'json'
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups-demo:status:do-update');
} else {
fw.soleModal.show(
'fw-ext-backups-demo-install-error',
((r.data && r.data.length) ? r.data[0].message : '')
);
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-demo-install-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
inst.isBusy = false;
fw.loading.hide(inst.fwLoadingId);
});
});
}
};
inst.init();
});
/**
* "Cancel" functionality
*/
jQuery(function($){
var inst = {
localized: _fw_ext_backups_demo,
isBusy: false,
fwLoadingId: 'fw-ext-backups-demo-install-cancel',
doCancel: function(){
if (this.isBusy) {
return;
} else {
if (!confirm(this.localized.l10n.abort_confirm)) {
return;
}
this.isBusy = true;
}
inst.isBusy = true;
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
data: {
action: inst.localized.ajax_action.cancel
},
type: 'POST',
dataType: 'json'
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups-demo:status:do-update');
} else {
console.warn('Cancel failed');
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-demo-install-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
inst.isBusy = false;
fw.loading.hide(inst.fwLoadingId);
});
},
init: function(){
var that = this;
fwEvents.on('fw:ext:backups-demo:cancel', function(){
that.doCancel();
});
}
};
inst.init();
});
/**
* If loopback request failed, execute steps via ajax
* @since 2.0.5
*/
jQuery(function($){
if (typeof fw_ext_backups_loopback_failed == 'undefined') {
return;
}
var inst = {
running: false,
isBusy: false,
onUpdate: function(data) {
this.running = data.is_busy;
this.executeNextStep(data.ajax_steps.token, data.ajax_steps.active_tasks_hash);
},
executeNextStep: function(token, activeTasksHash){
if (!this.running || this.isBusy) {
return false;
}
this.isBusy = true;
$.ajax({
url: ajaxurl,
data: {
action: 'fw:ext:backups:continue-pending-task',
token: token,
active_tasks_hash: activeTasksHash
},
type: 'POST',
dataType: 'json'
})
.done(function(r){ console.log(r);
if (r.success) {
fwEvents.trigger('fw:ext:backups-demo:status:do-update');
} else {
console.error('Ajax execution failed');
// execution will try to continue on next (auto) update
}
})
.fail(_.bind(function(jqXHR, textStatus, errorThrown){
console.error('Ajax error: '+ String(errorThrown));
}, this))
.always(_.bind(function(data_jqXHR, textStatus, jqXHR_errorThrown){
this.isBusy = false;
}, this));
},
init: function(){
fwEvents.on('fw:ext:backups-demo:status:update', _.bind(this.onUpdate, this));
}
};
inst.init();
});

View File

@@ -0,0 +1,66 @@
<?php if ( ! defined( 'FW' ) ) die( 'Forbidden' );
/**
* @var FW_Ext_Backups_Demo[] $demos
*/
/**
* @var FW_Extension_Backups $backups
*/
$backups = fw_ext('backups');
if ($backups->is_disabled()) {
$confirm = '';
} else {
$confirm = esc_html__(
'IMPORTANT: Installing this demo content will delete the content you currently have on your website.'
. ' However, we create a backup of your current content in (Tools > Backup).'
. ' You can restore the backup from there at any time in the future.',
'fw'
);
}
?>
<h2><?php esc_html_e('Demo Content Install', 'fw') ?></h2>
<div>
<?php if ( !class_exists('ZipArchive') ): ?>
<div class="error below-h2">
<p>
<strong><?php _e( 'Important', 'fw' ); ?></strong>:
<?php printf(
__( 'You need to activate %s.', 'fw' ),
'<a href="http://php.net/manual/en/book.zip.php" target="_blank">'. __('zip extension', 'fw') .'</a>'
); ?>
</p>
</div>
<?php endif; ?>
<?php if ($http_loopback_warning = fw_ext_backups_loopback_test()) : ?>
<div class="error">
<p><strong><?php _e( 'Important', 'fw' ); ?>:</strong> <?php echo $http_loopback_warning; ?></p>
</div>
<script type="text/javascript">var fw_ext_backups_loopback_failed = true;</script>
<?php endif; ?>
</div>
<p></p>
<div class="theme-browser rendered" id="fw-ext-backups-demo-list">
<?php foreach ($demos as $demo): ?>
<div class="theme fw-ext-backups-demo-item" id="demo-<?php echo esc_attr($demo->get_id()) ?>">
<div class="theme-screenshot">
<img src="<?php echo esc_attr($demo->get_screenshot()); ?>" alt="Screenshot" />
</div>
<?php if ($demo->get_preview_link()): ?>
<a class="more-details" target="_blank" href="<?php echo esc_attr($demo->get_preview_link()) ?>">
<?php esc_html_e('Live Preview', 'fw') ?>
</a>
<?php endif; ?>
<h3 class="theme-name"><?php echo esc_html($demo->get_title()); ?></h3>
<div class="theme-actions">
<a class="button button-primary"
href="#" onclick="return false;"
data-confirm="<?php echo esc_attr($confirm); ?>"
data-install="<?php echo esc_attr($demo->get_id()) ?>"><?php esc_html_e('Install', 'fw'); ?></a>
</div>
</div>
<?php endforeach; ?>
</div>

View File

@@ -0,0 +1,55 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @var bool $install_is_executing
* @var bool $install_is_pending
* @var null|FW_Ext_Backups_Task $executing_task
* @var null|FW_Ext_Backups_Task $pending_task
*/
$backups = fw_ext( 'backups' ); /** @var FW_Extension_Backups $backups */
$active_collection = $backups->tasks()->get_active_task_collection();
?>
<div class="fw-ext-backups-demo-status-modal">
<?php if ($install_is_executing): ?>
<h2 class="fw-text-muted">
<img src="<?php echo get_site_url() ?>/wp-admin/images/spinner.gif" alt="Loading" class="wp-spinner" />
<?php esc_html_e('Installing', 'fw') ?>
</h2>
<p class="fw-text-muted"><em><?php esc_html_e('We are currently installing your content.') ?></em></p>
<?php
$step = 0;
foreach ($active_collection->get_tasks() as $_task) {
++$step;
if (!$_task->result_is_finished()) {
break;
}
}
$percentage = $step / count($active_collection->get_tasks()) * 100;
?>
<div class="progress-percent"><div style="width: <?php echo $percentage; ?>%;"></div></div>
<?php if ($executing_task): ?>
<p class="fw-text-muted"><em><?php echo esc_html($backups->tasks()->get_task_type_title(
$executing_task->get_type(),
$executing_task->get_args(),
$executing_task->get_result()
)); ?></em></p>
<?php elseif ($pending_task): ?>
<p class="fw-text-muted"><em><?php echo esc_html($backups->tasks()->get_task_type_title(
$pending_task->get_type(),
$pending_task->get_args(),
$pending_task->get_result()
)); ?></em></p>
<?php endif; ?>
<?php elseif ($install_is_pending): ?>
<p><img src="<?php echo get_site_url() ?>/wp-admin/images/spinner.gif" alt="Loading"></p>
<em class="fw-text-muted"><?php esc_html_e('Pending', 'fw') ?></em>
<?php endif; ?>
<?php if ($active_collection && $active_collection->is_cancelable()): ?>
<a href="#" onclick="fwEvents.trigger('fw:ext:backups-demo:cancel'); return false;"><em><?php
esc_html_e('Abort', 'fw');
?></em></a>
<?php endif; ?>
</div>

View File

@@ -0,0 +1,307 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Test if HTTP Loopback Connections are enabled on this server
*/
function fw_ext_backups_loopback_test() {
/** @var FW_Extension_Backups $backups */
$backups = fw_ext('backups');
$url = site_url( 'wp-admin/admin-ajax.php' );
$response = wp_remote_post($url, array(
'blocking' => true,
'sslverify' => false,
'body' => array(
'action' => $backups->_get_test_ajax_action(),
),
));
$error = false;
if (is_wp_error($response)) {
$error = $response->get_error_message();
} elseif(200 !== ($response_code = intval(wp_remote_retrieve_response_code($response)))) {
$error = sprintf(esc_html__('Response code: %d', 'fw'), $response_code);
} elseif (
isset($response['body'])
&&
($response_json = json_decode($response['body'], true))
&&
isset($response_json['success'])
&&
true === $response_json['success']
) {
return false;
} else {
$error = __('Invalid JSON response', 'fw');
}
return str_replace(
array('{url}', '{error}'),
array($url, $error),
__(
'HTTP Loopback Connections are not enabled on this server. ' .
'If you need to contact your web host, '
. 'tell them that when PHP tries to connect back to the site '
. 'at the URL `{url}` and it gets the error `{error}`. '
. 'There may be a problem with the server configuration (eg local DNS problems, mod_security, etc) '
. 'preventing connections from working properly.',
'fw'
)
);
}
function fw_ext_backups_rmdir_recursive($dir) {
if (is_dir($dir = fw_fix_path($dir))) {
if ($files = array_diff(($files = scandir($dir)) ? $files : array(), array('.', '..'))) {
foreach ( $files as $file ) {
$file = $dir .'/'. $file;
if ( is_dir( $file ) ) {
if ( ! fw_ext_backups_rmdir_recursive( $file ) ) {
return false;
}
} else {
if ( ! unlink( $file ) ) {
return false;
}
}
}
}
if ( ! rmdir($dir) ) {
return false;
}
return true;
}
return false;
}
/**
* @param string $dir
* @return bool|null
* http://stackoverflow.com/a/7497848/1794248
*/
function fw_ext_backups_is_dir_empty($dir) {
if (!is_readable($dir)) {
return null;
}
if (false === ($handle = opendir($dir))) {
return null;
}
while (false !== ($entry = readdir($handle))) {
if ($entry !== '.' && $entry !== '..') {
return false;
}
}
return true;
}
/**
* @param string $source_dir
* @param string $destination_dir
* @return bool|WP_Error
*/
function fw_ext_backups_copy_dir_recursive($source_dir, $destination_dir) {
$source_dir = fw_fix_path($source_dir);
$destination_dir = fw_fix_path($destination_dir);
$dir_chmod = 0755;
if (!file_exists($destination_dir)) {
if (!mkdir($destination_dir, $dir_chmod)) {
return new WP_Error(
'mkdir_fail',
sprintf(__('Failed to create dir: %s'), $destination_dir)
);
}
}
try {
foreach (
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source_dir),
RecursiveIteratorIterator::SELF_FIRST
) as $item /** @var SplFileInfo $item */
) {
if (in_array(basename($iterator->getSubPathName()), array('.', '..'), true)) {
continue; // We can't use RecursiveDirectoryIterator::SKIP_DOTS, it was added in php 5.3
}
$destination_path = $destination_dir . '/' . $iterator->getSubPathName();
if ($item->isDir()) {
if (!mkdir($destination_path, $dir_chmod)) {
return new WP_Error(
'mk_sub_dir_fail',
sprintf(__('Failed to create dir: %s'), $destination_path)
);
}
} else {
if (!copy($item->getPathname(), $destination_path)) {
return new WP_Error(
'copy_fail',
sprintf(__('Failed to copy: %s'), $destination_path)
);
}
}
}
} catch (UnexpectedValueException $e) {
return new WP_Error(
'dir_copy_fail',
(string)$e->getMessage()
);
}
return true;
}
/**
* If current user is allowed to make full backup or restore
* This method must be used before calling $backups->tasks()->do_backup|restore()
* to not allow simple admins to make full backup|restore on multisite and affect all sites.
*
* $backups->tasks()->do_backup|restore() Can't do that check
* because those methods are also called in cron, when the user is not logged in
*/
function fw_ext_backups_current_user_can_full() {
if ( is_multisite() ) {
return is_main_site() &&
fw_current_user_can( array( 'manage_network_plugins' ), false ) &&
fw_current_user_can( array( 'manage_network_themes' ), false );
} else {
return fw_current_user_can( array( 'install_plugins' ), false ) &&
fw_current_user_can( array( 'install_themes' ), false );
}
}
/**
* Extract from zip files one by one and check if timeout wasn't reached
* @param string|resource $zip Path or zip_open() result
* @param string $destination_dir
* @param int $timeout
* @param string $last_entry
* @return array|WP_Error Done when $result['finished'] === true
* @since 2.0.16
*/
function fw_ext_backups_unzip_partial($zip, $destination_dir, $last_entry = '', $timeout = 0) {
if (!function_exists('zip_open')) {
return new WP_Error(
'zip_ext_missing', __('Zip extension missing', 'fw')
);
}
if (!is_resource($zip) && !is_resource($zip = zip_open($zip))) {
return new WP_Error(
'cannot_open_zip', sprintf(__('Cannot open zip (Error code: %s)', 'fw'), $zip)
);
}
if ($timeout <= 0) {
/** @var FW_Extension_Backups $ext */
$ext = fw_ext('backups');
$timeout = $ext->get_timeout(-10);
}
if ($last_entry) {
while(
($entry = zip_read($zip))
&&
zip_entry_name($entry) !== $last_entry
);
if (!$entry) {
zip_close($zip);
return new WP_Error(
'entry_restore_fail',
sprintf(__('Cannot restore previous zip entry: %s', 'fw'), $last_entry)
);
}
}
$result = array(
'finished' => false,
'last_entry' => $last_entry,
'extracted_files' => 0,
);
$max_time = time() + $timeout;
while (time() < $max_time) {
if (!($entry = zip_read($zip))) {
$result['finished'] = true;
return $result;
}
$name = zip_entry_name($entry);
if (substr($name, -1) === '/') {
continue; // it is a directory
}
$destination_path = $destination_dir .'/'. $name;
if (
!file_exists($dest_dir = dirname($destination_path))
&&
!mkdir($dest_dir, 0777, true)
) {
zip_close($zip);
return new WP_Error(
'mkdir_fail',
sprintf(__('Cannot create directory: %s', 'fw'), $dest_dir)
);
}
if (false === ($unzipped = fopen($destination_path, 'wb'))) {
zip_close($zip);
return new WP_Error(
'fopen_fail',
sprintf(__('Cannot create file: %s', 'fw'), $destination_path)
);
}
$size = zip_entry_filesize($entry);
while ($size > 0) {
$chunk_size = min($size, 10240);
$size -= $chunk_size;
if (false === ($chunk = zip_entry_read($entry, $chunk_size))) {
fclose($unzipped);
zip_close($zip);
return new WP_Error(
'zip_entry_read_fail',
sprintf(__('Cannot read chunk from zip entry: %s', 'fw'), $name)
);
} else {
fwrite($unzipped, $chunk);
}
}
if (false === fclose($unzipped)) {
zip_close($zip);
return new WP_Error(
'fclose_fail',
sprintf(__('Cannot close file: %s', 'fw'), $destination_path)
);
}
$result['last_entry'] = $name;
++$result['extracted_files'];
}
return $result;
}
function fw_ext_backups_destination_directory() {
$uploads = wp_upload_dir();
return fw_fix_path( $uploads['basedir'] ) . '/fw-backup';
}

View File

@@ -0,0 +1,51 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @param bool $exclude
* @param string $option_name
* @param bool $is_full_backup
*
* @return bool
*/
function _filter_fw_ext_backups_db_export_exclude_option($exclude, $option_name, $is_full_backup) {
foreach (array(
'_site_transient_',
'_transient_'
) as $option_prefix) {
if (substr($option_name, 0, strlen($option_prefix)) === $option_prefix) {
return true;
}
}
return $exclude;
}
add_filter('fw_ext_backups_db_export_exclude_option', '_filter_fw_ext_backups_db_export_exclude_option', 10, 3);
/**
* Other extensions options
*/
{
function _filter_fw_ext_backups_db_export_exclude_other_extensions_options($exclude, $option_name, $is_full_backup) {
if (!$is_full_backup) {
if ($option_name === 'fw_ext_settings_options:mailer') {
return true;
}
}
return $exclude;
}
add_filter('fw_ext_backups_db_export_exclude_option',
'_filter_fw_ext_backups_db_export_exclude_other_extensions_options', 10, 3
);
function _filter_fw_ext_backups_db_restore_keep_other_extensions_options($options, $is_full) {
if (!$is_full) {
$options[ 'fw_ext_settings_options:mailer' ] = true;
}
return $options;
}
add_filter('fw_ext_backups_db_restore_keep_options',
'_filter_fw_ext_backups_db_restore_keep_other_extensions_options', 10, 2
);
}

View File

@@ -0,0 +1,156 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Display extensions with updates on the Update Page
*/
class _FW_Ext_Backups_List_Table extends FW_WP_List_Table
{
private $items_pre_page = 1000;
private $total_items = null;
private $_archives = array();
private $_table_columns = array();
private $_table_columns_count = 0;
public function __construct($args)
{
parent::__construct(array(
'screen' => 'fw-ext-backups'
));
$this->_archives = $args['archives'];
$this->_table_columns = array(
'cb' => ' ',
'details' => ' ',
);
$this->_table_columns_count = count($this->_table_columns);
}
public function get_columns()
{
return $this->_table_columns;
}
public function prepare_items()
{
if (!is_null($this->total_items)) {
return;
}
$this->total_items = count($this->_archives);
$this->set_pagination_args(array(
'total_items' => $this->total_items,
'per_page' => $this->items_pre_page,
));
/**
* @var FW_Extension_Backups $backups
*/
$backups = fw_ext('backups');
/**
* Prepare items for output
*/
foreach ($this->_archives as $filename => $archive) {
$time = get_date_from_gmt(
gmdate('Y-m-d H:i:s', $archive['time']),
get_option('date_format') . ' ' . get_option('time_format')
);
$filename_hash = md5($filename);
{
$details = array();
$details[] = $archive['full'] ? __('Full Backup', 'fw') : __('Content Backup', 'fw');
if (function_exists('fw_human_bytes')) {
$details[] = fw_human_bytes(filesize($archive['path']));
}
$details[] = fw_html_tag('a', array(
'href' => $backups->get_download_link($filename),
'target' => '_blank',
'id' => 'download-'. $filename_hash,
'data-download-file' => $filename,
), esc_html__('Download', 'fw'));
$details[] = fw_html_tag('a', array(
'href' => '#',
'onclick' => 'return false;',
'id' => 'delete-'. $filename_hash,
'data-delete-file' => $filename,
'data-confirm' => __(
"Warning! \n".
"You are about to delete a backup, it will be lost forever. \n".
"Are you sure?",
'fw'
)
), esc_html__('Delete', 'fw'));
}
$this->items[] = array(
'cb' => fw_html_tag('input', array(
'type' => 'radio',
'name' => 'archive',
'value' => $filename,
'id' => 'archive-'. $filename_hash,
)),
'details' =>
'<div>'. $time .'</div>'.
'<div>'. implode(' | ', $details) .'</div>',
);
}
}
public function has_items()
{
$this->prepare_items();
return $this->total_items;
}
/**
* (override parent)
*/
function single_row($item)
{
static $row_class = '';
$row_class = ( $row_class == '' ? ' class="alternate"' : '' );
echo '<tr' . $row_class . '>';
echo $this->single_row_columns( $item );
echo '</tr>';
}
protected function column_cb($item)
{
echo $item['cb'];
}
protected function column_default($item, $column_name)
{
echo $item[$column_name];
}
function no_items()
{
esc_html_e('No archives found', 'fw');
}
function extra_tablenav( $which ) {
echo fw_html_tag('button', array(
'type' => 'button',
'onclick' => 'return false;',
'class' => 'button fw-ext-backups-archive-restore-button',
'disabled' => 'disabled',
'data-confirm' => esc_html__("Warning! \nThe restore will replace all of your content.", 'fw'),
), esc_html__('Restore Backup'));
}
}

View File

@@ -0,0 +1,176 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @internal
*/
class _FW_Ext_Backups_Log {
/**
* @var FW_Access_Key|null
*/
private static $access_key;
/**
* @return FW_Access_Key|null
*/
private static function get_access_key() {
if (empty(self::$access_key)) {
self::$access_key = new FW_Access_Key('fw:ext:backups:log');
}
return self::$access_key;
}
/**
* @return FW_Extension_Backups
*/
private static function backups() {
return fw_ext('backups');
}
private static $wp_option = 'fw:ext:backups:log';
private static $log_limit = 30;
public function __construct() {
add_action('fw:ext:backups:task:fail', array($this, '_action_task_fail'));
add_action('fw:ext:backups:tasks:success', array($this, '_action_tasks_success'));
add_action('fw_ext_backups_page_footer', array($this, '_action_page_footer'));
add_action('fw:ext:backups:enqueue_scripts', array($this, '_action_enqueue_scripts'));
add_filter(
'fw_ext_backups_db_export_exclude_option',
array($this, '_filter_fw_ext_backups_db_export_exclude_option'),
10, 3
);
add_filter(
'fw_ext_backups_db_restore_keep_options',
array($this, '_filter_fw_ext_backups_db_restore_keep_options')
);
add_filter(
'fw_ext_backups_ajax_status_extra_response',
array($this, '_filter_fw_ext_backups_ajax_status_extra_response')
);
}
private function get_log() {
return get_option(self::$wp_option, array());
}
private function set_log($log) {
while (count($log) > self::$log_limit) {
array_pop($log);
}
return update_option(self::$wp_option, $log, false);
}
private function add_log($type, $title, array $data = array()) {
if (!in_array($type, array('success', 'info', 'warning', 'error'))) {
trigger_error('Invalid log type: '. $type, E_USER_WARNING);
}
$log = $this->get_log();
array_unshift($log, array(
'type' => $type,
'title' => $title,
'data' => $data,
'time' => time(),
));
$this->set_log($log);
}
private function render_log() {
return fw_render_view(dirname(__FILE__) .'/view.php', array(
'log' => $this->get_log()
));
}
/**
* @param FW_Ext_Backups_Task $task
* @internal
*/
public function _action_task_fail(FW_Ext_Backups_Task $task) {
$this->add_log(
'error',
self::backups()->tasks()->get_task_type_title($task->get_type())
. (is_wp_error($task->get_result()) ? ': '. $task->get_result()->get_error_message() : ''),
is_wp_error($task->get_result()) ? (array)$task->get_result()->get_error_data() : array()
);
}
/**
* @param FW_Ext_Backups_Task_Collection $tasks
* @internal
*/
public function _action_tasks_success(FW_Ext_Backups_Task_Collection $tasks) {
$this->add_log(
'success',
$tasks->get_title()
);
}
/**
* @param array $options {option_name: true}
* @return array
*/
public function _filter_fw_ext_backups_db_restore_keep_options($options) {
$options[ self::$wp_option] = true;
return $options;
}
/**
* @param bool $exclude
* @param string $option_name
* @param bool $is_full_backup
* @return bool
*/
public function _filter_fw_ext_backups_db_export_exclude_option($exclude, $option_name, $is_full_backup) {
if (!$is_full_backup && $option_name === self::$wp_option) {
return true;
}
return $exclude;
}
/**
* @internal
*/
public function _action_page_footer() {
echo '<div id="fw-ext-backups-log"></div>';
}
/**
* @param $data
* @return mixed
* @internal
*/
public function _filter_fw_ext_backups_ajax_status_extra_response($data) {
$data['log'] = array(
'html' => $this->render_log(),
);
return $data;
}
/**
* @internal
*/
public function _action_enqueue_scripts() {
wp_enqueue_style(
'fw-ext-backups-log',
self::backups()->get_uri('/includes/log/styles.css'),
array(),
self::backups()->manifest->get_version()
);
wp_enqueue_script(
'fw-ext-backups-log',
self::backups()->get_uri('/includes/log/scripts.js'),
array('fw'),
self::backups()->manifest->get_version()
);
}
}
new _FW_Ext_Backups_Log();

View File

@@ -0,0 +1,26 @@
jQuery(function($){
var inst = {
localized: _fw_ext_backups_localized,
$el: $('#fw-ext-backups-log'),
onUpdating: function(){},
onUpdate: function(data) {
this.$el.html(data.log.html);
},
onUpdateFail: function() {},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups:status:updated': _.bind(this.onUpdated, this)
});
this.$el.on('click', '#fw-ext-backups-log-show-button a', function() {
inst.$el.toggleClass('show-list');
});
}
};
inst.init();
});

View File

@@ -0,0 +1,14 @@
#fw-ext-backups-log #fw-ext-backups-log-show-button .button-hide,
#fw-ext-backups-log #fw-ext-backups-log-list {
display: none;
}
#fw-ext-backups-log.show-list #fw-ext-backups-log-show-button .button-view {
display: none;
}
#fw-ext-backups-log.show-list #fw-ext-backups-log-show-button .button-hide {
display: inline;
}
#fw-ext-backups-log.show-list #fw-ext-backups-log-list {
display: block;
}

View File

@@ -0,0 +1,34 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @var array $log
*/
?>
<?php if ($log): ?>
<div id="fw-ext-backups-log-show-button">
<a href="#" onclick="return false;" class="button-view"><?php esc_html_e('View Activity Log', 'fw'); ?></a>
<a href="#" onclick="return false;" class="button-hide"><?php esc_html_e('Hide Activity Log', 'fw'); ?></a>
</div>
<div id="fw-ext-backups-log-list">
<ul>
<?php foreach ($log as $l): ?>
<?php
switch (isset($l['type']) ? $l['type'] : '') {
case 'success': $class = 'fw-text-success'; break;
case 'info': $class = 'fw-text-info'; break;
case 'warning': $class = 'fw-text-warning'; break;
case 'error': $class = 'fw-text-danger'; break;
default: $class = ''; break;
}
?>
<li>
<em><?php printf(esc_html__('%s ago', 'fw'), human_time_diff($l['time'])); ?></em>
<span class="<?php echo esc_attr($class) ?>"><?php echo esc_html($l['title']); ?></span>
</li>
<?php endforeach ?>
</ul>
</div>
<?php endif; ?>

View File

@@ -0,0 +1,12 @@
<?php if (!defined('FW')) die('Forbidden');
abstract class _FW_Ext_Backups_Module {
final public function __construct(FW_Access_Key $access_key) {
if ($access_key->get_key() !== 'fw:ext:backups') {
// only the Backups extension can create instances
trigger_error(__METHOD__ .' denied', E_USER_ERROR);
}
}
abstract public function _init();
}

View File

@@ -0,0 +1,383 @@
<?php if (!defined('FW')) die('Forbidden');
class _FW_Ext_Backups_Module_Schedule extends _FW_Ext_Backups_Module {
private static $wp_ajax_get_settings = 'fw:ext:backups:schedule:get-settings';
private static $wp_ajax_set_settings = 'fw:ext:backups:schedule:set-settings';
private static $wp_option_settings = 'fw:ext:backups:schedule:settings';
private static $wp_cron_prefix = 'fw:ext:backups:cron:';
private static $default_lifetime = 7;
/**
* @return FW_Extension_Backups
*/
private static function backups() {
return fw_ext('backups');
}
public function _init() {
{
add_action('fw:ext:backups:enqueue_scripts', array($this, '_action_enqueue_backup_scripts'));
add_action('wp_ajax_' . self::$wp_ajax_get_settings, array($this, '_action_ajax_get_settings'));
add_action('wp_ajax_' . self::$wp_ajax_set_settings, array($this, '_action_ajax_set_settings'));
foreach (array('full', 'content') as $type) {
add_action(self::$wp_cron_prefix . $type, array($this, '_action_cron_'. $type));
}
}
{
add_filter('fw:ext:backups:script_localized_data', array($this, '_filter_script_localized_data'));
add_filter('fw_ext_backups_ajax_status_extra_response', array($this, '_filter_ajax_status_response_data'));
add_filter('fw_ext_backups_db_export_exclude_option', array($this, '_filter_db_exclude_option'), 10, 2);
add_filter('fw_ext_backups_db_restore_exclude_option', array($this, '_filter_db_exclude_option'), 10, 2);
add_filter('fw_ext_backups_db_restore_keep_options', array($this, '_filter_db_restore_keep_options'));
add_filter('cron_schedules', array($this, '_filter_cron_schedules'));
}
$this->cleanup();
}
// At this hour the cron will be executed
private function get_cron_run_hour() {
return self::backups()->get_config('schedule.hour');
}
/**
* @param int $hour 0..24
* current_hour=22, hour=3, result=5 hours
* current_hour=2, hour=3, result=1 hour
* current_hour=5, hour=3, result=22 hours
*
* Test <?php
fw_print(
date('H:i:s', time()),
date('H:i:s', $this->get_time_until_hour(3)),
date('H:i:s', $this->get_time_until_hour(15)),
date('H:i:s', $this->get_time_until_hour(21)),
date('H:i:s', $this->get_time_until_hour(0)),
date('H:i:s', $this->get_time_until_hour(24)),
date('H:i:s', $this->get_time_until_hour(25)),
date('H:i:s', $this->get_time_until_hour(85))
);
* ?>
*
* @return int
*/
private function get_time_until_hour($hour) {
if ($hour < 0 || $hour > 24) {
$hour = 3;
}
$result = $hour - (int)date('H'); // hours until give hour
$result += $result < 1 ? 24 : 0; // add one day if hour already passed
$result *= HOUR_IN_SECONDS; // transform hours to seconds
$result -= ( // remove current minutes and seconds
(MINUTE_IN_SECONDS + (int)date('i') * MINUTE_IN_SECONDS)
-
(MINUTE_IN_SECONDS - (int)date('s'))
);
return $result;
}
private function get_options() {
$options = fw_get_variables_from_file(
dirname(__FILE__) .'/settings-options.php',
array('options' => array())
);
return $options['options'];
}
private function get_settings($type = null) {
$settings = get_option(self::$wp_option_settings, array(
'full' => array(
'interval' => '',
'lifetime' => self::$default_lifetime,
),
'content' => array(
'interval' => '',
'lifetime' => self::$default_lifetime,
),
));
/**
* In case wp option value and cron schedule will be different (after full restore or something else)
* To be sure, use every time cron schedule value
*/
foreach ($settings as $_type => &$_settings) {
$_settings['interval'] = (string)wp_get_schedule(self::$wp_cron_prefix . $_type);
}
if (is_null($type)) {
return $settings;
} else {
return $settings[$type];
}
}
private function set_settings($type, $settings) {
if (!in_array($type, array('full', 'content'))) {
return false;
}
if (!in_array($settings['interval'], array('monthly', 'weekly', 'daily'))) {
$settings['interval'] = '';
}
if (($settings['lifetime'] = (int)$settings['lifetime']) < 1) {
$settings['lifetime'] = self::$default_lifetime;
}
$settings = array(
'interval' => $settings['interval'],
'lifetime' => $settings['lifetime'],
);
$current_settings = $this->get_settings();
$all_settings = array_merge(
array(
'full' => $current_settings['full'],
'content' => $current_settings['content'],
),
array($type => $settings)
);
update_option(
self::$wp_option_settings,
$all_settings,
false
);
// update cron
{
$hour = $this->get_cron_run_hour();
foreach ( $all_settings as $type => $settings ) {
$hook = self::$wp_cron_prefix . $type;
wp_clear_scheduled_hook($hook);
if ( $settings['interval'] ) {
wp_schedule_event(
time() + $this->get_time_until_hour( $hour ),
$settings['interval'],
$hook
);
}
}
}
return true;
}
public function _filter_script_localized_data($data) {
$data['schedule'] = array(
'ajax_action' => array(
'get_settings' => self::$wp_ajax_get_settings,
'set_settings' => self::$wp_ajax_set_settings,
),
'popup_title' => __('Backup Schedule', 'fw'),
);
return $data;
}
public function _action_enqueue_backup_scripts() {
fw()->backend->enqueue_options_static($this->get_options());
}
/**
* @param bool $exclude
* @param string $option_name
*
* @return bool
*/
public function _filter_db_exclude_option($exclude, $option_name) {
if ($option_name === self::$wp_option_settings) {
return true;
}
return $exclude;
}
/**
* @param array $options {option_name: true}
* @return array
*/
public function _filter_db_restore_keep_options($options) {
$options[ self::$wp_option_settings ] = true;
return $options;
}
public function _action_ajax_get_settings() {
if (!current_user_can(self::backups()->get_capability())) {
wp_send_json_error();
}
$settings = $this->get_settings();
$values = array(
'full' => array(
'interval' => $settings['full']['interval'],
$settings['full']['interval'] => array(
'lifetime' => $settings['full']['lifetime'],
),
),
'content' => array(
'interval' => $settings['content']['interval'],
$settings['content']['interval'] => array(
'lifetime' => $settings['content']['lifetime'],
),
),
);
wp_send_json_success(array(
'options' => $this->get_options(),
'values' => $values,
));
}
public function _action_ajax_set_settings() {
if (!current_user_can(self::backups()->get_capability())) {
wp_send_json_error();
}
if (
empty($_POST['values'])
||
!is_array($values = $_POST['values'])
) {
wp_send_json_error();
}
foreach (array('full', 'content') as $type) {
if ($type === 'full' && !fw_ext_backups_current_user_can_full()) {
$this->set_settings( $type, array(
'interval' => '',
'lifetime' => self::$default_lifetime,
));
} else {
$this->set_settings( $type, array(
'interval' => $values[ $type ]['interval'],
'lifetime' => isset( $values[ $type ][ $values[ $type ]['interval'] ] )
? $values[ $type ][ $values[ $type ]['interval'] ]['lifetime']
: self::$default_lifetime,
) );
}
}
wp_send_json_success();
}
/**
* @link https://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
* @param array $schedules
* @return array
*/
public function _filter_cron_schedules($schedules) {
$schedules['weekly'] = array(
'interval' => 604800,
'display' => __('Once Weekly')
);
$schedules['monthly'] = array(
'interval' => 2635200,
'display' => __('Once a month')
);
return $schedules;
}
public function _action_cron_full() {
$this->cleanup();
self::backups()->tasks()->do_backup(true);
}
public function _action_cron_content() {
$this->cleanup();
self::backups()->tasks()->do_backup(false);
}
private function cleanup() {
foreach (array('full' => true, 'content' => false) as $type => $full) {
$settings = $this->get_settings($type);
if (empty($settings['interval'])) { // this schedule is disabled
continue;
}
{
$time_step = null;
switch ($settings['interval']) {
case 'monthly': $time_step = WEEK_IN_SECONDS * 4; break;
case 'weekly': $time_step = WEEK_IN_SECONDS; break;
case 'daily': $time_step = DAY_IN_SECONDS; break;
}
if (is_null($time_step)) { // should not happen, but just in case
continue;
}
}
foreach (self::backups()->get_archives($full) as $archive) {
if ($archive['time'] < time() - $settings['lifetime'] * $time_step) {
unlink($archive['path']);
}
}
}
}
public function _filter_ajax_status_response_data($data) {
$html = array();
foreach (array(
'full' => esc_html__('Full', 'fw'),
'content' => esc_html__('Content', 'fw')
) as $type => $title) {
$hook = self::$wp_cron_prefix . $type;
if (false === ($recurrence = wp_get_schedule($hook))) {
continue;
}
switch ($recurrence) {
case 'monthly': $recurrence_title = esc_html__('Monthly', 'fw'); break;
case 'weekly': $recurrence_title = esc_html__('Weekly', 'fw'); break;
case 'daily': $recurrence_title = esc_html__('Daily', 'fw'); break;
default: $recurrence_title = $recurrence;
}
$time = get_date_from_gmt(
gmdate('Y-m-d H:i:s', wp_next_scheduled($hook)),
get_option('date_format') . ' ' . get_option('time_format')
);
$html[] =
'<div class="updated"><p>'.
/**/'<strong>'. $title .' '. esc_html__('Backup Schedule Active', 'fw') .'</strong>: '.
/**/$recurrence_title .' | '. esc_html__('Next backup on', 'fw') .' '. $time .
'</p></div>';
}
if (empty($html)) {
$html =
'<div class="error"><p>' .
/**/esc_html__( 'No backup schedule created yet! We advise you to do it asap!', 'fw' ) .
'</p></div>';
}
$data['schedule'] = array(
'status_html' => $html,
);
return $data;
}
}

View File

@@ -0,0 +1,89 @@
<?php if (!defined('FW')) die('Forbidden');
$limits = apply_filters('fw_ext_backups_schedule_lifetime_limits', array(
'monthly' => 12,
'weekly' => 4,
'daily' => 7,
));
$sub_options = array(
'type' => 'multi-picker',
'label' => false,
'desc' => false,
'show_borders' => true,
'picker' => array(
'interval' => array(
'label' => __('Interval', 'fw'),
'type' => 'radio',
'inline' => true,
'choices' => array(
'' => __('Disabled', 'fw'),
'monthly' => __('Monthly', 'fw'),
'weekly' => __('Weekly', 'fw'),
'daily' => __('Daily', 'fw'),
),
'desc' => __('Select how often do you want to backup your website.', 'fw'),
)
),
'choices' => array(
'monthly' => array(
'lifetime' => array(
'type' => 'short-slider',
'label' => __('Age Limit', 'fw'),
'desc' => __('Age limit of backups in months', 'fw'),
'value' => $limits['monthly'],
'properties' => array(
'min' => 1,
'max' => $limits['monthly'],
'grid_snap' => true,
),
),
),
'weekly' => array(
'lifetime' => array(
'type' => 'short-slider',
'label' => __('Age Limit', 'fw'),
'desc' => __('Age limit of backups in weeks', 'fw'),
'value' => $limits['weekly'],
'properties' => array(
'min' => 1,
'max' => $limits['weekly'],
'grid_snap' => true,
),
),
),
'daily' => array(
'lifetime' => array(
'type' => 'short-slider',
'label' => __('Age Limit', 'fw'),
'desc' => __('Age limit of backups in days', 'fw'),
'value' => $limits['daily'],
'properties' => array(
'min' => 1,
'max' => $limits['daily'],
'grid_snap' => true,
),
),
),
),
);
$options = array();
if (fw_ext_backups_current_user_can_full()) {
$options['full'] = array(
'type' => 'tab',
'title' => __( 'Full Backup', 'fw' ),
'options' => array(
'full' => $sub_options,
),
);
}
$options['content'] = array(
'type' => 'tab',
'title' => __('Content Backup', 'fw'),
'options' => array(
'content' => $sub_options,
),
);

View File

@@ -0,0 +1,30 @@
<?php if (!defined('FW')) die('Forbidden');
class _FW_Ext_Backups_Task_Type_Register {
/**
* @var FW_Ext_Backups_Task_Type[]
*/
private $task_types = array();
public function register(FW_Ext_Backups_Task_Type $type) {
if (isset($this->task_types[$type->get_type()])) {
throw new Exception('Backup Task Type '. $type->get_type() .' already exists');
}
$this->task_types[$type->get_type()] = $type;
}
/**
* @param FW_Access_Key $access_key
*
* @return FW_Ext_Backups_Task_Type[]
* @internal
*/
public function _get_task_types(FW_Access_Key $access_key) {
if ($access_key->get_key() !== 'fw:ext:backups:tasks') {
trigger_error('Method call denied', E_USER_ERROR);
}
return $this->task_types;
}
}

View File

@@ -0,0 +1,35 @@
<?php if (!defined('FW')) die('Forbidden');
abstract class FW_Ext_Backups_Task_Type {
/**
* @return string Unique type
*/
abstract public function get_type();
/**
* @param array $args Same $args sent to $this->execute()
* @param array $state Same $state returned by $this->execute()
* @return string
*/
abstract public function get_title(array $args = array(), array $state = array());
/**
* Execute a step
*
* @param array $args
* @param array $state Continue from the last step state
*
* @return array|true|WP_Error
* * array - current state, task is not finished (should continue)
* * true - task finished successfully
* * WP_Error - task failed
*/
abstract public function execute(array $args, array $state = array());
/**
* @param array $args
* @param array $state
* @return int
*/
public function get_custom_timeout(array $args, array $state = array()) {}
}

View File

@@ -0,0 +1,195 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @since 2.0.0
*/
final class FW_Ext_Backups_Task_Collection {
/**
* @var string
* @since 2.0.0
*/
private $id;
/**
* @var string
* @since 2.0.0
*/
private $title;
/**
* @var FW_Ext_Backups_Task[]
* @since 2.0.0
*/
private $tasks = array();
/**
* @param string $id
*/
public function __construct($id = null) {
$this->id = (string)(is_null($id) ? fw_rand_md5() : $id);
}
/**
* @param FW_Ext_Backups_Task $task
*
* @return bool
* @since 2.0.0
*/
public function add_task(FW_Ext_Backups_Task $task) {
if (in_array($task, $this->tasks, true)) {
return false;
} else {
foreach ($this->tasks as $_task) {
if ($_task->get_id() === $task->get_id()) {
return false;
}
}
$this->tasks[] = $task;
return true;
}
}
/**
* @return string
* @since 2.0.0
*/
public function get_id() {
return $this->id;
}
public function get_title() {
if (is_null($this->title)) {
return fw_id_to_title($this->id);
} else {
return $this->title;
}
}
public function set_title($title) {
$this->title = $title;
return $this;
}
/**
* @return FW_Ext_Backups_Task[]
* @since 2.0.0
*/
public function get_tasks() {
return $this->tasks;
}
/**
* Empty out the collection internal state and return the deleted tasks
*
* @return FW_Ext_Backups_Task[]
* @since 2.0.17
*/
public function empty_collection() {
$tmp = $this->tasks;
$this->tasks = array();
return $tmp;
}
/**
* @param string $id
*
* @return FW_Ext_Backups_Task|null
* @since 2.0.0
*
* Note: The returned instance will be changed by reference https://3v4l.org/Ps5hs (use `clone $instance`)
*/
public function get_task($id) {
if (empty($this->tasks)) {
return null;
}
foreach ($this->tasks as $task) {
if ($task->get_id() === $id) {
return $task;
}
}
return null;
}
/**
* If the collection is in a state that can be Cancelled/Aborted
* @return bool
*/
public function is_cancelable() {
$tasks = $this->get_tasks();
if (
($first_task = reset($tasks))
&&
!$first_task->get_last_execution_start_time()
) {
return true; // The execution haven't started
}
foreach ($tasks as $task) {
if ( ! $task->get_last_execution_start_time() ) {
return false; // We reached a pending task
} elseif ( ! $task->get_last_execution_end_time() ) {
/** @var FW_Extension_Backups $ext */
$ext = fw_ext('backups');
if (($task->get_last_execution_start_time() + $ext->get_task_step_execution_threshold()) < time()) {
return true; // The task is execution for a too long time
} else {
return false;
}
}
}
return false;
}
/**
* @return array
* @since 2.0.0
*/
public function to_array() {
$tasks = array();
foreach ($this->get_tasks() as $task) {
$tasks[] = $task->to_array();
}
return array(
'id' => $this->get_id(),
'title' => $this->title,
'tasks' => $tasks,
);
}
/**
* @param array $c
*
* @return FW_Ext_Backups_Task_Collection
* @since 2.0.0
*/
public static function from_array(array $c) {
if (empty($c)) {
return null;
}
$collection = new self($c['id']);
if (isset($c['title'])) {
$collection->set_title($c['title']);
}
foreach ($c['tasks'] as $t) {
$collection->add_task(
FW_Ext_Backups_Task::from_array($t)
);
}
return $collection;
}
}

View File

@@ -0,0 +1,239 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @since 2.0.0
*/
final class FW_Ext_Backups_Task {
/**
* @var string
* @since 2.0.0
*/
private $id;
/**
* A registered type that will process this task
* @var string
* @since 2.0.0
*/
private $type;
/**
* @var array
* @since 2.0.0
*/
private $args = array();
/**
* @var int timestamp
* @since 2.0.0
* @internal
*/
private $last_execution_start_time;
/**
* @var int timestamp
* @since 2.0.0
* @internal
*/
private $last_execution_end_time;
/**
* @var mixed
* // null - in progress, not finished yet
* // {...} - step finished successfully. current state. task not finished
* // true - task finished successfully
* // string - task finished successfully with message
* // false - task failed
* // WP_Error - task failed with message
* @since 2.0.0
* @internal
*/
private $result;
public function __construct($id, $type, $args = array()) {
$this->id = (string)$id;
$this->type = (string)$type;
$this->set_args($args);
}
/**
* @return string
* @since 2.0.0
*/
public function get_id() {
return $this->id;
}
/**
* @return string
* @since 2.0.0
*/
public function get_type() {
return $this->type;
}
/**
* @return array
* @since 2.0.0
*/
public function get_args() {
return $this->args;
}
/**
* @param array $args
*
* @return $this
* @since 2.0.0
*/
public function set_args(array $args) {
$this->args = $args;
return $this;
}
/**
* @return int|null
* @since 2.0.0
* @internal
*/
public function get_last_execution_start_time() {
return $this->last_execution_start_time;
}
/**
* @param int $last_execution_start_time
*
* @return $this
* @since 2.0.0
* @internal
*/
public function set_last_execution_start_time($last_execution_start_time) {
$this->last_execution_start_time = $last_execution_start_time;
return $this;
}
/**
* @return int|null
* @since 2.0.0
* @internal
*/
public function get_last_execution_end_time() {
return $this->last_execution_end_time;
}
/**
* @param int $last_execution_end_time
*
* @return $this
* @since 2.0.0
* @internal
*/
public function set_last_execution_end_time($last_execution_end_time) {
$this->last_execution_end_time = $last_execution_end_time;
return $this;
}
/**
* @return null|array|true|string|false|WP_Error
* @since 2.0.0
*/
public function get_result() {
return $this->result;
}
/**
* @param $result
*
* @return $this
* @since 2.0.0
* @internal
*/
public function set_result($result) {
if (
in_array($result, array(null, true, false), true)
||
is_string($result)
||
is_array($result)
||
is_wp_error($result)
) {} else {
throw new LogicException('Not supported result value');
}
$this->result = $result;
return $this;
}
/**
* @return bool Task execution finished and will never continue/execute
* @since 2.0.0
*/
public function result_is_finished() {
return !(
is_null($this->get_result())
||
is_array($this->get_result())
);
}
/**
* @return bool
* @since 2.0.0
*/
public function result_is_fail() {
return (
$this->get_result() === false
||
is_wp_error($this->get_result())
);
}
/**
* @return bool
* @since 2.0.0
*/
public function result_is_success() {
return (
$this->get_result() === true
||
is_string($this->get_result())
);
}
/**
* @return array
* @since 2.0.0
* @internal
*/
public function to_array() {
return array(
'id' => $this->get_id(),
'type' => $this->get_type(),
'args' => $this->get_args(),
'last_execution_start_time' => $this->get_last_execution_start_time(),
'last_execution_end_time' => $this->get_last_execution_end_time(),
'result' => $this->get_result(),
);
}
/**
* @param array $t
*
* @return FW_Ext_Backups_Task
* @since 2.0.0
* @internal
*/
public static function from_array(array $t) {
$task = new self($t['id'], $t['type'], $t['args']);
$task->set_last_execution_start_time($t['last_execution_start_time']);
$task->set_last_execution_end_time($t['last_execution_end_time']);
$task->set_result($t['result']);
return $task;
}
}

View File

@@ -0,0 +1,412 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Exported format: Lines of JSON objects
*
* {
* type: "table",
* data: {
* name: "table_name", // without wp prefix
* opts: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
* columns: {
* 'column_name': 'bigint(20) unsigned NOT NULL AUTO_INCREMENT'
* },
* indexes: [
* 'PRIMARY KEY (`meta_id`)',
* 'KEY `comment_id` (`comment_id`)'
* ]
* }
* }
*
* {
* type: "row",
* data: {
* table: "table_name", // without wp prefix
* row: {
* "column_name": "column_value",
* ...
* }
* }
* }
*/
class FW_Ext_Backups_Task_Type_DB_Export extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'db-export';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Database export', 'fw');
}
/**
* {@inheritdoc}
* @param array $args
* * dir - destination directory in which will be created `database.json.txt`
*/
public function execute(array $args, array $state = array()) {
{
if (!isset($args['dir'])) {
return new WP_Error(
'no_destination_dir', __('Destination dir not specified', 'fw')
);
}
$args['full'] = isset($args['full']) ? (bool)$args['full'] : false;
}
$tables = $this->get_tables($args['full']);
if (empty($state)) {
$state = array(
'table' => key($tables),
'limit' => 0,
'params' => false, // if params exported or not
);
} else {
$state['limit'] = (int)$state['limit']; // just to make sure. this will not be escaped in sql
}
if (!isset($tables[$state['table']])) {
return new WP_Error(
'table_disappeared', __('Database table disappeared', 'fw')
);
}
$backups = fw_ext('backups'); /** @var FW_Extension_Backups $backups */
$exclude_options = $backups->get_config('db.backup.exclude_options');
global $wpdb; /** @var WPDB $wpdb */
$max_time = time() + fw_ext( 'backups' )->get_timeout(-7);
while (time() < $max_time) {
// open file for writing
{
$file_path = $args['dir'] .'/database.json.txt';
if (!file_exists($file_path)) {
if (!($fp = @fopen($file_path, 'w'))) {
return new WP_Error(
'cannot_create_file', __('Cannot create file', 'fw') .': '. $file_path
);
}
} else {
if (!($fp = @fopen($file_path, 'a'))) {
return new WP_Error(
'cannot_reopen_file', __('Cannot reopen file', 'fw') .': '. $file_path
);
}
}
}
if (!$state['params']) {
fwrite(
$fp,
json_encode(array(
'type' => 'param',
'data' => array(
'name' => 'wpdb_prefix',
'value' => $wpdb->prefix,
),
)) . "\n"
);
{
$tmp = wp_upload_dir();
fwrite(
$fp,
json_encode(array(
'type' => 'param',
'data' => array(
'name' => 'wp_upload_dir_baseurl',
'value' => $tmp['baseurl'],
),
)) . "\n"
);
unset($tmp);
}
$state['params'] = true;
}
if ($state['limit'] == 0) { // create table before data insert
$sql = $wpdb->get_col('SHOW CREATE TABLE '. $wpdb->prefix . esc_sql($state['table']), 1);
if (empty($sql)) {
fclose($fp);
return new WP_Error(
'create_table_sql',
sprintf(__('Cannot export CREATE TABLE sql for %s', 'fw'), $state['table'])
.( $wpdb->last_error ? '. '. $wpdb->last_error : '' )
);
} else {
$sql = $sql[0];
}
$data = array(
'name' => $state['table'],
'opts' => '', // 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
'columns' => array(
// 'column_name' => 'bigint(20) unsigned NOT NULL AUTO_INCREMENT'
),
'indexes' => array(
// 'PRIMARY KEY (`meta_id`)'
// 'KEY `comment_id` (`comment_id`)'
),
);
/**
* Remove 'CREATE TABLE `wp_...` ('
*/
{
$sql = explode('(', $sql);
array_shift($sql);
$sql = implode('(', $sql);
}
{
$sql = explode(')', $sql);
$data['opts'] = trim(array_pop($sql));
$sql = implode(')', $sql);
}
foreach (explode(",\n", trim($sql)) as $column_or_index) {
$column_or_index = trim($column_or_index);
if (empty($column_or_index)) continue; // don't know when this happens, just in case
if ($column_or_index{0} === '`') { // column
$column_or_index = explode(' ', $column_or_index);
$column_name = trim(array_shift($column_or_index), '`');
$column_or_index = implode(' ', $column_or_index);
$column_opts = $column_or_index;
$data['columns'][ $column_name ] = $column_opts;
} else {
$data['indexes'][] = $column_or_index;
}
}
fwrite(
$fp,
json_encode(array(
'type' => 'table',
'data' => $data
)) . "\n"
);
unset($sql, $data);
}
if (!($column = $this->get_table_order_by_column($state['table']))) {
$state['table'] = $this->get_next_table($state['table'], $args['full']);
if (is_null($state['table'])) {
fclose($fp);
return true;
} elseif (false === $state['table']) {
fclose($fp);
return new WP_Error(
'no_next_table', __('Cannot get next database table', 'fw')
);
} else {
$state['limit'] = 0;
}
}
$limit = $this->get_table_limit($state['table']);
$count = 0;
foreach ($wpdb->get_results(
'SELECT * FROM '. $wpdb->prefix . esc_sql($state['table'])
.' ORDER BY '. esc_sql($column)
.' LIMIT '. $state['limit'] .','. $limit,
ARRAY_A
) as $row) {
$count++;
if ('options' === $state['table']) {
if (
(
!$args['full'] && isset($exclude_options[ $row['option_name'] ])
)
||
apply_filters('fw_ext_backups_db_export_exclude_option', false,
$row['option_name'], $args['full']
)
) {
continue;
}
}
fwrite(
$fp,
json_encode(array(
'type' => 'row',
'data' => array(
'table' => $state['table'],
'row' => $row,
)
)) . "\n"
);
}
fclose($fp);
if ($count > 0 && $count == $limit) {
$state['limit'] += $limit;
} else {
$state['table'] = $this->get_next_table($state['table'], $args['full']);
if (is_null($state['table'])) {
return true;
} elseif (false === $state['table']) {
return new WP_Error(
'no_next_table', __('Cannot get next database table', 'fw')
);
} else {
$state['limit'] = 0;
}
}
}
return $state;
}
/**
* Cache
* @var array
*/
private $tables;
/**
* @param bool $is_full
* @return array {'table_name': {}} Note: Table name is without $wpdb->prefix
*/
private function get_tables($is_full) {
if (is_null($this->tables)) {
global $wpdb; /** @var WPDB $wpdb */
$tables = $wpdb->get_col(
$wpdb->prepare(
'SHOW TABLES LIKE %s',
$wpdb->esc_like($wpdb->prefix) .'%'
)
);
/**
* Use /i in regex because prefix can be mixed case.
* Fixes https://github.com/ThemeFuse/Unyson/issues/2068#issuecomment-250196792
*/
$prefix_regex = '/^'. preg_quote($wpdb->prefix, '/') .'/i';
foreach ($tables as $i => $table) {
$tables[$i] = preg_replace($prefix_regex, '', $table);
if (is_numeric($tables[$i]{0})) {
/**
* Skip multisite tables '1_options' (wp_1_options)
* This happens when export is done on main site.
* So when doing export on main site,
* only main site tables will be exported, without sub sites tables.
*/
unset($tables[$i]);
}
}
asort( $tables );
$this->tables = array_fill_keys( $tables, array() );
if (!$is_full) {
/** @since 2.0.24 */
$this->tables = apply_filters( 'fw:ext:backups:db-export:tables', $this->tables );
}
}
if ($is_full) {
return $this->tables;
} else {
$tables = $this->tables;
foreach(array_keys(array(
'users' => true,
'usermeta' => true,
'blogs' => true,
'blog_versions' => true,
'registration_log' => true,
'signups' => true,
'site' => true,
'sitemeta' => true,
'sitecategories' => true
)) as $excluded_table) {
unset($tables[$excluded_table]);
}
return $tables;
}
}
private function get_next_table($name, $is_full) {
$tables = $this->get_tables($is_full);
$keys = array_keys($tables);
$index = array_search($name, $keys);
if ($index === false) {
return false;
} elseif (isset($keys[$index + 1])) {
return $keys[$index + 1];
} else {
return null;
}
}
/**
* Cache
* @var array {'table' => 'column'}
*/
private $table_order_by_columns = array();
/**
* @param string $name
*
* @return string|false
*/
private function get_table_order_by_column($name) {
if (!isset($this->table_order_by_columns[$name])) {
global $wpdb; /** @var WPDB $wpdb */
$columns = $wpdb->get_results( 'SHOW COLUMNS FROM '. $wpdb->prefix . esc_sql($name), ARRAY_A );
if (empty($columns)) {
// table has no columns, not sure when this can happen, but better treat this case
$this->table_order_by_columns[$name] = false;
} else {
foreach ( $columns as $colum ) {
if ( $colum['Key'] === 'PRI' ) { // Column is primary key
$this->table_order_by_columns[ $name ] = $colum['Field'];
break;
}
}
// If table has no primary key, just use first column
$this->table_order_by_columns[ $name ] = $columns[0]['Field'];
}
}
return $this->table_order_by_columns[$name];
}
/**
* @param string $name Can be tables that can contain a lot of data in a single row, and can have a lower limit
*
* @return int How much rows to select in one query
*/
private function get_table_limit($name) {
return 100;
}
}

View File

@@ -0,0 +1,78 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Delete everything from the given directory
*/
class FW_Ext_Backups_Task_Type_Dir_Clean extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'dir-clean';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Directory Cleanup', 'fw');
}
/**
* {@inheritdoc}
*/
public function execute(array $args, array $state = array()) {
if (!isset($args['dir'])) {
return new WP_Error(
'no_dir', __('Dir not specified', 'fw')
);
}
$dir = $args['dir'];
if (file_exists($dir)) {
if (!fw_ext_backups_rmdir_recursive($dir)) {
return new WP_Error(
'rmdir_fail', __('Cannot remove directory', 'fw') .': '. $dir
);
}
}
if (!mkdir($dir, 0777, true)) {
return new WP_Error(
'mkdir_fail', __('Cannot create directory', 'fw') .': '. $dir
);
}
/**
* Additional backups dir security check
*/
{
$backups_dir = fw_ext('backups')->get_backups_dir();
if (!file_exists("$backups_dir/index.php")) {
$contents = implode("\n", array(
'<?php',
'header(\'HTTP/1.0 403 Forbidden\');',
'die(\'<h1>Forbidden</h1>\');'
));
if (@file_put_contents("$backups_dir/index.php", $contents) === false) {
return new WP_Error(
'index_create_fail', sprintf( __('Cannot create file: %s', 'fw'), "$backups_dir/index.php" )
);
}
}
if (!file_exists("$backups_dir/.htaccess")) {
$contents = implode("\n", array(
'Deny from all',
'<IfModule mod_rewrite.c>',
' RewriteEngine On',
' RewriteRule . - [R=404,L]',
'</IfModule>'
));
if (@file_put_contents("$backups_dir/.htaccess", $contents) === false) {
return new WP_Error(
'htaccess_create_fail', sprintf( __('Cannot create file: %s', 'fw'), "$backups_dir/htaccess" )
);
}
}
}
return true;
}
}

View File

@@ -0,0 +1,234 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Backups_Task_Type_Files_Export extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'files-export';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Files Export', 'fw');
}
/**
* {@inheritdoc}
* @param array $args
* * source_dirs - {'dir_id': 'dir_path'}
* * destination - dir
* * [exclude_paths] - {'dir_path': true}
*/
public function execute(array $args, array $state = array()) {
$backups = fw_ext('backups'); /** @var FW_Extension_Backups $backups */
{
if (empty($args['source_dirs'])) {
return new WP_Error(
'no_source', __('Source dirs not specified', 'fw')
);
} else {
$args['source_dirs'] = array_filter(array_map('fw_fix_path', $args['source_dirs']), 'file_exists');
}
if (empty($args['destination'])) {
return new WP_Error(
'no_destination', __('Destination not specified', 'fw')
);
} else {
$args['destination'] = fw_fix_path($args['destination']);
}
{
if (empty($args['exclude_paths'])) {
$args['exclude_paths'] = array(
// '/path/to/dir' => true,
// '/path/to/file.txt' => true, // NOT WORKING. If you need this feature let us know
);
}
/**
* @since 2.0.18
*/
$args['exclude_paths'] = apply_filters(
'fw:ext:backups:task-type:files-export:exclude-paths',
$args['exclude_paths']
);
$wp_upload_dir = wp_upload_dir();
$args['exclude_paths'] = array_merge($args['exclude_paths'], array(
$backups->get_backups_dir() => true,
$backups->get_tmp_dir() => true, // by default it's in backups dir, just in case it will be changed
fw_fix_path($wp_upload_dir['basedir']) .'/backup' => true, // Backup v1
fw_fix_path($wp_upload_dir['basedir']) .'/fw' => true, // created in Unyson 2.6.0 by FW_File_Cache
));
}
}
if (empty($state)) {
$state = array(
'dir_id' => key($args['source_dirs']),
'dirs' => array(
// 'parent_dir', 'dir', 'sub_dir' // --> {source_dir}/parent_dir/dir/sub_dir
),
'file' => '', // --> {source_dir}/parent_dir/dir/sub_dir/{file}
);
}
$max_time = time() + fw_ext( 'backups' )->get_timeout(-7);
while (time() < $max_time) {
if (empty($args['source_dirs'][ $state['dir_id'] ])) {
return new WP_Error(
'source_dir_empty',
sprintf(__('Source dir %s is empty', 'fw'), $state['dir_id'])
);
}
if (is_wp_error($files = $this->get_next_files(
$args['source_dirs'][ $state['dir_id'] ],
$state['dirs'],
$state['file'],
$args['exclude_paths']
))) {
return $files;
} elseif ($files === true) {
// move to the next source dir
{
while (key($args['source_dirs']) !== $state['dir_id']) {
next($args['source_dirs']);
}
next($args['source_dirs']);
}
if ($state['dir_id'] = key($args['source_dirs'])) {
$state['dirs'] = array();
$state['file'] = '';
continue;
} else {
return true;
}
}
$rel_dir = empty($state['dirs']) ? '' : '/'. implode('/', $state['dirs']);
$source_dir = $args['source_dirs'][ $state['dir_id'] ] . $rel_dir;
$destination_dir = $args['destination'] .'/'. $state['dir_id'] . $rel_dir;
$created_dirs = array();
foreach ($files as $file) {
if (!isset($created_dirs[$destination_dir])) {
if (!is_dir($destination_dir)) {
if ($source_dir_chmod = substr(sprintf('%o', fileperms($source_dir)), -4)) {
$source_dir_chmod = intval($source_dir_chmod, 8);
} else {
return new WP_Error(
'get_dir_chmod_fail', __('Failed to get dir chmod', 'fw')
);
}
if (!mkdir($destination_dir, $source_dir_chmod, true)) {
return new WP_Error(
'destination_dir_create_fail',
__('Failed to create destination dir', 'fw'),
array('dir' => $destination_dir,)
);
}
}
$created_dirs[$destination_dir] = true;
}
if (!copy(
$source_dir .'/'. $file,
$destination_dir .'/'. $file
)) {
return new WP_Error(
'copy_failed', sprintf(__('Failed to copy: %s', 'fw'), $source_dir .'/'. $file)
);
}
}
$state['file'] = $file;
}
return $state;
}
private function get_max_files_per_cycle() {
return 33;
}
/**
* @param string $root_dir
* @param array $dirs
* @param string $previous_file
* @param array $exclude_paths
* @return array|true|WP_Error ['file.txt', 'file.php', ...]
* Important: It will never return an empty array. Only: (array)files, true, WP_Error
*/
private function get_next_files($root_dir, array &$dirs, $previous_file, array $exclude_paths) {
$rel_dir = empty($dirs) ? '' : '/'. implode('/', $dirs);
$included_hidden_names = fw_ext('backups')->get_config('included_hidden_names');
if ($names = array_diff(($names = scandir($dir = $root_dir . $rel_dir)) ? $names : array(), array('.', '..'))) {
$files = array(); // result
$file_found = empty($previous_file); // find previous file and return next files
$count = 0;
foreach ($names as $file) {
$path = $dir .'/'. $file;
if (!$file_found) {
$file_found = ($file === $previous_file);
continue;
}
if ($file{0} === '.' && !isset($included_hidden_names[$file])) {
continue;
}
if (is_dir($path)) {
if (isset($exclude_paths[ fw_fix_path($path) ])) {
continue;
} elseif ($files) { // return collected files, will go inside directory on next call
return $files;
} else {
$dirs[] = $file;
return $this->get_next_files($root_dir, $dirs, '', $exclude_paths);
}
} else {
$files[] = $file;
if (++$count > $this->get_max_files_per_cycle()) {
return $files;
}
}
}
if (empty($files)) {
if ($file_found) { // reached end of the directory
if ($dirs) { // go a directory back
$previous_file = array_pop($dirs);
return $this->get_next_files($root_dir, $dirs, $previous_file, $exclude_paths);
} else { // root directory end reached
return true;
}
} else {
return new WP_Error(
'previous_file_not_found',
sprintf(__('Failed to restore dir listing from: %s', 'fw'), $root_dir . $rel_dir . '/' . $previous_file)
);
}
}
return $files;
} else { // directory is empty
if ($dirs) { // go a directory back
$previous_file = array_pop($dirs);
return $this->get_next_files($root_dir, $dirs, $previous_file, $exclude_paths);
} else { // root directory end reached
return true;
}
}
}
}

View File

@@ -0,0 +1,439 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Backups_Task_Type_Files_Restore extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'files-restore';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Files Restore', 'fw');
}
/**
* Files restore can't be done in steps,
* because the site will not work without all files (half of a theme, or a plugin)
* {@inheritdoc}
*/
public function get_custom_timeout(array $args, array $state = array()) {
return fw_ext('backups')->get_config('max_timeout');
}
/**
* {@inheritdoc}
* @param array $args
* * source_dir
* * destinations - {'dir_id': 'destination_path'}
* * [filesystem_args] - {}|{hostname: '', username: '', password: '', connection_type: ''}
*/
public function execute(array $args, array $state = array()) {
$backups = fw_ext('backups'); /** @var FW_Extension_Backups $backups */
$upload_dir = wp_upload_dir();
$upload_dir = fw_fix_path($upload_dir['basedir']);
{
if (empty($args['source_dir'])) {
return new WP_Error(
'no_source_dir', __('Source dir not specified', 'fw')
);
} else {
$args['source_dir'] = fw_fix_path($args['source_dir']);
if (empty($args['source_dir']) || !file_exists($args['source_dir'])) {
return new WP_Error(
'invalid_source_dir',
sprintf(__('Invalid source dir: %s', 'fw'), $args['source_dir'])
);
}
}
if (empty($args['destinations'])) {
return new WP_Error(
'no_source', __('Source dirs not specified', 'fw')
);
} else {
$args['destinations'] = array_map('fw_fix_path', $args['destinations']);
}
{
if (empty($args['skip_dirs'])) {
$args['skip_dirs'] = array(
// '/path/to/dir' => true,
// '/path/to/file.txt' => true, // NOT WORKING. If you need this feature let us know
);
}
$args['skip_dirs'] = array_merge($args['skip_dirs'], array(
$backups->get_tmp_dir() => true,
$backups->get_backups_dir() => true,
$upload_dir .'/backup' => true, // Backup v1
fw_get_framework_directory() => true, // prevent framework delete, it must exist and continue task execution
));
}
}
if (empty($state)) {
// prepare destinations
{
$fs_required = false;
$upload_dir_regex = '/^'. preg_quote($upload_dir, '/') .'/';
$destinations = array(
'no_fs' => array(), // file operations are done via mkdir|copy|move|...
'fs' => array(), // file operations are done via WP_Filesystem
);
foreach ($args['destinations'] as $dir_id => $dir_path) {
$dir_path = fw_fix_path($dir_path);
if (
!file_exists($args['source_dir'] .'/'. $dir_id)
||
!file_exists($dir_path)
) {
continue;
}
$is_in_uploads = preg_match($upload_dir_regex, $dir_path);
$destinations[$is_in_uploads ? 'no_fs' : 'fs'][$dir_id] = array(
'fs' => !$is_in_uploads,
'dir' => $dir_path,
);
if (!$is_in_uploads) {
$fs_required = true;
}
}
$destinations = array_merge($destinations['no_fs'], $destinations['fs']);
if (empty($destinations)) {
return true;
}
}
$state = array(
'pending_destinations' => $destinations,
'current_destination' => array(
'id' => null,
'data' => null,
),
'fs_required' => $fs_required,
);
unset($destinations);
$state['current_destination']['id'] = key($state['pending_destinations']);
$state['current_destination']['data'] = array_shift($state['pending_destinations']);
}
if ($state['fs_required']) {
if (!FW_WP_Filesystem::has_direct_access(ABSPATH)) {
if (empty($args['filesystem_args'])) {
return new WP_Error(
'fs_no_access', __('No filesystem access, credentials required', 'fw')
);
} elseif (!WP_Filesystem($args['filesystem_args'])) {
return new WP_Error(
'invalid_fs_credentials', __('No filesystem access, invalid credentials', 'fw')
);
}
} else {
if (!WP_Filesystem()) {
return new WP_Error(
'fs_init_fail', __('Filesystem init failed', 'fw')
);
}
}
global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
if (!$wp_filesystem || (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code())) {
return new WP_Error(
'fs_init_fail', __('Filesystem init failed', 'fw')
);
}
}
while ($state['current_destination']['id']) {
if (is_wp_error($result = $this->clear_dir(
$state['current_destination']['data']['dir'],
$state['current_destination']['data']['fs'],
$args['skip_dirs']
))) {
return $result;
}
if (is_wp_error($result = $this->copy_dir(
$args['source_dir'] .'/'. $state['current_destination']['id'],
$state['current_destination']['data']['dir'],
$state['current_destination']['data']['fs'],
$args['skip_dirs']
))) {
return $result;
}
$state['current_destination']['id'] = key($state['pending_destinations']);
$state['current_destination']['data'] = array_shift($state['pending_destinations']);
}
return true;
}
/**
* @param string $dir path
* @param bool $fs Use WP_Filesystem or not
* @param array $skip_dirs {'path': mixed}
*
* @return WP_Error|true
*/
private function clear_dir($dir, $fs, $skip_dirs) {
$included_hidden_names = fw_ext('backups')->get_config('included_hidden_names');
if ($fs) {
global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
$fs_dir = fw_fix_path(FW_WP_Filesystem::real_path_to_filesystem_path($dir));
if (empty($fs_dir)) {
return new WP_Error(
'dir_to_fs_failed',
sprintf(__('Cannot convert Filesystem path: %s', 'fw'), $dir)
);
} elseif (false === ($list = $wp_filesystem->dirlist($fs_dir, true))) {
return new WP_Error(
'dir_list_failed',
sprintf(__('Failed to list dir: %s', 'fw'), $dir)
);
}
foreach ($list as $file) {
if ($file['name']{0} === '.' && !isset($included_hidden_names[$file['name']])) {
continue;
}
$file_path = $dir .'/'. $file['name'];
$fs_file_path = $fs_dir .'/'. $file['name'];
if ($file['type'] === 'd') {
if (isset($skip_dirs[$file_path])) {
continue;
} else {
foreach ($skip_dirs as $skip_dir => $skip_dir_data) {
if (
strlen(preg_replace('/^'. preg_quote($file_path, '/') .'/', '', $skip_dir))
!=
strlen($skip_dir)
) {
continue 2; // skip dir if it's inside current dir
}
}
}
if (!$wp_filesystem->rmdir($fs_file_path, true)) {
return new WP_Error(
'dir_rm_fail',
sprintf(__('Failed to remove dir: %s', 'fw'), $file_path)
);
}
} else {
if (!$wp_filesystem->delete($fs_file_path)) {
return new WP_Error(
'file_rm_fail',
sprintf(__('Failed to remove file: %s', 'fw'), $file_path)
);
}
}
}
return true;
} else {
$files = array_diff(($files = scandir($dir)) ? $files : array(), array('.', '..'));
foreach ($files as $file_name) {
$file_path = $dir .'/'. $file_name;
if ($file_name{0} === '.' && !isset($included_hidden_names[$file_name])) {
continue;
}
if (is_dir($file_path)) {
if (isset($skip_dirs[ $file_path ])) {
continue;
} else {
foreach ($skip_dirs as $skip_dir => $skip_dir_data) {
if (
strlen(preg_replace('/^'. preg_quote($file_path, '/') .'/', '', $skip_dir))
!=
strlen($skip_dir)
) {
continue 2; // skip dir it's inside current dir
}
}
}
if (!fw_ext_backups_rmdir_recursive($file_path)) {
return new WP_Error(
'dir_rm_fail',
sprintf(__('Failed to remove dir: %s', 'fw'), $file_path)
);
}
} else {
if (!unlink($file_path)) {
return new WP_Error(
'file_rm_fail',
sprintf(__('Failed to remove file: %s', 'fw'), $file_path)
);
}
}
}
return true;
}
}
/**
* @param string $source_dir path
* @param string $destination_dir path
* @param bool $fs Use WP_Filesystem or not
* @param array $skip_dirs {'path': mixed}
*
* @return WP_Error|true
*/
private function copy_dir($source_dir, $destination_dir, $fs, $skip_dirs) {
$included_hidden_names = fw_ext('backups')->get_config('included_hidden_names');
if ($fs) {
global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
$fs_source_dir = fw_fix_path(FW_WP_Filesystem::real_path_to_filesystem_path($source_dir));
if (empty($fs_source_dir)) {
return new WP_Error(
'dir_to_fs_failed',
sprintf(__('Cannot convert Filesystem path: %s', 'fw'), $source_dir)
);
} elseif (false === ($list = $wp_filesystem->dirlist($fs_source_dir, true))) {
return new WP_Error(
'dir_list_failed',
sprintf(__('Failed to list dir: %s', 'fw'), $source_dir)
);
}
foreach ($list as $file) {
if ($file['name']{0} === '.' && !isset($included_hidden_names[$file['name']])) {
continue;
}
$file_path = $source_dir .'/'. $file['name'];
$fs_file_path = $fs_source_dir .'/'. $file['name'];
$destination_file_path = $destination_dir .'/'. $file['name'];
$fs_destination_file_path = fw_fix_path(FW_WP_Filesystem::real_path_to_filesystem_path(
$destination_file_path
));
if (empty($fs_destination_file_path)) {
return new WP_Error(
'path_to_fs_failed',
sprintf(__('Cannot convert Filesystem path: %s', 'fw'), $destination_file_path)
);
}
if ($file['type'] === 'd') {
if (isset($skip_dirs[$destination_file_path])) {
continue;
} else {
foreach ($skip_dirs as $skip_dir => $skip_dir_data) {
if (
strlen(preg_replace('/^'. preg_quote($destination_file_path, '/') .'/', '', $skip_dir))
!=
strlen($skip_dir)
) {
continue 2; // skip dir if it's inside current dir
}
}
}
if (!$wp_filesystem->mkdir($fs_destination_file_path)) {
return new WP_Error(
'fs_mkdir_fail',
sprintf(__('Failed to create dir: %s', 'fw'), $destination_file_path)
);
}
if (is_wp_error($result = copy_dir(
$fs_file_path, $fs_destination_file_path
))) {
return $result;
}
} else {
if (!$wp_filesystem->copy($fs_file_path, $fs_destination_file_path)) {
return new WP_Error(
'file_copy_fail',
sprintf(__('Failed to copy file: %s', 'fw'), $file_path)
);
}
}
}
return true;
} else {
$names = array_diff(($names = scandir($source_dir)) ? $names : array(), array('.', '..'));
foreach ($names as $file_name) {
$file_path = $source_dir .'/'. $file_name;
$destination_file_path = $destination_dir .'/'. $file_name;
if ($file_name{0} === '.' && !isset($included_hidden_names[$file_name])) {
continue;
}
if (is_dir($file_path)) {
if (isset($skip_dirs[ $destination_file_path ])) {
continue;
} else {
foreach ($skip_dirs as $skip_dir => $skip_dir_data) {
if (
strlen(preg_replace('/^'. preg_quote($destination_file_path, '/') .'/', '', $skip_dir))
!=
strlen($skip_dir)
) {
continue 2; // skip dir it's inside current dir
}
}
}
if (is_dir($destination_file_path)) {
/**
* Some times empty directories are not deleted ( @see fw_ext_backups_rmdir_recursive() )
* even if rmdir() returns true, the directory remains (I don't know why),
* so a workaround is to check if it exists and do not try to created it
* (because create will return false)
*/
} elseif (!mkdir($destination_file_path)) {
return new WP_Error(
'dir_mk_fail',
sprintf(__('Failed to create dir: %s', 'fw'), $destination_file_path)
);
}
if (is_wp_error($result = $this->copy_dir(
$file_path, $destination_file_path, $fs, array()
))) {
return $result;
}
} else {
if (!copy($file_path, $destination_file_path)) {
return new WP_Error(
'file_copy_fail',
sprintf(__('Failed to copy file: %s', 'fw'), $file_path)
);
}
}
}
return true;
}
}
}

View File

@@ -0,0 +1,107 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Backups_Task_Type_Image_Sizes_Remove extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'image-sizes-remove';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Image Sizes Remove', 'fw');
}
/**
* {@inheritdoc}
* @param array $args
* * uploads_dir - path to exported uploads dir (not the actual WP uploads dir! that remains untouched)
*/
public function execute(array $args, array $state = array()) {
$backups = fw_ext('backups'); /** @var FW_Extension_Backups $backups */
{
if (empty($args['uploads_dir'])) {
return new WP_Error(
'no_uploads_dir', __('Uploads dir not specified', 'fw')
);
} else {
$args['uploads_dir'] = fw_fix_path($args['uploads_dir']);
if (!file_exists($args['uploads_dir'])) {
/**
* The uploads directory was not exported, nothing to do.
*/
return true;
}
}
}
if (empty($state)) {
$state = array(
// The attachment at which the execution stopped and will continue in next request
'attachment_id' => 0,
);
}
/**
* @var WPDB $wpdb
*/
global $wpdb;
$sql = implode( array(
"SELECT * FROM {$wpdb->posts}",
"WHERE post_type = 'attachment' AND post_mime_type LIKE %s AND ID > %d",
"ORDER BY ID",
"LIMIT 7"
), " \n");
$wp_uploads_dir = wp_upload_dir();
$wp_uploads_dir_length = mb_strlen($wp_uploads_dir['basedir']);
$max_time = time() + fw_ext( 'backups' )->get_timeout(-7);
while (time() < $max_time) {
$attachments = $wpdb->get_results( $wpdb->prepare(
$sql, $wpdb->esc_like('image/').'%', $state['attachment_id']
), ARRAY_A );
if (empty($attachments)) {
return true;
}
foreach ($attachments as $attachment) {
if (
($meta = wp_get_attachment_metadata( $attachment['ID'] ))
&&
isset( $meta['sizes'] )
&&
is_array( $meta['sizes'] )
) {
$attachment_path = get_attached_file( $attachment['ID'] );
$filename_length = mb_strlen( basename( $attachment_path ) );
foreach ( $meta['sizes'] as $size => $sizeinfo ) {
// replace wp_uploads_dir path
$file_path = $args['uploads_dir'] . mb_substr($attachment_path, $wp_uploads_dir_length);
// replace file name with resize name
$file_path = mb_substr($file_path, 0, -$filename_length) . $sizeinfo['file'];
if (file_exists($file_path)) {
@unlink( $file_path );
}
}
}
if ( is_array( $backup_sizes = get_post_meta( $attachment['ID'], '_wp_attachment_backup_sizes', true ) ) ) {
foreach ( $backup_sizes as $size ) {
$del_file = path_join( dirname( $meta['file'] ), $size['file'] );
@unlink( path_join($args['uploads_dir'], $del_file) );
}
}
}
$state['attachment_id'] = $attachment['ID'];
}
return $state;
}
}

View File

@@ -0,0 +1,188 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Backups_Task_Type_Image_Sizes_Restore extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'image-sizes-restore';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Image Sizes Restore', 'fw') .(
empty($state)
? ''
: ' '. sprintf(__('(%d of %d)', 'fw'), $state['processed_images'], $state['total_images'])
);
}
public function get_custom_timeout(array $args, array $state = array()) {
/** @var FW_Extension_Backups $backups */
$backups = fw_ext( 'backups' );
/**
* Use a small value because problems with this step are quite often
* and it is frustrating to wait 10+ minutes just to see the Timed Out error (better to see it earlier)
*/
return $backups->get_task_step_execution_threshold() - 1;
}
/**
* {@inheritdoc}
* @param array $args
*/
public function execute(array $args, array $state = array()) {
/** @var WPDB $wpdb */
global $wpdb;
$args = array_merge(
array('remove_old_files' => false),
$args
);
if ( empty( $state ) ) {
$state = array(
// The attachment at which the execution stopped and will continue in next request
'attachment_id' => 0,
// Process one image size per request
'pending_sizes' => array(),
// Collect the processed sizes and use this value as attachment meta to prevent regenerating all sizes
'processed_sizes' => array(),
// Count the processed images
'processed_images' => 0,
);
if ($state['total_images'] = $wpdb->get_col(
$wpdb->prepare(
"SELECT COUNT(1) as total_images FROM {$wpdb->posts}"
." WHERE post_type = 'attachment' AND post_mime_type LIKE %s AND post_mime_type NOT LIKE %s"
." LIMIT 1",
$wpdb->esc_like( 'image/' ) . '%',
$wpdb->esc_like( 'image/svg' ) . '%'
),
0
)) {
$state['total_images'] = array_pop($state['total_images']);
} else {
return new WP_Error(
'total_images_fail',
__('Cannot get total images count', 'fw')
);
}
}
/** @var FW_Extension_Backups $backups */
$backups = fw_ext( 'backups' );
$max_time = time() + $backups->get_timeout(
// -SECONDS that one image size can take on a very slow server
-20 // Fixes https://github.com/ThemeFuse/Unyson/issues/2257#issuecomment-272604225
);
while (time() < $max_time) {
if ( $attachment_id = $wpdb->get_col(
$wpdb->prepare(
"SELECT ID FROM {$wpdb->posts}"
." WHERE post_type = 'attachment' AND post_mime_type LIKE %s AND post_mime_type NOT LIKE %s AND ID > %d"
." ORDER BY ID"
." LIMIT 1",
$wpdb->esc_like( 'image/' ) . '%',
$wpdb->esc_like( 'image/svg' ) . '%',
$state['attachment_id']
),
0
) ) {
$attachment_id = array_pop($attachment_id);
} else {
return true;
}
if (
isset($args['remove_old_files'])
&&
$args['remove_old_files']
&&
// Only remove when we start to process a single attachment
empty($state['processed_sizes'])
) {
$this->_remove_images_without_sizes_for_attachment(
$attachment_id
);
}
if ( $file_exists = file_exists( $file = get_attached_file( $attachment_id ) ) ) {
if (empty($state['pending_sizes'])) {
$state['pending_sizes'] = apply_filters( 'fw_ext_backups_restore_exclude_img_sizes', get_intermediate_image_sizes() );
$state['processed_sizes'] = array();
}
while (time() < $max_time && !empty($state['pending_sizes'])) {
{
$this->current_size = array_shift($state['pending_sizes']);
add_filter('intermediate_image_sizes', array($this, '_filter_image_sizes'));
$meta = wp_generate_attachment_metadata($attachment_id, $file);
$this->current_size = '';
remove_filter('intermediate_image_sizes', array($this, '_filter_image_sizes'));
}
$state['processed_sizes'] = array_merge($state['processed_sizes'], $meta['sizes']);
}
if (isset($meta)) {
$meta['sizes'] = $state['processed_sizes'];
wp_update_attachment_metadata($attachment_id, $meta);
unset($meta);
}
}
if (empty($state['pending_sizes']) || !$file_exists) { // Proceed to next attachment
$state['attachment_id'] = $attachment_id;
$state['processed_sizes'] = $state['pending_sizes'] = array();
++$state['processed_images'];
}
}
return $state;
}
private $current_size = '';
/**
* Very similar to the wp-cli implementation
* https://github.com/wp-cli/media-command/blob/e5574686c01de22ef294efc57f71dc05bd7c162e/src/Media_Command.php#L530-L555
*/
public function _remove_images_without_sizes_for_attachment($attachment_id) {
$metadata = wp_get_attachment_metadata( $attachment_id );
if ( empty( $metadata['sizes'] ) ) {
return;
}
$fullsizepath = get_attached_file($attachment_id);
$dir_path = dirname( $fullsizepath ) . '/';
foreach ( $metadata['sizes'] as $size_info ) {
$intermediate_path = $dir_path . $size_info['file'];
if ( $intermediate_path === $fullsizepath )
continue;
if ( file_exists( $intermediate_path ) )
@unlink( $intermediate_path );
}
}
/**
* Leave only one image size so it will be generated fast and will prevent timeout
* @param array $sizes
* @return array
*/
public function _filter_image_sizes($sizes) {
if ($this->current_size) {
return array($this->current_size);
} else {
return $sizes;
}
}
}

View File

@@ -0,0 +1,72 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Create zip
*/
class FW_Ext_Backups_Task_Type_Unzip extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'unzip';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Archive Unzip', 'fw') .(
empty($state['extracted_files'])
? ''
: ' '. sprintf(__('(%d files extracted)', 'fw'), $state['extracted_files'])
);
}
/**
* {@inheritdoc}
* @param array $args
* * zip - file path
* * dir - where the zip file will be extract
*/
public function execute(array $args, array $state = array()) {
{
if (!isset($args['zip'])) {
return new WP_Error(
'no_zip', __('Zip file not specified', 'fw')
);
} else {
$args['zip'] = fw_fix_path($args['zip']);
}
if (!isset($args['dir'])) {
return new WP_Error(
'no_dir', __('Destination dir not specified', 'fw')
);
} else {
$args['dir'] = fw_fix_path($args['dir']);
}
}
if (empty($state)) {
if (!fw_ext_backups_is_dir_empty($args['dir'])) {
return new WP_Error(
'destination_not_empty', __('Destination dir is not empty', 'fw')
);
}
$state = array(
'entry' => '', // Last extracted file (cursor)
'extracted_files' => 0,
);
}
wp_cache_flush();
FW_Cache::clear();
if (is_wp_error($extract_result = fw_ext_backups_unzip_partial($args['zip'], $args['dir'], $state['entry']))) {
return $extract_result;
} else {
if ($extract_result['finished']) {
return true;
} else {
$state['entry'] = $extract_result['last_entry'];
$state['extracted_files'] += $extract_result['extracted_files'];
return $state;
}
}
}
}

View File

@@ -0,0 +1,169 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Create zip
*/
class FW_Ext_Backups_Task_Type_Zip extends FW_Ext_Backups_Task_Type {
public function get_type() {
return 'zip';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Archive Zip', 'fw');
}
/**
* When the zip is big, adding just a single file will recompile the entire zip.
* So it can't be executed in steps.
* {@inheritdoc}
*/
public function get_custom_timeout(array $args, array $state = array()) {
return fw_ext('backups')->get_config('max_timeout');
}
/**
* {@inheritdoc}
* @param array $args
* * source_dir - everything from this directory will be added in zip
* * destination_dir - where the zip file will be created
*
* Warning!
* Zip can't be executed in steps, it will execute way too long,
* because it is impossible to update a zip file, every time you add a file to zip,
* a new temp copy of original zip is created with new modifications, it is compressed,
* and the original zip is replaced. So when the zip will grow in size,
* just adding a single file, will take a very long time.
*/
public function execute(array $args, array $state = array()) {
{
if (!isset($args['source_dir'])) {
return new WP_Error(
'no_source_dir', __('Source dir not specified', 'fw')
);
} elseif (!file_exists($args['source_dir'] = fw_fix_path($args['source_dir']))) {
return new WP_Error(
'invalid_source_dir', __('Source dir does not exist', 'fw')
);
}
if (!isset($args['destination_dir'])) {
return new WP_Error(
'no_destination_dir', __('Destination dir not specified', 'fw')
);
} else {
$args['destination_dir'] = fw_fix_path($args['destination_dir']);
}
}
if (empty($state)) {
$state = array(
'files_count' => 0,
// generate the file name only on first step
'zip_path' => $args['source_dir'] .'/'. implode('-', array(
'fw-backup',
date('Y_m_d-H_i_s'),
fw_ext('backups')->manifest->get_version()
)) .'.zip'
);
}
{
if (!class_exists('ZipArchive')) {
return new WP_Error(
'zip_ext_missing', __('Zip extension missing', 'fw')
);
}
$zip = new ZipArchive();
if (false === ($zip_error_code = $zip->open($state['zip_path'], ZipArchive::CREATE))) {
return new WP_Error(
'cannot_open_zip', sprintf(__('Cannot open zip (Error code: %s)', 'fw'), $zip_error_code)
);
}
}
/** @var FW_Extension_Backups $ext */
$ext = fw_ext('backups');
/**
* Files for zip (in pending) are added very fast
* but on zip close the processing/zipping starts and it is time consuming
* so allocate little time for files add and leave as much time as possible for $zip->close();
*/
$max_time = time() + min( abs( $ext->get_timeout() / 2 ), 10 );
$set_compression_is_available = method_exists( $zip, 'setCompressionName' );
$files = array_slice( $this->get_all_files( $args['source_dir'] ), $state['files_count'] );
foreach ($files as $file) {
if ($execution_not_finished = (time() > $max_time)) {
break;
}
++$state['files_count'];
$file_path = fw_fix_path($file->getRealPath());
$file_zip_path = substr($file_path, strlen($args['source_dir']) + 1); // relative
if (
$file->isDir() // Skip directories (they will be created automatically)
||
$file_path === $state['zip_path'] // this happens when zip exists from previous step
||
preg_match("|^".$args['destination_dir']."/.+\\.zip\$|", $file_path) // this happens when it's a old backup zip
) {
continue;
}
$zip->addFile($file_path, $file_zip_path);
if ( $set_compression_is_available ) {
$zip->setCompressionName( $file_zip_path, apply_filters( 'fw_backup_compression_method', ZipArchive::CM_DEFAULT ) );
}
}
// Zip archive will be created only after closing the object
if ( ! $zip->close() ) {
return new WP_Error(
'cannot_close_zip', __( 'Cannot close the zip file', 'fw' )
);
}
if ( $execution_not_finished ) {
// There are more files to be processed, the execution hasn't finished
return $state;
}
/**
* Happens on Content Backup when uploads/ is empty
*/
if ( ! $files ) {
return true;
}
if (!rename($state['zip_path'], $args['destination_dir'] .'/'. basename($state['zip_path']))) {
return new WP_Error(
'cannot_move_zip',
__('Cannot move zip in destination dir', 'fw')
);
}
return true;
}
public function get_all_files( $source_dir ) {
static $all_files = array();
if ( $all_files ) {
return $all_files;
}
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $source_dir ), RecursiveIteratorIterator::LEAVES_ONLY );
foreach ( $files as $file ) {
$all_files[] = $file;
}
return $all_files;
}
}

View File

@@ -0,0 +1,7 @@
<?php if ( ! defined( 'FW' ) ) die( 'Forbidden' );
class FW_Ext_Backups_Task_Type_Download_Type_Register extends FW_Type_Register {
protected function validate_type(FW_Type $type) {
return $type instanceof FW_Ext_Backups_Task_Type_Download_Type;
}
}

View File

@@ -0,0 +1,24 @@
<?php if (!defined('FW')) die('Forbidden');
abstract class FW_Ext_Backups_Task_Type_Download_Type extends FW_Type {
/**
* @param array $args
* @param array $state
* @return string User friendly title
*/
abstract public function get_title(array $args = array(), array $state = array());
/**
* {@inheritdoc}
* @param array $args
* * destination_dir - Path to dir where the downloaded files must be placed
*/
abstract public function download(array $args, array $state = array());
public function get_custom_timeout(array $args, array $state = array()) {
/**
* Usually downloading a file takes long time
*/
return fw_ext('backups')->get_config('max_timeout');
}
}

View File

@@ -0,0 +1,149 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Backups_Task_Type_Download extends FW_Ext_Backups_Task_Type {
/**
* {@inheritdoc}
*/
public function get_type() {
return 'download';
}
/**
* {@inheritdoc}
*/
public function get_title(array $args = array(), array $state = array()) {
if (isset($args['type']) && ($type = self::get_type_($args['type']))) {
return $type->get_title($args, $state);
} else {
return __('Download', 'fw');
}
}
/**
* {@inheritdoc}
*/
public function get_custom_timeout(array $args, array $state = array()) {
if (isset($args['type']) && ($type = self::get_type_($args['type']))) {
/**
* Download type can set custom timeout
* For e.g. some download types are performed in steps and don't require timeout increase
*/
return $type->get_custom_timeout($args, $state);
} else {
/**
* Usually downloading a file takes long time
*/
return fw_ext('backups')->get_config('max_timeout');
}
}
private static $access_key;
private static function get_access_key() {
if (is_null(self::$access_key)) {
self::$access_key = new FW_Access_Key('fw:ext:backups:task-type:download');
}
return self::$access_key;
}
/**
* @var FW_Ext_Backups_Task_Type_Download_Type[]
*/
private static $types;
private static function get_types() {
if (is_null(self::$types)) {
$dir = dirname(__FILE__);
if (!class_exists('FW_Ext_Backups_Task_Type_Download_Type_Register')) {
require_once $dir .'/class-fw-ext-backups-task-type-download-type-register.php';
}
if (!class_exists('FW_Ext_Backups_Task_Type_Download_Type')) {
require_once $dir .'/class-fw-ext-backups-task-type-download-type.php';
}
$register = new FW_Ext_Backups_Task_Type_Download_Type_Register(self::get_access_key()->get_key());
{
if (!class_exists('FW_Ext_Backups_Task_Type_Download_Local')) {
require_once $dir .'/type/class-fw-ext-backups-task-type-download-local.php';
}
$register->register(new FW_Ext_Backups_Task_Type_Download_Local());
if (!class_exists('FW_Ext_Backups_Task_Type_Download_Piecemeal')) {
require_once $dir .'/type/piecemeal/class-fw-ext-backups-task-type-download-piecemeal.php';
}
$register->register(new FW_Ext_Backups_Task_Type_Download_Piecemeal());
}
do_action('fw:ext:backups:task-type:download:register:types', $register);
self::$types = $register->_get_types(self::get_access_key());
}
return self::$types;
}
/**
* @param string $type
*
* @return FW_Ext_Backups_Task_Type_Download_Type|null
*/
private static function get_type_($type) {
$types = self::get_types();
if (isset($types[$type])) {
return $types[$type];
} else {
return null;
}
}
/**
* {@inheritdoc}
* @param array $args
* * type - registered download type
* * type_args - args for registered type instance
* * destination_dir - Where must be placed the downloaded files
*/
public function execute(array $args, array $state = array()) {
if (empty($args['destination_dir'])) {
return new WP_Error(
'no_destination_dir',
__('Destination dir not specified', 'fw')
);
} elseif (!($args['destination_dir'] = fw_fix_path($args['destination_dir']))) {
return new WP_Error(
'invalid_destination_dir',
__('Invalid destination dir', 'fw')
);
}
if (
empty($args['type'])
||
!($type = self::get_types())
||
!isset($type[ $args['type'] ])
) {
return new WP_Error(
'invalid_type',
sprintf(__('Invalid type: %s', 'fw'), $args['type'])
);
}
$type = $type[ $args['type'] ];
if (empty($args['type_args'])) {
return new WP_Error(
'no_type_args',
sprintf(__('Args not specified for type: %s', 'fw'), $type->get_type())
);
}
$args['type_args'] = array_merge($args['type_args'], array('destination_dir' => $args['destination_dir']));
return $type->download($args['type_args'], $state);
}
}

View File

@@ -0,0 +1,73 @@
<?php if ( ! defined( 'FW' ) ) die( 'Forbidden' );
class FW_Ext_Backups_Task_Type_Download_Local extends FW_Ext_Backups_Task_Type_Download_Type {
public function get_type() {
return 'local';
}
public function get_title(array $args = array(), array $state = array()) {
return __('Local Download', 'fw');
}
/**
* {@inheritdoc}
* @param $args
* * destination_dir - Path to dir where the downloaded files must be placed
* * source - Path to dir or zip file
*/
public function download(array $args, array $state = array()) {
// Note: destination_dir is already validated
if (empty($args['source'])) {
return new WP_Error(
'no_source',
__('Source not specified', 'fw')
);
} elseif (!file_exists($args['source'] = fw_fix_path($args['source']))) {
return new WP_Error(
'invalid_source',
__('Invalid source', 'fw')
);
} elseif (
!($is_dir = is_dir($args['source']))
||
!($is_zip = (substr($args['source'], -4, 4) !== '.zip'))
) {
return new WP_Error(
'invalid_source_type',
__('Invalid source type', 'fw')
);
}
if ($is_dir) {
return fw_ext_backups_copy_dir_recursive(
$args['source'],
$args['destination_dir']
);
} elseif ($is_zip) {
if (!class_exists('ZipArchive')) {
return new WP_Error(
'zip_ext_missing', __('Zip extension missing', 'fw')
);
}
$zip = new ZipArchive();
if (true === $zip->open($args['source'])) {
return new WP_Error(
'zip_open_fail',
sprintf(__('Cannot open zip: %s', 'fw'), $args['source'])
);
}
$zip->extractTo($args['destination_dir']);
$zip->close();
unset($zip);
return true;
} else {
return new WP_Error('unhandled_type', __('Unhandled type', 'fw'));
}
}
}

View File

@@ -0,0 +1,238 @@
<?php if ( ! defined( 'FW' ) ) die( 'Forbidden' );
/**
* Download zip piece by piece (not at once, to prevent timeout)
*/
class FW_Ext_Backups_Task_Type_Download_Piecemeal extends FW_Ext_Backups_Task_Type_Download_Type {
public function get_type() {
return 'piecemeal';
}
public function get_title(array $args = array(), array $state = array()) {
if (empty($state)) {
return __( 'Downloading', 'fw' );
} elseif ('download' === $state['type']) {
if (!empty($state['filesize']) && $state['position']) {
return sprintf(
__( 'Downloading (%s of %s)', 'fw' ),
size_format($state['position']), size_format($state['filesize'])
);
} else {
return __( 'Downloading', 'fw' );
}
} elseif ('unzip' === $state['type']) {
if ($state['extracted_files']) {
return sprintf(__('Archive Unzip (%d files extracted)', 'fw'), $state['extracted_files']);
} else {
return __('Download finished. Doing unzip', 'fw');
}
} else {
return __( 'Downloading (invalid state)', 'fw' );
}
}
private function get_min_piece_size() {
return $this->get_mb_in_bytes();
}
private function get_mb_in_bytes() {
return 1000 * 1000;
}
/**
* {@inheritdoc}
* @param $args
* * destination_dir - Path to dir where the downloaded files must be placed
* * url - Remote php script that will send the pieces of the zip file
* * file_id - File name/id registered in server script
*/
public function download(array $args, array $state = array()) {
// Note: destination_dir is already validated
{
if (empty($args['url'])) {
return new WP_Error(
'no_url',
__('Url not specified', 'fw')
);
} elseif (filter_var($args['url'], FILTER_VALIDATE_URL) === false) {
return new WP_Error(
'invalid_url',
__('Invalid url', 'fw')
);
}
if (empty($args['file_id'])) {
return new WP_Error(
'no_file_id',
__('File id not specified', 'fw')
);
} elseif (!is_string($args['file_id'])) {
return new WP_Error(
'invalid_file_id',
__('Invalid file id', 'fw')
);
}
}
if (empty($state)) {
$state = array(
'type' => 'download', // 'unzip'
'position' => 0, // byte position in file (also can be used as 'downloaded bytes')
'file_size' => 0, // total file size in bytes
'piece_size' => $this->get_mb_in_bytes() * 3, // piece size in bytes
);
}
$zip_path = $args['destination_dir'] .'/'. $this->get_type() .'.zip';
if ('download' === $state['type']) {
if (true === ($state = $this->do_download($args, $state, $zip_path))) {
return array(
'type' => 'unzip',
'entry' => '',
'extracted_files' => 0
);
} else {
return $state;
}
} elseif ('unzip' === $state['type']) {
return $this->do_unzip($args, $state, $zip_path);
} else {
return new WP_Error(
'invalid_state',
__('Partial download invalid state', 'fw')
);
}
}
private function do_download($args, $state, $zip_path) {
/** @var FW_Extension_Backups $backups */
$backups = fw_ext('backups');
$response = wp_remote_get(add_query_arg(
array_merge(
/**
* @since 2.0.18
*/
apply_filters(
'fw:ext:backups:task-type:piecemeal-download:query-args',
$default_query_args = array(
'id' => urlencode($args['file_id']),
'position' => $state['position'],
'size' => $state['piece_size']
),
$args
),
$default_query_args
),
$args['url']
), array(
'timeout' => $backups->get_timeout() - 7
));
if (is_wp_error($response)) {
if (
($state['piece_size'] = abs($state['piece_size'] - $this->get_mb_in_bytes()))
&&
$state['piece_size'] >= $this->get_min_piece_size()
) {
return $state;
}
return $response;
} elseif (200 !== ($response_code = intval(wp_remote_retrieve_response_code($response)))) {
return new WP_Error(
'request_failed',
sprintf(__('Request failed. Error code: %d', 'fw'), $response_code)
);
} elseif (
(
!($position = intval(isset($response['headers']['x-position']) ? $response['headers']['x-position'] : 0))
||
($position > 0 && $position <= $state['position'])
)
) {
return new WP_Error(
'invalid_position',
__('Invalid byte position', 'fw') .' (current: '. $state['position'] .', received: '. $position .')'
);
} elseif ($position > 0 && empty($response['body'])) {
return new WP_Error(
'empty_body',
__('Empty response body', 'fw')
);
}
if (!$state['position']) {
if (
($filesize = intval(isset($response['headers']['x-filesize']) ? $response['headers']['x-filesize'] : 0))
&&
$filesize > 0
&&
$filesize > $position
) {
$state['filesize'] = $filesize;
}
}
if ($position < 0) {
if (!$state['position']) {
return new WP_Error(
'empty_file',
__('File ended without content', 'fw')
);
}
$state['position'] = $position;
return true;
}
$state['position'] = $position;
if (!($f = fopen($zip_path, $state['position'] ? 'a' : 'w'))) {
return new WP_Error(
'file_open_fail',
__('Failed to open file', 'fw')
);
}
if (substr($response['body'], 0, 3) === "\xEF\xBB\xBF") {
/**
* Remove UTF-8 BOM added by the server
* Fixes https://github.com/ThemeFuse/Unyson-Backups-Extension/issues/25
*/
$response['body'] = substr($response['body'], 3);
}
$write_result = fwrite($f, $response['body']);
fclose($f);
if (false === $write_result) {
return new WP_Error(
'file_write_fail',
__('Failed to write data to file', 'fw')
);
}
return $state;
}
private function do_unzip($args, $state, $zip_path) {
if (is_wp_error($extract_result = fw_ext_backups_unzip_partial(
$zip_path, $args['destination_dir'], $state['entry'], 1
))) {
return $extract_result;
} else {
if ($extract_result['finished']) {
return true;
} else {
$state['entry'] = $extract_result['last_entry'];
$state['extracted_files'] += $extract_result['extracted_files'];
return $state;
}
}
}
}

View File

@@ -0,0 +1,10 @@
<?php
/**
* Overwrite default config
*/
$cfg = array(
'files' => array(
// 'demo-id' => '/path/to/demo.zip',
),
);

View File

@@ -0,0 +1,118 @@
<?php
/**
* Send parts of file contents
*/
$megabyte = 1000 * 1000;
{
$cfg = array();
/**
* You can create `config.php` in the same directory to overwrite default config
*/
if (file_exists($config_path = dirname(__FILE__) .'/config.php')) {
include $config_path;
}
$cfg = array_merge(array(
'files' => array(
// 'demo-id' => '/path/to/demo.zip',
),
'size' => $megabyte * 3, // piece size in bytes
), $cfg);
if (empty($cfg['files'])) {
header('HTTP/1.1 500 Internal Server Error');
exit;
}
}
{
{ // file id
if (empty($_GET['id'])) {
header('HTTP/1.1 400 Bad Request');
exit;
}
$id = $_GET['id'];
if (!isset($cfg['files'][ $id ])) {
header('HTTP/1.1 400 Bad Request');
exit;
}
}
{ // file byte position
if (
!isset($_GET['position'])
||
!is_numeric($_GET['position'])
) {
header('HTTP/1.1 400 Bad Request');
exit;
}
$position = intval($_GET['position']);
if ($position < 0) {
header('HTTP/1.1 400 Bad Request');
exit;
}
}
if (isset($_GET['size'])) { // custom piece size requested by client
$size = $_GET['size'];
if (
is_numeric($size)
&&
($size = intval($size))
&&
$size > 0
&&
$size < $megabyte * 10
) {
$cfg['size'] = $size;
} else {
header('HTTP/1.1 400 Bad Request');
exit;
}
}
}
$f = fopen($cfg['files'][ $id ], 'r');
if (!$f) {
header('HTTP/1.1 500 Internal Server Error');
exit;
}
if (-1 === fseek($f, $position)) {
header('HTTP/1.1 500 Internal Server Error');
exit;
}
if (false === ($data = fread($f, $cfg['size']))) {
header('HTTP/1.1 500 Internal Server Error');
exit;
}
$f = null;
$data_length = strlen($data);
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('X-Position: '. ($data_length ? ($position + $data_length) : '-1'));
if (!$position) {
if ( $filesize = filesize( $cfg['files'][ $id ] ) ) {
header( 'X-Filesize: ' . $filesize );
} else {
header( 'HTTP/1.1 500 Internal Server Error' );
exit;
}
}
echo $data;

View File

@@ -0,0 +1,43 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @param _FW_Ext_Backups_Task_Type_Register $task_types
* @internal
*/
function _action_fw_ext_backups_register_built_in_task_types(_FW_Ext_Backups_Task_Type_Register $task_types) {
$dir = dirname(__FILE__);
require_once $dir .'/class-fw-ext-backups-task-type-db-export.php';
$task_types->register(new FW_Ext_Backups_Task_Type_DB_Export());
require_once $dir .'/class-fw-ext-backups-task-type-db-restore.php';
$task_types->register(new FW_Ext_Backups_Task_Type_DB_Restore());
require_once $dir .'/class-fw-ext-backups-task-type-dir-clean.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Dir_Clean());
require_once $dir .'/class-fw-ext-backups-task-type-zip.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Zip());
require_once $dir .'/class-fw-ext-backups-task-type-unzip.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Unzip());
require_once $dir .'/class-fw-ext-backups-task-type-files-export.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Files_Export());
require_once $dir .'/class-fw-ext-backups-task-type-files-restore.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Files_Restore());
require_once $dir .'/class-fw-ext-backups-task-type-image-sizes-remove.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Image_Sizes_Remove());
require_once $dir .'/class-fw-ext-backups-task-type-image-sizes-restore.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Image_Sizes_Restore());
require_once $dir .'/download/class-fw-ext-backups-task-type-download.php';
$task_types->register(new FW_Ext_Backups_Task_Type_Download());
}
add_action(
'fw_ext_backups_task_types_register',
'_action_fw_ext_backups_register_built_in_task_types'
);

View File

@@ -0,0 +1,26 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
$manifest = array();
$manifest['name'] = __( 'Backup & Demo Content', 'fw' );
$manifest['description'] = __(
'This extension lets you create an automated backup schedule,'
.' import demo content or even create a demo content archive for migration purposes.',
'fw'
);
$manifest['author'] = 'ThemeFuse';
$manifest['author_uri'] = 'http://themefuse.com/';
$manifest['github_repo'] = 'https://github.com/ThemeFuse/Unyson-Backups-Extension';
$manifest['uri'] = 'http://manual.unyson.io/en/latest/extension/backups/index.html';
$manifest['version'] = '2.0.32';
$manifest['display'] = true;
$manifest['standalone'] = true;
$manifest['requirements'] = array(
'framework' => array(
'min_version' => '2.6.16',
),
);
$manifest['github_update'] = 'ThemeFuse/Unyson-Backups-Extension';

View File

@@ -0,0 +1,616 @@
/**
* Other scripts use this
* @type {boolean}
*/
var fw_ext_backups_is_busy = false;
/**
* Check current status
*/
jQuery(function ($) {
var inst = {
localized: _fw_ext_backups_localized,
getEventName: function(name) {
return 'fw:ext:backups:status:'+ name;
},
timeoutId: 0,
timeoutTime: 3000,
/**
* 0 - (false) not busy
* 1 - (true) busy
* 2 - (true) busy and a pending ajax
*/
isBusy: 0,
doAjax: function() {
if (this.isBusy) {
this.isBusy = 2;
return false;
}
clearTimeout(this.timeoutId);
fwEvents.trigger(this.getEventName('updating'));
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: this.localized.ajax_action_status
}
})
.done(_.bind(function(r){
if (r.success) {
fwEvents.trigger(this.getEventName('update'), r.data);
} else {
fwEvents.trigger(this.getEventName('update-fail'));
}
}, this))
.fail(_.bind(function(jqXHR, textStatus, errorThrown){
console.error('Ajax error', jqXHR, textStatus, errorThrown);
fwEvents.trigger(this.getEventName('update-fail'));
}, this))
.always(_.bind(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fwEvents.trigger(this.getEventName('updated'));
if (this.isBusy === 2) {
this.isBusy = 0;
this.doAjax();
} else {
this.isBusy = 0;
}
this.timeoutId = setTimeout(_.bind(this.doAjax, this), this.timeoutTime);
}, this));
return true;
},
onUpdate: function(data) {
this.timeoutTime = data.is_busy ? 3000 : 10000;
fw_ext_backups_is_busy = data.is_busy;
},
init: function(){
this.init = function(){};
fwEvents.on(this.getEventName('do-update'), _.bind(function(){ this.doAjax(); }, this));
fwEvents.on(this.getEventName('update'), _.bind(function(data){ this.onUpdate(data); }, this));
this.doAjax();
}
};
// let other scripts to listen events
setTimeout(function(){ inst.init(); }, 12);
});
/**
* Current tasks status
*/
jQuery(function($){
var inst = {
$el: $('#fw-ext-backups-status'),
failCount: 0,
onUpdating: function(){},
onUpdate: function(data) {
this.$el.html(data.tasks_status.html);
this.failCount = 0;
},
onUpdateFail: function() {
if (this.failCount > 3) {
this.$el.html(
'<span class="fw-text-danger dashicons dashicons-warning" style="vertical-align: text-bottom;">' +
'</span> <em>ajax errors</em>'
);
}
++this.failCount;
},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups:status:updated': _.bind(this.onUpdated, this)
});
}
};
inst.init();
});
/**
* 'Backup Now' buttons
*/
jQuery(function($){
var inst = {
localized: _fw_ext_backups_localized,
$buttons: $('.fw-ext-backups-backup-now'),
fwLoadingId: 'fw-ext-loading-backup-now',
onUpdating: function(){
this.$buttons.addClass('busy');
},
onUpdate: function(data) {
if (!data.is_busy) {
this.$buttons.removeClass('busy');
}
},
onUpdateFail: function() {},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups:status:updated': _.bind(this.onUpdated, this)
});
this.$buttons.on('click', function(){
if ($(this).hasClass('busy')) {
return;
}
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: inst.localized.ajax_action_backup,
full: $(this).attr('data-full')
}
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups:status:do-update');
window.scrollTo(0, 0);
} else {
fw.soleModal.show(
'fw-ext-backups-restore-error',
'<h2>Error</h2>'
);
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-backup-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fw.loading.hide(inst.fwLoadingId);
});
});
}
};
inst.init();
});
/**
* Archives list
*/
jQuery(function($){
var inst = {
localized: _fw_ext_backups_localized,
$el: $('#fw-ext-backups-archives'),
fwLoadingId: 'fw-ext-backups-archives',
modal: new fw.Modal({
title: ' ',
size: 'small'
}),
onUpdating: function(){},
onUpdate: function(data) {
var checkedRadio = inst.$el.find('input[type=radio][name=archive]:checked').val();
this.$el.html(data.archives.html);
if (checkedRadio) {
inst.$el.find('input[type=radio][name=archive]')
.filter(function(){ return $(this).val() === checkedRadio; })
.first()
.trigger('click');
}
this.$el[data.archives.count ? 'removeClass' : 'addClass']('no-archives');
},
onUpdateFail: function() {},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups:status:updated': _.bind(this.onUpdated, this)
});
this.modal.on('closing', function(){
$('#fw-ext-backups-filesystem-form form').append(
// move the form html back in page, to prevent to be deleted
$('#request-filesystem-credentials-form')
);
});
this.modal.once('open', function(){
inst.modal.content.$el.on('submit', function(){
// click again on Restore button to make an ajax request
inst.$el.find('.fw-ext-backups-archive-restore-button:first').trigger('click');
});
});
this.$el.on('click', 'input[type=radio][name=archive]', function(){
inst.$el.find('.fw-ext-backups-archive-restore-button').removeAttr('disabled');
});
this.$el.on('click', '.fw-ext-backups-archive-restore-button', function(){
if (fw_ext_backups_is_busy) {
window.scrollTo(0, 0);
return;
}
var $radio = inst.$el.find('input[type=radio][name=archive]:checked'),
file = $radio.val(),
$button = $(this),
confirm_message = $button.attr('data-confirm'),
fs_args = undefined;
if (!$radio.length && !file) {
return;
}
if (confirm_message) {
if (!confirm(confirm_message)) {
return;
}
}
if (inst.modal.content.$el.find('#request-filesystem-credentials-form')) {
fs_args = {
hostname: inst.modal.content.$el.find('input[name="hostname"]').val(),
username: inst.modal.content.$el.find('input[name="username"]').val(),
password: inst.modal.content.$el.find('input[name="password"]').val(),
connection_type: inst.modal.content.$el.find('input[name="connection_type"]').val()
};
}
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: inst.localized.ajax_action_restore,
file: file,
filesystem_args: fs_args
}
})
.done(function(r){
if (r.success) {
inst.modal.close();
fwEvents.trigger('fw:ext:backups:status:do-update');
inst.$el.find('input[type=radio][name=archive]').prop('checked', false);
window.scrollTo(0, 0);
} else if (r.data.request_fs) {
inst.modal.open(); // here the html is replaced with 'html' attribute value
inst.modal.content.$el.html('').css('padding', '0 20px').append(
$('#request-filesystem-credentials-form')
);
} else {
fw.soleModal.show(
'fw-ext-backups-restore-error',
r.data.message ? r.data.message : 'Error'
);
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-restore-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fw.loading.hide(inst.fwLoadingId);
});
});
this.$el.on('click', '[data-delete-file]', function(){
var $this = $(this),
confirm_message = $this.attr('data-confirm');
if (fw_ext_backups_is_busy) {
window.scrollTo(0, 0);
return;
}
if (confirm_message) {
if (!confirm(confirm_message)) {
return;
}
}
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: inst.localized.ajax_action_delete,
file: $(this).attr('data-delete-file')
}
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups:status:do-update');
} else {
fw.soleModal.show(
'fw-ext-backups-delete-error',
'<h2>Error</h2>'
);
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-delete-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fw.loading.hide(inst.fwLoadingId);
});
});
this.$el.on('click', '[data-download-file]', function(e) {
if (fw_ext_backups_is_busy) {
e.preventDefault();
window.scrollTo(0, 0);
return;
}
});
}
};
inst.init();
});
/**
* Schedule settings
*/
jQuery(function($){
var inst = {
modal: new fw.OptionsModal(),
localized: _fw_ext_backups_localized.schedule,
isBusy: false,
fwLoadingId: 'fw-ext-backups-schedule',
openModal: function() {
if (this.isBusy) {
return false;
}
this.isBusy = true;
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: inst.localized.ajax_action.get_settings
}
})
.done(function(r){
if (r.success) {
inst.modal.set('options', r.data.options);
inst.modal.off('change:values', inst.onModalValuesChange);
inst.modal.set('values', r.data.values);
inst.modal.on('change:values', inst.onModalValuesChange);
inst.modal.open();
} else {
fw.soleModal.show(inst.fwLoadingId, '<h2>Error</h2>');
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
inst.fwLoadingId,
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fw.loading.hide(inst.fwLoadingId);
inst.isBusy = false;
});
},
onModalValuesChange: function(){
if (inst.isBusy) {
console.error('The script is busy');
return;
}
inst.isBusy = true;
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: inst.localized.ajax_action.set_settings,
values: inst.modal.get('values')
}
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups:status:do-update');
} else {
fw.soleModal.show(inst.fwLoadingId, '<h2>Error</h2>');
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
inst.fwLoadingId,
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
fw.loading.hide(inst.fwLoadingId);
inst.isBusy = false;
});
},
init: function(){
this.modal.set('title', this.localized.popup_title);
$('#fw-ext-backups-edit-schedule').on('click', function(){
inst.openModal();
});
this.modal.on('change:values', this.onModalValuesChange);
}
};
inst.init();
});
/**
* Schedule status
*/
jQuery(function($){
var inst = {
$el: $('#fw-ext-backups-schedule-status'),
onUpdating: function(){},
onUpdate: function(data) {
this.$el.html(data.schedule.status_html);
},
onUpdateFail: function() {},
onUpdated: function() {},
init: function(){
fwEvents.on({
'fw:ext:backups:status:updating': _.bind(this.onUpdating, this),
'fw:ext:backups:status:update': _.bind(this.onUpdate, this),
'fw:ext:backups:status:update-fail': _.bind(this.onUpdateFail, this),
'fw:ext:backups:status:updated': _.bind(this.onUpdated, this)
});
}
};
inst.init();
});
/**
* "Cancel" functionality
*/
jQuery(function($){
var inst = {
localized: _fw_ext_backups_localized,
isBusy: false,
fwLoadingId: 'fw-ext-backups-cancel',
doCancel: function(){
if (this.isBusy) {
return;
} else {
if (!confirm(this.localized.l10n.abort_confirm)) {
return;
}
this.isBusy = true;
}
inst.isBusy = true;
fw.loading.show(inst.fwLoadingId);
$.ajax({
url: ajaxurl,
data: {
action: inst.localized.ajax_action_cancel
},
type: 'POST',
dataType: 'json'
})
.done(function(r){
if (r.success) {
fwEvents.trigger('fw:ext:backups:status:do-update');
} else {
console.warn('Cancel failed');
}
})
.fail(function(jqXHR, textStatus, errorThrown){
fw.soleModal.show(
'fw-ext-backups-demo-install-error',
'<h2>Ajax error</h2>'+ '<p>'+ String(errorThrown) +'</p>'
);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown){
inst.isBusy = false;
fw.loading.hide(inst.fwLoadingId);
});
},
init: function(){
var that = this;
fwEvents.on('fw:ext:backups:cancel', function(){
that.doCancel();
});
}
};
inst.init();
});
/**
* If loopback request failed, execute steps via ajax
* @since 2.0.5
*/
jQuery(function($){
if (typeof fw_ext_backups_loopback_failed == 'undefined') {
return;
}
var inst = {
running: false,
isBusy: false,
onUpdate: function(data) {
this.running = data.is_busy;
this.executeNextStep(data.ajax_steps.token, data.ajax_steps.active_tasks_hash);
},
executeNextStep: function(token, activeTasksHash){
if (!this.running || this.isBusy) {
return false;
}
this.isBusy = true;
$.ajax({
url: ajaxurl,
data: {
action: 'fw:ext:backups:continue-pending-task',
token: token,
active_tasks_hash: activeTasksHash
},
type: 'POST',
dataType: 'json'
})
.done(function(r){ console.log(r);
if (r.success) {
fwEvents.trigger('fw:ext:backups:status:do-update');
} else {
console.error('Ajax execution failed');
// execution will try to continue on next (auto) update
}
})
.fail(_.bind(function(jqXHR, textStatus, errorThrown){
console.error('Ajax error: '+ String(errorThrown));
}, this))
.always(_.bind(function(data_jqXHR, textStatus, jqXHR_errorThrown){
this.isBusy = false;
}, this));
},
init: function(){
fwEvents.on('fw:ext:backups:status:update', _.bind(this.onUpdate, this));
}
};
inst.init();
});

View File

@@ -0,0 +1,21 @@
#fw-ext-backups-status {
font-size: 13px;
font-weight: normal;
}
#fw-ext-backups-status img {
vertical-align: text-bottom;
}
#fw-ext-backups-archives table thead,
#fw-ext-backups-archives table tfoot,
#fw-ext-backups-archives .tablenav.bottom .tablenav-pages,
#fw-ext-backups-archives .tablenav .bulkactions,
#fw-ext-backups-archives.no-archives .tablenav {
display: none;
}
.fw-ext-backups-description ul {
list-style-type: disc;
padding-left: 18px;
}

View File

@@ -0,0 +1,22 @@
<?php if ( ! defined( 'FW' ) ) die( 'Forbidden' );
/**
* @var array $archives
* @var bool $is_busy
*/
/**
* @var FW_Extension_Backups $backups
*/
$backups = fw_ext('backups');
if (!class_exists('_FW_Ext_Backups_List_Table')) {
fw_include_file_isolated(
fw_ext('backups')->get_path('/includes/list-table/class--fw-ext-backups-list-table.php')
);
}
$list_table = new _FW_Ext_Backups_List_Table(array(
'archives' => $archives
));
$list_table->display();

View File

@@ -0,0 +1,75 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @var string $archives_html
*/
?>
<?php
$backups = fw_ext( 'backups' ); /** @var FW_Extension_Backups $backups */
$page_url = $backups->get_page_url();
?>
<h2><?php esc_html_e('Backup', 'fw') ?> <span id="fw-ext-backups-status"></span></h2>
<div>
<?php if ( !class_exists('ZipArchive') ): ?>
<div class="error below-h2">
<p>
<strong><?php _e( 'Important', 'fw' ); ?></strong>:
<?php printf(
__( 'You need to activate %s.', 'fw' ),
'<a href="http://php.net/manual/en/book.zip.php" target="_blank">'. __('zip extension', 'fw') .'</a>'
); ?>
</p>
</div>
<?php endif; ?>
<?php if ($http_loopback_warning = fw_ext_backups_loopback_test()) : ?>
<div class="error">
<p><strong><?php _e( 'Important', 'fw' ); ?>:</strong> <?php echo $http_loopback_warning; ?></p>
</div>
<script type="text/javascript">var fw_ext_backups_loopback_failed = true;</script>
<?php endif; ?>
<div class="fw-ext-backups-description">
<p class="description"><?php esc_html_e( 'Here you can create a backup schedule for your website.', 'fw' ); ?></p>
<ul>
<?php if (fw_ext_backups_current_user_can_full()): ?>
<li>
<span class="description">
<strong><?php esc_html_e('Full Backup', 'fw'); ?></strong>
- <?php esc_html_e('will save your themes, plugins, uploads and full database.'); ?>
</span>
</li>
<?php endif; ?>
<li>
<span class="description">
<strong><?php esc_html_e('Content Backup', 'fw'); ?></strong>
- <?php esc_html_e('will save your uploads and database without private data like users, admin email, etc.'); ?>
</span>
</li>
</ul>
</div>
<div id="fw-ext-backups-schedule-status"></div>
<div>
<a href="#" onclick="return false;" id="fw-ext-backups-edit-schedule"
class="button button-primary"><?php esc_html_e( 'Edit Backup Schedule', 'fw' ) ?></a>
&nbsp;
<?php if (fw_ext_backups_current_user_can_full()): ?>
<a href="#" onclick="return false;" id="fw-ext-backups-full-backup-now"
class="button fw-ext-backups-backup-now" data-full="1"><?php esc_html_e('Create Full Backup Now', 'fw') ?></a>
&nbsp;
<?php endif; ?>
<a href="#" onclick="return false;" id="fw-ext-backups-content-backup-now"
class="button fw-ext-backups-backup-now" data-full=""><?php esc_html_e('Create Content Backup Now', 'fw'); ?></a>
</div>
</div>
<br>
<h3><?php _e( 'Archives', 'fw' ) ?></h3>
<div id="fw-ext-backups-archives"><?php echo $archives_html; ?></div>
<br>
<?php do_action('fw_ext_backups_page_footer'); ?>

View File

@@ -0,0 +1,42 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @var null|FW_Ext_Backups_Task_Collection $active_task_collection
* @var null|FW_Ext_Backups_Task $executing_task
* @var null|FW_Ext_Backups_Task $pending_tasks
*/
/**
* @var FW_Extension_Backups $backups
*/
$backups = fw_ext('backups');
?>
<?php if ($active_task_collection): ?>
<img src="<?php echo get_site_url() ?>/wp-admin/images/spinner.gif" alt="Loading">
<em class="fw-text-muted"><?php
if ($executing_task) {
echo esc_html($backups->tasks()->get_task_type_title(
$executing_task->get_type(),
$executing_task->get_args(),
$executing_task->get_result()
));
} elseif ($pending_tasks) {
echo esc_html($backups->tasks()->get_task_type_title(
$pending_tasks->get_type(),
$pending_tasks->get_args(),
$pending_tasks->get_result()
));
} else {
esc_html_e('Unknown task');
}
?></em>
<?php else: ?>
<em class="fw-text-muted" style="color: transparent;"><?php esc_html_e('Nothing running in background', 'fw'); ?></em>
<?php endif; ?>
<?php if ($active_task_collection && $active_task_collection->is_cancelable()): ?>
<a href="#" onclick="fwEvents.trigger('fw:ext:backups:cancel'); return false;"><em><?php
esc_html_e('Abort', 'fw');
?></em></a>
<?php endif; ?>