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; ?>

View File

@@ -0,0 +1,90 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
class FW_Extension_Blog extends FW_Extension {
private $post_type = 'post';
/**
* @internal
*/
public function _init() {
if ( is_admin() ) {
add_action( 'admin_menu', array( $this, '_admin_action_rename_post_menu' ) );
add_action( 'init', array( $this, '_admin_action_change_post_labels' ), 999 );
} else {
add_action( 'init', array( $this, '_theme_action_change_post_labels' ), 999 );
}
}
/**
* Changes the labels value od the posts type: post from Post to Blog Post
* @internal
*/
public function _theme_action_change_post_labels() {
global $wp_post_types;
$p = $this->post_type;
// Someone has changed this post type, always check for that!
if ( empty ( $wp_post_types[ $p ] )
or ! is_object( $wp_post_types[ $p ] )
or empty ( $wp_post_types[ $p ]->labels )
) {
return;
}
$wp_post_types[ $p ]->labels->name = __( 'Blog', 'fw' );
$wp_post_types[ $p ]->labels->singular_name = __( 'Blog', 'fw' );
$wp_post_types[ $p ]->labels->add_new = __( 'Add blog post', 'fw' );
$wp_post_types[ $p ]->labels->add_new_item = __( 'Add new blog post', 'fw' );
$wp_post_types[ $p ]->labels->all_items = __( 'All blog posts', 'fw' );
$wp_post_types[ $p ]->labels->edit_item = __( 'Edit blog post', 'fw' );
$wp_post_types[ $p ]->labels->name_admin_bar = __( 'Blog Post', 'fw' );
$wp_post_types[ $p ]->labels->menu_name = __( 'Blog Post', 'fw' );
$wp_post_types[ $p ]->labels->new_item = __( 'New blog post', 'fw' );
$wp_post_types[ $p ]->labels->not_found = __( 'No blog posts found', 'fw' );
$wp_post_types[ $p ]->labels->not_found_in_trash = __( 'No blog posts found in trash', 'fw' );
$wp_post_types[ $p ]->labels->search_items = __( 'Search blog posts', 'fw' );
$wp_post_types[ $p ]->labels->view_item = __( 'View blog post', 'fw' );
}
/**
* Changes the labels value od the posts type: post from Post to Blog Post
* @internal
*/
public function _admin_action_change_post_labels() {
global $wp_post_types, $wp_taxonomies;
$p = $this->post_type;
// Someone has changed this post type, always check for that!
if ( empty ( $wp_post_types[ $p ] )
or ! is_object( $wp_post_types[ $p ] )
or empty ( $wp_post_types[ $p ]->labels )
) {
return;
}
$wp_post_types[ $p ]->labels->name = __( 'Blog Posts', 'fw' );
if ( empty ( $wp_taxonomies['category'] )
or ! is_object( $wp_taxonomies['category'] )
or empty ( $wp_taxonomies['category']->labels )
) {
return;
}
$wp_taxonomies['category']->labels->name = __( 'Blog Categories', 'fw' );
}
/**
* Changes the name in admin menu from Post to Blog Post
* @internal
*/
public function _admin_action_rename_post_menu() {
global $menu;
if ( isset( $menu[5] ) ) {
$menu[5][0] = __( 'Blog Posts', 'fw' );
}
}
}

View File

@@ -0,0 +1,13 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
$manifest = array();
$manifest['name'] = __( 'Blog Posts', 'fw' );
$manifest['description'] = __( 'Blog Posts', 'fw' );
$manifest['version'] = '1.0.2';
$manifest['display'] = false;
$manifest['standalone'] = true;
$manifest['github_update'] = 'ThemeFuse/Unyson-Blog-Extension';

View File

@@ -0,0 +1,44 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
class FW_Extension_Breadcrumbs extends FW_Extension {
/**
* @internal
*/
public function _init() {
}
/**
* Creates the breadcrumbs HTML
*
* @param string $separator , separator symbol that will be set between elements
*
* @return string
*/
public function render( $separator = ">" ) {
$data = array(
'labels' => array()
);
$settings['labels']['homepage-title'] = fw_get_db_ext_settings_option( $this->get_name(), 'homepage-title' );
$settings['labels']['blogpage-title'] = fw_get_db_ext_settings_option( $this->get_name(), 'blogpage-title' );
$settings['labels']['404-title'] = fw_get_db_ext_settings_option( $this->get_name(), '404-title' );
$breadcrumbs = new Breadcrumbs_Builder( $settings );
$data['items'] = $breadcrumbs->get_breadcrumbs();
$data['separator'] = $separator;
return $this->render_view( 'breadcrumbs', $data );
}
/**
* Returns an hardcoded id for the breadcrumbs option
* @return string
*/
public function get_option_id() {
return $this->get_name() . '-option';
}
}

View File

@@ -0,0 +1,23 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
/**
* Returns the breadcrumbs HTML
*
* @param string $separator, separator symbol that will be set between elements
*
* @return string
*/
function fw_ext_get_breadcrumbs( $separator = ">" ) {
return fw()->extensions->get( 'breadcrumbs' )->render( $separator, false, 'breadcrumbs' );
}
/**
* Displays the breadcrumbs HTML
*
* @param string $separator, separator symbol that will be set between elements
*/
function fw_ext_breadcrumbs( $separator = ">" ) {
echo fw()->extensions->get( 'breadcrumbs' )->render( $separator, false, 'breadcrumbs' );
}

View File

@@ -0,0 +1,312 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
class Breadcrumbs_Builder {
public function __construct( $settings = array() ) {
$this->settings['labels'] = array(
'homepage-title' => __( 'Homepage', 'fw' ),
'blogpage-title' => __( 'Blog', 'fw' ),
'404-title' => __( '404 Not found', 'fw' ),
);
if ( isset( $settings['labels'] ) ) {
$this->settings['labels'] = array_merge( $this->settings['labels'], $settings['labels'] );
}
}
/**
* Determine if the page has parents and in case it has, adds all page parents hierarchy
*
* @param $id , page id
*
* @return array
*/
private function get_page_hierarchy( $id ) {
$page = get_post( $id );
if ( empty( $page ) || is_wp_error( $page ) ) {
return array();
}
$return = array();
$page_obj = array();
$page_obj['type'] = 'post';
$page_obj['post_type'] = $page->post_type;
$page_obj['name'] = $page->post_title;
$page_obj['id'] = $id;
$page_obj['url'] = get_permalink( $id );
$return[] = $page_obj;
if ( $page->post_parent > 0 ) {
$return = array_merge( $return, $this->get_page_hierarchy( $page->post_parent ) );
}
return $return;
}
/**
* Determine if the term has parents and in case it has, adds all term parents hierarchy
*
* @param $id , term id
* @param $taxonomy , term taxonomy name
*
* @return array
*/
private function get_term_hierarchy( $id, $taxonomy ) {
$term = get_term( $id, $taxonomy );
if ( empty( $term ) || is_wp_error( $term ) ) {
return array();
}
$return = array();
$term_obj = array();
$term_obj['type'] = 'taxonomy';
$term_obj['name'] = $term->name;
$term_obj['id'] = $id;
$term_obj['url'] = get_term_link( $id, $taxonomy );
$term_obj['taxonomy'] = $taxonomy;
$return[] = $term_obj;
if ( $term->parent > 0 ) {
$return = array_merge( $return, $this->get_term_hierarchy( $term->parent, $taxonomy ) );
}
return $return;
}
/**
* Determine the current frontend page location, in creates the breadcrumbs array
* @return array
*/
private function build_breadcrumbs() {
if ( is_admin() ) {
return array();
}
if ( did_action( 'wp' ) == 0 ) {
return array();
}
$return = array(
0 => array(
'name' => $this->settings['labels']['homepage-title'],
'url' => esc_url( home_url('/') ),
'type' => 'front_page'
),
);
$custom_page = apply_filters( 'fw_ext_breadcrumbs_current_page', array() );
if ( is_array( $custom_page ) && ! empty( $custom_page ) ) {
$return[] = $custom_page;
$return = apply_filters( 'fw_ext_breadcrumbs_build', $return );
return $return;
}
if ( is_404() ) {
$page = array();
$page['type'] = '404';
$page['name'] = $this->settings['labels']['404-title'];
$page['url'] = fw_current_url();
$return[] = $page;
} elseif ( is_search() ) {
$search = array();
$search['type'] = 'search';
$search['name'] = __( 'Searching for:', 'fw' ) . ' ' . get_search_query();
$s = '?s=' . apply_filters( 'fw_ext_breadcrumbs_search_query', get_search_query() );
$search['url'] = home_url( '/' ) . $s;
$return[] = $search;
} elseif ( is_front_page() ) {
} elseif ( is_home() ) {
$blog = array(
'name' => $this->settings['labels']['blogpage-title'],
'url' => fw_current_url(),
'type' => 'front_page'
);
$return[] = $blog;
} elseif ( is_page() ) {
global $post;
$return = array_merge( $return, array_reverse( $this->get_page_hierarchy( $post->ID ) ) );
} elseif ( is_single() ) {
global $post;
$taxonomies = get_object_taxonomies( $post->post_type, 'objects' );
$slugs = array();
if ( ! empty( $taxonomies ) ) {
foreach ( $taxonomies as $key => $tax ) {
if ( $tax->show_ui === true && $tax->public === true && $tax->hierarchical !== false ) {
array_push( $slugs, $tax->name );
}
}
$terms = wp_get_post_terms( $post->ID, $slugs );
if ( ! empty( $terms ) ) {
$lowest_term = $this->get_lowest_taxonomy_terms($terms);
$term = $lowest_term[0];
$return = array_merge( $return,
array_reverse( $this->get_term_hierarchy( $term->term_id, $term->taxonomy ))
);
}
}
$return = array_merge( $return, array_reverse( $this->get_page_hierarchy( $post->ID ) ) );
} elseif ( is_category() ) {
$term_id = get_query_var( 'cat' );
$return = array_merge( $return, array_reverse( $this->get_term_hierarchy( $term_id, 'category' ) ) );
} elseif ( is_tag() ) {
$term_id = get_query_var( 'tag' );
$term = get_term_by( 'slug', $term_id, 'post_tag' );
if ( empty( $term ) || is_wp_error( $term ) ) {
return array();
}
$tag = array();
$tag['type'] = 'taxonomy';
$tag['name'] = $term->name;
$tag['url'] = get_term_link( $term_id, 'post_tag' );
$tag['taxonomy'] = 'post_tag';
$return[] = $tag;
} elseif ( is_tax() ) {
$term_id = get_queried_object()->term_id;
$taxonomy = get_query_var( 'taxonomy' );
$return = array_merge( $return, array_reverse( $this->get_term_hierarchy( $term_id, $taxonomy ) ) );
} elseif ( is_author() ) {
$author = array();
$author['name'] = get_queried_object()->data->display_name;
$author['id'] = get_queried_object()->data->ID;
$author['url'] = get_author_posts_url( $author['id'], get_queried_object()->data->user_nicename );
$author['type'] = 'author';
$return[] = $author;
} elseif ( is_date() ) {
$date = array();
if ( get_option( 'permalink_structure' ) ) {
$day = get_query_var( 'day' );
$month = get_query_var( 'monthnum' );
$year = get_query_var( 'year' );
} else {
$m = get_query_var('m');
$year = substr( $m, 0, 4 );
$month = substr( $m, 4, 2 );
$day = substr( $m, 6, 2 );
}
if ( is_day() ) {
$date['name'] = mysql2date( apply_filters( 'fw_ext_breadcrumbs_date_day_format', 'd F Y' ),
$day . '-' . $month . '-' . $year );
$date['url'] = get_day_link( $year, $month, $day );
$date['date_type'] = 'daily';
$date['day'] = $day;
$date['month'] = $month;
$date['year'] = $year;
} elseif ( is_month() ) {
$date['name'] = mysql2date( apply_filters( 'fw_ext_breadcrumbs_date_month_format', 'F Y' ),
'01.' . $month . '.' . $year );
$date['url'] = get_month_link( $year, $month );
$date['date_type'] = 'monthly';
$date['month'] = $month;
$date['year'] = $year;
} else {
$date['name'] = mysql2date( apply_filters( 'fw_ext_breadcrumbs_date_year_format', 'Y' ),
'01.01.' . $year );
$date['url'] = get_year_link( $year );
$date['date_type'] = 'yearly';
$date['year'] = $year;
}
$return[] = $date;
} elseif ( is_archive() ) {
$post_type = get_query_var( 'post_type' );
if ( $post_type ) {
$post_type_obj = get_post_type_object( $post_type );
$archive = array();
$archive['name'] = $post_type_obj->labels->name;
$archive['url'] = get_post_type_archive_link( $post_type );
$return[] = $archive;
}
}
foreach ( $return as $key => $item ) {
if ( empty( $item['name'] ) ) {
$return[ $key ]['name'] = __( 'No title', 'fw' );
}
}
/* Reserved for pagination
* global $wp_query;
$paged = array();
$paged['name'] = get_query_var('paged');
$paged['max_pages'] = $wp_query->max_num_pages;
if( intval( $paged['name'] ) > 0 ){
$paged['name'] = __('Page', 'fw') . ' ' . $paged['name'];
$return[] = $paged;
}*/
$return = apply_filters( 'fw_ext_breadcrumbs_build', $return );
return $return;
}
/**
* Returns the lowest hierarchical term
* @return array
*/
private function get_lowest_taxonomy_terms( $terms ) {
// if terms is not array or its empty don't proceed
if ( ! is_array( $terms ) || empty( $terms ) ) {
return false;
}
return $this->filter_terms($terms);
}
private function filter_terms($terms) {
$return_terms = array();
$term_ids = array();
foreach ($terms as $t) {
$term_ids[] = $t->term_id;
}
foreach ( $terms as $t ) {
if ( $t->parent == false || !in_array($t->parent,$term_ids) ) {
// remove this term
} else {
$return_terms[] = $t;
}
}
if ( count($return_terms) ) {
return $this->filter_terms($return_terms);
} else {
return $terms;
}
}
/**
* Returns the breadcrumbs array
* @return string
*/
public function get_breadcrumbs() {
return $this->build_breadcrumbs();
}
}

View File

@@ -0,0 +1,21 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
$manifest = array();
$manifest['name'] = __( 'Breadcrumbs', 'fw' );
$manifest['description'] = __(
'Creates a simplified navigation menu for the pages that can be placed anywhere in the theme.'
.' This will make navigating the website much easier.',
'fw'
);
$manifest['version'] = '1.0.15';
$manifest['display'] = true;
$manifest['standalone'] = true;
$manifest['github_repo'] = 'https://github.com/ThemeFuse/Unyson-Breadcrumbs-Extension';
$manifest['uri'] = 'http://manual.unyson.io/en/latest/extension/breadcrumbs/index.html#content';
$manifest['author'] = 'ThemeFuse';
$manifest['author_uri'] = 'http://themefuse.com/';
$manifest['github_update'] = 'ThemeFuse/Unyson-Breadcrumbs-Extension';

View File

@@ -0,0 +1,35 @@
<?php if (!defined('FW')) die('Forbidden'); ?>
##STEP 1
###Copy the breadcrumbs code
This code is what displays the breadcrumbs on your website. Copy the following to your clipboard:
<code>&lt;?php if( function_exists('fw_ext_breadcrumbs') ) { fw_ext_breadcrumbs(); } ?&gt;</code>
---
##STEP 2
###Paste the breadcrumbs code in your theme
Open Appearance/Editor and select <strong>single.php</strong> file to edit.
In the theme, paste the code where you want your breadcrumbs to appear (usually beneath the the_title() tag) and then save your theme.
---
##STEP 3
###Add the breadcrumbs to your archive listings
Copy the following code to your clipboard:
<code>&lt;?php if( function_exists('fw_ext_breadcrumbs') ) { fw_ext_breadcrumbs(); } ?&gt;</code>
Open Appearance/Editor and select <strong>archive.php</strong> file to edit.
In the theme, find the place where each item is rendered and paste the code inside that code block.
Then, save your theme.

View File

@@ -0,0 +1,38 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
$default_values = apply_filters('fw_ext_breadcrumbs_settings_options_default_values', array(
'homepage-title' => __( 'Homepage', 'fw' ),
'blogpage-title' => __( 'Blog', 'fw' ),
'404-title' => __('404 Not Found', 'fw'),
));
$options = array(
apply_filters('fw:ext:breadcrumbs:settings-options:before', array()),
'box' => array(
'title' => false,
'type' => 'box',
'options' => array(
'homepage-title' => array(
'label' => __( 'Text for Homepage', 'fw' ),
'desc' => __( 'The homepage anchor will have this text', 'fw' ),
'type' => 'text',
'value' => $default_values['homepage-title']
),
'blogpage-title' => array(
'label' => __( 'Text for Blog Page', 'fw' ),
'desc' => __( 'The blog page anchor will have this text. In case homepage will be set as blog page, will be taken the homepage text', 'fw' ),
'type' => 'text',
'value' => $default_values['blogpage-title']
),
'404-title' => array(
'label' => __( 'Text for 404 Page', 'fw' ),
'desc' => __( 'The 404 anchor will have this text', 'fw' ),
'type' => 'text',
'value' => $default_values['404-title']
),
)
),
apply_filters('fw:ext:breadcrumbs:settings-options:after', array()),
);

View File

@@ -0,0 +1,7 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
if (!is_admin()) {
wp_enqueue_style( 'fw-ext-breadcrumbs-add-css', fw()->extensions->get( 'breadcrumbs' )->locate_css_URI( 'style' ) );
}

View File

@@ -0,0 +1,10 @@
.breadcrumbs {
margin: 12px 0;
font-size: 80%;
line-height: 1.3em;
}
.breadcrumbs a{
text-decoration: none;
/*color: inherit;*/
}

View File

@@ -0,0 +1,63 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
/**
* Breadcrumbs default view
* Parameters:
*
* @var array $items , array with pages ordered hierarchical
* $items = array(
* 0 => array(
* 'name' => 'Item name',
* 'url' => 'Item URL'
* )
* )
* Each $items array will contain additional information about item, e.g.:
* 'items' => array (
* 0 => array (
* 'name' => 'Homepage',
* 'type' => 'front_page',
* 'url' => 'http://yourdomain.com/',
* ),
* 1 => array (
* 'type' => 'taxonomy',
* 'name' => 'Uncategorized',
* 'id' => 1,
* 'url' => 'http://yourdomain.com/category/uncategorized/',
* 'taxonomy' => 'category',
* ),
* 2 => array (
* 'name' => 'Post Article',
* 'id' => 4781,
* 'post_type' => 'post',
* 'type' => 'post',
* 'url' => 'http://yourdomain.com/post-article/',
* ),
* ),
* @var string $separator , the separator symbol
*/
?>
<?php if ( ! empty( $items ) ) : ?>
<div class="breadcrumbs">
<?php for ( $i = 0; $i < count( $items ); $i ++ ) : ?>
<?php if ( $i == ( count( $items ) - 1 ) ) : ?>
<span class="last-item"><?php echo $items[ $i ]['name'] ?></span>
<?php elseif ( $i == 0 ) : ?>
<span class="first-item">
<?php if( isset( $items[ $i ]['url'] ) ) : ?>
<a href="<?php echo esc_attr($items[ $i ]['url']) ?>"><?php echo $items[ $i ]['name'] ?></a></span>
<?php else : echo $items[ $i ]['name']; endif ?>
<span class="separator"><?php echo $separator ?></span>
<?php
else : ?>
<span class="<?php echo( $i - 1 ) ?>-item">
<?php if( isset( $items[ $i ]['url'] ) ) : ?>
<a href="<?php echo esc_attr($items[ $i ]['url']) ?>"><?php echo $items[ $i ]['name'] ?></a></span>
<?php else : echo $items[ $i ]['name']; endif ?>
<span class="separator"><?php echo $separator ?></span>
<?php endif ?>
<?php endfor ?>
</div>
<?php endif ?>

View File

@@ -0,0 +1,80 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Extension_Builder extends FW_Extension
{
/**
* @internal
*/
protected function _init()
{
add_action('fw_option_types_init', array($this, '_action_option_types_init'),
9 // Other option types requires it
);
spl_autoload_register(array($this, '_spl_autoload'));
add_filter(
'fw:options-default-values:skip-types',
array($this, '_filter_skip_builder_option_types_default_value_process')
);
}
public function _action_option_types_init() {
require_once dirname( __FILE__ ) . '/includes/option-types/builder/builder.php';
}
/**
* Backwards compatibility when builder-types and builder-item-types were registered right away
* @param string $class
*/
public function _spl_autoload($class) {
if ('FW_Option_Type_Builder' === $class) {
$this->_action_option_types_init();
if (
is_admin()
&&
// https://github.com/ThemeFuse/Unyson-Extensions-Approval/issues/258
version_compare(fw()->manifest->get_version(), '2.6.2', '>')
) {
FW_Flash_Messages::add(
'builder-option-type-register-wrong',
__("Please register builder types on 'fw_option_types_init' action", 'fw'),
'warning'
);
}
} elseif ('FW_Option_Type_Builder_Item' === $class) {
if (
is_admin()
&&
// https://github.com/ThemeFuse/Unyson-Extensions-Approval/issues/258
version_compare(fw()->manifest->get_version(), '2.6.2', '>')
) {
FW_Flash_Messages::add(
'builder-item-type-register-wrong',
__("Please register builder item-types on 'fw_option_type_builder:{builder-type}:register_items' action", 'fw'),
'warning'
);
}
}
}
/**
* Skip Builders from default value extract via $option_type->get_value_from_input() because it's process intensive
* @param array $types
* @return array
* @since 1.2.9
*/
public function _filter_skip_builder_option_types_default_value_process(array $types) {
if (version_compare(fw()->manifest->get_version(), '2.6.11', '<')) {
return $types; // fw()->backend->get_option_types() is not available
}
foreach (fw()->backend->get_option_types() as $type) {
if (fw()->backend->option_type($type) instanceof FW_Option_Type_Builder) {
$types[$type] = true;
}
}
return $types;
}
}

View File

@@ -0,0 +1,69 @@
<?php if (!defined('FW')) die('Forbidden');
$cfg = array();
/**
* Default item widths for all builders
*
* It is better to use fw_ext_builder_get_item_width() function to retrieve the item widths
* because it has a filter and users will be able to customize the widths for a specific builder
*
* @see fw_ext_builder_get_item_width()
* @since 1.2.0
*
* old $cfg['default_item_widths'] https://github.com/ThemeFuse/Unyson-Builder-Extension/issues/8
* https://github.com/ThemeFuse/Unyson-Builder-Extension/blob/v1.1.17/config.php#L13
*/
$cfg['grid.columns'] = array(
'1_6' => array(
'title' => '1/6',
'backend_class' => 'fw-col-sm-2',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-2',
),
'1_5' => array(
'title' => '1/5',
'backend_class' => 'fw-col-sm-15',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-15',
),
'1_4' => array(
'title' => '1/4',
'backend_class' => 'fw-col-sm-3',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-3',
),
'1_3' => array(
'title' => '1/3',
'backend_class' => 'fw-col-sm-4',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-4',
),
'1_2' => array(
'title' => '1/2',
'backend_class' => 'fw-col-sm-6',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-6',
),
'2_3' => array(
'title' => '2/3',
'backend_class' => 'fw-col-sm-8',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-8',
),
'3_4' => array(
'title' => '3/4',
'backend_class' => 'fw-col-sm-9',
'frontend_class' => 'fw-col-xs-12 fw-col-sm-9',
),
'1_1' => array(
'title' => '1/1',
'backend_class' => 'fw-col-sm-12',
'frontend_class' => 'fw-col-xs-12',
),
);
/**
* @since 1.2.0
*/
$cfg['grid.row.class'] = 'fw-row';
/**
* @deprecated since 1.2.0
* if this is empty fw_ext_builder_get_item_width() will use $cfg['grid.columns']
*/
$cfg['default_item_widths'] = false;

View File

@@ -0,0 +1,78 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* Get builder item width data
*
* Default widths are specified in the config, but some builder types can have custom widths
*
* Usage example:
* <div class="<?php echo esc_attr(fw_ext_builder_get_item_width('builder-type', $item['width'] .'/frontend_class')) ?>" >
*
* @param string $builder_type Builder option type (some builders can have different item widths)
* @param null|string $width_id Specify width id (accepts multikey) or leave empty to get all widths
* @param null|mixed $default_value Return this value if specified key does not exist
* @return array
*/
function fw_ext_builder_get_item_width($builder_type, $width_id = null, $default_value = null) {
try {
$cache_key = fw()->extensions->get('builder')->get_cache_key('item_widths/'. $builder_type);
$widths = FW_Cache::get($cache_key);
} catch (FW_Cache_Not_Found_Exception $e) {
if ($widths = fw()->extensions->get('builder')->get_config('default_item_widths')) {
// Custom (old config key) widths are defined in theme (by default $cfg['default_item_widths'] is empty)
} else {
$widths = fw()->extensions->get('builder')->get_config('grid.columns'); // new config key
}
$widths = apply_filters('fw_builder_item_widths:'. $builder_type, $widths);
FW_Cache::set($cache_key, $widths);
}
if (is_null($width_id)) {
return $widths;
} else {
return fw_akg($width_id, $widths, $default_value);
}
}
/**
* Get builder item widths for using in js (wp_localize_script() or json_encode())
*
* @param string $builder_type Builder option type (some builders can have different item widths)
* @return array
*/
function fw_ext_builder_get_item_widths_for_js($builder_type) {
$item_widths = array();
foreach (fw_ext_builder_get_item_width($builder_type) as $width_id => $width_data) {
$width_data['id'] = $width_id;
$item_widths[] = $width_data;
}
return $item_widths;
}
/**
* @param string $icon A string that is meant to be an icon (an image, a font icon class, or something else)
* @return string
*/
function fw_ext_builder_string_to_icon_html($icon) {
if (preg_match('/\.(png|jpg|jpeg|gif|svg|webp)$/', $icon)) {
// http://.../image.png
return fw_html_tag('img', array(
'class' => 'fw-ext-builder-icon',
'src' => $icon
));
} elseif (preg_match('/^[a-zA-Z0-9\-_ ]+$/', $icon)) {
// 'font-icon font-icon-class'
return fw_html_tag('span', array(
'class' => 'fw-ext-builder-icon '. trim($icon)
), true);
} else {
// can't detect. maybe it's raw html '<span ...'
return $icon;
}
}

View File

@@ -0,0 +1,27 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
spl_autoload_register( '_fw_ext_builder_includes_autoload' );
function _fw_ext_builder_includes_autoload( $class ) {
switch ( $class ) {
case 'FW_Option_Type_Builder' :
require_once dirname( __FILE__ ) . '/option-types/builder/extends/class-fw-option-type-builder.php';
break;
case 'FW_Option_Type_Builder_Item' :
require_once dirname( __FILE__ ) . '/option-types/builder/extends/class-fw-option-type-builder-item.php';
break;
case '_FW_Ext_Builder_Fullscreen' :
require_once dirname( __FILE__ ) . '/option-types/builder/includes/fullscreen.php';
break;
case 'FW_Ext_Builder_Templates' :
require_once dirname( __FILE__ ) . '/option-types/builder/includes/templates/class-fw-ext-builder-templates.php';
break;
case 'FW_Ext_Builder_Templates_Component' :
require_once dirname( __FILE__ ) . '/option-types/builder/includes/templates/class-fw-ext-builder-templates-component.php';
break;
case 'FW_Ext_Builder_Templates_Component_Full' :
require_once dirname( __FILE__ ) . '/option-types/builder/includes/templates/components/full/class-fw-ext-builder-templates-component-full.php';
break;
}
}

View File

@@ -0,0 +1,3 @@
<?php if (!defined('FW')) die('Forbidden');
require_once dirname( __FILE__ ) . '/includes/templates/init.php';

View File

@@ -0,0 +1,140 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
abstract class FW_Option_Type_Builder_Item {
/**
* Specify which builder type this item type belongs to
* @return string
*/
abstract public function get_builder_type();
/**
* The item type
* @return string
*/
abstract public function get_type();
/**
* The boxes that appear on top of the builder and can be dragged down or clicked to create items
* @return array(
* array(
* 'html' =>
* '<div class="item-type-icon-title">'.
* ' <div class="item-type-icon"><span class="dashicons dashicons-smiley"></span></div>'.
* ' <div class="item-type-title">Item Title</div>'.
* '</div>',
* ),
* array(
* 'tab' => __('Tab Title', 'fw'),
* 'html' =>
* '<div class="item-type-icon-title">'.
* ' <div class="item-type-icon"><span class="dashicons dashicons-smiley"></span></div>'.
* ' <div class="item-type-title">Item Title</div>'.
* '</div>',
* ),
* ...
* )
*/
abstract public function get_thumbnails();
/**
* Enqueue item type scripts and styles
*/
abstract public function enqueue_static();
final public function __construct() {
// Maybe in the future this method will have some functionality
}
/**
* @param FW_Access_Key $access_key
*
* @internal
* This must be called right after an instance of builder item type has been created
* and was added to the registered array, so it is available through
* builder->get_item_types()
*/
final public function _call_init( $access_key ) {
if ( $access_key->get_key() !== 'fw_ext_builder_option_type' ) {
trigger_error( 'Method call not allowed', E_USER_ERROR );
}
if ( method_exists( $this, '_init' ) ) {
$this->_init();
}
}
/**
* @see FW_Option_Type::storage_save()
*
* @param array $item
* @param array $params
*
* @return array $item
* @since 1.2.0
*/
final public function storage_save( array $item, array $params = array() ) {
if ( $this->get_type() === $item['type'] ) {
return $this->_storage_save( $item, $params );
} else {
return $item;
}
}
/**
* @see FW_Option_Type::storage_load()
*
* @param array $item
* @param array $params
*
* @return array
* @since 1.2.0
*/
final public function storage_load( array $item, array $params = array() ) {
if ( $this->get_type() === $item['type'] ) {
return $this->_storage_load( $item, $params );
} else {
return $item;
}
}
/**
* Overwrite this method if you want to change/fix attributes that comes from js
*
* @param $attributes array Backbone Item (Model) attributes
*
* @return mixed
*/
public function get_value_from_attributes( $attributes ) {
return $attributes;
}
/**
* @see FW_Option_Type::_storage_save()
*
* @param array $item
* @param array $params
*
* @return array $item
* @since 1.2.0
* @internal
*/
protected function _storage_save( array $item, array $params ) {
return $item;
}
/**
* @see FW_Option_Type::_storage_load()
*
* @param array $item
* @param array $params
*
* @return mixed
* @since 1.2.0
* @internal
*/
protected function _storage_load( array $item, array $params ) {
return $item;
}
}

View File

@@ -0,0 +1,732 @@
<?php if ( ! defined( 'FW' ) ) {
die( 'Forbidden' );
}
abstract class FW_Option_Type_Builder extends FW_Option_Type {
/**
* Registered item types of the current builder type
* @var array {item-type => item-instance}
*/
private static $item_types = array();
/**
* @var FW_Access_Key
*/
private static $access_key;
/**
* @param string|FW_Option_Type_Builder_Item $item_type_class
* @param $type $item_type_class
* @param string $builder_type
*/
public static function register_item_type( $item_type_class, $type = null, $builder_type = null ) {
if ( empty( $type ) || empty( $builder_type ) ) {
if ( ! is_subclass_of( $item_type_class, 'FW_Option_Type_Builder_Item' ) ) {
trigger_error( "Invalid builder item type class $item_type_class", E_USER_WARNING );
return;
}
$instance = $item_type_class instanceof FW_Option_Type_Builder_Item
? $item_type_class
: self::get_instance( $item_type_class );
$type = $instance->get_type();
$builder_type = $instance->get_builder_type();
unset( $instance );
}
if ( ! isset( self::$item_types[ $builder_type ] ) ) {
if ( ! is_subclass_of( $item_type_class, 'FW_Option_Type_Builder_Item' ) ) {
trigger_error( "Invalid builder type $builder_type", E_USER_WARNING );
return;
}
}
if ( isset( self::$item_types[ $builder_type ][ $type ] ) ) {
if ( ! is_subclass_of( $item_type_class, 'FW_Option_Type_Builder_Item' ) ) {
trigger_error( "Builder item type $type is already registered", E_USER_WARNING );
return;
}
}
if ( apply_filters(
'fw_ext_builder:option_type:' . $builder_type . ':exclude_item_type:' . $type,
false
) ) {
return;
}
self::$item_types[ $builder_type ][ $type ] = $item_type_class;
}
/**
* @param $type
*
* @return FW_Option_Type_Builder_Item
*/
protected function get_item_type( $type ) {
try {
return FW_Cache::get( "fw-option-type-builder:{$this->get_type()}:items:$type" );
} catch ( FW_Cache_Not_Found_Exception $e ) {
$instance = $this->get_item_instance( $type );
FW_Cache::set( "fw-option-type-builder:{$this->get_type()}:items:$type", $instance );
$instance->_call_init( self::get_access_key() );
return $instance;
}
}
/**
* @return FW_Option_Type_Builder_Item[]
*/
protected function get_item_types() {
static $did_action = false;
if ( ! $did_action ) {
/**
* @since 1.2.4
*/
do_action( 'fw_option_type_builder:' . $this->get_type() . ':register_items' );
$did_action = true;
}
$items = array();
foreach ( array_keys( $this->get_items_classes() ) as $type ) {
$items[ $type ] = $this->get_item_type( $type );
}
return $items;
}
/**
* Get correct value from items
*
* @param array $items
*
* @return array
*/
public function get_value_from_items( $items ) {
/**
* @var FW_Option_Type_Builder_Item[] $item_types
*/
$item_types = $this->get_item_types();
$fixed_items = array();
foreach ( $items as $item_attributes ) {
if ( ! isset( $item_attributes['type'] ) || ! isset( $item_types[ $item_attributes['type'] ] ) ) {
// invalid item type
continue;
}
$fixed_item_attributes = $item_types[ $item_attributes['type'] ]
->get_value_from_attributes( $item_attributes );
if ( isset( $fixed_item_attributes['_items'] ) ) {
$fixed_item_attributes['_items'] = $this->get_value_from_items( $fixed_item_attributes['_items'] );
}
$fixed_items[] = $fixed_item_attributes;
}
return $fixed_items;
}
/**
* @internal
*/
public function _get_backend_width_type() {
return 'full';
}
private function fix_base_defaults( $option = array() ) {
return array_merge( array(
'fullscreen' => false,
'template_saving' => false,
'history' => false,
/**
* Enable fixed header so it follows you on scroll down.
* It's convenient when you have many elements in builder and it's tedious to:
* scroll up -> add element -> scroll down -> configure it -> scroll up -> ...
*/
'fixed_header' => false,
/**
* Enable drag and drop manipulation of every collection from Builder.
* Sometimes, when your creating your own builder,
* it's convenient to throw it away in order to wire up your own
* drag and drop behavior.
*/
'drag_and_drop' => true,
/**
* Builder may be read_only. This may be necessary if we want
* to provide some content to user just for presentation,
* without the user to be able to interact with the items
* or change the way they are alligned.
*
* This is not some magick option that will make your builder
* read-only only by making it true. Every builder is responsible
* to give their read-only experience as they want.
* That's why it is turned off by default. You may not need this
* option.
*
* This option will add a data-read-only attribute to the builder
* if it's set to true. You are responsible to handle it
* accordingly in your client-side logic.
*/
'read_only' => false,
/**
* Option-type html input json value will be compressed.
* Prevent max_post_size error when builder contains a lot of elements.
*/
'compress_form_value' => false,
),
$option );
}
private function get_static_uri( $append = '' ) {
return fw()->extensions->get( 'builder' )->get_uri( '/includes/option-types/builder/static' . $append );
}
private static function get_access_key() {
if ( ! self::$access_key ) {
self::$access_key = new FW_Access_Key( 'fw_ext_builder_option_type' );
}
return self::$access_key;
}
/**
* @return array
*/
protected function get_items_classes() {
return fw_akg( $this->get_type(), self::$item_types, array() );
}
/**
* @param $type
*
* @return string
* @throws FW_Option_Type_Exception_Not_Found
*/
protected function get_item_class( $type ) {
$class = fw_akg( $type, $this->get_items_classes() );
if ( $class == null ) {
throw new FW_Option_Type_Exception_Not_Found();
}
return $class;
}
/**
* @param $type
*
* @return FW_Option_Type_Builder_Item
* @throws FW_Option_Type_Exception_Not_Found
* @throws FW_Option_Type_Exception_Invalid_Class
*/
protected function get_item_instance( $type ) {
$class = $this->get_item_class( $type );
if ( ! is_subclass_of( $class, 'FW_Option_Type_Builder_Item' ) ) {
throw new FW_Option_Type_Exception_Invalid_Class();
}
return $this->get_instance( $class );
}
/**
* @param $class
*
* @return mixed
*/
private static function get_instance( $class ) {
return new $class();
}
/**
* Overwrite this method to force your builder type items to extend custom class or to have custom requirements
*
* @param FW_Option_Type_Builder_Item $item_type_instance
*
* @return bool
*/
protected function item_type_is_valid( $item_type_instance ) {
return is_subclass_of( $item_type_instance, 'FW_Option_Type_Builder_Item' );
}
/**
* @internal
*/
protected function _get_defaults() {
return $this->fix_base_defaults( array(
'value' => array(
'json' => '[]',
),
) );
}
/**
* @param array $option
* @return bool
* @since 1.2.8
*/
protected function compression_is_enabled($option) {
return isset($option['compress_form_value']) && $option['compress_form_value'] && function_exists('gzinflate');
}
/**
* @param $ZIPContentStr
*
* @return string
* @source http://stackoverflow.com/a/15966905
*/
private function decompress_first_file_from_zip( $ZIPContentStr ) {
// Input: ZIP archive - content of entire ZIP archive as a string
// Output: decompressed content of the first file packed in the ZIP archive
// let's parse the ZIP archive
// (see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details)
// parse 'local file header' for the first file entry in the ZIP archive
if ( strlen( $ZIPContentStr ) < 102 ) {
// any ZIP file smaller than 102 bytes is invalid
printf( "error: input data too short<br />\n" );
return '';
}
$CompressedSize = $this->binstrtonum( substr( $ZIPContentStr, 18, 4 ) );
$UncompressedSize = $this->binstrtonum( substr( $ZIPContentStr, 22, 4 ) );
$FileNameLen = $this->binstrtonum( substr( $ZIPContentStr, 26, 2 ) );
$ExtraFieldLen = $this->binstrtonum( substr( $ZIPContentStr, 28, 2 ) );
$Offs = 30 + $FileNameLen + $ExtraFieldLen;
$ZIPData = substr( $ZIPContentStr, $Offs, $CompressedSize );
$Data = gzinflate( $ZIPData );
if ( strlen( $Data ) != $UncompressedSize ) {
printf( "error: uncompressed data have wrong size<br />\n" );
return '';
} else {
return $Data;
}
}
/**
* @param $Str
* @return int
* @see decompress_first_file_from_zip()
*/
private function binstrtonum( $Str ) {
// Returns a number represented in a raw binary data passed as string.
// This is useful for example when reading integers from a file,
// when we have the content of the file in a string only.
// Examples:
// chr(0xFF) will result as 255
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215
$Num = 0;
for ( $TC1 = strlen( $Str ) - 1; $TC1 >= 0; $TC1 -- ) { // go from most significant byte
$Num <<= 8; // shift to left by one byte (8 bits)
$Num |= ord( $Str[ $TC1 ] ); // add new byte
}
return $Num;
}
/**
* @param string $input_value
* @param array $option
* @return string
* @since 1.2.8
*/
protected function maybe_decompress($input_value, $option) {
if (!$this->compression_is_enabled($option) || $input_value[0] === '[') {
return $input_value;
} else {
return $this->decompress_first_file_from_zip(base64_decode($input_value));
}
}
/**
* @internal
* {@inheritdoc}
*/
protected function _enqueue_static( $id, $option, $data ) {
$option = $this->fix_base_defaults( $option );
$version = fw_ext( 'builder' )->manifest->get_version();
do_action( 'fw_ext_builder:option_type:builder:before_enqueue',
array(
'option' => $option,
'version' => $version,
) );
wp_register_script(
'jszip',
$this->get_static_uri('/lib/jszip.min.js'),
array(),
$version,
true
);
{
wp_enqueue_style(
'fw-option-builder',
$this->get_static_uri( '/css/builder.css' ),
version_compare( fw()->manifest->get_version(), '2.4.0', '<' )
? array( 'fw' )
: array( 'fw', 'fw-unycon' ),
$version
);
wp_enqueue_script(
'fw-option-builder',
$this->get_static_uri( '/js/builder.js' ),
array(
'jquery-ui-draggable',
'jquery-ui-sortable',
'fw',
'fw-events',
'backbone',
'backbone-relational'
),
$version,
true
);
}
wp_enqueue_media();
wp_enqueue_script(
'fw-option-builder-initialize',
$this->get_static_uri( '/js/initialize-builder.js' ),
array( 'fw-option-builder', 'jszip' ),
$version,
true
);
{
wp_enqueue_style(
'fw-option-builder-helpers',
$this->get_static_uri( '/css/helpers.css' ),
array( 'fw-option-builder' ),
$version
);
wp_enqueue_script(
'fw-option-builder-helpers',
$this->get_static_uri( '/js/helpers.js' ),
array( 'fw-option-builder' ),
$version,
true
);
wp_enqueue_script(
'fw-option-builder-qtips',
$this->get_static_uri( '/js/qtips.js' ),
array( 'fw-option-builder' ),
$version,
true
);
wp_localize_script(
'fw-option-builder-helpers',
'_fw_option_type_builder_helpers',
array(
'l10n' => array(
'save' => __( 'Save', 'fw' ),
),
'item_widths' => fw_ext_builder_get_item_widths_for_js( $this->get_type() )
)
);
}
if ( $option['fullscreen'] ) {
wp_enqueue_style(
'fw-option-builder-fullscreen',
$this->get_static_uri( '/css/fullscreen.css' ),
array( 'fw-option-builder' ),
$version
);
wp_enqueue_script(
'fw-option-builder-fullscreen',
$this->get_static_uri( '/js/fullscreen.js' ),
array( 'fw-option-builder', ),
$version,
true
);
wp_localize_script(
'fw-option-builder-fullscreen',
'_fw_option_type_builder_fullscreen',
array(
'l10n' => array(
'fullscreen' => __( 'Full Screen', 'fw' ),
'exit_fullscreen' => __( 'Exit Full Screen', 'fw' ),
),
)
);
}
if ( $option['history'] ) {
wp_enqueue_style(
'fw-option-builder-history',
$this->get_static_uri( '/css/history.css' ),
array( 'fw-option-builder' ),
$version
);
wp_enqueue_script(
'fw-option-builder-history',
$this->get_static_uri( '/js/history.js' ),
array( 'fw-option-builder', ),
$version,
true
);
wp_localize_script(
'fw-option-builder-history',
'_fw_option_type_builder_history',
array(
'l10n' => array(
'undo' => __( 'Undo', 'fw' ),
'redo' => __( 'Redo', 'fw' ),
),
)
);
}
do_action( 'fw_ext_builder:option_type:builder:enqueue',
array(
'option' => $option,
'version' => $version,
'uri' => fw()->extensions->get( 'builder' )->get_uri( '/includes/option-types/builder' )
) );
foreach ( $this->get_item_types() as $item ) {
/** @var FW_Option_Type_Builder_Item $item */
$item->enqueue_static();
}
}
/**
* @internal
* {@inheritdoc}
*/
protected function _render( $id, $option, $data ) {
$option = $this->fix_base_defaults( $option );
/**
* array(
* 'Tab title' => array(
* '<thumbnail html>',
* '<thumbnail html>',
* '<thumbnail html>',
* ),
* 'Tab title' => array(
* '<thumbnail html>',
* )
* )
*/
$thumbnails = array();
/**
* If you want to customize what css class your thumbnails receive
* you can implement `get_thumbnail_class` in your
* FW_Option_Type_Builder subclass. Whatever you return from this
* method is inserted right into html.
*
* You can add additional classes by concatenating them to the
* default class. You receive default class as an argument to the
* method.
*
* class Some_Cool_Builder extends FW_Option_Type_Builder {
* // initialization
*
* public function get_thumbnail_class ($default_css_class, $item) {
* return $default_css_class . ' some-cool-class-that-you-really-need';
* }
* }
*
* // Don't forget to register your builder
* FW_Option_Type::register('Some_Cool_Builder');
*/
foreach ( $this->get_item_types() as $item ) {
/** @var FW_Option_Type_Builder_Item $item */
$item_classes = 'builder-item-type';
if ( method_exists( $this, 'get_thumbnail_class' ) ) {
$item_classes = $this->get_thumbnail_class( $item_classes, $item );
}
$item_classes = esc_attr( $item_classes );
foreach ( $item->get_thumbnails() as $key => $thumbnail ) {
if ( ! isset( $thumbnail['tab'] ) ) {
$tab_title = '~';
} else {
$tab_title = $thumbnail['tab'];
}
if ( ! isset( $thumbnails[ $tab_title ] ) ) {
$thumbnails[ $tab_title ] = array();
}
if ( empty( $thumbnail['html'] ) ) {
continue;
}
if ( ! isset( $thumbnails[ $tab_title ][ $key ] ) ) {
$thumbnails[ $tab_title ][ $key ] =
'<div class="' . $item_classes . '" data-builder-item-type="' . esc_attr( $item->get_type() ) . '">' .
$thumbnail['html'] .
'</div>';
} else {
$thumbnails[ $tab_title ][] =
'<div class="' . $item_classes . '" data-builder-item-type="' . esc_attr( $item->get_type() ) . '">' .
$thumbnail['html'] .
'</div>';
}
}
}
foreach ( $thumbnails as &$type ) {
ksort( $type );
}
if ( method_exists( $this, 'sort_thumbnails' ) ) {
$this->sort_thumbnails( $thumbnails );
}
// prepare attr
{
$option['attr']['data-builder-option-type'] = $this->get_type();
$option['attr']['class'] .= ' fw-option-type-builder';
if ( $option['fullscreen'] ) {
$option['attr']['class'] .= apply_filters( 'fw_builder_fullscreen_add_classes', '' );
}
if ( $option['fixed_header'] ) {
$option['attr']['data-fixed-header'] = '~';
}
if ( $option['drag_and_drop'] ) {
$option['attr']['data-drag-and-drop'] = '~';
}
if ( $option['read_only'] ) {
$option['attr']['data-read-only'] = '~';
}
if ($this->compression_is_enabled($option)) {
$option['attr']['data-compression'] = '~';
}
}
return fw_render_view( dirname( __FILE__ ) . '/../view.php',
array(
'id' => $id,
'option' => $option,
'data' => $data,
'thumbnails' => $thumbnails,
) );
}
/**
* {@inheritdoc}
*/
protected function _get_value_from_input( $option, $input_value ) {
if ( empty( $input_value ) || ! is_string( $input_value ) ) {
$input_value = $option['value']['json'];
} else {
$input_value = $this->maybe_decompress($input_value, $option);
}
if ( ! ($items = json_decode( $input_value, true )) ) {
$items = array();
}
return array(
'json' => json_encode($this->get_value_from_items( $items )),
);
}
/**
* {@inheritdoc}
*/
protected function _storage_save( $id, array $option, $value, array $params ) {
$value['json'] = json_encode( $this->storage_save_recursive( json_decode( $value['json'], true ), $params ) );
return fw_db_option_storage_save( $id, $option, $value, $params );
}
protected function storage_save_recursive( array $items, array $params ) {
/**
* @var FW_Option_Type_Builder_Item[] $item_types
*/
$item_types = $this->get_item_types();
foreach ( $items as &$atts ) {
if ( ! isset( $atts['type'] ) || ! isset( $item_types[ $atts['type'] ] ) ) {
continue; // invalid item
}
$atts = $item_types[ $atts['type'] ]->storage_save( $atts, $params );
if ( isset( $atts['_items'] ) ) {
$atts['_items'] = $this->storage_save_recursive( $atts['_items'], $params );
}
}
return $items;
}
/**
* {@inheritdoc}
*/
protected function _storage_load( $id, array $option, $value, array $params ) {
$value = fw_db_option_storage_load( $id, $option, $value, $params );
$value['json'] = json_decode( $value['json'], true );
$value['json'] = $this->storage_load_recursive( $value['json'] ? $value['json'] : array(), $params );
$value['json'] = json_encode( $value['json'] );
return $value;
}
protected function storage_load_recursive( array $items, array $params ) {
/**
* @var FW_Option_Type_Builder_Item[] $item_types
*/
$item_types = $this->get_item_types();
foreach ( $items as &$atts ) {
if ( ! isset( $atts['type'] ) || ! isset( $item_types[ $atts['type'] ] ) ) {
continue; // invalid item
}
$atts = $item_types[ $atts['type'] ]->storage_load( $atts, $params );
if ( isset( $atts['_items'] ) ) {
$atts['_items'] = $this->storage_load_recursive( $atts['_items'], $params );
}
}
return $items;
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* Builder FullScreen functionality
* @internal
*/
final class _FW_Ext_Builder_Fullscreen
{
public static function init()
{
add_action('wp_ajax_fw_builder_fullscreen_set_storage_item', array(__CLASS__, '_action_ajax_set_storage_item'));
add_action('wp_ajax_fw_builder_fullscreen_unset_storage_item', array(__CLASS__, '_action_ajax_unset_storage_item'));
add_filter('fw_builder_fullscreen_add_classes', array(__CLASS__, '_filter_add_builder_classes'));
add_action('fw_builder_fullscreen_add_backdrop', array(__CLASS__, '_action_add_builder_backdrop'));
}
private static function get_storage_items()
{
return fw_get_db_extension_data('builder', 'fullscreen', array());
}
private static function set_storage_items($items)
{
fw_set_db_extension_data('builder', 'fullscreen', $items);
}
public static function _action_ajax_set_storage_item()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
self::set_storage_items(
array_unique(
array_merge(
self::get_storage_items(),
array( (int)FW_Request::POST('post_id') )
)
)
);
wp_send_json_success();
}
public static function _action_ajax_unset_storage_item()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
$storage_items = self::get_storage_items();
$key = array_search(
(int)FW_Request::POST('post_id'),
$storage_items
);
unset($storage_items[$key]);
self::set_storage_items($storage_items);
wp_send_json_success();
}
public static function is_fullscreen_on()
{
$post_id = get_the_ID();
return (false !== $post_id && in_array($post_id, self::get_storage_items()));
}
public static function _filter_add_builder_classes($str)
{
return self::is_fullscreen_on() ? ($str . ' builder-fullscreen') : $str;
}
public static function _action_add_builder_backdrop()
{
echo
'<div class="fw-option-type-builder-fullscreen-backdrop' . (self::is_fullscreen_on() ? '' : ' fw-hidden') . '" >'.
' <div class="buttons-wrapper">'.
' <span class="spinner"></span>'.
' <a class="preview button">'. __('Preview Changes', 'fw') .'</a>'.
' <a class="button button-primary">'. __('Update', 'fw') .'</a>'.
' </div>'.
'</div>';
}
}
_FW_Ext_Builder_Fullscreen::init();

View File

@@ -0,0 +1,32 @@
### Create new component
* Create a class that extends `FW_Ext_Builder_Templates_Component`
```php
class FW_Ext_Builder_Templates_Component_Demo extends FW_Ext_Builder_Templates_Component {
// Create all required abstract methods ...
}
```
* Register the class on special action
```php
add_action('fw_ext_builder:template_components_register', '_action_fw_ext_builder_template_component_demo');
function _action_fw_ext_builder_template_component_demo() {
require_once dirname(__FILE__) .'/.../path/to/class.php';
FW_Ext_Builder_Templates::register_component(
new FW_Ext_Builder_Templates_Component_Demo()
);
}
```
* In javascript, init the html returned by `FW_Ext_Builder_Templates_Component_Demo::_render()`
```javascript
fwEvents.on('fw:option-type:builder:templates:init', function(data){
data.$elements.find('.fw-builder-templates-type-COMPONENT_TYPE .whatever-element a').on('click', function(){
alert('Hello World!');
});
});
```

View File

@@ -0,0 +1,93 @@
<?php
abstract class FW_Ext_Builder_Templates_Component
{
/**
* Unique type
* @return string
*/
abstract public function get_type();
/**
* @return string
*/
abstract public function get_title();
/**
* @param array $data {'builder_type': '...'}
* @return string HTML for tooltip
* @internal
*/
abstract public function _render($data);
/**
* Enqueue css and js
* @param array $data {'builder_type': '...'}
* @internal
*/
abstract public function _enqueue($data);
/**
* Called right after the component was fully registered
* @internal
*/
public function _init() {}
/**
* @param string $builder_type Builder option type
* @return bool
*/
protected function builder_type_is_valid($builder_type)
{
if (
empty($builder_type)
||
!fw()->backend->option_type($builder_type)
||
!(fw()->backend->option_type($builder_type) instanceof FW_Option_Type_Builder)
) {
return false;
} else {
return true;
}
}
/**
* @param string $builder_type
* @return array|mixed
* @since 1.1.14
*/
protected function get_predefined_templates($builder_type)
{
$cache_id = 'fw_ext_builder/predefined_templates/'. $builder_type .'/'. $this->get_type();
try {
return FW_Cache::get($cache_id);
} catch (FW_Cache_Not_Found_Exception $e) {
$templates = array();
foreach(apply_filters('fw_ext_builder:predefined_templates:'. $builder_type .':'. $this->get_type(), array(
// 'id' => array('title' => 'Title', 'json' => '[]')
)) as $id => $template) {
if (
isset($template['title']) && is_string($template['title'])
&&
isset($template['json']) && is_string($template['json']) && null !== json_decode($template['json'])
) {
$templates[ $id ] = array(
'title' => $template['title'],
'json' => $template['json'],
'type' => 'predefined'
);
} else {
trigger_error('Invalid predefined template: '. $id, E_USER_WARNING);
}
}
FW_Cache::set($cache_id, $templates);
return $templates;
}
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* Builder templates functionality
*/
final class FW_Ext_Builder_Templates
{
/**
* @var FW_Ext_Builder_Templates_Component[]
*/
private static $components;
private static $registration_is_allowed = false;
/**
* @internal
*/
public static function _init()
{
add_action('fw_ext_builder:option_type:builder:enqueue', array(__CLASS__, '_action_builder_enqueue'));
add_action('wp_ajax_fw_builder_templates_render', array(__CLASS__, '_action_ajax_render'));
add_action('init', array(__CLASS__, '_action_init'));
}
/**
* @internal
*/
public static function _action_init()
{
if (defined('DOING_AJAX') && DOING_AJAX === true) {
/**
* Load and init components
* Some of them may have add_action('wp_ajax_...')
*/
self::get_components();
}
}
/**
* @internal
*/
public static function _action_ajax_render()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
$builder_type = (string)FW_Request::POST('builder_type');
if (!fw()->backend->option_type($builder_type)) {
wp_send_json_error();
}
$first = true;
$html = '<div class="fw-builder-templates-types">';
foreach (self::get_components() as $component) {
$component_html = $component->_render(array('builder_type' => $builder_type));
if (empty($component_html)) {
continue;
}
$html .=
'<div class="fw-builder-templates-type fw-builder-templates-type-'. esc_attr($component->get_type()) .'"'.
' data-type="'. esc_attr($component->get_type()) .'">'
. '<a class="fw-builder-templates-type-title" href="#" onclick="return false;">'
. $component->get_title()
. '</a>'
. '<div class="fw-builder-templates-type-content'. ($first ? '' : ' fw-hidden') .'">'
. $component_html
. '</div>'
. '</div>';
$first = false;
unset($component_html);
}
$html .= '</div>';
wp_send_json_success(array(
'html' => $html
));
}
/**
* @internal
*/
public static function _action_builder_enqueue($data)
{
if (!
apply_filters(
'fw_builder_has_template_saving_feature',
$data['option']['template_saving'],
$data['option']
)
) {
return;
}
$uri = $data['uri'] .'/includes/templates/static';
wp_enqueue_style(
'fw-option-builder-templates',
$uri .'/styles.css',
array('fw-option-builder'),
$data['version']
);
wp_enqueue_script(
'fw-option-builder-templates',
$uri .'/scripts.js',
array('fw-option-builder'),
$data['version'],
true
);
wp_localize_script(
'fw-option-builder-templates',
'_fw_option_type_builder_templates',
array(
'l10n' => array(
'templates' => __('Templates', 'fw'),
),
)
);
foreach (self::get_components() as $component) {
$component->_enqueue(array('builder_type' => $data['option']['type']));
}
}
public static function register_component(FW_Ext_Builder_Templates_Component $component)
{
if (!self::$registration_is_allowed) {
trigger_error('Registration is not allowed. Tried to register component: '. $component->get_type(), E_USER_ERROR);
}
if (isset(self::$components[ $component->get_type() ])) {
trigger_error('Component already registered: '. $component->get_type(), E_USER_ERROR);
}
self::$components[ $component->get_type() ] = $component;
}
/**
* @return FW_Ext_Builder_Templates_Component[]
*/
private static function get_components()
{
if (is_null(self::$components)) {
self::$components = array();
self::$registration_is_allowed = true;
do_action('fw_ext_builder:template_components_register');
self::$registration_is_allowed = false;
foreach (self::$components as $component) {
$component->_init();
}
}
return self::$components;
}
}

View File

@@ -0,0 +1,307 @@
<?php if (!defined('FW')) die('Forbidden');
class FW_Ext_Builder_Templates_Component_Full extends FW_Ext_Builder_Templates_Component
{
public function get_type()
{
return 'full';
}
public function get_title()
{
return __('Full Templates', 'fw');
}
public function _render($data)
{
$html = '';
$templates = $this->get_templates($data['builder_type']);
{
$this->fake_created_value = 0;
$templates = array_map( // make this to keep elements order after applying uasort()
array($this, 'array_map_add_fake_created_key'),
$templates
);
}
uasort($templates, array($this, 'sort_templates'));
foreach ($templates as $template_id => $template) {
if (isset($template['type']) && $template['type'] === 'predefined') {
$delete_btn = '';
} else {
$delete_btn = '<a href="#" onclick="return false;" data-delete-template="'. fw_htmlspecialchars($template_id) .'"'
. ' class="template-delete dashicons fw-x"></a>';
}
$html .=
'<li>'
. $delete_btn
. '<a href="#" onclick="return false;" data-load-template="'. fw_htmlspecialchars($template_id) .'"'
. ' class="template-title">'
. fw_htmlspecialchars($template['title'])
. '</a>'
. '</li>';
}
if (empty($html)) {
$html = '<div class="fw-text-muted no-'. $this->get_type() .'-templates">'. __('No Templates Saved', 'fw') .'</div>';
} else {
$html =
'<p class="fw-text-muted load-template-title">'. __('Load Template', 'fw') .':</p>'
. '<ul class="std">'. $html .'</ul>';
}
$html =
'<div class="save-template-wrapper">'
. '<a href="#" onclick="return false;" class="save-template button button-primary">'
. __('Save Full Template', 'fw')
. '</a>'
. '</div>'
. $html;
return $html;
}
public function _enqueue($data)
{
$uri = fw_ext('builder')->get_uri('/includes/option-types/builder/includes/templates/components/'. $this->get_type());
$version = fw_ext('builder')->manifest->get_version();
wp_enqueue_style(
'fw-option-builder-templates-'. $this->get_type(),
$uri .'/styles.css',
array('fw-option-builder-templates'),
$version
);
wp_enqueue_script(
'fw-option-builder-templates-'. $this->get_type(),
$uri .'/scripts.js',
array('fw-option-builder-templates'),
$version,
true
);
wp_localize_script(
'fw-option-builder-templates-'. $this->get_type(),
'_fw_option_type_builder_templates_'. $this->get_type(),
array(
'l10n' => array(
'template_name' => __('Template Name', 'fw'),
'save_template' => __('Save Builder Template', 'fw'),
),
)
);
}
public function _init()
{
add_action('wp_ajax_fw_builder_templates_'. $this->get_type() .'_load', array($this, '_action_ajax_load_template'));
add_action('wp_ajax_fw_builder_templates_'. $this->get_type() .'_save', array($this, '_action_ajax_save_template'));
add_action('wp_ajax_fw_builder_templates_'. $this->get_type() .'_delete', array($this, '_action_ajax_delete_template'));
}
private $fake_created_value;
private function array_map_add_fake_created_key($el)
{
if (!isset($el['created'])) {
/**
* Before 1.1.14 templates were appended
* After 1.1.14 templates are prepended
* So reverse old templates to be in the same order as the new ones
*/
$el['created'] = (++$this->fake_created_value);
}
return $el;
}
private function get_templates($builder_type)
{
return $this->get_db_templates($builder_type) + $this->get_predefined_templates($builder_type);
}
private function get_wp_option_prefix($builder_type)
{
return 'fw:bt:f:'. $builder_type .':';
}
private function sort_templates($a, $b)
{
$at = isset($a['created']) ? $a['created'] : 0;
$bt = isset($b['created']) ? $b['created'] : 0;
if ($at == $bt) {
return 0;
}
return ($at > $bt) ? -1 : 1;
}
/**
* @internal
*/
public function _action_ajax_load_template()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
$builder_type = (string)FW_Request::POST('builder_type');
if (!$this->builder_type_is_valid($builder_type)) {
wp_send_json_error();
}
$templates = $this->get_templates($builder_type);
$template_id = (string)FW_Request::POST('template_id');
if (!isset($templates[$template_id])) {
wp_send_json_error();
}
wp_send_json_success(array(
'json' => $templates[$template_id]['json']
));
}
/**
* @internal
*/
public function _action_ajax_save_template()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
$builder_type = (string)FW_Request::POST('builder_type');
if (!$this->builder_type_is_valid($builder_type)) {
wp_send_json_error();
}
$template = array(
'title' => trim((string)FW_Request::POST('template_name')),
'json' => trim((string)FW_Request::POST('builder_json')),
'created' => time(),
);
if (
empty($template['json'])
||
($decoded_json = json_decode($template['json'], true)) === null
) {
wp_send_json_error();
}
unset($decoded_json);
if (empty($template['title'])) {
$template['title'] = __('No Title', 'fw');
}
$template_id = md5($template['json']);
update_option(
$this->get_wp_option_prefix($builder_type) . $template_id,
$template,
false
);
/**
* Remove from old storage (to prevent array key merge with old value on get)
*/
{
$old_templates = fw_get_db_extension_data('builder', 'templates/'. $builder_type, array());
unset($old_templates[$template_id]);
fw_set_db_extension_data('builder', 'templates/'. $builder_type, $old_templates);
unset($old_templates);
}
wp_send_json_success();
}
/**
* @internal
*/
public function _action_ajax_delete_template()
{
if (!current_user_can('edit_posts')) {
wp_send_json_error();
}
$builder_type = (string)FW_Request::POST('builder_type');
if (!$this->builder_type_is_valid($builder_type)) {
wp_send_json_error();
}
$template_id = (string)FW_Request::POST('template_id');
delete_option($this->get_wp_option_prefix($builder_type) . $template_id);
/**
* Remove from old storage
*/
{
$old_templates = fw_get_db_extension_data('builder', 'templates/'. $builder_type, array());
unset($old_templates[$template_id]);
fw_set_db_extension_data('builder', 'templates/'. $builder_type, $old_templates);
unset($old_templates);
}
wp_send_json_success();
}
/**
* @param $builder_type
* @return mixed|null
*
* Note: Templates can be very big and saving them in a single wp option can throw mysql error on update query
*/
protected function get_db_templates($builder_type)
{
$templates = array();
/**
* Note: 'prefix + name' max length should be 64
*/
$option_prefix = $this->get_wp_option_prefix($builder_type); // + md5 (length=32)
/**
* @var WPDB $wpdb
*/
global $wpdb;
foreach ((array)$wpdb->get_results($wpdb->prepare(
"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
$wpdb->esc_like( $option_prefix ) .'%'
), ARRAY_A) as $row) {
$templates[
// extract (suffix) md5 used as id
preg_replace('/^'. preg_quote($option_prefix, '/') .'/', '', $row['option_name'])
] = get_option($row['option_name']);
}
$templates +=
/**
* Append old templates
* This can't be removed because a lot of installations already use this
*/
fw_get_db_extension_data('builder', 'templates/'. $builder_type, array());
return $templates;
}
}

View File

@@ -0,0 +1,8 @@
<?php if (!defined('FW')) die('Forbidden');
add_action('fw_ext_builder:template_components_register', '_action_fw_ext_builder_template_component_full', 3);
function _action_fw_ext_builder_template_component_full() {
FW_Ext_Builder_Templates::register_component(
new FW_Ext_Builder_Templates_Component_Full()
);
}

View File

@@ -0,0 +1,141 @@
(function($, localized){
var eventsNamespace = '.templates-full',
loadingId = 'fw-builder-templates-type-full',
modal,
lazyInitModal = function () {
lazyInitModal = function () {};
modal = new fw.OptionsModal({
title: localized.l10n.save_template,
options: [
{
'template_name': {
'type': 'text',
'label': localized.l10n.template_name
}
}
],
values: ''
});
};
fwEvents.on('fw:option-type:builder:templates:init', function(data){
var loading = data.tooltipLoading,
builder = data.builder,
tooltipHideCallback = data.tooltipHideCallback,
tooltipRefreshCallback = data.tooltipRefreshCallback;
data.$elements.find('.fw-builder-templates-type-full')
.off(eventsNamespace)
.on('click'+ eventsNamespace, 'a[data-load-template]', function(){
var templateId = $(this).attr('data-load-template');
loading.show();
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'fw_builder_templates_full_load',
'builder_type': builder.get('type'),
'template_id': templateId
}
})
.done(function(json){
loading.hide();
if (!json.success) {
console.error('Failed to load builder template', json);
return;
}
if (JSON.stringify(builder.rootItems) === json.data.json) {
console.log('Loaded value is the same as current');
} else {
builder.rootItems.reset(JSON.parse(json.data.json));
}
tooltipHideCallback();
})
.fail(function(xhr, status, error){
loading.hide();
console.error('Ajax error', error);
});
})
.on('click'+ eventsNamespace, 'a[data-delete-template]', function(){
var templateId = $(this).attr('data-delete-template');
loading.show();
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'fw_builder_templates_full_delete',
'builder_type': builder.get('type'),
'template_id': templateId
}
})
.done(function(json){
loading.hide();
if (!json.success) {
console.error('Failed to delete builder template', json);
return;
}
tooltipRefreshCallback();
})
.fail(function(xhr, status, error){
loading.hide();
console.error('Ajax error', error);
});
})
.on('click'+ eventsNamespace, 'a.save-template', function () {
tooltipHideCallback();
lazyInitModal();
// reset previous values
modal.set('values', {}, {silent: true});
// remove previous listener
modal.off('change:values');
modal.on('change:values', function (modal, values) {
fw.loading.show(loadingId);
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'fw_builder_templates_full_save',
'template_name': values.template_name,
'builder_json': JSON.stringify(builder.rootItems),
'builder_type': builder.get('type')
}
})
.done(function (json) {
fw.loading.hide(loadingId);
if (!json.success) {
console.error('Failed to save builder template', json);
return;
}
})
.fail(function (xhr, status, error) {
fw.loading.hide(loadingId);
console.error('Ajax save error', error);
});
});
modal.open();
});
});
})(jQuery, _fw_option_type_builder_templates_full);

View File

@@ -0,0 +1,4 @@
.fw-builder-templates-type-full .save-template-wrapper a {
text-decoration: none !important;
font-style: normal;
}

View File

@@ -0,0 +1,7 @@
<?php if (!defined('FW')) die('Forbidden');
foreach (array('full') as $component_id) {
require_once dirname(__FILE__) .'/components/'. $component_id .'/init.php';
}
FW_Ext_Builder_Templates::_init();

View File

@@ -0,0 +1,182 @@
(function ($, fwe, _, localized) {
$(document.body).on('fw:option-type:builder:init', function(e, data) {
var inst = {
$el: {
builder: $(e.target),
tooltipContent: $('<div class="fw-builder-templates-tooltip-content"></div>'),
tooltipLoading: $(
'<div class="fw-builder-templates-tooltip-loading">'+
/**/'<div class="loading-icon fw-animation-rotate-reverse-180 unycon unycon-unyson-o"></div>'+
'</div>'
),
headerTools: data.$headerTools
},
builder: data.builder,
isBusy: false,
tooltipLoading: {
show: function() {
inst.$el.tooltipContent.prepend(inst.$el.tooltipLoading);
},
hide: function() {
inst.$el.tooltipLoading.detach();
}
},
tooltipApi: null, // initialized below
refresh: function() {
if (this.isBusy) {
console.log('Working... Try again later');
return;
}
this.isBusy = true;
this.tooltipLoading.show();
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'fw_builder_templates_render',
'builder_type': this.builder.get('type')
}
})
.done(_.bind(function(json){
this.isBusy = false;
this.tooltipLoading.hide();
if (!json.success) {
console.error('Failed to render builder templates', json);
return;
}
this.$el.tooltipContent.html(json.data.html);
/**
* Html was replaced
* Components that have html in tooltip, must init js events
*/
fwe.trigger('fw:option-type:builder:templates:init', {
$elements: this.$el.tooltipContent,
builder: this.builder,
tooltipLoading: this.tooltipLoading,
tooltipRefreshCallback: _.bind(this.refresh, this),
tooltipHideCallback: _.bind(function(){ this.tooltipApi.hide(); }, this)
});
this.$el.tooltipContent.trigger('fw:option-type:builder:templates:after-html-replace');
}, this))
.fail(_.bind(function(xhr, status, error){
this.isBusy = false;
this.tooltipLoading.hide();
fw.soleModal.show(
'fw-builder-templates-error',
'<h4>Ajax Error</h4><p class="fw-text-danger">'+ String(error) +'</p>',
{showCloseButton: false}
);
}, this));
}
};
inst.$el.headerTools
.removeClass('fw-hidden')
.append(
'<div class="template-container fw-pull-right">' +
/**/'<a class="template-btn" href="#" onclick="return false;">'+ localized.l10n.templates +'</a>' +
'</div>'
);
inst.tooltipApi = inst.$el.headerTools
.find('.template-container .template-btn')
.qtip({
show: 'click',
hide: 'unfocus',
position: {
at: 'bottom center',
my: 'top center',
viewport: $(document.body)
},
events: {
show: function () {
inst.refresh();
}
},
style: {
classes: 'qtip-fw qtip-fw-builder',
tip: {
width: 12,
height: 5
},
width: 180
},
content: {
text: inst.$el.tooltipContent
}
})
.qtip('api');
/**
* Accordion
*/
inst.$el.tooltipContent
.on(
'click',
'.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-title',
function() {
var $wrapper = $(this).closest('.fw-builder-templates-type'),
$content = $wrapper.find('> .fw-builder-templates-type-content'),
$root = $wrapper.closest('.fw-builder-templates-types'),
specialClass = 'current';
if ($root.hasClass('is-busy')) {
return;
} else {
$root.addClass('is-busy');
}
$content.addClass(specialClass);
$root
.find('> .fw-builder-templates-type > .fw-builder-templates-type-content:not(.'+specialClass+'):not(.fw-hidden)')
.slideUp(function(){
$(this).addClass('fw-hidden').removeAttr('style');
});
$content.removeClass(specialClass);
inst.$el.tooltipContent.removeAttr('data-open-type');
if ($content.hasClass('fw-hidden')) {
$content
.css('display', 'none')
.removeClass('fw-hidden')
.slideDown(function(){
$root.removeClass('is-busy');
$(this).removeAttr('style');
inst.$el.tooltipContent.attr('data-open-type', $wrapper.attr('data-type'));
});
} else {
$content.slideUp(function(){
$root.removeClass('is-busy');
$(this).addClass('fw-hidden').removeAttr('style');
});
}
}
)
.on('fw:option-type:builder:templates:after-html-replace', function(){
// reopen accordion type that was open before tooltip html replace
{
var openType = inst.$el.tooltipContent.attr('data-open-type');
if (openType) {
inst.$el.tooltipContent // close all
.find('.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-content')
.addClass('fw-hidden');
inst.$el.tooltipContent // open one
.find('.fw-builder-templates-types > .fw-builder-templates-type-'+ openType +' > .fw-builder-templates-type-content')
.removeClass('fw-hidden');
}
}
});
});
})(jQuery, fwEvents, _, _fw_option_type_builder_templates);

View File

@@ -0,0 +1,146 @@
body.rtl .fw-option-type-builder .template-container {
float: left;
}
.fw-option-type-builder .template-container .template-btn {
text-decoration: none;
cursor: pointer;
}
.fw-option-type-builder .template-container .template-btn:before {
content: "\f135";
font-family: dashicons;
padding-right: 3px;
vertical-align: text-bottom;
line-height: normal;
}
.fw-option-type-builder .template-container a:focus {
box-shadow: none;
}
.fw-builder-templates-tooltip-content {
text-align: left;
padding: 5px;
min-height: 70px; /* space for loading */
}
.fw-builder-templates-tooltip-content .fw-builder-templates-tooltip-loading {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #333333;
}
.fw-builder-templates-tooltip-content .fw-builder-templates-tooltip-loading .loading-icon {
display: block;
position: relative;
top: 50%;
margin: -15px auto 0 auto;
font-size: 30px;
color: #555;
text-align: center;
}
.fw-builder-templates-types > .fw-builder-templates-type {
border-bottom: 1px solid #4B4B4B;
border-bottom: 1px solid rgba(208, 208, 208, 0.15);
padding-bottom: 10px;
margin-bottom: 10px;
}
.fw-builder-templates-types > .fw-builder-templates-type:last-child {
border-bottom-width: 0;
padding-bottom: 0;
margin-bottom: 0;
}
.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-title {
display: block;
font-style: normal;
text-decoration: none;
}
.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-title:focus {
box-shadow: none;
}
.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-content {
border-top: 1px dashed #4B4B4B;
border-top: 1px dashed rgba(208, 208, 208, 0.15);
padding-top: 10px;
margin-top: 10px;
}
.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-content .no-full-templates {
margin-top: 10px;
}
.fw-builder-templates-types > .fw-builder-templates-type > .fw-builder-templates-type-content .load-template-title {
margin: 10px 0;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std {
margin: 0;
width: 100%;
max-height: 200px;
overflow: auto;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li {
font-style: normal;
padding-bottom: 10px;
margin-bottom: 0px;
list-style-type: none;
margin-left: 4px;
text-align: left;
line-height: 18px;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a.template-title {
display: block;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a.template-title:before {
content: "•"; /* emulate native list bullet */
font-size: 1.6em;
vertical-align: sub;
line-height: 1px;
padding-right: 5px;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li,
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a {
color: #b1b1b1 !important;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li:hover,
.fw-builder-templates-types > .fw-builder-templates-type ul.std li:hover a {
color: #eee !important;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a {
text-decoration: none !important;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a:focus {
box-shadow: none;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li:last-child {
padding-bottom: 0px;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li a.template-delete {
float: right;
visibility: hidden;
margin-top: 3px;
text-decoration: none !important;
}
.fw-builder-templates-types > .fw-builder-templates-type ul.std li:hover a.template-delete {
visibility: visible;
}

View File

@@ -0,0 +1,437 @@
.fw-option-type-builder > .builder-items-types {
padding: 0;
margin-bottom: 1px; /* space for border that will appear on fixed header */
background-color: #fff;
}
.fw-option-type-builder.fixed-header {
position: relative;
}
.fw-option-type-builder.fixed-header > .builder-items-types {
position: absolute;
width: 100%;
z-index: 1;
}
.fw-option-type-builder.fixed-header.has-header-tools > .builder-items-types {
margin-bottom: 0;
border-bottom: 1px solid #eeeeee;
}
.fw-option-type-builder > .builder-items-types > .fw-options-tabs-wrapper {
padding-bottom: 15px;
border-bottom: 1px solid #eeeeee;
}
.fw-option-type-builder > .builder-items-types > .fw-builder-header-tools {
padding: 20px;
}
.fw-option-type-builder > .builder-items-types > .fw-builder-header-tools .fw-builder-header-post-save-button {
position: relative;
top: -5px;
margin-bottom: -10px;
}
.fw-option-type-builder .fw-option-type-builder-thumbnails-tab > .fw-backend-option-type-html {
padding: 0 16px;
}
.fw-modal .fw-option-type-builder .fw-option-type-builder-thumbnails-tab > .fw-backend-option-type-html {
padding: 1px 16px; /* 1px vertical padding for thumbnails outline */
}
.fw-option-type-builder span.fw-ext-builder-icon {
font-size: 16px;
color: #b3b3b3;
}
.fw-option-type-builder span.fw-ext-builder-icon.dashicons {
/* dashicons are smaller than font grid (it's like padding), I don't know why the font was created like that */
font-size: 20px;
}
/* tabs */
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .fw-options-tabs-contents {
margin: 20px 0 0 !important;
}
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .fw-option-type-builder-thumbnails-tab > .fw-backend-option-type-html {
padding: 0 16px !important;
}
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .ui-tabs-nav li {
margin-right: 1px !important;
}
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .ui-tabs-nav a {
font-size: 12px !important;
font-weight: 400 !important;
padding: 1px 14px 0 14px !important;
line-height: 25px !important;
color: #222222 !important;
background-color: #F1F1F1;
}
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .ui-tabs-nav .ui-state-active a {
color: #0074a2 !important;
background-color: #ffffff;
}
.fw-option-type-builder.fw-option-type-builder-tabs-count-1 > .builder-items-types .fw-options-tabs-wrapper .fw-options-tabs-list {
display: none;
}
.fw-option-type-builder.fw-option-type-builder-tabs-count-1 > .builder-items-types .fw-options-tabs-wrapper .fw-options-tabs-contents {
margin-top: 0 !important;
}
@media (max-width: 782px) {
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper .fw-options-tabs-list {
text-align: center;
}
body.rtl .fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .fw-options-tabs-list > ul {
float: none;
}
body.rtl .fw-option-type-builder > .builder-items-types .fullscreen-btn {
float: none;
}
}
@media (min-width: 782px) {
body.rtl .fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .fw-options-tabs-list > ul {
float: right;
}
}
/* end: tabs */
/* builder-item-type */
.fw-option-type-builder .builder-item-type {
width: 70px;
height: 70px;
font-size: 11px;
background-color: #ffffff;
float: left;
display: table;
position: relative;
outline: 1px solid #e1e1e1;
margin: 0 1px 1px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
-webkit-transition: outline-color .1s ease-in;
transition: outline-color .1s ease-in;
}
body.rtl .fw-option-type-builder .builder-item-type {
float: right;
}
.fw-option-type-builder .builder-item-type:hover {
outline-color: #8f8f8f;
z-index: 9999;
cursor: pointer;
}
.fw-option-type-builder .builder-item-type.ui-draggable-dragging {
cursor: move;
}
.fw-option-type-builder .builder-item-type .item-type-icon-title {
display: table-cell;
vertical-align: middle;
}
.fw-option-type-builder .builder-item-type .item-type-icon-title .item-type-icon {
text-align: center;
}
.fw-option-type-builder .builder-item-type .item-type-icon-title .item-type-icon .dashicons {
font-size: 24px;
display: inline-table;
color: #b3b3b3;
}
.fw-option-type-builder .builder-item-type:hover .item-type-icon-title .item-type-icon .dashicons,
.fw-option-type-builder .builder-item-type:hover span.fw-ext-builder-icon {
color: #8c8c8c;
}
.fw-option-type-builder .builder-item-type .item-type-icon-title .item-type-icon img {
display: block;
margin: 0 auto;
opacity: 0.66;
-webkit-transition: opacity .1s ease-in;
transition: opacity .1s ease-in;
}
.fw-option-type-builder .builder-item-type:hover .item-type-icon-title .item-type-icon img {
opacity: 1;
}
.fw-option-type-builder .builder-item-type .item-type-icon-title .item-type-title {
text-align: center;
line-height: 1.2;
font-size: 10px;
color: #666;
padding-top: 5px;
}
/* builder builder-item-type add animation */
@-webkit-keyframes fwBuilderItemTypeAdd {
0% {
opacity: 1;
}
70% {
opacity: 0;
-webkit-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
71% {
opacity: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
-webkit-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
100% {
opacity: 1;
}
}
@keyframes fwBuilderItemTypeAdd {
0% {
opacity: 1;
}
70% {
opacity: 0;
-webkit-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
71% {
opacity: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
-webkit-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
100% {
opacity: 1;
}
}
.fw-builder-animation-item-type-add {
-webkit-animation-name: fwBuilderItemTypeAdd;
animation-name: fwBuilderItemTypeAdd;
-webkit-animation-duration: 500ms;
animation-duration: 500ms;
}
/* end: builder-item-type add animation */
/* end: builder-item-type */
.fw-option-type-builder > .builder-root-items {
padding-top: 0px;
}
.fw-option-type-builder > .builder-root-items > .builder-items {
min-height: 200px;
}
.fw-option-type-builder.has-header-tools > .builder-root-items > .builder-items {
padding-top: 0;
}
.fw-option-type-builder.has-header-tools > .builder-root-items > .builder-items:before {
margin-top: -10px;
}
.fw-option-type-builder > .builder-root-items > .builder-items span.fw-ext-builder-icon {
bottom: -2px; /* fix for text smaller size */
position: relative;
}
.fw-option-type-builder > .builder-root-items > .builder-items span.fw-ext-builder-icon.dashicons {
bottom: 0;
}
.fw-option-type-builder > .builder-root-items > .builder-items span.fw-ext-builder-icon {
color: #8c8c8c;
margin-right: 9px;
}
.fw-option-type-builder.fw-option-type-builder-tabs-count-0 > .builder-root-items {
border-top-width: 0;
}
.fw-option-type-builder .builder-items {
padding: 10px;
}
.fw-option-type-builder .builder-items .builder-item {
float: none;
display: inline-block;
vertical-align: top;
padding: 10px;
}
.fw-option-type-builder .builder-items .builder-item .controls > * {
vertical-align: middle;
}
.fw-option-type-builder .builder-items .builder-item .controls .unycon,
.fw-option-type-builder .builder-items .builder-item .controls .fa {
margin-left: 4px;
margin-right: 4px;
font-size: 14px;
}
.fw-option-type-builder .builder-items .builder-item .controls .dashicons {
height: 16px;
line-height: 14px;
}
.fw-option-type-builder .builder-items .builder-item:hover {
cursor: pointer;
}
.fw-option-type-builder .builder-items .builder-item.ui-sortable-helper {
cursor: move;
}
.fw-option-type-builder .builder-items .builder-item.new-item {
animation: fwDropIn .3s ease-in;
animation-iteration-count: 1;
-webkit-animation: fwDropIn .3s ease-in;
-webkit-animation-iteration-count: 1;
-moz-animation: fwDropIn .3s ease-in;
-moz-animation-iteration-count: 1;
-o-animation: fwDropIn .3s ease-in;
-o-animation-iteration-count: 1;
-ms-animation: fwDropIn .3s ease-in;
-ms-animation-iteration-count: 1;
}
.fw-option-type-builder > .builder-root-items .fw-builder-placeholder {
display: inline-block;
float: none;
padding: 10px;
min-height: 50px;
position: relative;
}
.fw-option-type-builder > .builder-root-items .fw-builder-placeholder:before {
content: ' ';
border: 1px dashed #d8d8d8;
background-color: rgba(85, 85, 85, 0.03);
display: block;
position: absolute;
top: 10px;
right: 10px;
bottom: 10px;
left: 10px;
}
.fw-option-type-builder > .builder-root-items .fw-builder-placeholder.no-top:before {
top: 0;
}
.fw-option-type-builder .builder-items .builder-item.fw-builder-item-deny-incoming-type > div > .builder-items > .fw-builder-placeholder {
display: none;
}
/* allow/deny items in _items */
.fw-option-type-builder .builder-items .builder-item.fw-builder-item-allow-incoming-type > div > .builder-items {
/*background-color: #DDFFD2;*/
}
.fw-option-type-builder .builder-items .builder-item.fw-builder-item-deny-incoming-type > div > .builder-items {
/*background-color: #FFEFE7;*/
}
.fw-option-type-builder .builder-items .builder-item.fw-builder-item-deny-incoming-type > div {
position: relative;
}
.fw-option-type-builder .builder-items .builder-item.fw-builder-item-deny-incoming-type > div > .builder-items:before {
content: ' ';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: transparent url('../img/gradient-slash.png') repeat scroll 0 0;
opacity: 0.65;
}
/* end: allow/deny*/
/* backend fixes */
[class*="-collapsed"] .builder-items,
[class*="-collapsed"] .builder-items * {
height:0;
display:none;
}
.fw-backend-option-type-builder {
padding: 0;
}
.fw-backend-option-type-builder > .fw-backend-option-desc {
padding: 15px 25px 0;
}
.fw-option-type-builder .fw-backend-option-type-html {
padding-top: 0;
border-bottom: 0;
}
/* end: backend fixes */
/* qtip */
.qtip-fw-builder {
padding: 5px 10px;
min-width: 0;
}
.qtip-fw-builder .qtip-content {
text-align: center;
}
/* end: qtip */

View File

@@ -0,0 +1,101 @@
.fw-option-type-builder-fullscreen-backdrop {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 99997;
margin: 0;
background-color: #E1E1E1;
}
body.admin-bar .fw-option-type-builder-fullscreen-backdrop {
top: 32px;
}
.fw-option-type-builder-fullscreen-backdrop .buttons-wrapper {
float: right;
margin: 10px 20px;
}
.fw-option-type-builder-fullscreen-backdrop .button {
margin-left: 5px;
float: left;
}
.fw-option-type-builder-fullscreen-backdrop .buttons-wrapper .spinner {
float: left;
margin-top: 4px;
margin-right: 0px;
}
.fw-option-type-builder > .builder-items-types .fullscreen-btn {
float: right;
cursor: pointer;
color: #0074a2;
margin: -5px 10px 10px 0;
}
body.rtl .fw-option-type-builder > .builder-items-types .fullscreen-btn {
float: left;
}
.fw-option-type-builder > .builder-items-types .fullscreen-btn div {
float: left;
}
.fw-option-type-builder > .builder-items-types .fullscreen-btn .icon-fullscreen-on {
width: 9px;
height: 18px;
margin-right: 5px;
background-position: center;
background-image: url(../img/fullscreen/fullscreen-on.png);
background-repeat: no-repeat;
}
.fw-option-type-builder > .builder-items-types .fullscreen-btn .icon-fullscreen-off {
width: 9px;
height: 18px;
margin-right: 5px;
background-position: center;
background-image: url(../img/fullscreen/fullscreen-off.png);
background-repeat: no-repeat;
}
@media (max-width: 782px) {
.fw-option-type-builder > .builder-items-types .fullscreen-btn {
float: none;
margin: 0 auto 10px;
display: inline-block;
}
}
@media (min-width: 783px) {
.fw-option-type-builder > .builder-items-types .fw-options-tabs-wrapper.fw-options-tabs-first-level .fw-options-tabs-list > ul {
float: left; /* needed when the Fullscreen button goes on top of tabs when page width is small http://bit.ly/1FSCB7p */
}
}
.fw-option-type-builder .ui-tabs-nav.ui-helper-clearfix:after {
clear: none;
}
.fw-option-type-builder.builder-fullscreen {
position: fixed;
padding-top: 10px;
top: 82px;
left: 20px;
right: 20px;
z-index: 99998;
margin: 0;
background-color: #fff;
}
.fw-option-type-builder.builder-fullscreen > .builder-root-items {
overflow: auto;
overflow-x: hidden;
}

View File

@@ -0,0 +1,24 @@
/* Width Changer */
.fw-builder-item-width-changer {
white-space: nowrap;
font-weight: bold;
}
.fw-builder-item-width-changer a {
font-size: 13px;
font-weight: bold;
line-height: 18px;
width: 18px;
height: 18px;
outline: 0;
}
.fw-builder-item-width-changer.is-first a.decrease-width,
.fw-builder-item-width-changer.is-last a.increase-width {
color: #b2b2b2;
}
.fw-builder-col-1-5{
width: 20%;
}

View File

@@ -0,0 +1,46 @@
.fw-option-type-builder .history-container {
float: left;
}
body.rtl .fw-option-type-builder .history-container {
float: right;
}
.fw-option-type-builder .history-container a {
margin-right: 10px;
text-decoration: none;
}
.fw-option-type-builder .history-container a:focus {
-webkit-box-shadow: none;
box-shadow: none;
}
.fw-option-type-builder .history-container a.disabled {
margin-right: 10px;
text-decoration: none;
color: #b2b2b2;
}
.fw-option-type-builder a.undo {
background-image: url(../img/history/undo.png);
background-repeat: no-repeat;
padding-left: 14px;
background-position: left center;
}
.fw-option-type-builder a.undo.disabled {
background-image: url(../img/history/undo_disabled.png);
}
.fw-option-type-builder a.redo {
background-image: url(../img/history/redo.png);
background-repeat: no-repeat;
padding-left: 14px;
background-position: left center;
margin-left: 14px;
}
.fw-option-type-builder a.redo.disabled {
background-image: url(../img/history/redo_disabled.png);
}

View File

@@ -0,0 +1,979 @@
jQuery( document ).ready( function ( $ ) {
/** Some functions */
{
/**
* Loop recursive through all items in given collection
*/
function forEachItemRecursive( collection, callback ) {
collection.each( function ( item ) {
callback( item );
forEachItemRecursive( item.get( '_items' ), callback );
} );
}
}
var Builder = Backbone.Model.extend( {
defaults: {
type: null // required
},
/**
* Extract item type from class
* @param {this.classes.Item} ItemClass
* @returns {String}
*/
getItemClassType: function ( ItemClass ) {
return (
typeof ItemClass.prototype.defaults === 'function'
)
? ItemClass.prototype.defaults().type
: ItemClass.prototype.defaults.type;
},
/**
* @param {String} type
* @returns {this.classes.Item}
*/
getRegisteredItemClassByType: function ( type ) {
return this.registeredItemsClasses[type];
},
/**
* Register Item Class (with unique type)
* @param {this.classes.Item} ItemClass
* @returns {boolean}
*/
registerItemClass: function ( ItemClass ) {
if ( ! (
ItemClass.prototype instanceof this.classes.Item
) ) {
console.error( 'Tried to register Item Type Class that does not extend this.classes.Item', ItemClass );
return false;
}
var type = this.getItemClassType( ItemClass );
if ( typeof type != 'string' ) {
console.error( 'Invalid Builder Item type: ' + type, ItemClass );
return false;
}
if ( typeof this.registeredItemsClasses[type] != 'undefined' ) {
console.error( 'Builder Item type "' + type + '" already registered', ItemClass );
return false;
}
this.registeredItemsClasses[type] = ItemClass;
return true;
},
/**
* Find Item instance recursive in Items collection
* @param {Object} itemAttr (can be specified cid)
* @param {this.classes.Items} [items]
* @return {this.classes.Item|null}
*/
findItemRecursive: function ( itemAttr, items ) {
if ( arguments.length < 2 ) {
items = this.rootItems;
}
var item = items.get( itemAttr );
if ( item ) {
return item;
}
var that = this;
items.each( function ( _item ) {
if ( item ) {
// stop search if item found
return false;
}
/** @var {builder.classes.Item} _item */
item = that.findItemRecursive(
itemAttr,
_item.get( '_items' )
);
} );
return item;
},
/**
* ! Do not rewrite this (it's final)
* @private
*
* Properties created in initialize():
*
* Classes to extend
* - classes.Item
* - classes.ItemView
* - classes.Items
* - classes.ItemsView
*
* From this classes will be created items instances
* { 'type' => Class }
* - registeredItemsClasses
*
* Reference to root this.classes.Items Collection instance that contains all items
* - rootItems
*
* Hidden input that stores JSON.stringify(this.rootItems)
* - $input
*/
initialize: function ( attributes, options ) {
var builder = this;
/**
* todo: To be able to extend and customize for e.g. only Item class. To not rewrite entire .initialize()
* this.__definePrivateMethods()
* this.__defineItem()
* this.__defineItemView()
* this.__defineItems()
* this.__defineItemsView()
*/
/**
* Assign a value to define this property inside this, not in prototype
* Instances of Builder should not share items
*/
this.registeredItemsClasses = {};
/** Define private functions accessible only within this method */
{
/**
* (Re)Create Items from json
*
* Used on collection.reset([...]) to create nested items
*
* @param {this.classes.Item} item
* @param {Array} _items
* @returns {boolean}
* @private
*/
function createItemsFromJSON( item, _items ) {
if ( ! _items ) {
return false;
}
_.each( _items, function ( _item ) {
var ItemClass = builder.getRegisteredItemClassByType( _item['type'] );
if ( ! ItemClass ) {
return;
}
var __items = _item['_items'];
delete _item['_items'];
var subItem = new ItemClass( _item );
item.get( '_items' ).add( subItem );
createItemsFromJSON( subItem, __items );
} );
return true;
}
// Mark new added items with special class, to be able to add css effects to it
{
var markItemAsNew;
(
function () {
var lastNewItem = false;
var rootItemsInitialized = false;
var removeClassTimeout;
var removeClassAfter = 700;
markItemAsNew = function ( item ) {
clearTimeout( removeClassTimeout );
if ( lastNewItem ) {
lastNewItem.view.$el.removeClass( 'new-item' );
}
item.view.$el.addClass( 'new-item' );
lastNewItem = item;
removeClassTimeout = setTimeout( function () {
if ( lastNewItem ) {
lastNewItem.view.$el.removeClass( 'new-item' );
}
}, removeClassAfter );
if ( ! rootItemsInitialized ) {
builder.rootItems.on( 'builder:change', function () {
if ( lastNewItem ) {
lastNewItem.view.$el.removeClass( 'new-item' );
}
lastNewItem = false;
} );
rootItemsInitialized = true;
}
}
}
)();
}
}
/** Define classes */
{
this.classes = {};
/** Items */
{
this.classes.Items = Backbone.Collection.extend( {
/**
* Guess which item type to create from json
* (usually called on .reset())
*/
model: function ( attrs, options ) {
do {
if ( typeof attrs == 'function' ) {
// It's a class. Check if has correct type
if ( builder.getItemClassType( attrs ) ) {
return attrs;
} else {
break;
}
} else if ( typeof attrs == 'object' ) {
/**
* it's an object with attributes for new instance
* check if has correct type in it (get registered class with this type)
*/
var ItemClass = builder.getRegisteredItemClassByType( attrs['type'] );
if ( ! ItemClass ) {
break;
}
var _items = attrs['_items'];
delete attrs['_items'];
var item = new ItemClass( attrs );
createItemsFromJSON( item, _items );
return item;
}
} while ( false );
console.error( 'Cannot detect Item type', attrs, options );
return new builder.classes.Item;
},
/**
* View that contains sortable with items views
*/
view: null,
initialize: function () {
this.defaultInitialize();
this.view = new builder.classes.ItemsView( {
collection: this
} );
},
/**
* It is required to call this method in .initialize()
*/
defaultInitialize: function () {
this.on( 'add', function ( item ) {
// trigger custom event on rootItems to update input value
builder.rootItems.trigger( 'builder:change' );
// markItemAsNew(item); // prevent glitches
} );
this.on( 'remove', function ( item ) {
// trigger custom event on rootItems to update input value
builder.rootItems.trigger( 'builder:change' );
} );
}
} );
this.classes.ItemsView = Backbone.View.extend( {
// required
collection: null,
// end: required
tagName: 'div',
className: 'builder-items fw-row fw-border-box-sizing',
template: _.template( '' ),
events: {},
initSortableTimeout: 0,
initialize: function () {
this.defaultInitialize();
},
/**
* It is required to call this method in .initialize()
*/
defaultInitialize: function () {
this.listenTo( this.collection, 'add change remove reset', this.render );
this.render();
},
render: function () {
/**
* First .detach() elements
* to prevent them to be removed (reset) on .html('...') replace
*/
{
this.collection.each( function ( item ) {
item.view.$el.detach();
} );
}
if ( this.$el.hasClass( 'ui-sortable' ) ) {
this.$el.sortable( 'destroy' );
}
this.$el.html( this.template( {
items: this.collection
} ) );
var that = this;
this.collection.each( function ( item ) {
that.$el.append( item.view.$el );
} );
/**
* init sortable with delay, after element added to DOM
* fixes bug: sortable sometimes not initialized if element is not in DOM
*/
{
clearTimeout( this.initSortableTimeout );
this.initSortableTimeout = setTimeout( function () {
that.initSortable();
}, 12 );
}
return this;
},
initSortable: function () {
var hasDragAndDrop = builder.rootItems.view.$el
.closest( '.fw-option-type-builder' )
.attr( 'data-drag-and-drop' );
if ( ! hasDragAndDrop ) {
return;
}
if ( this.$el.hasClass( 'ui-sortable' ) ) {
// already initialized
return false;
}
// remove "allowed" and "denied" classes from all items
function itemsRemoveAllowedDeniedClasses() {
builder.rootItems.view.$el.removeClass(
'fw-builder-item-allow-incoming-type fw-builder-item-deny-incoming-type'
);
forEachItemRecursive( builder.rootItems, function ( item ) {
item.view.$el.removeClass(
'fw-builder-item-allow-incoming-type fw-builder-item-deny-incoming-type'
);
} );
}
var rearrangeTimeout;
var additionalSortableOptions = {}
fwEvents.trigger(
'fw-builder:'+ builder.get('type') +':sortable-additional-options',
additionalSortableOptions
)
this.$el.sortable(_.extend({
items: '> .builder-item',
helper: 'original',
connectWith: '#' + builder.$input.closest( '.fw-option-type-builder' ).attr( 'id' ) + ' .builder-root-items .builder-items',
distance: 10,
opacity: 0.6,
scrollSpeed: 10,
placeholder: 'fw-builder-placeholder',
tolerance: 'pointer',
start: function ( event, ui ) {
{
ui.placeholder
.addClass( ui.item.attr( 'class' ) )
.css( 'height', ui.helper.outerHeight() );
if ( ! parseInt( ui.placeholder.css( 'padding-top' ) ) ) {
ui.placeholder.addClass( 'no-top' );
}
if ( ui.item.hasClass( 'builder-item-type' ) ) {
ui.placeholder.removeClass( 'builder-item-type' ).css( 'width', '100%' );
}
}
// check if it is an exiting item (and create variables)
{
// extract cid from view id
var movedItemCid = ui.item.attr( 'id' );
if ( ! movedItemCid ) {
// not an existing item, it's a thumbnail from draggable
return;
}
movedItemCid = movedItemCid.split( '-' ).pop();
if ( ! movedItemCid ) {
// not an existing item, it's a thumbnail from draggable
return;
}
var movedItem = builder.findItemRecursive( {cid: movedItemCid} );
if ( ! movedItem ) {
console.warn( 'Item not found (cid: "' + movedItemCid + '")' );
return;
}
// fixme: this is hardcode. need to think a better/general solution
if ( movedItem.attributes.type != 'column'
&& movedItem.attributes.type != 'section' ) {
ui.item.parents( '.builder-root-items' ).addClass( 'fw-move-simple-item' );
}
}
var movedItemType = movedItem.get( 'type' );
/**
* add "allowed" classes to items vies where allowIncomingType(movedItemType) returned true
* else add "denied" class
*/
{
{
if ( movedItem.allowDestinationType( null ) ) {
builder.rootItems.view.$el.addClass( 'fw-builder-item-allow-incoming-type' );
} else {
builder.rootItems.view.$el.addClass( 'fw-builder-item-deny-incoming-type' );
}
}
forEachItemRecursive( builder.rootItems, function ( item ) {
if ( item.cid === movedItemCid ) {
// this is current moved item
return;
}
if (
item.allowIncomingType( movedItemType )
&&
movedItem.allowDestinationType( item.get( 'type' ) )
) {
item.view.$el.addClass( 'fw-builder-item-allow-incoming-type' );
} else {
item.view.$el.addClass( 'fw-builder-item-deny-incoming-type' );
}
} );
}
// Freeze the container height
{
var container = builder.$input.closest( '.fw-option-type-builder' )
.find( '.builder-root-items > .builder-items' );
container.css( 'min-height', container.height() + 'px' );
}
},
stop: function ( event, ui ) {
clearTimeout( rearrangeTimeout );
itemsRemoveAllowedDeniedClasses();
ui.item.parents( '.builder-root-items' ).removeClass( 'fw-move-simple-item' );
// unfreeze the container height
{
var container = builder.$input.closest( '.fw-option-type-builder' )
.find( '.builder-root-items > .builder-items' );
container.css( 'min-height', '' );
}
if (ui.helper) {
$(ui.helper).remove()
}
},
receive: function ( event, ui ) {
// sometimes the "stop" event is not triggered and classes remains
itemsRemoveAllowedDeniedClasses();
{
var currentItemType = null; // will remain null if it is root collection
var currentItem;
if ( this.collection._item ) {
currentItemType = this.collection._item.get( 'type' );
currentItem = this.collection._item;
}
}
var incomingItemType = ui.item.attr( 'data-builder-item-type' );
if ( incomingItemType ) {
// received item type from draggable
var IncomingItemClass = builder.getRegisteredItemClassByType( incomingItemType );
if ( IncomingItemClass ) {
if (
IncomingItemClass.prototype.allowDestinationType( currentItemType )
&&
(
! currentItemType
||
currentItem.allowIncomingType( incomingItemType )
)
) {
this.collection.add(
new IncomingItemClass( {}, {
$thumb: ui.item
} ),
{
at: this.$el.find( '> .builder-item-type' ).index()
}
);
} else {
// replace all html, so dragged element will be removed
this.render();
}
} else {
console.error( 'Unregistered item type: ' + incomingItemType );
this.render();
}
} else {
// received existing item from another sortable
if ( ! ui.item.attr( 'id' ) ) {
console.warn( 'Invalid view id', ui.item );
return;
}
// extract cid from view id
var incomingItemCid = ui.item.attr( 'id' ).split( '-' ).pop();
var incomingItem = builder.findItemRecursive( {cid: incomingItemCid} );
if ( ! incomingItem ) {
console.warn( 'Item not found (cid: "' + incomingItemCid + '")' );
return;
}
var incomingItemType = incomingItem.get( 'type' );
var IncomingItemClass = builder.getRegisteredItemClassByType( incomingItemType );
if (
IncomingItemClass.prototype.allowDestinationType( currentItemType )
&&
(
! currentItemType
||
currentItem.allowIncomingType( incomingItemType )
)
) {
// move item from one collection to another
{
var at = ui.item.index();
// prevent 'remove', that will remove all events from the element
incomingItem.view.$el.detach();
incomingItem.collection.remove( incomingItem );
this.collection.add( incomingItem, {
at: at
} );
}
} else {
console.warn( '[Builder] Item move denied' );
ui.sender.sortable( 'cancel' );
}
}
}.bind( this ),
update: function ( event, ui ) {
if ( ui.item.attr( 'data-ignore-update-once' ) ) {
ui.item.removeAttr( 'data-ignore-update-once' );
return;
}
if ( ui.item.attr( 'data-builder-item-type' ) ) {
// element just received from draggable, it is not builder item yet, do nothing
return;
}
if ( ! ui.item.attr( 'id' ) ) {
console.warn( 'Invalid item, no id' );
return;
}
if ( ! $( this ).find( '> #' + ui.item.attr( 'id' ) + ':first' ).length ) {
// Item not in sortable, probably moved to another sortable, do nothing
/**
* Right after this event, is expected to be next 'update' for on same item.
* But between this two 'update' is a 'receive' that takes care about item move from
* one collection to another and place ar right index position in destination model,
* so it is better to ignore next coming 'update'.
* Set a special attribute to ignore 'update' once
*/
ui.item.attr( 'data-ignore-update-once', 'true' );
return;
}
// extract cid from view id
var itemCid = ui.item.attr( 'id' ).split( '-' ).pop();
var item = builder.findItemRecursive( {cid: itemCid} );
if ( ! item ) {
console.warn( 'Item not found (cid: "' + itemCid + '")' );
return;
}
var index = ui.item.index();
// change item position in collection
{
var collection = item.collection;
// prevent 'remove', that will remove all events from the element
item.view.$el.detach();
collection.remove( item );
collection.add( item, {at: index} );
}
}
}, additionalSortableOptions) );
/**
* Delay placeholder possition change to prevent "jumping"
* Fixes https://github.com/ThemeFuse/Unyson-PageBuilder-Extension/issues/25
* Original code https://github.com/jquery/jquery-ui/blob/1.12.0-rc.2/ui/widgets/sortable.js#L1384
* Note: Uses the above `var rearrangeTimeout;`
*/
this.$el.sortable( 'instance' )._rearrange = function ( event, i, a, hardRefresh ) {
clearTimeout( rearrangeTimeout );
rearrangeTimeout = setTimeout( function () {
/* The Original Code:
a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
*/
if ( this.a ) {
this.a[0].appendChild( this.instance.placeholder[0] );
} else {
if ( this.instance.placeholder.parent().length ) {
this.i.item[0].parentNode.insertBefore(
this.instance.placeholder[0],
(
this.direction === "down" ? this.i.item[0] : this.i.item[0].nextSibling
)
);
} else {
/**
* This happens for draggable items
* Do nothing to prevent DOM flood with orphaned placeholders
*/
}
}
/* The Original Code:
//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var counter = this.counter;
this._delay(function() {
if(counter === this.counter) {
this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
}
});
*/
this.instance.refreshPositions( ! this.hardRefresh );
}.bind( {
instance: this,
i: i,
a: a,
hardRefresh: hardRefresh,
direction: this.direction
} ), 100 );
};
return true;
}
} );
}
/** Item */
{
this.classes.Item = Backbone.RelationalModel.extend( {
// required
defaults: {
/** @type {String} Your item unique type (withing the builder) */
type: null
},
/** @type {builder.classes.ItemView} */
view: null,
// end: required
/** ! Do not overwrite this property */
relations: [
{
type: Backbone.HasMany,
key: '_items',
//relatedModel: builder.classes.Item, // class does not exists at this point, initialized below
collectionType: builder.classes.Items,
collectionKey: '_item'
}
],
initialize: function () {
this.view = new builder.classes.ItemView( {
id: 'fw-builder-item-' + this.cid,
model: this
} );
this.defaultInitialize();
},
/**
* It is required to call this method in .initialize()
*/
defaultInitialize: function () {
// trigger custom event on rootItems to update input value
this.on( 'change', function () {
builder.rootItems.trigger( 'builder:change' );
} );
},
/**
* Item decide if allows an incoming item type to be placed inside it's _items
*
* @param {String} type
* @returns {boolean}
*/
allowIncomingType: function ( type ) {
return false;
},
/**
* Item decide if allows to be placed into _items of another item type
*
* ! Do not use "this" in this method, it will be called without an instance via Class.prototype.allowDestinationType()
*
* @param {String|null} type String - item type; null - root items
* @returns {boolean}
*/
allowDestinationType: function ( type ) {
return true;
}
} );
{
this.classes.Item.prototype.relations[0].relatedModel = this.classes.Item;
}
this.classes.ItemView = Backbone.View.extend( {
// required
/** @type {builder.classes.Item} */
model: null,
/** @type {String} 'any-string-'+ this.model.cid */
id: null,
// end: required
tagName: 'div',
className: 'builder-item fw-border-box-sizing fw-col-xs-12',
template: _.template( [
'<div style="border: 1px solid #CCC; padding: 5px; color: #999; background: #fff;">',
'<em class="fw-text-muted">Default View</em>',
'<a href="#" onclick="return false;" class="dashicons fw-x"></a>',
'<div class="builder-items"></div>',
'</div>'
].join( '' ) ),
events: {
'click a.dashicons.fw-x': 'defaultRemove'
},
initialize: function () {
this.defaultInitialize();
this.render();
},
/**
* It is required to call this method in .initialize()
*/
defaultInitialize: function () {
this.listenTo( this.model, 'change', this.render );
},
render: function () {
this.defaultRender();
},
defaultRender: function ( templateData ) {
var _items = this.model.get( '_items' );
/**
* First .detach() elements
* to prevent them to be removed (reset) on .html('...') replace
*/
_items.view.$el.detach();
this.$el.html(
this.template(
templateData || {}
)
);
/**
* Sometimes sub items sortable view is not initialized or (destroyed if was initialized)
* Tell it to render and maybe it will fix itself
*/
if ( ! _items.view.$el.hasClass( 'ui-sortable' ) ) {
_items.view.render();
}
/**
* replace <div class="builder-items"> with builder.classes.ItemsView.$el
*/
this.$el.find( '.builder-items:first' ).replaceWith(
_items.view.$el
);
return this;
},
defaultRemove: function () {
this.remove();
this.model.collection.remove( this.model );
}
} );
}
}
this.rootItems = new this.classes.Items;
/**
* Something happened in WP 4.5 (or backbone.relational compatibility with latest backbone)
* and items restored from input doesn't have the .collection property
* and it's impossible to remove them from builder (console errors).
* So loop recursive and fix item.collection
*/
{
function _fixItemsCollections( collection, c ) {
if ( typeof collection.cid != 'undefined' ) {
// it's a model, the second param is the collection
collection = c;
}
collection.each( function ( item ) {
item.collection = collection;
item.collection.off( null, _fixItemsCollections );
item.collection.on( 'reset add', _fixItemsCollections );
/**
* Sometimes item.get('_items') is empty at this point, wait a few milliseconds
* Bad solution, I home BackboneRelation will be fixed and this code will be removed
*/
setTimeout( _.bind( function () {
_fixItemsCollections( this.get( '_items' ) );
}, item ), 0 );
} );
}
this.rootItems.on( 'reset add', _fixItemsCollections );
}
// prepare this.$input
{
if ( typeof options.$input == 'undefined' ) {
console.warn( '$input not specified. Items will no be saved' );
this.$input = $( '<input type="hidden">' );
} else {
this.$input = options.$input;
}
fwEvents.trigger( 'fw-builder:' + this.get( 'type' ) + ':register-items', this );
/**
* @since 1.2.11
*/
fwEvents.trigger( 'fw-builder:' + this.get( 'type' ) + ':after-register-items', this );
// load saved items from input
{
try {
this.rootItems.reset( JSON.parse( this.$input.val() || '[]' ) );
fwEvents.trigger( 'fw-builder:' + this.get( 'type' ) + ':items-loaded', this );
} catch ( e ) {
console.error( 'Failed to recover items from input', e );
}
}
// listen to items changes and update input
(
function () {
function saveBuilderValueToInput() {
builder.$input.val( JSON.stringify( builder.rootItems ) );
builder.$input.trigger( 'fw-builder:input:change' );
builder.$input.trigger( 'change' );
}
/**
* use timeout to not load browser/cpu when there are many changes at once (for e.g. on .reset())
*/
var saveTimeout = 0;
builder.listenTo( builder.rootItems, 'builder:change', function () {
clearTimeout( saveTimeout );
saveTimeout = setTimeout( function () {
saveTimeout = 0;
saveBuilderValueToInput();
}, 100 );
} );
/**
* Save value to input if there is a pending timeout on form submit
*/
builder.$input.closest( 'form' ).on( 'submit', function () {
if ( saveTimeout ) {
clearTimeout( saveTimeout );
saveTimeout = 0;
saveBuilderValueToInput();
}
} );
}
)();
}
}
} );
fwExtBuilderInitialize.init( Builder );
} );

View File

@@ -0,0 +1,131 @@
(function ($, fwe, _, localized) {
fwe.on('fw:option-type:builder:init', function (data) {
if (!data.$elements.length) {
return;
}
if (!$('#post_ID').length) {
/**
* Don't enable fullscreen if not on post edit page
* Because this script requires the Publish and Preview post buttons
*/
return;
}
var elements = {
$saveButton: $('#publish'),
$previewButton: $('#post-preview')
};
var utils = {
toogleFullscreen: function ($builder) {
if ($builder.hasClass('builder-fullscreen')) {
utils.fullscreenOff.call($builder);
utils.unsetStorageItem();
} else {
utils.fullscreenOn.call($builder);
}
},
getFullscreenHeight: function () {
var $diffHeight = parseInt($('.builder-items-types').height() + 80);
return parseInt($('body').height() - $diffHeight);
},
selectBackdrop: function ($builder) {
return $builder.next('.fw-option-type-builder-fullscreen-backdrop');
},
fullscreenOn: function () {
var $builder = $(this);
utils.selectBackdrop($builder).removeClass('fw-hidden');
$builder.addClass('builder-fullscreen');
$(document.body).css('overflow-y', 'hidden'); // remove body scroll
$builder.find('> .builder-items-types .fullscreen-btn .text').text(localized.l10n.exit_fullscreen);
$builder.find('> .builder-items-types .fullscreen-btn .icon').removeClass('icon-fullscreen-on').addClass('icon-fullscreen-off');
$builder.find('> .builder-root-items')
.css({'max-height': utils.getFullscreenHeight() + 'px'})
.on('scroll.builder-fullscreen', function(){
$builder.find('> .builder-items-types').css(
'border-bottom-color',
$(this).scrollTop() ? '#eee' : ''
);
});
},
fullscreenOff: function () {
var $builder = $(this);
utils.selectBackdrop($builder).addClass('fw-hidden');
$builder.removeClass('builder-fullscreen');
$(document.body).css('overflow-y', '');
$builder.find('> .builder-items-types .fullscreen-btn .text').text(localized.l10n.fullscreen);
$builder.find('> .builder-items-types .fullscreen-btn .icon').removeClass('icon-fullscreen-off').addClass('icon-fullscreen-on');
$builder.find('> .builder-root-items')
.css({'max-height': ''})
.off('.builder-fullscreen');
$builder.find('> .builder-items-types').css('border-bottom-color', '');
},
getPostId: function () {
return $('#post_ID').val();
},
setStorageItem: function () {
return $.ajax({
type: "post",
dataType: "json",
url: ajaxurl,
data: {
'action': 'fw_builder_fullscreen_set_storage_item',
'post_id': utils.getPostId()
}
});
},
unsetStorageItem: function () {
return $.ajax({
type: "post",
dataType: "json",
url: ajaxurl,
data: {
'action': 'fw_builder_fullscreen_unset_storage_item',
'post_id': utils.getPostId()
}
});
}
};
data.$elements.each(function(){
var $builder = $(this);
$builder.find('.fw-options-tabs-list ul').before(
'<div class="fullscreen-btn">'+
' <div class="icon icon-fullscreen-on"></div>'+
' <div class="text">'+ localized.l10n.fullscreen +'</div>'+
'</div>'
);
$builder.find('> .builder-items-types .fullscreen-btn').on('click', function(e){
e.preventDefault();
utils.toogleFullscreen($builder);
});
utils.selectBackdrop($builder)
.on('click', '.preview', function (e) {
e.preventDefault();
utils.setStorageItem();
elements.$previewButton.trigger('click');
})
.one('click', '.button-primary', function (e) {
e.preventDefault();
utils.selectBackdrop($builder).removeClass('fw-hidden');
utils.setStorageItem().done(function () {
elements.$saveButton.focus().trigger('click');
});
});
if ($builder.hasClass('builder-fullscreen')) {
$builder.removeClass('builder-fullscreen');
utils.toogleFullscreen($builder);
}
});
});
})(jQuery, fwEvents, _, _fw_option_type_builder_fullscreen);

View File

@@ -0,0 +1,282 @@
var FwBuilderComponents = {
Item: {},
ItemView: {},
Items: {},
ItemsView: {}
};
/**
* Change item width
*
* Usage:
*
* // in ItemView.initialize()
*
* this.widthChangerView = new FwBuilderComponents.ItemView.WidthChanger({
* model: this.model,
* view: this,
* widths: [
* {
* title: '1/12',
* id: '1_12',
* backend_class: 'fw-col-sm-1',
* frontend_class: 'col-sm-1'
* },
* ...
* {
* title: '12/12',
* id: '12_12',
* backend_class: 'fw-col-sm-12',
* frontend_class: 'col-sm-12'
* }
* ],
* modelAttribute: 'width',
* });
*
* // in ItemView.render()
*
* this.$('.some-class').append( this.widthChangerView.$el );
*
* this.widthChangerView.delegateEvents(); // rebind events after element "remove" happened
*/
FwBuilderComponents.ItemView.WidthChanger = Backbone.View.extend({
tagName: 'div',
className: 'fw-builder-item-width-changer',
template: _.template(
'<a href="#" class="decrease-width dashicons '+ (
jQuery(document.body).hasClass('rtl') ? 'dashicons-arrow-right-alt2' : 'dashicons-arrow-left-alt2'
) +'"'+
/**//**/' onclick="return false;"></a>'+
' <span class="current-width fw-wp-link-color"><%- title %></span> '+
'<a href="#" class="increase-width dashicons '+ (
jQuery(document.body).hasClass('rtl') ? 'dashicons-arrow-left-alt2' : 'dashicons-arrow-right-alt2'
) +'"'+
/**//**/' onclick="return false;"></a>'
),
events: {
'click .decrease-width': 'decreaseWidth',
'click .increase-width': 'increaseWidth'
},
widths: _fw_option_type_builder_helpers['item_widths'],
/**
* The attribute name that will be changed in item on width changes
* this.model.set(this.modelAttribute, this.widths[N].id)
*/
modelAttribute: 'width',
initialize: function(options) {
_.extend(this, _.pick(options,
'view',
'widths',
'modelAttribute'
));
// set special properties for first and last width
{
this.widths[0].first = true;
this.widths[ this.widths.length - 1 ].last = true;
}
this.listenTo(this.model, 'change:' + this.modelAttribute, this.render);
this.render();
},
render: function() {
this.updateWidth();
var widthId = this.model.get(this.modelAttribute);
var width = _.findWhere(this.widths, {id: widthId});
var widthTitle = '?';
if (width) {
widthTitle = width.title;
}
{
this.$el.removeClass('is-first is-last');
if (!!width.first) {
this.$el.addClass('is-first');
}
if (!!width.last) {
this.$el.addClass('is-last');
}
}
this.$el.html(
this.template({
title: widthTitle
})
);
},
decreaseWidth: function(e) {
e.stopPropagation();
var widthId = this.model.get(this.modelAttribute);
var widthsIds = _.pluck(this.widths, 'id');
var currentWidthIndex = _.indexOf(widthsIds, widthId);
if (currentWidthIndex == -1) {
// Current id does not exists (invalid) set first width
widthId = widthsIds[0];
} else if (currentWidthIndex == 0) {
// Do nothing, this is the smallest width
} else {
// Set smaller width
widthId = widthsIds[currentWidthIndex - 1];
}
this.updateWidth(widthId);
},
increaseWidth: function(e) {
e.stopPropagation();
var widthId = this.model.get(this.modelAttribute);
var widthsIds = _.pluck(this.widths, 'id');
var currentWidthIndex = _.indexOf(widthsIds, widthId);
if (currentWidthIndex == -1) {
// Current id does not exists (invalid) set last width
widthId = widthsIds[ widthsIds.length - 1 ];
} else if (currentWidthIndex == widthsIds.length - 1) {
// Do nothing, this is the biggest width
} else {
// Set bigger width
widthId = widthsIds[currentWidthIndex + 1];
}
this.updateWidth(widthId);
},
updateWidth: function(widthId) {
if (typeof widthId == 'undefined') {
widthId = this.model.get(this.modelAttribute);
}
var widthsIds = _.pluck(this.widths, 'id');
// check if correct
if (-1 == _.indexOf(widthsIds, widthId)) {
// set default
widthId = widthsIds[
parseInt(widthsIds.length / 2) // middle width
];
}
if (widthId != this.model.get(this.modelAttribute)) {
// set only when is different, to prevent trigger actions on those who listens to model 'change'
this.model.set(this.modelAttribute, widthId);
}
this.view.$el
.removeClass(
_.pluck(this.widths, 'backend_class').join(' ')
)
.addClass(
_.findWhere(this.widths, {id: widthId})['backend_class']
);
}
});
/**
* Usage:
*
* // in ItemView.initialize()
*
* this.inlineEditor = new FwBuilderComponents.ItemView.InlineTextEditor({
* model: item,
* editAttribute: 'model_attr_name' // also is available nested attribute property notation: 'a/b/c' will do {a: {b: {c: 'value'}}}
* })
*
* // in ItemView.render()
*
* this.$('.some-class').append( this.inlineEditor.$el );
*
* this.inlineEditor.delegateEvents(); // rebind events after element "remove" happened
*/
FwBuilderComponents.ItemView.InlineTextEditor = Backbone.View.extend({
tagName: 'div',
className: 'fw-builder-item-inline-text-editor',
template: _.template(
'<input type="text" style="width: auto;" value="<%- value %>" onclick="return false;">&nbsp;<button class="button" onclick="return false;"><%- save %></button>'
),
events: {
'change input': 'update',
'focusout input': 'hide'
},
render: function() {
var localized = _fw_option_type_builder_helpers;
this.$el.html(
this.template({
value: this.editAttributeWitoutRoot
? fw.opg(this.editAttributeWitoutRoot, this.model.get(this.editAttributeRoot))
: this.model.get(this.editAttributeRoot),
save: localized.l10n.save
})
);
this.$el.addClass('fw-hidden');
},
initialize: function(options) {
_.extend(this, _.pick(options,
'editAttribute'
));
this.delimiter = '/';
/**
* From 'a/b/c', extract: 'a' and 'b/c'
*/
{
var editAttributeSplit = this.editAttribute.split(this.delimiter);
this.editAttributeRoot = editAttributeSplit.shift();
this.editAttributeWitoutRoot = editAttributeSplit.join(this.delimiter);
}
this.listenTo(this.model, 'change:'+ this.editAttributeRoot, this.render);
this.render();
},
update: function() {
var val = this.$el.find('input').val();
var value = this.editAttributeWitoutRoot
? fw.ops(this.editAttributeWitoutRoot, val,
// clone to not change by reference, else values will be equal and model.set() will not trigger 'change'
_.clone(this.model.get(this.editAttributeRoot)))
: val;
this.model.set(this.editAttributeRoot, value);
},
hide: function() {
this.$el.addClass('fw-hidden');
this.trigger('hide');
},
show: function() {
this.$el.removeClass('fw-hidden');
this.$el.find('input').focus();
return this;
}
});
FwBuilderComponents.ItemView.iconToHtml = function(icon) {
if (/\.(png|jpg|jpeg|gif|svg|webp)$/.test(icon)) {
// http://.../image.png
return jQuery('<div>').append(
jQuery('<img />')
.attr('class', 'fw-ext-builder-icon')
.attr('src', icon)
).html();
} else if (/^[a-zA-Z0-9\-_ ]+$/.test(icon)) {
// 'font-icon font-icon-class'
return jQuery('<div>').append(
jQuery('<span></span>')
.attr('class', 'fw-ext-builder-icon '+ jQuery.trim(icon))
).html();
} else {
// can't detect. maybe it's raw html '<span ...'
return icon;
}
};

View File

@@ -0,0 +1,121 @@
(function ($, fwe, _, localized) {
$(document.body).on('fw:option-type:builder:init', function (e, data) {
var elements = {
$builder: $(e.target),
$undo: $('<a class="disabled undo" href="#">'+ localized.l10n.undo +'</a>'),
$redo: $('<a class="disabled redo" href="#">'+ localized.l10n.redo +'</a>')
},
saveStateFlag = true,
builder = data.builder,
type = builder.get('type');
data.$headerTools
.removeClass('fw-hidden')
.append('<div class="history-container"></div>')
.find('> .history-container')
.append(elements.$undo)
.append(elements.$redo);
var utils = {
disableUndo: function () {
elements.$undo.addClass('disabled');
},
enableUndo: function () {
elements.$undo.removeClass('disabled');
},
disableRedo: function () {
elements.$redo.addClass('disabled');
},
enableRedo: function () {
elements.$redo.removeClass('disabled');
}
};
var history = {
storage: [],
activeIndex: 0,
undo: function () {
--this.activeIndex;
if ((this.activeIndex === 0)) {
utils.disableUndo();
}
return this.storage[this.activeIndex];
},
redo: function () {
++this.activeIndex;
if (this.activeIndex === this.storage.length - 1) {
utils.disableRedo();
}
return this.storage[this.activeIndex];
},
saveState: function (item) {
this.storage = _.initial(this.storage, (this.storage.length-1) - this.activeIndex);
this.storage.push(item);
this.activeIndex = this.storage.length - 1;
}
};
history.saveState(builder.$input.val());
builder.$input.on('fw-builder:input:change', function () {
if (true === saveStateFlag) {
history.saveState($(this).val());
utils.enableUndo();
utils.disableRedo();
} else {
saveStateFlag = true;
}
});
elements.$undo.on('click', function (e) {
e.preventDefault();
if ($(this).hasClass('disabled')) {
return;
}
utils.enableUndo();
utils.enableRedo();
saveStateFlag = false;
var undoSnapshot = history.undo();
if (undoSnapshot !== undefined) {
var parsedUndoSnaphot = JSON.parse(undoSnapshot);
builder.rootItems.reset(parsedUndoSnaphot);
if ( parsedUndoSnaphot.length === 0 ) {
builder.$input.val('[]');
}
} else {
utils.disableUndo();
}
});
elements.$redo.on('click', function (e) {
e.preventDefault();
if ($(this).hasClass('disabled')) {
return;
}
utils.enableRedo();
utils.enableUndo();
saveStateFlag = false;
var redoSnapshot = history.redo();
if (redoSnapshot !== undefined) {
builder.rootItems.reset(JSON.parse(redoSnapshot));
} else {
utils.disableRedo();
}
});
});
})(jQuery, fwEvents, _, _fw_option_type_builder_history);

View File

@@ -0,0 +1,592 @@
window.fwExtBuilderInitialize = (function ($) {
var fixedHeaderHelpers = {
increment: 0,
$adminBar: $('#wpadminbar'),
getAdminBarHeight: function() {
var height = 0;
if (this.$adminBar.length && this.$adminBar.css('position') === 'fixed') {
height = this.$adminBar.height();
}
var gutenbergContainer = $( '#editor.block-editor__container' );
if ( gutenbergContainer.length > 0 ) {
height += gutenbergContainer.find( '.edit-post-header' ).outerHeight() + gutenbergContainer.find( '.components-notice-list' ).height();
}
return height;
},
fix: function($header, $builder, $scrollParent){
var topSpace = this.getAdminBarHeight(),
scrollParentHeight = $scrollParent.height(),
scrollParentScrollTop = $( document ).scrollTop(),
scrollParentOffset = $( document ).offset(),
builderHeight = $builder.get(0).clientHeight,
builderOffsetTop = $builder.offset().top,
headerHeight = $header.get(0).clientHeight;
/**
* Fixes inside options modal
*/
if (scrollParentOffset) {
builderOffsetTop -= scrollParentOffset.top;
if (builderOffsetTop <= 0) {
builderOffsetTop = topSpace;
}
}
do {
if (builderOffsetTop >= scrollParentScrollTop + topSpace) {
// scroll top didn't reached the builder
break;
}
if (builderHeight < scrollParentHeight - topSpace) {
// the builder fits inside the scroll element
break;
}
var bottomLimit = Math.floor(scrollParentHeight / 2);
if (bottomLimit < headerHeight) {
bottomLimit = headerHeight;
}
if (bottomLimit < 256) {
bottomLimit = 256;
}
if (builderHeight < headerHeight + bottomLimit) {
break;
}
if (scrollParentHeight < headerHeight + bottomLimit) {
// the scroll element must have space to display header and bottomLimit
break;
}
var headerTopShift = (scrollParentScrollTop + topSpace) - builderOffsetTop;
if (headerTopShift + headerHeight + bottomLimit > builderHeight) {
// do not allow header to cover last items
headerTopShift -= headerTopShift + headerHeight + bottomLimit - builderHeight;
}
// set fixed header
{
if (!$builder.hasClass('fixed-header')) {
$builder.addClass('fixed-header');
}
$builder.css({
'padding-top': headerHeight +'px' // set ghost space in builder, like the header is still there
});
$header.css({
'top': headerTopShift +'px'
});
return true;
}
} while(false);
// remove fixed header
{
if ($builder.hasClass('fixed-header')) {
$builder.removeClass('fixed-header');
$builder.css({
'padding-top': ''
});
$header.css({
'top': ''
});
}
return false;
}
}
};
return {
init: init
};
/**
* Loop recursive through all items in given collection
*/
function forEachItemRecursive(collection, callback) {
collection.each(function(item){
callback(item);
forEachItemRecursive(item.get('_items'), callback);
});
}
function initDraggable ($this, builder, id) {
fwEvents.trigger('fw:options:init:tabs', {$elements: $this.find('> .builder-items-types')});
var additionalSortableOptions = {}
fwEvents.trigger(
'fw-builder:'+ builder.get('type') +':toolbar-sortable-additional-options',
additionalSortableOptions
)
$this.find('> .builder-items-types .builder-item-type').draggable(_.extend({
connectToSortable: '#'+ id +' .builder-root-items .builder-items',
helper: 'clone',
distance: 10,
placeholder: 'fw-builder-placeholder',
zIndex: 99999,
start: function(event, ui) {
var movedType = ui.helper.attr('data-builder-item-type');
if (!movedType) {
return;
}
var MovedTypeClass = builder.getRegisteredItemClassByType(movedType);
if (!MovedTypeClass) {
return;
}
/**
* add "allowed" classes to items vies where allowIncomingType(movedType) returned true
* else add "denied" class
*/
{
{
if (MovedTypeClass.prototype.allowDestinationType(null)) {
builder.rootItems.view.$el.addClass('fw-builder-item-allow-incoming-type');
} else {
builder.rootItems.view.$el.addClass('fw-builder-item-deny-incoming-type');
}
}
forEachItemRecursive(builder.rootItems, function(item){
if (
item.allowIncomingType(movedType)
&&
MovedTypeClass.prototype.allowDestinationType(item.get('type'))
) {
item.view.$el.addClass('fw-builder-item-allow-incoming-type');
} else {
item.view.$el.addClass('fw-builder-item-deny-incoming-type');
}
});
}
},
stop: function() {
// remove "allowed" and "denied" classes from all items
{
builder.rootItems.view.$el.removeClass(
'fw-builder-item-allow-incoming-type fw-builder-item-deny-incoming-type'
);
forEachItemRecursive(builder.rootItems, function(item){
item.view.$el.removeClass(
'fw-builder-item-allow-incoming-type fw-builder-item-deny-incoming-type'
);
});
}
}
}, additionalSortableOptions));
/**
* Add item on thumbnail click
*/
$this.find('.builder-items-types').on('click', '.builder-item-type', function(){
var $itemType = $(this);
var itemType = $itemType.attr('data-builder-item-type');
if (itemType) {
var ItemTypeClass = builder.getRegisteredItemClassByType(itemType);
if (ItemTypeClass) {
if (ItemTypeClass.prototype.allowDestinationType(null)) {
builder.rootItems.add(
new ItemTypeClass({}, {
$thumb: $itemType
})
);
// animation
{
// stop previous animation
{
clearTimeout($itemType.attr('data-animation-timeout-id'));
$itemType.removeClass('fw-builder-animation-item-type-add');
}
$itemType.addClass('fw-builder-animation-item-type-add');
$itemType.attr('data-animation-timeout-id',
setTimeout(function(){
$itemType.removeClass('fw-builder-animation-item-type-add');
}, 500)
);
}
} else {
console.warn('Item type "'+ itemType +'" is not allowed as first level item');
}
} else {
console.error('Unregistered item type: '+ itemType);
}
} else {
console.error('Cannot extract item type from element', $itemType);
}
});
// scroll to the added element
builder.rootItems.on('add', function(el){
var $el = el.view.$el;
clearTimeout($this.attr('data-scroll-bottom-timeout'));
var timeout = setTimeout(function(){
if (!$el.length) {
return; // not in DOM already
}
var $builderOption = $this,
$scrollParent = $builderOption.scrollParent();
if ($scrollParent.get(0) === document || $scrollParent.get(0) === document.body) {
$scrollParent = $(window);
}
if ($builderOption.height() <= $scrollParent.height() + 300) {
/**
* Do not scroll if the builder can fit or is almost entirely visible
* To prevent "jumping" https://github.com/ThemeFuse/Unyson/issues/815
*/
return;
}
var scrollParentHeight = $scrollParent.height()
$scrollParent.scrollTop(Math.min( // use min() to not allow scroll to far down hiding the fixed header
$el.offset().top - scrollParentHeight / 2,
$builderOption.offset().top + $builderOption.outerHeight() - scrollParentHeight
));
}, 100);
$this.attr('data-scroll-bottom-timeout', timeout);
});
}
function init (Builder) {
fwEvents.on('fw:options:init', function (data) {
var $options = data.$elements.find('.fw-option-type-builder:not(.initialized)');
if (! $options.length) {
return;
}
initBuilderDelayed(Builder, data);
});
}
function initBuilderDelayed (Builder, data) {
var $options = data.$elements.find('.fw-option-type-builder:not(.initialized)');
$options.closest('.fw-backend-option').addClass('fw-backend-option-type-builder');
var triggerInit = _.once(function () {
fwEvents.trigger('fw:option-type:builder:init', {
$elements: $options
});
});
$options.each(function () {
var $el = $(this);
var type = $el.attr('data-builder-option-type');
var promises = [];
fwEvents.trigger(
'fw-builder:'+ type + ':collect-async-init-promises',
{
promises: promises
}
);
jQuery.when.apply(jQuery, promises).then(function () {
initSingleBuilder($el);
triggerInit();
});
});
function initSingleBuilder ($el) {
var $this = $el,
hasDragAndDrop = $this.attr('data-drag-and-drop'),
id = $this.attr('id'),
type = $this.attr('data-builder-option-type');
/**
* Create instance of Builder
*/
{
var data = {
type: type,
$option: $this,
$input: $this.find('> [data-fw-option-type="hidden"]:first > input'),
$types: $this.find('.builder-items-types:first'),
$rootItems: $this.find('.builder-root-items:first'),
$headerTools: $('<div class="fw-builder-header-tools fw-clearfix fw-hidden"></div>')
};
var eventData = $.extend({}, data, {
/**
* In event you can extend (customize/change) and replace this (property) class
*/
Builder: Builder
});
fwEvents.trigger('fw-builder:'+ type +':before-create', eventData);
$this.find('> .builder-items-types').append(data.$headerTools);
var builder = new eventData.Builder(
{
type: data.type
},
{
$input: data.$input
}
);
builder.rootItems.view.$el.appendTo(data.$rootItems);
new fwExtBuilderRootItemsTips(builder.rootItems);
}
/**
* Init draggable thumbnails just if user wants it to be around
*/
if (hasDragAndDrop) {
initDraggable($this, builder, id);
}
/**
* Add tips to thumbnails
*/
$this.find('.builder-items-types .builder-item-type [data-hover-tip]').each(function(){
$(this).qtip({
position: {
at: 'top center',
my: 'bottom center',
viewport: $('body')
},
style: {
classes: 'qtip-fw qtip-fw-builder',
tip: {
width: 12,
height: 5
}
},
content: {
text: $(this).attr('data-hover-tip')
}
});
});
/**
* Make header follow you when you scroll down
*/
if ($this.attr('data-fixed-header')) {
var fixedHeaderEventsNamespace = '.fw-builder-fixed-header-'+ (++fixedHeaderHelpers.increment),
$fixedHeader = $this.find('> .builder-items-types:first'),
/**
* In OptionsModal we must track the modal scroll not the window scroll
*/
$scrollParent;
$scrollParent = $this.scrollParent();
if ($scrollParent.get(0) === document || $scrollParent.get(0) === document.body) {
$scrollParent = $(window);
}
/**
* Options modal fixed tabs are initialized after options init
*/
setTimeout(function(){
$scrollParent = $this.scrollParent();
if ($scrollParent.get(0) === document || $scrollParent.get(0) === document.body) {
$scrollParent = $(window);
}
$scrollParent
.on('scroll'+ fixedHeaderEventsNamespace, function(){
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
})
.on('resize'+ fixedHeaderEventsNamespace, function(){
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
});
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
}, 0);
/**
* On thumbnails tab change, the new tab may contain more thumbnails that previous
* thus having different height
*/
$fixedHeader.on('click'+ fixedHeaderEventsNamespace, '.fw-options-tabs-list a, .fullscreen-btn', function(){
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
/**
* When you scroll down to the last items (to the limit when the fixed header stops and begins to go under page)
* and you switch to a tab with a bigger height, there are some issues with positioning.
* Calling this send time fixes it
*/
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
});
/**
* Listen builder value/items change
* For e.g. when you delete an element from the builder (or press undo/redo buttons)
* its height is changed and the fixed header needs repositioning
*/
builder.$input.on('fw-builder:input:change'+ fixedHeaderEventsNamespace, function(){
fixedHeaderHelpers.fix($fixedHeader, $this, $scrollParent);
});
/**
* Remove events from external elements
* In case the builder is created and remove dynamically multiple times, for e.g. inside fw.OptionsModal
*/
$this.on('remove', function(){
$scrollParent.off(fixedHeaderEventsNamespace);
});
}
if ($this.attr('data-compression') && window.JSZip) {
var compress = {
eventsNamespace: '.fw-builder-compress',
isBusy: false,
listenFormSubmit: function () {
$this.closest('form').on('submit'+ compress.eventsNamespace, function(e){
var $form = $(this),
$submitButton = $form.find('input[type="submit"]:focus');
if (!$submitButton.length && $form.find(':focus').is('#post-preview')) {
// Do nothing on "Preview Changes" button press
return;
}
var builderValue = builder.$input.val();
if (builderValue.length < 200000) {
// compress only when builder has a lot of elements
return;
}
e.preventDefault();
if (compress.isBusy) {
return console.log('Zipping...');
} else {
fw.loading.show();
compress.isBusy = true;
}
var zip = new JSZip();
zip.file('builder.json', builderValue);
zip.generateAsync({type: 'base64', compression: 'DEFLATE'}).then(function(content) {
builder.$input.val(content);
fw.loading.hide();
$form.off('submit'+ compress.eventsNamespace);
$submitButton.length
? $submitButton.focus().trigger('click')
: $form.submit();
});
});
}
};
$this.one('fw:option-type:builder:init', function () {
compress.listenFormSubmit();
});
}
$this.on('fw:option-type:builder:dump-json', function(e, data){
if (typeof data != 'undefined' && typeof data.cid != 'undefined') {
console.log('[Builder JSON Dump] Item '+ data.cid +'\n\n'+
JSON.stringify(builder.findItemRecursive({cid: data.cid}))
);
} else {
console.log('[Builder JSON Dump] Full\n\n'+
JSON.stringify(builder.rootItems)
);
}
});
$this.trigger('fw:option-type:builder:init', $.extend({}, eventData, {
builder: builder
}));
}
// add special class for builders that has header tools div
$options.find('> .builder-items-types .fw-builder-header-tools:not(.fw-hidden)')
.closest('.fw-option-type-builder').addClass('has-header-tools')
// Add "Save" post button if the builder is within edit post form
.each(function(){
var $postForm = $(this).closest('form#post');
if (!$postForm.length) {
return;
}
var isLocalStorageAvailable = function(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
},
localStorageKey = 'fw-ext-builder-save-scroll-position',
$savePostButton = $postForm.find('#publishing-action #publish'),
$savePostBuilderButton = $(
'<button'+
' type="button"'+
' class="button button-primary fw-pull-right fw-builder-header-post-save-button"'+
' onclick="return false;">' +
'</button>')
.text($savePostButton.attr('value'))
.on('click', function(){
$(this).attr('disabled', 'disabled').off('click');
if (isLocalStorageAvailable()) {
localStorage.setItem(localStorageKey, $(window).scrollTop());
}
$savePostButton.trigger('click');
});
$(this).find('.fw-builder-header-tools:first')
.prepend('<span class="pull-right">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>')
.prepend($savePostBuilderButton);
if (isLocalStorageAvailable()) {
var scrollTopOnLastSave = localStorage.getItem(localStorageKey);
if (scrollTopOnLastSave !== null) {
localStorage.removeItem(localStorageKey);
// http://stackoverflow.com/a/16475234/1794248
$('html, body').animate({scrollTop: scrollTopOnLastSave}, '100', 'swing');
}
}
});
$options.addClass('initialized');
}
})(jQuery);

View File

@@ -0,0 +1,50 @@
/**
* Create qTips for elements with data-hover-tip="Tip Text" attribute
*/
window.fwExtBuilderRootItemsTips = (function(rootItems){
var $ = jQuery,
/**
* Store all created qTip instances APIs
*/
tipsAPIs = [],
destroyTips = function(){
_.each(tipsAPIs, function(api) { api.destroy(true); });
tipsAPIs = [];
},
makeTip = function($el){
if ($el.attr('data-hasqtip')) {
return;
}
$el.qtip({
position: {
at: 'top center',
my: 'bottom center',
viewport: rootItems.view.$el.parent()
},
style: {
classes: 'qtip-fw qtip-fw-builder',
tip: {
width: 12,
height: 5
}
},
content: {
text: $el.attr('data-hover-tip')
}
});
tipsAPIs.push($el.qtip('api'));
$el.qtip('api').show();
};
rootItems.view.$el.on('mouseenter', '[data-hover-tip]', function(){
makeTip($(this));
});
rootItems.on('builder:change', function(){
destroyTips();
});
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,69 @@
<?php if (!defined('FW')) die('Forbidden');
/**
* @var string $id
* @var array $option
* @var array $data
* @var array $thumbnails
*/
{
$tabs_options = array();
foreach ($thumbnails as $thumbnails_tab_title => &$thumbnails_tab_thumbnails) {
$tabs_options[ 'random-'. fw_unique_increment() ] = array(
'type' => 'tab',
'title' => $thumbnails_tab_title,
'attr' => array(
'class' => 'fw-option-type-builder-thumbnails-tab',
),
'options' => array(
fw_rand_md5() => array(
'type' => 'html',
'label' => false,
'desc' => false,
'html' => implode("\n", $thumbnails_tab_thumbnails),
),
),
);
}
}
{
$div_attr = $option['attr'];
unset(
$div_attr['value'],
$div_attr['name']
);
$div_attr['class'] .= ' fw-option-type-builder-tabs-count-'. count($tabs_options);
}
?>
<div <?php echo fw_attr_to_html($div_attr) ?>>
<?php
echo fw()->backend->option_type('hidden')->render(
$id,
array(),
array(
'value' => $data['value']['json'],
'id_prefix' => $data['id_prefix'] .'input--',
'name_prefix' => $data['name_prefix']
)
);
?>
<div class="builder-items-types fw-clearfix">
<?php echo fw()->backend->render_options($tabs_options) ?>
</div>
<div class="builder-root-items"></div>
<?php do_action('fw_builder:' . $option['type'] . ':content_below_root_items'); ?>
</div>
<?php
// do action once to add one backdrop for all builders in page
if ($option['fullscreen']) {
do_action('fw_builder_fullscreen_add_backdrop');
}
?>

View File

@@ -0,0 +1,11 @@
<?php if (!defined('FW')) die('Forbidden');
$manifest = array();
$manifest['name'] = __( 'Builder', 'fw' );
$manifest['version'] = '1.2.12';
$manifest['github_update'] = 'ThemeFuse/Unyson-Builder-Extension';
$manifest['github_repo'] = 'https://github.com/ThemeFuse/Unyson-Builder-Extension';
$manifest['uri'] = 'http://manual.unyson.io/en/latest/extension/builder/index.html';
$manifest['author'] = 'ThemeFuse';
$manifest['author_uri'] = 'http://themefuse.com/';

Some files were not shown because too many files have changed in this diff Show More