first commit

This commit is contained in:
User A0264400
2026-04-01 23:20:16 +03:00
commit a766acdc90
23071 changed files with 4933189 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
<?php
/**
* Activator for the cyrlitera
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 09.03.2018, Webcraftic
* @see Wbcr_Factory480_Activator
* @version 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WGNZ_Activation extends Wbcr_Factory480_Activator {
/**
* Runs activation actions.
*/
public function activate() {
wbcr_gnz_deploy_mu_plugin();
}
/**
* Runs deactivation actions.
*/
public function deactivate() {
wbcr_gnz_remove_mu_plugin();
}
}

View File

@@ -0,0 +1,109 @@
<?php
/**
* Save settings ajax action
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 21.09.2019, Webcraftic
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Ajax action for save plugin settings.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
*/
function wam_save_settings_action()
{
check_ajax_referer('wam_save_settigns');
if( !current_user_can('manage_options') ) {
wp_send_json_error([
'error_message_title' => __('Save settings failed!', 'gonzales'),
'error_message_content' => __('You don\'t have enough capability to edit this information.', 'gonzales')
]);
}
$save_message_title = __('Settings saved successfully!', 'clearfy');
$save_message_content = __('If you use test mode, do not forget to disable it. We also recommend that you flush the cache if you use caching plugins.', 'clearfy');
$scope = WGZ_Plugin::app()->request->post('scope', 'frontend');
$raw_updated_settings = WGZ_Plugin::app()->request->post('settings', [], true);
if( !empty($raw_updated_settings) ) {
if( 'networkadmin' === $scope ) {
$settings = WGZ_Plugin::app()->getNetworkOption('backend_assets_states', []);
} else if( 'admin' === $scope ) {
$settings = WGZ_Plugin::app()->getOption('backend_assets_states', []);
} else {
$settings = WGZ_Plugin::app()->getOption('assets_states', []);
}
if( !defined('WGZP_PLUGIN_ACTIVE') || (is_array($settings) && !isset($settings['save_mode'])) ) {
$settings['save_mode'] = false;
}
if( !empty($raw_updated_settings['plugins']) ) {
foreach((array)$raw_updated_settings['plugins'] as $plugin_name => $plugin_group) {
if( !empty($plugin_group['load_mode']) ) {
if( 'enable' == $plugin_group['load_mode'] ) {
$plugin_group['visability'] = "";
} else {
foreach(['js', 'css'] as $assets_type) {
if( !empty($plugin_group[$assets_type]) ) {
foreach($plugin_group[$assets_type] as $resource_handle => $resource_params) {
$plugin_group[$assets_type][$resource_handle]['visability'] = "";
}
}
}
}
}
$settings['plugins'][$plugin_name] = $plugin_group;
}
}
if( !empty($raw_updated_settings['theme']) ) {
$settings['theme'] = $raw_updated_settings['theme'];
}
if( !empty($raw_updated_settings['misc']) ) {
$settings['misc'] = $raw_updated_settings['misc'];
}
/**
* Filter run before save settings.
*
* @param array $settings
* @param array $raw_updated_settings
* @param string $scope
*/
$settings = apply_filters('wam/before_save_settings', $settings, $raw_updated_settings, $scope);
if( 'networkadmin' === $scope ) {
WGZ_Plugin::app()->updateNetworkOption('backend_assets_states', $settings);
} else if( 'admin' === $scope ) {
WGZ_Plugin::app()->updateOption('backend_assets_states', $settings);
} else {
WGZ_Plugin::app()->updateOption('assets_states', $settings);
}
// If mu plugin does not exist, install it.
wbcr_gnz_deploy_mu_plugin();
// Flush cache for all cache plugins
WBCR\Factory_Templates_134\Helpers::flushPageCache();
}
wp_send_json_success([
'save_massage_title' => $save_message_title,
'save_message_content' => $save_message_content
]);
}
add_action('wp_ajax_nopriv_wam-save-settings', 'wam_save_settings_action');
add_action('wp_ajax_wam-save-settings', 'wam_save_settings_action');

View File

@@ -0,0 +1,211 @@
<?php
/**
* Admin boot
*
* @author Webcraftic <wordpress.webraftic@gmail.com>
* @copyright Webcraftic 25.05.2017
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
if( defined('LOADING_ASSETS_MANAGER_AS_ADDON') ) {
/**
* Уведомление, которое сообщает о возможности импорта опций из плагина Assets manager в Clearfy
*
* @param array $notices
*/
/*add_filter( 'wbcr/factory/admin_notices', function ( $notices ) {
if ( is_multisite() && is_network_admin() ) {
$am_options = get_site_option( 'wbcr_gnz_assets_manager_options' );
} else {
$am_options = get_option( 'wbcr_gnz_assets_manager_options' );
}
if ( $am_options ) {
$notice_text = '<p><b>Clearfy:</b> ' . __( 'We detected that you used the Assets manager plugin. Do you want to import settings from this plugin to the Clearfy plugin?', 'gonzales' ) . '</p>';
$notice_text .= '<p><a href="' . admin_url( '?wbcr_assets_manager_transfer' ) . '" class="button button-default">' . __( 'Import options', 'gonzales' ) . '</a></p>';
$notices[] = [
'id' => 'gnz_plugin_import_options',
'type' => 'warning',
'dismissible' => true,
'dismiss_expires' => 0,
'text' => $notice_text
];
}
if ( isset( $_GET['wbcr_assets_manager_transfer_completed'] ) ) {
$notices[] = [
'id' => 'gnz_plugin_transfer_options_completed',
'type' => 'success',
'dismissible' => false,
'dismiss_expires' => 0,
'text' => '<p><b>Clearfy:</b> ' . __( 'Settings has been successfully imported!', 'gonzales' )
];
}
return $notices;
}, 10, 2 );*/
/**
* Импорт опций из плагина Assets manager в плагин Clearfy.
* При попытке использовать премиум версию, у многих пользователей уже настроен бесплатный плагин и
* на ручной перенос настроек уходит очень много времени. Этот кусок кода решает проблему переноса настроек между плагинами.
*/
/*add_action( 'admin_init', function () {
if ( isset( $_GET['wbcr_assets_manager_transfer'] ) ) {
global $wpdb;
if ( is_multisite() && is_network_admin() ) {
$am_options = get_site_option( 'wbcr_gnz_assets_manager_options' );
} else {
$am_options = get_option( 'wbcr_gnz_assets_manager_options' );
}
if ( ! $am_options || ! class_exists( 'WCL_Plugin' ) ) {
return;
}
$am_prefix = 'wbcr_gnz_';
if ( is_multisite() && is_network_admin() ) {
$request = $wpdb->get_results( "SELECT meta_key, meta_value
FROM {$wpdb->sitemeta}
WHERE option_name LIKE '{$am_prefix}_%'" );
} else {
$request = $wpdb->get_results( "SELECT option_name, option_value
FROM {$wpdb->options}
WHERE option_name LIKE '{$am_prefix}_%'" );
}
if ( $request ) {
foreach ( (array) $request as $option ) {
if ( is_multisite() && is_network_admin() ) {
$new_option_name = str_replace( $am_prefix, WCL_Plugin::app()->getPrefix(), $option->meta_key );
update_site_option( $new_option_name, $option->meta_value );
delete_site_option( $option->meta_key );
} else {
$new_option_name = str_replace( $am_prefix, WCL_Plugin::app()->getPrefix(), $option->option_name );
update_option( $new_option_name, $option->option_value );
delete_option( $option->option_name );
}
}
wp_redirect( admin_url( '?wbcr_assets_manager_transfer_completed' ) );
die();
}
}
} );*/
function wbcr_gnz_group_options($options)
{
$options[] = [
'name' => 'disable_assets_manager',
'title' => __('Disable assets manager', 'gonzales'),
'tags' => [],
'values' => []
];
$options[] = [
'name' => 'disable_assets_manager_panel',
'title' => __('Disable assets manager panel', 'gonzales'),
'tags' => []
];
$options[] = [
'name' => 'disable_assets_manager_on_front',
'title' => __('Disable assets manager on front', 'gonzales'),
'tags' => []
];
$options[] = [
'name' => 'disable_assets_manager_on_backend',
'title' => __('Disable assets manager on back-end', 'gonzales'),
'tags' => []
];
$options[] = [
'name' => 'manager_options',
'title' => __('Assets manager options', 'gonzales'),
'tags' => []
];
return $options;
}
add_filter("wbcr_clearfy_group_options", 'wbcr_gnz_group_options');
} else {
/**
* Удаляем лишние виджеты в левом сайдбаре
*
* @param array $widgets
* @param string $position
* @param Wbcr_Factory480_Plugin $plugin
*/
add_filter('wbcr/factory/pages/impressive/widgets', function ($widgets, $position, $plugin) {
if( $plugin->getPluginName() == WGZ_Plugin::app()->getPluginName() ) {
unset($widgets['business_suggetion']);
if( $position == 'right' ) {
unset($widgets['donate_widget']);
unset($widgets['rating_widget']);
unset($widgets['info_widget']);
}
}
return $widgets;
}, 20, 3);
/**
* Заменяем премиум возможности в бизнес виджете
*
* @param array $features
* @param string $page_id
* @param string $plugin
*/
add_filter('wbcr/clearfy/pages/suggetion_features', function ($features, $plugin_name, $page_id) {
if( !empty($plugin_name) && ($plugin_name == WGZ_Plugin::app()->getPluginName()) ) {
$upgrade_feature = [];
$upgrade_feature[] = __('Disable plugins (groups of scripts)', 'gonzales');
$upgrade_feature[] = __('Conditions by the link template', 'gonzales');
$upgrade_feature[] = __('Conditions by the regular expression', 'gonzales');
$upgrade_feature[] = __('Safe mode', 'gonzales');
$upgrade_feature[] = __('Statistics and optimization results', 'gonzales');
return $upgrade_feature;
}
return $features;
}, 20, 3);
function wbcr_gnz_set_plugin_meta($links, $file)
{
if( $file == WGZ_PLUGIN_BASE ) {
$url = WGZ_Plugin::app()->get_support()->get_tracking_page_url('assets-manager', 'plugin_row');
$links[] = '<a href="' . $url . '" style="color: #FF5722;font-weight: bold;" target="_blank">' . __('Get premium', 'gonzales') . '</a>';
}
return $links;
}
add_filter('plugin_row_meta', 'wbcr_gnz_set_plugin_meta', 10, 2);
function wbcr_gnz_rating_widget_url($page_url, $plugin_name)
{
if( !defined('LOADING_ASSETS_MANAGER_AS_ADDON') && ($plugin_name == WGZ_Plugin::app()->getPluginName()) ) {
return 'https://goo.gl/zyNV6z';
}
return $page_url;
}
add_filter('wbcr_factory_pages_480_imppage_rating_widget_url', 'wbcr_gnz_rating_widget_url', 10, 2);
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,22 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Рекламная страница.
*
* Используется для рекламы плагина Clearfy. Пользователь может изучить все возможности плагина Clearfy
* и перейти на лендинг плагина, чтобы скачать и попробовать его.
*
* Может быть использована только, если этот плагин используется как отдельный плагин, а не как аддон
* для плагина Clearfy. Если плагин загружен, как аддон для Clearfy, эта страница не будет подключена.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WGZ_MoreFeaturesPage extends \WBCR\Factory_Templates_134\Pages\MoreFeatures {
}

View File

@@ -0,0 +1,170 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Страница общих настроек для этого плагина.
*
* Может быть использована только, если этот плагин используется как отдельный плагин, а не как аддон
* дя плагина Clearfy. Если плагин загружен, как аддон для Clearfy, эта страница не будет подключена.
*
* Поддерживает режим работы с мультисаймами. Вы можете увидеть эту страницу в панели настройки сети.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WGZ_AssetsManagerPage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* The id of the page in the admin menu.
*
* Mainly used to navigate between pages.
*
* @since 1.0.0
* @see FactoryPages480_AdminPage
*
* @var string
*/
public $id = "gonzales";
/**
* @var string
*/
public $page_menu_dashicon = 'dashicons-image-filter';
/**
* @var int
*/
public $page_menu_position = 95;
/**
* Доступена для мультисайтов
*
* @var bool
*/
public $available_for_multisite = true;
/**
* @param Wbcr_Factory480_Plugin $plugin
*/
public function __construct(Wbcr_Factory480_Plugin $plugin)
{
$this->menu_title = __('Assets manager', 'gonzales');
if( !defined('LOADING_ASSETS_MANAGER_AS_ADDON') ) {
$this->internal = false;
$this->menu_target = 'options-general.php';
$this->add_link_to_plugin_actions = true;
$this->show_search_options_form = false;
} else {
$this->page_parent_page = 'performance';
}
parent::__construct($plugin);
}
/**
* Метод позволяет менять заголовок меню, в зависимости от сборки плагина.
*
* @return string|void
*/
public function getMenuTitle()
{
return defined('LOADING_ASSETS_MANAGER_AS_ADDON') ? __('General', 'hide-login-page') : __('Assets manager', 'gonzales');
}
/**
* @return string|void *
*/
public function getPageTitle()
{
return defined('LOADING_ASSETS_MANAGER_AS_ADDON') ? __('Assets manager', 'gonzales') : __('General', 'hide-login-page');
}
/**
* Permalinks options.
*
* @return mixed[]
* @since 1.0.0
*/
public function getPageOptions()
{
$options = [];
$options[] = [
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header"><strong>' . __('Disable unused scripts, styles, and fonts', 'gonzales') . '</strong><p>' . __('There is a button in the adminbar called "Script Manager". If you click on it you will see a list of loaded scripts, styles and fonts on the current page of your site. If you think that one of the assets is superfluous on this page, you can disable it individually, so that it does not create unnecessary queries when page loading. Use the script manager very carefull to non-corrupt your website. We recommend to test this function at a local server.', 'gonzales') . '</p></div>'
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'disable_assets_manager',
'title' => __('Disable assets manager', 'gonzales'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Full disable of the module.', 'gonzales'),
'eventsOn' => [
'hide' => '#wbcr-gnz-asset-manager-extend-options'
],
'eventsOff' => [
'show' => '#wbcr-gnz-asset-manager-extend-options'
],
'default' => false
];
$options[] = [
'type' => 'div',
'id' => 'wbcr-gnz-asset-manager-extend-options',
'items' => [
[
'type' => 'separator',
'cssClass' => 'factory-separator-dashed'
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'disable_assets_manager_panel',
'title' => __('Disable assets manager panel', 'gonzales'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('By default in your admin bar there is a button for control the assets scripts and styles. With this option, you can turn off the script manager on front and back-end.', 'gonzales'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'disable_assets_manager_on_front',
'title' => __('Disable assets manager on front', 'gonzales'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Disables assets manager initialization for frontend.', 'gonzales'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'disable_assets_manager_on_backend',
'title' => __('Disable assets manager on back-end', 'gonzales'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Disables assets manager initialization for backend.', 'gonzales'),
'default' => true
]
]
];
$options[] = [
'type' => 'separator',
'cssClass' => 'factory-separator-dashed'
];
$formOptions = [];
$formOptions[] = [
'type' => 'form-group',
'items' => $options,
//'cssClass' => 'postbox'
];
return apply_filters('wbcr_gnz_assets_manager_options', $formOptions);
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,224 @@
/*
Color Scheme: http://paletton.com/palette.php?uid=c1T3n2J040kpEKzpEKzbEPSOEyiNk9W
*/
[ui-pnotify].ui-pnotify {
z-index: 999999999 !important;
}
[ui-pnotify].ui-pnotify .brighttheme {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
[ui-pnotify].ui-pnotify .brighttheme.ui-pnotify-container {
padding: 1.3rem;
}
[ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-title,
[ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-text,
[ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-confirm {
margin-left: 1.8rem;
}
[dir=rtl] [ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-title,
[dir=rtl] [ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-text,
[dir=rtl] [ui-pnotify].ui-pnotify-with-icon .brighttheme .ui-pnotify-confirm {
margin-right: 1.8rem;
margin-left: 0;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-title {
font-size: 1.2rem;
line-height: 1.4rem;
margin-top: -.2rem;
margin-bottom: 1rem;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-text {
font-size: 1rem;
line-height: 1.2rem;
margin-top: 0;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-icon {
line-height: 1;
}
[ui-pnotify].ui-pnotify .brighttheme-notice {
background-color: #FFFFA2;
border: 0 solid #FFFF00;
}
[ui-pnotify].ui-pnotify .brighttheme-notice h4,
[ui-pnotify].ui-pnotify .brighttheme-notice div {
color: #4F4F00;
}
[ui-pnotify].ui-pnotify .brighttheme-info {
background-color: #8FCEDD;
border: 0 solid #0286A5;
}
[ui-pnotify].ui-pnotify .brighttheme-info h4,
[ui-pnotify].ui-pnotify .brighttheme-info div {
color: #012831;
}
[ui-pnotify].ui-pnotify .brighttheme-success {
background-color: #AFF29A;
border: 0 solid #35DB00;
}
[ui-pnotify].ui-pnotify .brighttheme-success h4,
[ui-pnotify].ui-pnotify .brighttheme-success div {
color: #104300;
}
[ui-pnotify].ui-pnotify .brighttheme-error {
background-color: #FFABA2;
background-image: repeating-linear-gradient(135deg, transparent, transparent 35px, rgba(255, 255, 255, .3) 35px, rgba(255, 255, 255, .3) 70px);
border: 0 solid #FF1800;
}
[ui-pnotify].ui-pnotify .brighttheme-error h4,
[ui-pnotify].ui-pnotify .brighttheme-error div {
color: #4F0800;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-closer,
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-sticker {
font-size: 1rem;
line-height: 1.2rem;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-notice,
[ui-pnotify].ui-pnotify .brighttheme-icon-info,
[ui-pnotify].ui-pnotify .brighttheme-icon-success,
[ui-pnotify].ui-pnotify .brighttheme-icon-error,
[ui-pnotify].ui-pnotify .brighttheme-icon-closer,
[ui-pnotify].ui-pnotify .brighttheme-icon-sticker {
position: relative;
width: 1rem;
height: 1rem;
font-size: 1rem;
font-weight: bold;
line-height: 1rem;
font-family: "Courier New", Courier, monospace;
border-radius: 50%;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-notice:after,
[ui-pnotify].ui-pnotify .brighttheme-icon-info:after,
[ui-pnotify].ui-pnotify .brighttheme-icon-success:after,
[ui-pnotify].ui-pnotify .brighttheme-icon-closer:after,
[ui-pnotify].ui-pnotify .brighttheme-icon-sticker:after {
position: absolute;
top: 0;
left: .2rem;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-notice {
background-color: #2E2E00;
color: #FFFFA2;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-notice:after {
content: "!";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-info {
background-color: #012831;
color: #8FCEDD;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-info:after {
content: "i";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-success {
background-color: #104300;
color: #AFF29A;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-success:after {
content: "\002713";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-error {
width: 0;
height: 0;
font-size: 0;
line-height: 0;
border-radius: 0;
border-left: .6rem solid transparent;
border-right: .6rem solid transparent;
border-bottom: 1.2rem solid #2E0400;
color: #FFABA2;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-error:after {
position: absolute;
top: .1rem;
left: -0.25rem;
font-size: .9rem;
font-weight: bold;
line-height: 1.4rem;
font-family: "Courier New", Courier, monospace;
content: "!";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-closer,
[ui-pnotify].ui-pnotify .brighttheme-icon-sticker {
display: inline-block;
}
[ui-pnotify].ui-pnotify .brighttheme-icon-closer:after {
content: "\002715";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-sticker:after {
top: -1px;
content: "\002016";
}
[ui-pnotify].ui-pnotify .brighttheme-icon-sticker.brighttheme-icon-stuck:after {
content: "\00003E";
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-confirm {
margin-top: 1rem;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-prompt-bar {
margin-bottom: 1rem;
}
[ui-pnotify].ui-pnotify .brighttheme .ui-pnotify-action-button {
text-transform: uppercase;
font-weight: bold;
padding: .4rem 1rem;
border: none;
background: transparent;
cursor: pointer;
}
[ui-pnotify].ui-pnotify .brighttheme-notice .ui-pnotify-action-button.brighttheme-primary {
background-color: #FFFF00;
color: #4F4F00;
}
[ui-pnotify].ui-pnotify .brighttheme-info .ui-pnotify-action-button.brighttheme-primary {
background-color: #0286A5;
color: #012831;
}
[ui-pnotify].ui-pnotify .brighttheme-success .ui-pnotify-action-button.brighttheme-primary {
background-color: #35DB00;
color: #104300;
}
[ui-pnotify].ui-pnotify .brighttheme-error .ui-pnotify-action-button.brighttheme-primary {
background-color: #FF1800;
color: #4F0800;
}

View File

@@ -0,0 +1,175 @@
/* ==*/
#WBCR-AM .wam-cleditor {
box-sizing: border-box;
/* Conditions */
/* Buttons */
}
#WBCR-AM .wam-cleditor input {
float: none;
position: relative;
top: 0;
padding: 4px;
}
#WBCR-AM .wam-cleditor.wam-cleditor__disable-plugin-mode .wam-cleditor__param-select option[value="location-taxonomy"],
#WBCR-AM .wam-cleditor.wam-cleditor__disable-plugin-mode .wam-cleditor__param-select option[value="location-post-type"],
#WBCR-AM .wam-cleditor.wam-cleditor__disable-plugin-mode .wam-cleditor__param-select option[value="location-some-page"] {
display: none;
}
#WBCR-AM .wam-cleditor .wam-cleditor__text {
width: 300px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__box {
padding: 25px 15px 15px 15px;
border-left: 1px solid #ddd;
background-color: #f9f9f9;
}
#WBCR-AM .wam-cleditor .wam-cleditor__when-empty {
display: none;
}
#WBCR-AM .wam-cleditor .wam-cleditor__empty .wam-cleditor__when-empty {
display: block;
}
#WBCR-AM .wam-cleditor .wam-cleditor__head {
display: flex;
overflow: auto;
background-color: #fff;
border-bottom: 1px solid #ddd;
border-left: 1px solid #ddd;
padding: 10px 15px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__head .wam-cleditor__head-left,
#WBCR-AM .wam-cleditor .wam-cleditor__head .wam-cleditor__head-right {
display: inline-block;
}
#WBCR-AM .wam-cleditor .wam-cleditor__head .wam-cleditor__head-left {
text-align: left;
flex: 2 0 0;
}
#WBCR-AM .wam-cleditor .wam-cleditor__head .wam-cleditor__head-right {
text-align: right;
flex: 1 0 0;
}
#WBCR-AM .wam-cleditor .wam-cleditor__head .wam-cleditor__first-group-title {
text-transform: uppercase;
margin: 0;
font-weight: 600;
font-size: 14px;
line-height: 2.3;
}
#WBCR-AM .wam-cleditor .wam-cleditor__wrap .wam-cleditor__groups {
padding-left: 20px;
border-left: 1px solid #ddd;
}
#WBCR-AM .wam-cleditor .wam-cleditor__groups .wam-cleditor__point {
background-color: #fff;
border: 1px solid #0073aa;
border-radius: 100%;
width: 11px;
height: 11px;
display: block;
position: absolute;
margin-left: -26px;
margin-top: 19px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__groups .wam-cleditor__point:after {
position: absolute;
content: " ";
display: block;
width: 15px;
border-top: 1px solid #ddd;
margin-left: 10px;
margin-top: 4px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__group {
/*@{prefix}__group + @{prefix}__group {
margin-top: 20px;
}*/
}
#WBCR-AM .wam-cleditor .wam-cleditor__group .wam-cleditor__group-type {
display: none;
text-transform: uppercase;
margin: 0;
line-height: 2.3;
font-size: 12px;
font-weight: bold;
font-style: normal;
color: #222;
background: #f3f3f3;
text-align: center;
border-radius: 3px;
padding: 5px 10px 5px 10px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__empty .wam-cleditor__conditions {
display: none;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition {
position: relative;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint,
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint-content {
display: none;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint {
position: relative;
display: inline-block;
padding: 0 6px 0 3px;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint-icon {
background: url('../img/help.png') no-repeat 0 0 transparent;
position: relative;
height: 14px;
width: 13px;
display: inline-block;
cursor: help;
vertical-align: middle;
top: -1px;
opacity: 0.55;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint:hover .wam-cleditor__hint-content {
display: block;
position: absolute;
width: 280px;
background-color: rgba(0, 0, 0, 0.8);
white-space: normal;
padding: 10px 12px 12px 12px;
font-weight: normal;
line-height: 150%;
border-radius: 4px;
color: #fff;
font-size: 13px;
z-index: 999;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint .wam-cleditor__hint-content,
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__hint .wam-cleditor__hint-content a {
color: #fff;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__operator-and {
display: block;
color: rgba(0, 0, 0, 0.7);
font-weight: bold;
border-top: 1px solid #ddd;
margin: 18px 0;
position: relative;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__operator-and span {
position: absolute;
top: -10px;
background-color: #f9f9f9;
padding-right: 7px;
text-transform: uppercase;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition:first-child .wam-cleditor__operator-and {
display: none;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition > span {
display: inline-block;
vertical-align: top;
}
#WBCR-AM .wam-cleditor .wam-cleditor__condition .wam-cleditor__condition-actions {
position: absolute;
right: 0;
}
#WBCR-AM .wam-cleditor .wam-cleditor__buttons-group {
margin-top: 20px;
}
/*# sourceMappingURL=assets-conditions.css.map */

View File

@@ -0,0 +1,252 @@
/**
* Float panel
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright Webcraftic 26.08.2019
*/
.wam-float-panel {
position: fixed;
z-index: 50;
top: 30px;
right: 0;
left: 0;
width: 100%;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-ms-flex-pack: justify;
-webkit-justify-content: space-between;
justify-content: space-between;
height: 62px;
padding: 0 20px;
margin: 0;
color: #FFF;
background: #23282d;
font-size: 16px;
border-top: 2px solid #ffcb1e;
}
.wam-float-panel__premium {
position: relative;
display: block;
width: 20px;
height: 40px;
background: #ffcb1e;
margin-left: -30px;
}
.wam-float-panel__premium:hover {
cursor: pointer;
}
.wam-float-panel__premium .wam-tooltip {
position: relative;
right: -30px;
top: 8px;
font-size: 12px;
font-weight: bold;
font-style: normal;
color: #ffffff;
background: #f22714;
width: 45px;
text-align: center;
border-radius: 3px;
padding: 5px 0 5px 0;
line-height: 1.2;
}
.wam-float-panel__premium:after {
display: block;
content: '';
position: absolute;
top: 1px;
left: 0;
width: 19px;
height: 38px;
background: #23282d;
}
.wam-float-panel__left,
.wam-float-panel__right {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
align-items: center;
-ms-flex-align: center;
}
.wam-float-panel__left {
min-width: 800px;
margin: 0 44px 0 0;
}
.wam-float-panel__logo {
width: 38px;
height: 32px;
margin: 0 44px 0 0;
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAgCAMAAABJuvqBAAAC+lBMVEUAAAD7bBgLxt8LyOP/oRqTVqOWV6T/gALpHxCKT5oMy+bwCgX/dhn/oxeXV6XxJxP/igzxIQztFAP/iQAIwNfoIBP/jgkPz+wOzun/igf/fgD/iggOze3hHxDuDAF0P4KWV6UP0OzyKxX/lw3iHxD/hAaXV6XyGgsPzu3/ggaJTpn/iw6JTZiUVqOUVqTlFQsve3T2Qy1lazvqIhOBHyvvlxW7FRCTaR3xGQX/kBIP0eyGTJbjIBKASJAAXn3uFQMPzewJxNo1JFOLUZuHTZb/xCEAkqmXV6X/ggB5QogNyOD/WSaWV6VjNnBHFTsLUVnrEgMQ0en/ggADtsz/mRTvJRT/igfpDwLgHw//ixD/igYQ0un/xiXlIBP/rhnnIRSXV6X/lgT/ig36OBz/ZzbkJBj/fAAMyeD/iQoFtMkPzeyNUZziHxHgHw/mCwIBobT/yy3kBQNIIVp2dz4PzewAc4L/ckKXV6V6JDr/oRb0DAD9egD/jAcOze2XV6XeHw7jAwPnIRSXV6X/vSoPz+j/fgB+DjKXV6X/ziAPzuzlIBP/iw7/yx7yJxT/YCLpIRQP0uwLxt2TV6T/YSD/nBTuJBT/jhCQVKCNUp2DSpL/xRf8PRf4LhTsIhT/kREQ0egOzOQMyuEJwtiKT5qGTZaASI9xPn//XSH/tRr/Uhf/oBb3KRPjHxAHv9UGvNEDsMUCqLwAjp98RItdMWg3Hkr/VyD/xh//wR7/Xx7/XBv/rxn6NBf/rBb/lxP/lBP+RRP9NQ3/igv/iQv+Kwv3Iwf/pQUOzuYGt813QoZqOnYAYHRULmJBJVQwFz3+Tx//1R3/uxz8Rhz/Shv/pxj/phb/vhL/sgr/mAIPzucEuc4BoLMBnK4AmKoAg5MAf5IAd4cAbYEAbHxkNnAAT2kIVGQASF5KJ1kARlcVU1U+ZEYsGEVfdTtIHDltKzJ6fS2OOCyniinWsCL/YyD3YCDkSyCrNCDvyR+8KR/50Bj/uRH/tQ7/qwnxGwX/kQIQ63s7AAAAh3RSTlMAAyIQCsuvaz8wKx4Y/vn58PDp5+Xk5NbAu6+rqJuVgH15d3dpXE1HRTAoIyAYFhQNCv7+/fz7+vn39vX19PLy8O/u6urk397c29ra19TU087JyMfGxMO6squjoJ+fnpyZmZiUk5GRkI+Oi4uJiINybGZhYV1dWldPTk1LQzo6OCopJSMYEw7x8GTCAAACaUlEQVQ4y2LABzgi6hkIgsZYmzUqhBQZKol2da3JJaBKPXRuP1CZLF5FPMn8vVON+/ErYyzznj2ndyrIuBw8rkrZsfzinN5ekDI8XlBaObnv3O7VYOM4MGSZmZiYmIE0t+D+HX1bIbaK6qMq0VCMlvASEQnOByoTOrCzb/klkHH98YwwFVwaJYoy4lYTbiycuPbmho2lDAxyR4C2go0TRNgp0wkCE+YvmLho3fqNp/wNGNQtZu/oA3lidSrCvloHsKpjQMPW33n43LyaQT/gMMQT/BWMCHVZMMOO37r/9N3RNAaGvCP7QbYeNnHyldeCO18CpGrhonUb7j5+/eOaBw9Dgz3YE9+3nF621CVbD6qOSXwCyEqgw15+O3/1ryoDQzjQE5++vDlzctPMxdNZOWGeBSgQZOXtBy8+nu+YdVSKgaHwz/7Jn99u2Xxi5pIZ0yf5NEHVtaQ7rttw78mHWT0dPdeEecBB9/4V0Moli6dPam9n1YWHXqabndGeFds6Oq5eZwcG3eGvZ5+BrJwxqR0IEhAeNig2vbJrew/IVkaGKrOzZx6dWAq0EqyMTw2hLnHKqj0XgLb+EtZkaPPbsnnZUrBhYMAGV1VjuXfKZZCts0C2Fm1etgnsfj53NoXyOh14Uoyctm8KL8jWnt9BLAwM8p621s6sbApqeihpRFtg2ry9YFs7foq1AgV0ODm1dBnRUxtgqt3d8/ZNuQK2VRl3ks3o7p42b8oqkK0xLLiVSR/qBtl6eYVrAR5VDJKHurtBnohrxpszw0DK5oVUEsjlkgcPdospszAQAFEHBZK0GQgCdmlNfNIAQzEmYu+mR3cAAAAASUVORK5CYII=");
}
.wam-float-panel__data {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
align-items: center;
-ms-flex-align: center;
margin: 0 -22px;
padding: 0;
list-style: none;
}
.wam-float-panel__data:not(:last-child) {
margin-right: 22px;
}
.wam-float-panel__data-item {
margin: 0 22px;
color: #909090;
text-align: center;
vertical-align: top;
padding: 8px 0 8px;
}
.wam-float-panel__data-hidden {
display: none;
margin: 0 44px 0 0;
}
.wam-float-panel__data-hidden img {
vertical-align: middle;
}
.wam-float-panel__item_value {
font-size: 15px;
color: #d0d0d0;
background: #4c4c4c;
border-radius: 2px;
padding: 2px 5px;
}
.wam-float-panel__reset,
.wam-float-panel__save,
.wam-float-panel__reset.input[type="submit"],
.wam-float-panel__save.input[type="submit"] {
display: inline-block;
padding: 8px 15px 7px;
cursor: pointer;
transition: 0.1s;
vertical-align: middle;
text-transform: uppercase !important;
border: none;
border-radius: 2px;
font-size: 14px;
line-height: 1.5;
color: #222 !important;
}
.wam-float-panel__reset:hover,
.wam-float-panel__save:hover,
.wam-float-panel__reset:focus,
.wam-float-panel__save:focus {
outline: none;
text-decoration: none;
}
.wam-float-panel__reset:active,
.wam-float-panel__save:active {
-webkit-transform: translateY(2px);
transform: translateY(2px);
}
.wam-float-panel__reset,
.wam-float-panel__reset.input[type="submit"] {
margin: 0 10px 0 0;
padding-right: 30px;
padding-left: 30px;
background: #E1E5E9;
box-shadow: 0 4px #A8AEB3 !important;
}
.wam-float-panel__reset:hover,
.wam-float-panel__reset:focus {
background: #E7EAED !important;
}
.wam-float-panel__reset:active {
box-shadow: 0 2px #A8AEB3 !important;
}
.wam-float-panel__save,
.wam-float-panel__save.input[type="submit"] {
margin: 0 10px 0 0;
padding-right: 30px;
padding-left: 30px;
color: #222 !important;
background: #FFCB1E !important;
box-shadow: 0 4px #BF9A17 !important;
}
.wam-float-panel__save:hover,
.wam-float-panel__save:focus {
background: #FFD340 !important;
box-shadow: 0 4px #BF9A17 !important;
}
.wam-float-panel__save:active {
background: #FFD340 !important;
box-shadow: 0 2px #BF9A17 !important;
}
.wam-float-panel__save + div {
margin: 0;
}
.wam-float-panel__checkbox {
cursor: pointer;
font-size: 15px;
transform: none;
}
.wam-float-panel__checkbox-text,
.wam-float-panel__checkbox-text-premium {
position: relative;
padding: 0 0 0 26px;
}
.wam-float-panel__checkbox-text::before,
.wam-float-panel__checkbox-text-premium::before {
content: "";
position: absolute;
top: -1px;
left: 0;
width: 20px;
height: 20px;
border-radius: 2px;
background: #ffcb1e;
}
.wam-float-panel__checkbox-input:checked + .wam-float-panel__checkbox-text::after,
.wam-float-panel__checkbox-input:checked + .wam-float-panel__checkbox-text-premium::after {
content: "";
position: absolute;
top: 5px;
left: 6px;
width: 8px;
height: 5px;
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
border: solid #444;
border-width: 0 0 2px 2px;
}
.wam-float-panel__checkbox-text-premium {
display: inline;
color: rgba(245, 245, 245, 0.3);
}
.wam-float-panel__checkbox-text-premium b {
display: inline-block;
font-size: 9px;
font-weight: 700;
color: #fff;
background: #f22714;
width: 25px;
padding: 3px 0;
text-align: center;
vertical-align: top;
border-radius: 3px;
line-height: 1.5;
}
.wam-float-panel__checkbox-text-premium::before {
background: rgba(245, 245, 245, 0.3);
}
.wam-float-panel__close,
.wam-float-panel__close:hover {
width: 36px;
height: 36px;
margin: 0 20px 0 20px;
cursor: pointer;
transition: 0.2s;
border: 4px solid #FFF;
border-radius: 50%;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 352 512'%3E%3Cpath fill='%23FFF' d='M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z'/%3E%3C/svg%3E") no-repeat 50% 0px;
}
.wam-float-panel__close:focus,
.wam-float-panel__close:hover:focus {
opacity: 0.5;
outline: none;
}
/*# sourceMappingURL=float-panel.css.map */

View File

@@ -0,0 +1,251 @@
/**
* Reset styles
* @author Webcraftic <wordpress.webraftic@gmail.com>
* @copyright Webcraftic 15.10.2018
*/
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h2,
h3,
h4,
h5,
h6,
p,
strong,
b,
span,
em,
i,
a,
div,
main,
section,
li,
button,
input[type="submit"],
input[type="reset"],
.wbcr-gnz-switch-premium {
font-family: Arial, "Helvetica Neue", sans-serif !important;
font-size: 14px;
font-style: normal;
font-weight: normal;
text-transform: none;
text-shadow: none;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible;
}
pre {
font-family: monospace, monospace;
font-size: 1em;
}
a {
background-color: transparent;
}
abbr[title] {
border-bottom: none;
text-decoration: underline dotted;
}
b,
strong {
font-weight: bolder;
}
code,
kbd,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
img {
border-style: none;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
height: auto;
width: auto;
}
button,
input,
optgroup,
select,
textarea,
button:hover,
input:hover,
optgroup:hover,
select:hover,
textarea:hover,
button:focus,
input:focus,
optgroup:focus,
select:focus,
textarea:focus {
-moz-box-shadow: none;
-ms-box-shadow: none;
-webkit-box-shadow: none;
-o-box-shadow: none;
}
button,
input {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
fieldset {
padding: 0.35em 0.75em 0.625em;
}
legend {
box-sizing: border-box;
color: inherit;
display: table;
max-width: 100%;
padding: 0;
white-space: normal;
}
textarea {
overflow: auto;
}
[type="checkbox"],
[type="radio"] {
box-sizing: border-box;
padding: 0;
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
-webkit-appearance: textfield;
outline-offset: -2px;
}
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit;
}
fieldset {
padding: 0.35em 0.75em 0.625em;
}
legend {
box-sizing: border-box;
color: inherit;
display: table;
max-width: 100%;
padding: 0;
white-space: normal;
}
progress {
vertical-align: baseline;
}
textarea {
overflow: auto;
}
[type=checkbox],
[type=radio] {
box-sizing: border-box;
padding: 0;
}
[type=number]::-webkit-inner-spin-button,
[type=number]::-webkit-outer-spin-button {
height: auto;
}
[type=search] {
-webkit-appearance: textfield;
outline-offset: -2px;
}
[type=search]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit;
}
details {
display: block;
}
summary {
display: list-item;
}
template {
display: none;
}
[hidden] {
display: none;
}
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: middle;
line-height: 1.2;
}
table {
table-layout: auto;
border-collapse: collapse;
border-spacing: 0;
}

View File

@@ -0,0 +1,85 @@
/**
* Tabless
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright Webcraftic 26.08.2019
*/
.wam-table {
width: 100%;
box-sizing: border-box;
table-layout: fixed;
border-collapse: collapse;
}
.wam-table__handle-deps {
margin-top: 15px;
}
.wam-table__handle-deps span,
.wam-table__handle-deps a {
font-size: 11px !important;
}
.wam-table__handle-deps a {
color: red;
text-decoration: underline;
}
.wam-table tr:nth-child(2n) > td {
background: #f9f9f9;
}
.wam-table th {
padding: 12px 10px;
text-align: left;
color: #333;
background: #ECEDED;
box-shadow: none;
}
.wam-table th:not(:last-child) {
border-right: 2px solid #FFF;
}
.wam-table__th-actions {
width: 200px;
}
.wam-table__th-type {
width: 100px;
}
.wam-table__th-version {
width: 100px;
}
.wam-table__th-size {
width: 100px;
}
.wam-table__th-plugins-list,
.wam-table__td-plugins-list {
width: 350px;
}
.wam-table td {
padding: 17px 10px;
vertical-align: top;
text-align: left;
box-shadow: none;
}
.wam-table__td-handle {
word-break: break-word;
}
.wam-table__td-plugins-list {
padding: 0 !important;
}
.wam-table__th-plugins-settings,
.wam-table__td-plugins-settings {
width: 80%;
padding: 15px;
text-align: left;
}
.wam-table .js-wam-table__tr--disabled-section {
background: #fbf5f4;
opacity: 0.7;
}
.wam-table__asset-settings-conditions {
display: none;
background: #f3f3f3;
color: #7b7b7b;
font-size: 13px;
box-shadow: 0 2px 0 #d4d4d4;
}
.wam-table__asset-settings-conditions > td {
padding: 0 25px 15px 25px;
}
/*# sourceMappingURL=tables.css.map */

View File

@@ -0,0 +1,55 @@
/**
* Tooltip
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright Webcraftic 26.08.2019
*/
.wam-tooltip {
position: relative;
}
.wam-tooltip::before {
content: "";
position: absolute;
z-index: 60;
left: 5px;
display: none;
width: 20px;
height: 20px;
}
.wam-tooltip::after {
content: attr(data-tooltip);
position: absolute;
z-index: 60;
left: 5px;
display: none;
min-width: 200px;
padding: 8px 15px;
color: #6d5506;
background: #FFCB1E;
font-size: 13px;
font-weight: normal;
line-height: 1.2;
}
.wam-tooltip-top::before {
bottom: 100%;
background: linear-gradient(135deg, #FFCB1E, #FFCB1E 50%, transparent 50%, transparent) no-repeat;
}
.wam-tooltip-top::after {
bottom: 100%;
margin: 0 0 10px;
border-radius: 6px 6px 6px 0;
}
.wam-tooltip--bottom::before {
top: 100%;
background: linear-gradient(45deg, #FFCB1E, #FFCB1E 50%, transparent 50%, transparent) no-repeat;
}
.wam-tooltip--bottom::after {
top: 100%;
margin: 15px 0 0;
border-radius: 0 6px 6px 6px;
}
.wam-tooltip:hover::before,
.wam-tooltip:hover::after {
display: block;
}
/*# sourceMappingURL=tooltip.css.map */

Binary file not shown.

After

Width:  |  Height:  |  Size: 435 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 314 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 493 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 330 330" width="36" height="36"><g fill="#FFF"><path d="M165 0C74.019 0 0 74.02 0 165.001 0 255.982 74.019 330 165 330s165-74.018 165-164.999S255.981 0 165 0zm0 300c-74.44 0-135-60.56-135-134.999S90.56 30 165 30s135 60.562 135 135.001C300 239.44 239.439 300 165 300z"/><path d="M164.998 70c-11.026 0-19.996 8.976-19.996 20.009 0 11.023 8.97 19.991 19.996 19.991 11.026 0 19.996-8.968 19.996-19.991 0-11.033-8.97-20.009-19.996-20.009zM165 140c-8.284 0-15 6.716-15 15v90c0 8.284 6.716 15 15 15 8.284 0 15-6.716 15-15v-90c0-8.284-6.716-15-15-15z"/></g></svg>

After

Width:  |  Height:  |  Size: 608 B

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,790 @@
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
/* src/PNotifyConfirm.html generated by Svelte v2.16.1 */
var WamPnotifyConfirm = function (PNotify) {
"use strict";
PNotify = PNotify && PNotify.__esModule ? PNotify["default"] : PNotify;
function data() {
return _extends({
'_notice': null, // The PNotify notice.
'_options': {} // The options for the notice.
}, PNotify.modules.Confirm.defaults);
};
var methods = {
initModule: function initModule(options) {
this.set(options);
},
afterOpen: function afterOpen() {
if (this.get().prompt && this.get().focus !== false) {
if (this.get().promptMultiLine) {
this.refs.promptMulti.focus();
} else {
this.refs.promptSingle.focus();
}
} else if (this.get().confirm && (this.get().focus === true || this.get().focus === null && this.get()._options.stack.modal)) {
var buttons = this.get().buttons;
if (buttons.length) {
var i = buttons.length - 1;
while (i >= 0) {
if (buttons[i].promptTrigger) {
break;
}
i--;
}
this.refs.buttons.children[i].focus();
}
}
},
handleClick: function handleClick(button, event) {
if (button.click) {
button.click(this.get()._notice, this.get().prompt ? this.get().promptValue : null, event);
}
},
handleKeyPress: function handleKeyPress(event) {
if (event.keyCode === 13 && !event.shiftKey) {
event.preventDefault();
var _get = this.get(),
buttons = _get.buttons;
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].promptTrigger && buttons[i].click) {
buttons[i].click(this.get()._notice, this.get().prompt ? this.get().promptValue : null, event);
}
}
}
}
};
function oncreate() {
this.fire('init', { module: this });
};
function setup(Component) {
Component.key = 'Confirm';
Component.defaults = {
// Make a confirmation box.
confirm: false,
// Make a prompt.
prompt: false,
// Classes to add to the input element of the prompt.
promptClass: '',
// The value of the prompt.
promptValue: '',
// Whether the prompt should accept multiple lines of text.
promptMultiLine: false,
// For confirmation boxes, true means the first button or the button with promptTrigger will be focused, and null means focus will change only for modal notices. For prompts, true or null means focus the prompt. When false, focus will not change.
focus: null,
// Where to align the buttons. (flex-start, center, flex-end, space-around, space-between)
align: 'flex-end',
// The buttons to display, and their callbacks.
buttons: [{
text: 'Ok',
textTrusted: false,
addClass: '',
primary: true,
// Whether to trigger this button when the user hits enter in a single line prompt. Also, focus the button if it is a modal prompt.
promptTrigger: true,
click: function click(notice, value) {
notice.close();
notice.fire('pnotify.confirm', { notice: notice, value: value });
}
}, {
text: 'Cancel',
textTrusted: false,
addClass: '',
click: function click(notice) {
notice.close();
notice.fire('pnotify.cancel', { notice: notice });
}
}]
};
// Register the module with PNotify.
PNotify.modules.Confirm = Component;
// Append this module to the container.
PNotify.modulesAppendContainer.push(Component);
// Add button styles to styling objects.
_extends(PNotify.styling.brighttheme, {
actionBar: '',
promptBar: '',
btn: '',
btnPrimary: 'brighttheme-primary',
input: ''
});
_extends(PNotify.styling.bootstrap3, {
actionBar: 'ui-pnotify-confirm-ml',
promptBar: 'ui-pnotify-confirm-ml',
btn: 'btn btn-default ui-pnotify-confirm-mx-1',
btnPrimary: 'btn btn-default ui-pnotify-confirm-mx-1 btn-primary',
input: 'form-control'
});
_extends(PNotify.styling.bootstrap4, {
actionBar: 'ui-pnotify-confirm-ml',
promptBar: 'ui-pnotify-confirm-ml',
btn: 'btn btn-secondary mx-1',
btnPrimary: 'btn btn-primary mx-1',
input: 'form-control'
});
if (!PNotify.styling.material) {
PNotify.styling.material = {};
}
_extends(PNotify.styling.material, {
actionBar: '',
promptBar: '',
btn: '',
btnPrimary: 'ui-pnotify-material-primary',
input: ''
});
};
function add_css() {
var style = createElement("style");
style.id = 'svelte-1y9suua-style';
style.textContent = ".ui-pnotify-action-bar.svelte-1y9suua,.ui-pnotify-prompt-bar.svelte-1y9suua{margin-top:5px;clear:both}.ui-pnotify-action-bar.svelte-1y9suua{display:flex;flex-wrap:wrap;justify-content:flex-end}.ui-pnotify-prompt-input.svelte-1y9suua{margin-bottom:5px;display:block;width:100%}.ui-pnotify-confirm-mx-1.svelte-1y9suua{margin:0 5px}.ui-pnotify.ui-pnotify-with-icon .ui-pnotify-confirm-ml.svelte-1y9suua{margin-left:24px}[dir=rtl] .ui-pnotify.ui-pnotify-with-icon .ui-pnotify-confirm-ml.svelte-1y9suua{margin-right:24px;margin-left:0}";
append(document.head, style);
}
function click_handler(event) {
var _svelte = this._svelte,
component = _svelte.component,
ctx = _svelte.ctx;
component.handleClick(ctx.button, event);
}
function get_each_context(ctx, list, i) {
var child_ctx = Object.create(ctx);
child_ctx.button = list[i];
return child_ctx;
}
function create_main_fragment(component, ctx) {
var if_block_anchor;
var if_block = (ctx.confirm || ctx.prompt) && create_if_block(component, ctx);
return {
c: function c() {
if (if_block) if_block.c();
if_block_anchor = createComment();
},
m: function m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p: function p(changed, ctx) {
if (ctx.confirm || ctx.prompt) {
if (if_block) {
if_block.p(changed, ctx);
} else {
if_block = create_if_block(component, ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
d: function d(detach) {
if (if_block) if_block.d(detach);
if (detach) {
detachNode(if_block_anchor);
}
}
};
}
// (1:0) {#if confirm || prompt}
function create_if_block(component, ctx) {
var div1, text, div0, div0_class_value;
var if_block = ctx.prompt && create_if_block_2(component, ctx);
var each_value = ctx.buttons;
var each_blocks = [];
for (var i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(component, get_each_context(ctx, each_value, i));
}
return {
c: function c() {
div1 = createElement("div");
if (if_block) if_block.c();
text = createText("\n ");
div0 = createElement("div");
for (var i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
div0.className = div0_class_value = "\n ui-pnotify-action-bar\n " + (ctx._notice.get()._styles.actionBar ? ctx._notice.get()._styles.actionBar : '') + "\n " + (ctx._notice.get()._styles.text ? ctx._notice.get()._styles.text : '') + "\n " + " svelte-1y9suua";
setStyle(div0, "justify-content", ctx.align);
div1.className = "ui-pnotify-confirm";
},
m: function m(target, anchor) {
insert(target, div1, anchor);
if (if_block) if_block.m(div1, null);
append(div1, text);
append(div1, div0);
for (var i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div0, null);
}
component.refs.buttons = div0;
},
p: function p(changed, ctx) {
if (ctx.prompt) {
if (if_block) {
if_block.p(changed, ctx);
} else {
if_block = create_if_block_2(component, ctx);
if_block.c();
if_block.m(div1, text);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (changed.buttons || changed._notice) {
each_value = ctx.buttons;
for (var i = 0; i < each_value.length; i += 1) {
var child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(changed, child_ctx);
} else {
each_blocks[i] = create_each_block(component, child_ctx);
each_blocks[i].c();
each_blocks[i].m(div0, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (changed._notice && div0_class_value !== (div0_class_value = "\n ui-pnotify-action-bar\n " + (ctx._notice.get()._styles.actionBar ? ctx._notice.get()._styles.actionBar : '') + "\n " + (ctx._notice.get()._styles.text ? ctx._notice.get()._styles.text : '') + "\n " + " svelte-1y9suua")) {
div0.className = div0_class_value;
}
if (changed.align) {
setStyle(div0, "justify-content", ctx.align);
}
},
d: function d(detach) {
if (detach) {
detachNode(div1);
}
if (if_block) if_block.d();
destroyEach(each_blocks, detach);
if (component.refs.buttons === div0) component.refs.buttons = null;
}
};
}
// (3:4) {#if prompt}
function create_if_block_2(component, ctx) {
var div, div_class_value;
function select_block_type(ctx) {
if (ctx.promptMultiLine) return create_if_block_3;
return create_else_block_1;
}
var current_block_type = select_block_type(ctx);
var if_block = current_block_type(component, ctx);
return {
c: function c() {
div = createElement("div");
if_block.c();
div.className = div_class_value = "\n ui-pnotify-prompt-bar\n " + (ctx._notice.get()._styles.promptBar ? ctx._notice.get()._styles.promptBar : '') + "\n " + (ctx._notice.get()._styles.text ? ctx._notice.get()._styles.text : '') + "\n " + " svelte-1y9suua";
},
m: function m(target, anchor) {
insert(target, div, anchor);
if_block.m(div, null);
},
p: function p(changed, ctx) {
if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) {
if_block.p(changed, ctx);
} else {
if_block.d(1);
if_block = current_block_type(component, ctx);
if_block.c();
if_block.m(div, null);
}
if (changed._notice && div_class_value !== (div_class_value = "\n ui-pnotify-prompt-bar\n " + (ctx._notice.get()._styles.promptBar ? ctx._notice.get()._styles.promptBar : '') + "\n " + (ctx._notice.get()._styles.text ? ctx._notice.get()._styles.text : '') + "\n " + " svelte-1y9suua")) {
div.className = div_class_value;
}
},
d: function d(detach) {
if (detach) {
detachNode(div);
}
if_block.d();
}
};
}
// (21:8) {:else}
function create_else_block_1(component, ctx) {
var input,
input_updating = false,
input_class_value;
function input_input_handler() {
input_updating = true;
component.set({ promptValue: input.value });
input_updating = false;
}
function keypress_handler(event) {
component.handleKeyPress(event);
}
return {
c: function c() {
input = createElement("input");
addListener(input, "input", input_input_handler);
addListener(input, "keypress", keypress_handler);
setAttribute(input, "type", "text");
input.className = input_class_value = "\n ui-pnotify-prompt-input\n " + (ctx._notice.get()._styles.input ? ctx._notice.get()._styles.input : '') + "\n " + ctx.promptClass + "\n " + " svelte-1y9suua";
},
m: function m(target, anchor) {
insert(target, input, anchor);
component.refs.promptSingle = input;
input.value = ctx.promptValue;
},
p: function p(changed, ctx) {
if (!input_updating && changed.promptValue) input.value = ctx.promptValue;
if ((changed._notice || changed.promptClass) && input_class_value !== (input_class_value = "\n ui-pnotify-prompt-input\n " + (ctx._notice.get()._styles.input ? ctx._notice.get()._styles.input : '') + "\n " + ctx.promptClass + "\n " + " svelte-1y9suua")) {
input.className = input_class_value;
}
},
d: function d(detach) {
if (detach) {
detachNode(input);
}
removeListener(input, "input", input_input_handler);
removeListener(input, "keypress", keypress_handler);
if (component.refs.promptSingle === input) component.refs.promptSingle = null;
}
};
}
// (10:8) {#if promptMultiLine}
function create_if_block_3(component, ctx) {
var textarea,
textarea_updating = false,
textarea_class_value;
function textarea_input_handler() {
textarea_updating = true;
component.set({ promptValue: textarea.value });
textarea_updating = false;
}
function keypress_handler(event) {
component.handleKeyPress(event);
}
return {
c: function c() {
textarea = createElement("textarea");
addListener(textarea, "input", textarea_input_handler);
addListener(textarea, "keypress", keypress_handler);
textarea.rows = "5";
textarea.className = textarea_class_value = "\n ui-pnotify-prompt-input\n " + (ctx._notice.get()._styles.input ? ctx._notice.get()._styles.input : '') + "\n " + ctx.promptClass + "\n " + " svelte-1y9suua";
},
m: function m(target, anchor) {
insert(target, textarea, anchor);
component.refs.promptMulti = textarea;
textarea.value = ctx.promptValue;
},
p: function p(changed, ctx) {
if (!textarea_updating && changed.promptValue) textarea.value = ctx.promptValue;
if ((changed._notice || changed.promptClass) && textarea_class_value !== (textarea_class_value = "\n ui-pnotify-prompt-input\n " + (ctx._notice.get()._styles.input ? ctx._notice.get()._styles.input : '') + "\n " + ctx.promptClass + "\n " + " svelte-1y9suua")) {
textarea.className = textarea_class_value;
}
},
d: function d(detach) {
if (detach) {
detachNode(textarea);
}
removeListener(textarea, "input", textarea_input_handler);
removeListener(textarea, "keypress", keypress_handler);
if (component.refs.promptMulti === textarea) component.refs.promptMulti = null;
}
};
}
// (51:57) {:else}
function create_else_block(component, ctx) {
var text_value = ctx.button.text,
text;
return {
c: function c() {
text = createText(text_value);
},
m: function m(target, anchor) {
insert(target, text, anchor);
},
p: function p(changed, ctx) {
if (changed.buttons && text_value !== (text_value = ctx.button.text)) {
setData(text, text_value);
}
},
d: function d(detach) {
if (detach) {
detachNode(text);
}
}
};
}
// (51:14) {#if button.textTrusted}
function create_if_block_1(component, ctx) {
var raw_value = ctx.button.text,
raw_before,
raw_after;
return {
c: function c() {
raw_before = createElement('noscript');
raw_after = createElement('noscript');
},
m: function m(target, anchor) {
insert(target, raw_before, anchor);
raw_before.insertAdjacentHTML("afterend", raw_value);
insert(target, raw_after, anchor);
},
p: function p(changed, ctx) {
if (changed.buttons && raw_value !== (raw_value = ctx.button.text)) {
detachBetween(raw_before, raw_after);
raw_before.insertAdjacentHTML("afterend", raw_value);
}
},
d: function d(detach) {
if (detach) {
detachBetween(raw_before, raw_after);
detachNode(raw_before);
detachNode(raw_after);
}
}
};
}
// (43:6) {#each buttons as button}
function create_each_block(component, ctx) {
var button, button_class_value;
function select_block_type_1(ctx) {
if (ctx.button.textTrusted) return create_if_block_1;
return create_else_block;
}
var current_block_type = select_block_type_1(ctx);
var if_block = current_block_type(component, ctx);
return {
c: function c() {
button = createElement("button");
if_block.c();
button._svelte = { component: component, ctx: ctx };
addListener(button, "click", click_handler);
button.type = "button";
button.className = button_class_value = "\n ui-pnotify-action-button\n " + (ctx.button.primary ? ctx._notice.get()._styles.btnPrimary ? ctx._notice.get()._styles.btnPrimary : '' : ctx._notice.get()._styles.btn ? ctx._notice.get()._styles.btn : '') + "\n " + (ctx.button.addClass ? ctx.button.addClass : '') + "\n " + " svelte-1y9suua";
},
m: function m(target, anchor) {
insert(target, button, anchor);
if_block.m(button, null);
},
p: function p(changed, _ctx) {
ctx = _ctx;
if (current_block_type === (current_block_type = select_block_type_1(ctx)) && if_block) {
if_block.p(changed, ctx);
} else {
if_block.d(1);
if_block = current_block_type(component, ctx);
if_block.c();
if_block.m(button, null);
}
button._svelte.ctx = ctx;
if ((changed.buttons || changed._notice) && button_class_value !== (button_class_value = "\n ui-pnotify-action-button\n " + (ctx.button.primary ? ctx._notice.get()._styles.btnPrimary ? ctx._notice.get()._styles.btnPrimary : '' : ctx._notice.get()._styles.btn ? ctx._notice.get()._styles.btn : '') + "\n " + (ctx.button.addClass ? ctx.button.addClass : '') + "\n " + " svelte-1y9suua")) {
button.className = button_class_value;
}
},
d: function d(detach) {
if (detach) {
detachNode(button);
}
if_block.d();
removeListener(button, "click", click_handler);
}
};
}
function PNotifyConfirm(options) {
var _this = this;
init(this, options);
this.refs = {};
this._state = assign(data(), options.data);
this._intro = true;
if (!document.getElementById("svelte-1y9suua-style")) add_css();
this._fragment = create_main_fragment(this, this._state);
this.root._oncreate.push(function () {
oncreate.call(_this);
_this.fire("update", { changed: assignTrue({}, _this._state), current: _this._state });
});
if (options.target) {
this._fragment.c();
this._mount(options.target, options.anchor);
flush(this);
}
}
assign(PNotifyConfirm.prototype, {
destroy: destroy,
get: get,
fire: fire,
on: on,
set: set,
_set: _set,
_stage: _stage,
_mount: _mount,
_differs: _differs
});
assign(PNotifyConfirm.prototype, methods);
PNotifyConfirm.prototype._recompute = noop;
setup(PNotifyConfirm);
function createElement(name) {
return document.createElement(name);
}
function append(target, node) {
target.appendChild(node);
}
function createComment() {
return document.createComment('');
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor);
}
function detachNode(node) {
node.parentNode.removeChild(node);
}
function createText(data) {
return document.createTextNode(data);
}
function setStyle(node, key, value) {
node.style.setProperty(key, value);
}
function destroyEach(iterations, detach) {
for (var i = 0; i < iterations.length; i += 1) {
if (iterations[i]) iterations[i].d(detach);
}
}
function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}
function setAttribute(node, attribute, value) {
if (value == null) node.removeAttribute(attribute);else node.setAttribute(attribute, value);
}
function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}
function setData(text, data) {
text.data = '' + data;
}
function detachBetween(before, after) {
while (before.nextSibling && before.nextSibling !== after) {
before.parentNode.removeChild(before.nextSibling);
}
}
function init(component, options) {
component._handlers = blankObject();
component._slots = blankObject();
component._bind = options._bind;
component._staged = {};
component.options = options;
component.root = options.root || component;
component.store = options.store || component.root.store;
if (!options.root) {
component._beforecreate = [];
component._oncreate = [];
component._aftercreate = [];
}
}
function assign(tar, src) {
for (var k in src) {
tar[k] = src[k];
}return tar;
}
function assignTrue(tar, src) {
for (var k in src) {
tar[k] = 1;
}return tar;
}
function flush(component) {
component._lock = true;
callAll(component._beforecreate);
callAll(component._oncreate);
callAll(component._aftercreate);
component._lock = false;
}
function destroy(detach) {
this.destroy = noop;
this.fire('destroy');
this.set = noop;
this._fragment.d(detach !== false);
this._fragment = null;
this._state = {};
}
function get() {
return this._state;
}
function fire(eventName, data) {
var handlers = eventName in this._handlers && this._handlers[eventName].slice();
if (!handlers) return;
for (var i = 0; i < handlers.length; i += 1) {
var handler = handlers[i];
if (!handler.__calling) {
try {
handler.__calling = true;
handler.call(this, data);
} finally {
handler.__calling = false;
}
}
}
}
function on(eventName, handler) {
var handlers = this._handlers[eventName] || (this._handlers[eventName] = []);
handlers.push(handler);
return {
cancel: function cancel() {
var index = handlers.indexOf(handler);
if (~index) handlers.splice(index, 1);
}
};
}
function set(newState) {
this._set(assign({}, newState));
if (this.root._lock) return;
flush(this.root);
}
function _set(newState) {
var oldState = this._state,
changed = {},
dirty = false;
newState = assign(this._staged, newState);
this._staged = {};
for (var key in newState) {
if (this._differs(newState[key], oldState[key])) changed[key] = dirty = true;
}
if (!dirty) return;
this._state = assign(assign({}, oldState), newState);
this._recompute(changed, this._state);
if (this._bind) this._bind(changed, this._state);
if (this._fragment) {
this.fire("state", { changed: changed, current: this._state, previous: oldState });
this._fragment.p(changed, this._state);
this.fire("update", { changed: changed, current: this._state, previous: oldState });
}
}
function _stage(newState) {
assign(this._staged, newState);
}
function _mount(target, anchor) {
this._fragment[this._fragment.i ? 'i' : 'm'](target, anchor || null);
}
function _differs(a, b) {
return a != a ? b == b : a !== b || a && (typeof a === "undefined" ? "undefined" : _typeof(a)) === 'object' || typeof a === 'function';
}
function noop() {}
function blankObject() {
return Object.create(null);
}
function callAll(fns) {
while (fns && fns.length) {
fns.shift()();
}
}
return PNotifyConfirm;
}(WamPnotify);
//# sourceMappingURL=PNotifyConfirm.js.map

View File

@@ -0,0 +1,305 @@
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
/* src/PNotifyHistory.html generated by Svelte v2.16.1 */
var WamPnotifyHistory = function (PNotify) {
"use strict";
PNotify = PNotify && PNotify.__esModule ? PNotify["default"] : PNotify;
function data() {
return _extends({
'_notice': null, // The PNotify notice.
'_options': {} // The options for the notice.
}, PNotify.modules.History.defaults);
};
var methods = {
initModule: function initModule(options) {
this.set(options);
if (this.get().history) {
// Don't destroy notices that are in history.
var _get = this.get(),
_notice = _get._notice;
if (_notice.get().destroy) {
_notice.set({ 'destroy': false });
}
}
},
beforeOpen: function beforeOpen() {
var _get2 = this.get(),
maxInStack = _get2.maxInStack,
_options = _get2._options;
if (maxInStack === Infinity) {
return;
}
var stack = _options.stack;
if (stack === false) {
return;
}
// Remove oldest notifications leaving only maxInStack from the stack.
if (PNotify.notices && PNotify.notices.length > maxInStack) {
// Oldest are normally in front of array, or if stack.push=='top' then
// they are at the end of the array!
var top = stack.push === 'top';
var forRemoval = [];
var currentOpen = 0;
for (var i = top ? 0 : PNotify.notices.length - 1; top ? i < PNotify.notices.length : i >= 0; top ? i++ : i--) {
if (['opening', 'open'].indexOf(PNotify.notices[i].get()._state) !== -1 && PNotify.notices[i].get().stack === stack) {
if (currentOpen >= maxInStack) {
forRemoval.push(PNotify.notices[i]);
} else {
currentOpen++;
}
}
}
for (var _i = 0; _i < forRemoval.length; _i++) {
forRemoval[_i].close(false);
}
}
}
};
function setup(Component) {
Component.key = 'History';
Component.defaults = {
// Place the notice in the history.
history: true,
// Maximum number of notices to have open in its stack.
maxInStack: Infinity
};
Component.init = function (notice) {
return new Component({ target: document.body });
};
Component.showLast = function (stack) {
if (stack === undefined) {
stack = PNotify.defaultStack;
}
if (stack === false) {
return;
}
var top = stack.push === 'top';
// Look up the last history notice, and display it.
var i = top ? 0 : PNotify.notices.length - 1;
var notice = void 0;
do {
notice = PNotify.notices[i];
if (!notice) {
return;
}
i += top ? 1 : -1;
} while (notice.get().stack !== stack || !notice.get()._modules.History.get().history || notice.get()._state === 'opening' || notice.get()._state === 'open');
notice.open();
};
Component.showAll = function (stack) {
if (stack === undefined) {
stack = PNotify.defaultStack;
}
if (stack === false) {
return;
}
// Display all notices. (Disregarding non-history notices.)
for (var i = 0; i < PNotify.notices.length; i++) {
var notice = PNotify.notices[i];
if ((stack === true || notice.get().stack === stack) && notice.get()._modules.History.get().history) {
notice.open();
}
}
};
// Register the module with PNotify.
PNotify.modules.History = Component;
};
function create_main_fragment(component, ctx) {
return {
c: noop,
m: noop,
p: noop,
d: noop
};
}
function PNotifyHistory(options) {
init(this, options);
this._state = assign(data(), options.data);
this._intro = true;
this._fragment = create_main_fragment(this, this._state);
if (options.target) {
this._fragment.c();
this._mount(options.target, options.anchor);
}
}
assign(PNotifyHistory.prototype, {
destroy: destroy,
get: get,
fire: fire,
on: on,
set: set,
_set: _set,
_stage: _stage,
_mount: _mount,
_differs: _differs
});
assign(PNotifyHistory.prototype, methods);
PNotifyHistory.prototype._recompute = noop;
setup(PNotifyHistory);
function noop() {}
function init(component, options) {
component._handlers = blankObject();
component._slots = blankObject();
component._bind = options._bind;
component._staged = {};
component.options = options;
component.root = options.root || component;
component.store = options.store || component.root.store;
if (!options.root) {
component._beforecreate = [];
component._oncreate = [];
component._aftercreate = [];
}
}
function assign(tar, src) {
for (var k in src) {
tar[k] = src[k];
}return tar;
}
function destroy(detach) {
this.destroy = noop;
this.fire('destroy');
this.set = noop;
this._fragment.d(detach !== false);
this._fragment = null;
this._state = {};
}
function get() {
return this._state;
}
function fire(eventName, data) {
var handlers = eventName in this._handlers && this._handlers[eventName].slice();
if (!handlers) return;
for (var i = 0; i < handlers.length; i += 1) {
var handler = handlers[i];
if (!handler.__calling) {
try {
handler.__calling = true;
handler.call(this, data);
} finally {
handler.__calling = false;
}
}
}
}
function on(eventName, handler) {
var handlers = this._handlers[eventName] || (this._handlers[eventName] = []);
handlers.push(handler);
return {
cancel: function cancel() {
var index = handlers.indexOf(handler);
if (~index) handlers.splice(index, 1);
}
};
}
function set(newState) {
this._set(assign({}, newState));
if (this.root._lock) return;
flush(this.root);
}
function _set(newState) {
var oldState = this._state,
changed = {},
dirty = false;
newState = assign(this._staged, newState);
this._staged = {};
for (var key in newState) {
if (this._differs(newState[key], oldState[key])) changed[key] = dirty = true;
}
if (!dirty) return;
this._state = assign(assign({}, oldState), newState);
this._recompute(changed, this._state);
if (this._bind) this._bind(changed, this._state);
if (this._fragment) {
this.fire("state", { changed: changed, current: this._state, previous: oldState });
this._fragment.p(changed, this._state);
this.fire("update", { changed: changed, current: this._state, previous: oldState });
}
}
function _stage(newState) {
assign(this._staged, newState);
}
function _mount(target, anchor) {
this._fragment[this._fragment.i ? 'i' : 'm'](target, anchor || null);
}
function _differs(a, b) {
return a != a ? b == b : a !== b || a && (typeof a === "undefined" ? "undefined" : _typeof(a)) === 'object' || typeof a === 'function';
}
function blankObject() {
return Object.create(null);
}
function flush(component) {
component._lock = true;
callAll(component._beforecreate);
callAll(component._oncreate);
callAll(component._aftercreate);
component._lock = false;
}
function callAll(fns) {
while (fns && fns.length) {
fns.shift()();
}
}
return PNotifyHistory;
}(WamPnotify);
//# sourceMappingURL=PNotifyHistory.js.map

View File

@@ -0,0 +1,856 @@
(function($) {
class cEditorCondition {
constructor(editor, group, options) {
this.editor = editor;
this.group = group;
this.element = editor.element;
this.options = $.extend({}, {
index: null,
operator: 'equals'
}, options);
this._index = this.options.index;
this._conditionElement = this._createMarkup();
this._hintElement = this._conditionElement.find(".wam-cleditor__hint");
this._hintContentElement = this._conditionElement.find(".wam-cleditor__hint-content");
this._prepareFields(true);
this._register_events()
}
getData() {
let paramOptions = this._getParamOptions(),
currentParam = this._conditionElement.find(".wam-cleditor__param-select").val(),
$operator = this._conditionElement.find(".wam-cleditor__operator-select"),
currentOperator = $operator.val();
let value = null;
if( 'select' === paramOptions['type'] ) {
value = this._getSelectControlValue(paramOptions);
} else if( 'equals' === paramOptions['type'] ) {
value = this._getEqualsControlValue(paramOptions);
} else if( 'integer' === paramOptions['type'] ) {
value = this._getIntegerControlValue(paramOptions);
} else {
value = this._getTextValue(paramOptions);
}
return {
param: currentParam,
operator: currentOperator,
type: paramOptions['type'],
value: value
};
}
_createMarkup() {
let conditionTmpl = this.editor.getTemplate(".wam-cleditor__condition");
this.group.groupElement.find(".wam-cleditor__conditions").append(conditionTmpl);
return conditionTmpl;
}
_remove() {
this.group.removeCondition(this._index);
this._conditionElement.remove();
this.group.groupElement.trigger('winp.conditions-changed');
this.element.trigger('wam.editor-updated');
}
_register_events() {
let self = this;
this._conditionElement.find(".wam-cleditor__param-select").change(function() {
self._prepareFields();
self.element.trigger('wam.editor-updated');
});
this._conditionElement.find(".wam-cleditor__operator-select").change(function() {
self.element.trigger('wam.editor-updated');
});
this._conditionElement.find(".wam-cleditor__condition-value").on('change keyup', function() {
self.element.trigger('wam.editor-updated');
})
// buttons
this._conditionElement.find(".js-wam-cleditor__condition-remove").click(function() {
self._remove();
return false;
});
this._conditionElement.find(".js-wam-cleditor__condition-add-and").click(function() {
self.group.addCondition();
return false;
});
}
_prepareFields(isInit) {
if( isInit && this.options.param ) {
this._selectParam(this.options.param);
}
let paramOptions = this._getParamOptions();
this._setParamHint(paramOptions.description);
let operators = [];
if( 'select' === paramOptions['type'] || paramOptions['onlyEquals'] ) {
operators = ['equals', 'notequal'];
} else if( 'date' === paramOptions['type'] ) {
operators = ['equals', 'notequal', 'younger', 'older', 'between'];
} else if( 'date-between' === paramOptions['type'] ) {
operators = ['between'];
} else if( 'integer' === paramOptions['type'] ) {
operators = ['equals', 'notequal', 'less', 'greater', 'between'];
} else if( 'equals' === paramOptions['type'] ) {
operators = ['equals', 'notequal'];
} else if( 'regexp' === paramOptions['type'] ) {
operators = ['equals'];
} else if( 'default' === paramOptions['type'] ) {
operators = ['equals', 'notequal'];
} else {
operators = ['equals', 'notequal', 'contains', 'notcontain'];
}
this._setOperators(operators);
if( isInit && this.options.operator ) {
this._selectOperator(this.options.operator);
} else {
this._selectFirstOperator();
}
this._createValueControl(paramOptions, isInit);
}
/**
* Displays and configures the param hint.
*/
_setParamHint(description) {
if( description ) {
this._hintContentElement.html(description);
this._hintElement.show();
} else {
this._hintElement.hide();
}
}
/**
* Creates control to specify value.
*/
_createValueControl(paramOptions, isInit) {
if( 'select' === paramOptions['type'] ) {
this._createValueAsSelect(paramOptions, isInit);
} else if( 'equals' === paramOptions['type'] ) {
this._createValueAsEquals(paramOptions, isInit);
} else if( 'integer' === paramOptions['type'] ) {
this._createValueAsInteger(paramOptions, isInit);
} else {
this._createValueAsText(paramOptions, isInit);
}
}
// -------------------
// Select Control
// -------------------
/**
* Creates the Select control.
*/
_createValueAsSelect(paramOptions, isInit) {
let self = this;
let createSelectField = function(values) {
let $select = self._createSelect(values);
self._insertValueControl($select);
if( isInit && self.options.value ) {
self._setSelectValue(self.options.value);
}
self._conditionElement.find(".wam-cleditor__condition-value").trigger("insert.select");
};
if( !paramOptions['values'] ) {
return;
}
if( 'ajax' === paramOptions['values']['type'] ) {
let $fakeSelect = self._createSelect([
{
value: null,
title: '- loading -'
}
]);
self._insertValueControl($fakeSelect);
$fakeSelect.attr('disabled', 'disabled');
$fakeSelect.addClass('wam-cleditor__fake-select');
if( isInit && this.options.value ) {
$fakeSelect.data('value', this.options.value);
}
let req = $.ajax({
url: window.ajaxurl,
method: 'post',
data: {
action: paramOptions['values']['action']
},
dataType: 'json',
success: function(data) {
createSelectField(data.values);
},
error: function() {
console.log('Unexpected error during the ajax request.');
},
complete: function() {
if( $fakeSelect ) {
$fakeSelect.remove();
}
$fakeSelect = null;
}
});
} else {
createSelectField(paramOptions['values']);
}
}
/**
* Returns a value for the select control.
*/
_getSelectControlValue() {
let $select = this._conditionElement.find(".wam-cleditor__condition-value select");
let value = $select.val();
if( !value ) {
value = $select.data('value');
}
return value;
}
/**
* Sets a select value.
*/
_setSelectValue(value) {
let $select = this._conditionElement.find(".wam-cleditor__condition-value select");
if( $select.hasClass('.wam-cleditor__fake-select') ) {
$select.data('value', value);
} else {
$select.val(value);
}
}
// -------------------
// Integer Control
// -------------------
/**
* Creates a control for the input linked with the integer.
*/
_createValueAsInteger(paramOptions, isInit) {
let self = this;
let $operator = this._conditionElement.find(".wam-cleditor__operator-select");
$operator.on('change', function() {
let currentOperator = $operator.val();
let $control;
if( 'between' === currentOperator ) {
$control = $("<span><input type='text' class='wam-cleditor__integer-start' /> and <input type='text' class='wam-cleditor__integer-end' /></span>");
} else {
$control = $("<input type='text' class='wam-cleditor__integer-solo' /></span>");
}
self._insertValueControl($control);
});
$operator.change();
if( isInit && this.options.value ) {
this._setIntegerValue(this.options.value);
}
}
/**
* Returns a value for the Integer control.
*/
_getIntegerControlValue() {
let value = {};
let $operator = this._conditionElement.find(".wam-cleditor__operator-select");
let currentOperator = $operator.val();
if( 'between' === currentOperator ) {
value.range = true;
value.start = this._conditionElement.find(".wam-cleditor__integer-start").val();
value.end = this._conditionElement.find(".wam-cleditor__integer-end").val();
} else {
value = this._conditionElement.find(".wam-cleditor__integer-solo").val();
}
return value;
}
/**
* Sets a value for the Integer control.
*/
_setIntegerValue(value) {
if( !value ) {
value = {};
}
if( value.range ) {
this._conditionElement.find(".wam-cleditor__integer-start").val(value.start);
this._conditionElement.find(".wam-cleditor__integer-end").val(value.end);
} else {
this._conditionElement.find(".wam-cleditor__integer-solo").val(value);
}
}
// -------------------
// Query string Control
// -------------------
/**
* Creates a control for the input linked with the integer.
*/
_createValueAsEquals(paramOptions, isInit) {
let self = this;
let $operator = this._conditionElement.find(".wam-cleditor__operator-select");
let $control;
$control = $("<span><input type='text' class='wam-cleditor__equals-value1' /> <span class='wam-cleditor__equals-icon'>=</span> <input type='text' class='wam-cleditor__equals-value2' /></span>");
if( paramOptions['placeholder'] && $.isArray(paramOptions['placeholder']) ) {
$control.find('.wam-cleditor__equals-value1').attr('placeholder', paramOptions['placeholder'][0]);
if( paramOptions['placeholder'][1] ) {
$control.find('.wam-cleditor__equals-value2').attr('placeholder', paramOptions['placeholder'][1]);
}
}
self._insertValueControl($control);
$operator.on('change', function() {
let currentOperator = $operator.val();
let equalIcon = $control.find('.wam-cleditor__equals-icon');
if( 'equals' === currentOperator ) {
equalIcon.text('=');
} else {
equalIcon.text('≠');
}
});
$operator.change();
if( isInit && this.options.value ) {
this._setEqualsControlValue(this.options.value);
}
}
/**
* Returns a value for the Integer control.
*/
_getEqualsControlValue() {
let value = {};
value.var_name = this._conditionElement.find(".wam-cleditor__equals-value1").val();
value.var_value = this._conditionElement.find(".wam-cleditor__equals-value2").val();
return value;
}
/**
* Sets a value for the Integer control.
*/
_setEqualsControlValue(value) {
if( !value ) {
value = {};
}
this._conditionElement.find(".wam-cleditor__equals-value1").val(value.var_name);
this._conditionElement.find(".wam-cleditor__equals-value2").val(value.var_value);
}
// -------------------
// Text Control
// -------------------
/**
* Creates a control for the input linked with the integer.
*/
_createValueAsText(paramOptions, isInit) {
let $control = $("<input type='text' class='wam-cleditor__text' /></span>");
if( paramOptions['placeholder'] ) {
$control.attr('placeholder', paramOptions['placeholder']);
}
this._insertValueControl($control);
if( isInit && this.options.value && "" !== this.options.value ) {
this._setTextValue(this.options.value);
} else if( paramOptions['default_value'] ) {
this._setTextValue(paramOptions['default_value'])
}
}
/**
* Returns a value for the Text control.
* @returns {undefined}
*/
_getTextValue() {
return this._conditionElement.find(".wam-cleditor__text").val();
}
/**
* Sets a value for the Text control.
*/
_setTextValue(value) {
this._conditionElement.find(".wam-cleditor__text").val(value);
}
// -------------------
// Helper Methods
// -------------------
_selectParam(value) {
this._conditionElement.find(".wam-cleditor__param-select").val(value);
}
_selectOperator(value) {
this._conditionElement.find(".wam-cleditor__operator-select").val(value);
}
_selectFirstOperator() {
this._conditionElement.find(".wam-cleditor__operator-select").prop('selectedIndex', 0);
}
_setOperators(values) {
let $operator = this._conditionElement.find(".wam-cleditor__operator-select");
$operator.show();//.off('change');
$operator.find("option").hide();
for( let index in values ) {
if( !values.hasOwnProperty(index) ) {
continue;
}
$operator.find("option[value='" + values[index] + "']").show();
}
let value = $operator.find("option:not(:hidden):eq(0)").val();
$operator.val(value);
}
_insertValueControl($control) {
this._conditionElement.find(".wam-cleditor__condition-value").html("").append($control);
}
_getParamOptions() {
let selectElement = this._conditionElement.find(".wam-cleditor__param-select"),
optionElement = selectElement.find('option:selected');
if( !selectElement.length ) {
return false;
}
let type = optionElement.data('type'),
data = {
id: selectElement.val(),
title: optionElement.text().trim(),
type: optionElement.data('type'),
default_value: optionElement.data('default-value'),
values: optionElement.data('params'),
description: optionElement.data('hint').trim()
};
if( "text" === type || "default" === type || "regexp" === type || "equals" === type ) {
data['placeholder'] = optionElement.data('placeholder');
delete data['values'];
}
return data;
}
_createSelect(values, attrs) {
let $select = $("<select></select>");
if( attrs ) {
$select.attr(attrs);
}
for( let index in values ) {
if( !values.hasOwnProperty(index) ) {
continue;
}
let item = values[index];
let $option = '';
if( typeof index === "string" && isNaN(index) === true ) {
let $optgroup = $("<optgroup></optgroup>").attr('label', index);
for( let subindex in item ) {
if( !item.hasOwnProperty(subindex) ) {
continue;
}
let subvalue = item[subindex];
$option = $("<option></option>").attr('value', subvalue['value']).text(subvalue['title']);
$optgroup.append($option);
}
$select.append($optgroup);
} else {
$option = $("<option></option>").attr('value', item['value']).text(item['title']);
$select.append($option);
}
}
return $select;
}
}
class cEditorGroup {
constructor(editor, options) {
this.editor = editor;
this.element = editor.element;
this.options = $.extend({}, {
conditions: null,
index: null
}, options);
this._index = this.options.index;
this.conditions = {};
this.groupElement = this._createMarkup();
this._conditionsCounter = 0;
this._load();
}
getData() {
let condtions = [];
for( let ID in this.conditions ) {
if( !this.conditions.hasOwnProperty(ID) ) {
continue;
}
condtions.push(this.conditions[ID].getData());
}
if( !condtions.length ) {
return null;
}
return {
type: 'OR',
conditions: condtions
};
}
getCountConditions() {
return Object.keys(this.conditions).length;
}
removeCondition(ID) {
if( this.conditions[ID] ) {
delete this.conditions[ID];
}
}
_createMarkup() {
let $group = this.editor.getTemplate('.wam-cleditor__group');
this.element.find(".wam-cleditor__groups").append($group);
if( this._index <= 1 ) {
$group.find('.wam-cleditor__group-type').hide();
$group.find('.js-wam-cleditor__remove-group').remove();
} else {
$group.find('.wam-cleditor__group-type').show();
$group.find('.wam-cleditor__first-group-title').remove();
}
return $group;
}
_registerEvents() {
let self = this;
this.groupElement.find(".js-wam-cleditor__add-condition").click(function() {
self.addCondition();
return false;
});
this.groupElement.find(".js-wam-cleditor__remove-group").click(function() {
self._remove();
return false;
});
this.groupElement.on('winp.conditions-changed', function() {
self._checkIsEmpty();
});
}
_load() {
if( !this.options.conditions ) {
this.addCondition();
} else {
this._setGroupData();
}
this._registerEvents();
}
_remove() {
this.editor.removeGroup(this._index);
this.groupElement.remove();
this.element.trigger('wam.filters-changed');
this.element.trigger('wam.editor-updated');
}
_setGroupData() {
this.groupElement.find('.wam-cleditor__condition').remove();
if( this.options.conditions ) {
for( let index in this.options.conditions ) {
if( !this.options.conditions.hasOwnProperty(index) ) {
continue;
}
this.addCondition(this.options.conditions[index]);
}
}
this._checkIsEmpty();
}
addCondition(data) {
if( !data ) {
data = {type: 'AND'};
}
this._conditionsCounter = this._conditionsCounter + 1;
data.index = this._index + '_' + this._conditionsCounter;
this.conditions[data.index] = new cEditorCondition(this.editor, this, data);
this.groupElement.trigger('winp.conditions-changed');
this.element.trigger('wam.editor-updated');
}
_checkIsEmpty() {
if( this.getCountConditions() === 0 ) {
this.groupElement.addClass('wam-cleditor__empty');
} else {
this.groupElement.removeClass('wam-cleditor__empty');
}
}
}
class cEditor {
constructor(element, options) {
this.element = element;
this.options = $.extend({}, {
groups: null,
// where to get an editor template
templateSelector: null,
// where to put editor options
saveInputSelector: null,
callback: null
}, options);
this.groups = {};
this.groupsCounter = 0;
this.element = this._createMarkup();
this._load();
if( this.options.callback ) {
this.options.callback(this);
}
}
/*showParams() {
this.element.find('.wam-cleditor__param-select').find('options').show();
}
hideParams(params) {
if( params.length ) {
for( let i = 0; i < params.length; i++ ) {
this.element.find('.wam-cleditor__param-select').find('option[value="' + params[i] + '"]').hide();
}
}
}*/
getData() {
let self = this;
let groups = [];
for( let ID in self.groups ) {
if( !self.groups.hasOwnProperty(ID) ) {
continue;
}
let groupData = self.groups[ID].getData();
if( groupData ) {
groups.push(self.groups[ID].getData());
}
}
if( !groups.length ) {
return null;
}
return groups;
}
getImportData() {
if( this.options.saveInputSelector ) {
let data = this.element.parent().find(this.options.saveInputSelector).val();
if( !data ) {
return null;
}
return JSON.parse(data);
}
return null;
}
setExportData() {
if( this.options.saveInputSelector && $(this.options.saveInputSelector).length ) {
let data = !this.getData() ? '' : JSON.stringify(this.getData());
this.element.parent().find(this.options.saveInputSelector).val(data);
} else {
throw new Error('[Error]: Save input is not found! Selector: ' + this.options.saveInputSelector);
}
}
getTemplate(selector) {
let tmpl = $($(this.options.templateSelector).html());
if( !tmpl.length ) {
throw new Error('[Error]: Editor template is not found! Selector: ' + this.options.templateSelector);
}
return tmpl.find(selector).clone();
}
getCountGroups() {
return Object.keys(this.groups).length;
}
removeGroup(ID) {
if( this.groups[ID] ) {
delete this.groups[ID];
}
}
destroy() {
this.element.remove();
}
_registerEvents() {
let self = this;
this.element.on('wam.editor-updated', function() {
self.setExportData();
});
this.element.on('wam.filters-changed', function() {
self._checkIsEmpty();
});
this.element.find(".js-wam-cleditor__add-group").click(function() {
self._addGroup();
return false;
});
}
_createMarkup() {
let $editor = $('<div></div>').addClass('wam-cleditor');
this.element.prepend($editor);
$editor.append(this.getTemplate('.wam-cleditor__wrap'));
$editor.append(this.getTemplate('.wam-cleditor__buttons-group'));
return $editor;
}
_load() {
let groups, savedOptions;
savedOptions = this.getImportData();
if( savedOptions ) {
groups = savedOptions;
} else if( this.options.groups && this.options.groups.length > 0 ) {
groups = this.options.groups;
}
if( groups ) {
for( let index in groups ) {
if( !groups.hasOwnProperty(index) ) {
continue;
}
this._addGroup(groups[index]);
}
}
this._checkIsEmpty();
this._registerEvents();
// If editor will create demo data, we will trigger an event
if( !savedOptions ) {
this.element.trigger('wam.editor-updated');
}
}
_addGroup(data) {
if( !data ) {
data = {type: 'OR'};
}
this.groupsCounter = this.groupsCounter + 1;
this.groups[this.groupsCounter] = new cEditorGroup(this, {
index: this.groupsCounter,
conditions: data.conditions
});
this.element.trigger('wam.editor-updated');
this.element.trigger('wam.filters-changed');
}
_checkIsEmpty() {
if( this.getCountGroups() === 0 ) {
this.element.addClass('wam-cleditor__empty');
} else {
this.element.removeClass('wam-cleditor__empty');
}
}
}
$.fn.wamConditionsEditor = function(options) {
return this.each(function() {
new cEditor($(this), options);
});
};
})(jQuery);

View File

@@ -0,0 +1,678 @@
/**
* Assets manager scripts
* @author Webcraftic <wordpress.webraftic@gmail.com>
* @copyright (c) 13.11.2017, Webcraftic
* @version 1.0
*/
(function($) {
'use strict';
class AssetsManager {
constructor() {
if( undefined === typeof window.wam_localize_data || !wam_localize_data.ajaxurl ) {
throw new Error("Undefined wam_localize_data, please check the var in source!");
}
this.pluginVars = window.wam_localize_data;
this.initEvents();
this.updateStat();
this.setDefaultCategoryTab();
}
initEvents() {
var self = this;
$('.js-wam-require-handle-tag').click(function() {
let handle = $(this).data('tag-handle'),
assetElement = $('[data-asset-handle="' + handle + '"]'),
currentTabElement = $(this).closest('.wam-assets-type-tab-content'),
searchTabElement = assetElement.closest('.wam-assets-type-tab-content');
self.switchCategoryTab($('.wam-assets-type-tabs__button--' + searchTabElement.data('category')));
assetElement.get(0).scrollIntoView({
block: 'center'
});
assetElement.css('border', '1px solid red');
setTimeout(function() {
assetElement.css('border', '0');
}, 2000)
return false;
});
$('.js-wam-assets-type-tabs__button').click(function() {
self.switchCategoryTab($(this));
return false;
});
$('.js-wam-nav-plugins__tab-switch').click(function() {
self.switchPluginTab($(this));
return false;
});
$('.js-wam-top-panel__save-button').click(function() {
self.saveSettings();
return false;
});
$('.js-wam-select-plugin-load-mode').change(function() {
if( 'enable' === $(this).val() ) {
self.enablePlugin($(this));
} else if( 'disable_assets' === $(this).val() || 'disable_plugin' === $(this).val() ) {
self.disablePlugin($(this));
}
return false;
});
$('.js-wam-open-plugin-settings').click(function() {
if( $(this).hasClass('js-wam-button--opened') ) {
self.closePluginSettings($(this));
return false;
}
self.openPluginSettings($(this));
return false;
});
$('.js-wam-select-asset-load-mode').change(function() {
let selectElement = $(this),
requires = selectElement.closest('tr').find('.js-wam-table__asset-requires');
if( 'enable' === selectElement.val() ) {
self.enableAsset(selectElement);
return false;
}
if( requires.length ) {
// show warning
var notice = WamPnotify.notice({
title: self.pluginVars.i18n.asset_canbe_required_title,
text: self.pluginVars.i18n.asset_canbe_required_text.replace('%s', requires.text()),
icon: 'fas fa-question-circle',
hide: false,
stack: {
'dir1': 'down',
'modal': true,
'firstpos1': 25
},
modules: {
Confirm: {
confirm: true
},
Buttons: {
closer: false,
sticker: false
},
History: {
history: false
},
}
});
notice.on('pnotify.confirm', function() {
self.disableAsset(selectElement);
});
return false;
}
self.disableAsset(selectElement);
return false;
});
$('.js-wam-open-asset-settings').click(function() {
if( $(this).hasClass('js-wam-button--opened') ) {
self.closeAssetSettings($(this));
return false;
}
self.openAssetSettings($(this));
return false;
});
$('.js-wam-reset-settings').click(function() {
self.setWarningForClearSettingsAction($(this));
return false;
});
}
setWarningForClearSettingsAction(button) {
var notice = WamPnotify.notice({
title: this.pluginVars.i18n.reset_settings_warning_title,
text: this.pluginVars.i18n.reset_settings_warning_text,
icon: 'fas fa-question-circle',
hide: false,
stack: {
'dir1': 'down',
'modal': true,
'firstpos1': 25
},
modules: {
Confirm: {
confirm: true
},
Buttons: {
closer: false,
sticker: false
},
History: {
history: false
},
}
});
notice.on('pnotify.confirm', function() {
window.location.href = button.attr('href');
});
/*notice.on('pnotify.cancel', function() {
alert('Oh ok. Chicken, I see.');
});*/
}
setDefaultCategoryTab() {
let tabHash = window.location.hash.replace('#', '');
tabHash && $('.js-wam-assets-type-tabs__button[data-type="' + tabHash + '"]').click();
}
switchCategoryTab(element) {
window.location.hash = '#' + element.data('type');
$('.js-wam-assets-type-tabs__button').removeClass('wam-assets-type-tab__active');
element.addClass('wam-assets-type-tab__active');
$('.wam-assets-type-tab-content').removeClass('wam-assets-type-tab-content__active');
$('#wam-assets-type-tab-content__' + element.data('type')).addClass('wam-assets-type-tab-content__active');
}
switchPluginTab(element) {
$('.js-wam-nav-plugins__tab-switch').removeClass('wam-nav-plugins__tab--active');
element.addClass('wam-nav-plugins__tab--active');
$('.wam-nav-plugins__tab-content').removeClass('js-wam-nav-plugins__tab-content--active');
$(element.find('a').attr('href')).addClass('js-wam-nav-plugins__tab-content--active');
$('.wam-table__th-plugins-settings').text(element.find('.wam-plugin-name').text());
}
setSettingsButtonOpenState(buttonElement) {
buttonElement.removeClass('js-wam-button--opened');
buttonElement.addClass('js-wam-button__icon--cogs').removeClass('js-wam-button__icon--close');
}
setSettingsButtonCloseState(buttonElement) {
buttonElement.addClass('js-wam-button--opened');
buttonElement.removeClass('js-wam-button__icon--cogs').addClass('js-wam-button__icon--close');
}
disablePlugin(selectElement) {
let activeContainerElement = selectElement.closest('.js-wam-nav-plugins__tab-content--active'),
settingsButtonElement = selectElement.closest('.wam-plugin-settings__controls').find('.js-wam-open-plugin-settings');
/*if( currentContentTabElement.find('.js-wam-select-asset-load-mode option[value="disable"]:selected').length ) {
var passAction = confirm("If you want to change the plugins load mode, all your logical settings to disable the plugins assets will be reset. Do you really want to do this?");
if( !passAction ) {
return;
}
}*/
/*var notice = PNotify.notice({
title: 'Confirmation Needed',
text: 'Are you sure?',
icon: 'fas fa-question-circle',
hide: false,
stack: {
'dir1': 'down',
'modal': true,
'firstpos1': 25
},
modules: {
Confirm: {
confirm: true
},
Buttons: {
closer: false,
sticker: false
},
History: {
history: false
},
}
});
notice.on('pnotify.confirm', function() {
alert('Ok, cool.');
});
notice.on('pnotify.cancel', function() {
alert('Oh ok. Chicken, I see.');
});*/
settingsButtonElement.removeClass('js-wam-button--hidden');
selectElement.removeClass('js-wam-select--enable')
.addClass('js-wam-select--disable');
// Disable assets table
let assetSettingsContainer = activeContainerElement.find('.wam-table__asset-settings');
assetSettingsContainer.addClass('js-wam-table__tr--disabled-section');
//assetSettingsContainer.hide();
let assetConditionsContainer = activeContainerElement.find('.wam-table__asset-settings-conditions');
assetConditionsContainer.hide();
assetConditionsContainer.find(".wam-cleditor").remove();
assetConditionsContainer.find(".wam-conditions-builder__settings").val('');
activeContainerElement.find('.js-wam-select-asset-load-mode').val('disable')
.removeClass('js-wam-select--enable')
.addClass('js-wam-select--disable')
.prop('disabled', true);
activeContainerElement.find('.js-wam-open-asset-settings')
.removeClass('js-wam-button--opened')
.addClass('js-wam-button--hidden');
this.openPluginSettings(settingsButtonElement, "disable_plugin" === selectElement.val());
this.updateStat();
}
enablePlugin(selectElement) {
let activeContainerElement = selectElement.closest('.js-wam-nav-plugins__tab-content--active'),
settingsButtonElement = selectElement.closest('.wam-plugin-settings__controls').find('.js-wam-open-plugin-settings');
settingsButtonElement.addClass('js-wam-button--hidden');
selectElement.removeClass('js-wam-select--disable')
.addClass('js-wam-select--enable');
// Enable assets table
activeContainerElement.find('.wam-table__asset-settings').removeClass('js-wam-table__tr--disabled-section');
activeContainerElement.find('.js-wam-select-asset-load-mode').val('enable')
.addClass('js-wam-select--enable')
.removeClass('js-wam-select--disable')
.prop('disabled', false);
activeContainerElement.find('.js-wam-open-asset-settings')
.addClass('js-wam-button--hidden');
this.closePluginSettings(settingsButtonElement, true);
this.updateStat();
}
openPluginSettings(buttonElement) {
let containerElement = buttonElement.closest('.wam-plugin-settings'),
editorContainerElement = containerElement.find('.js-wam-plugin-settings__conditions');
this.setSettingsButtonCloseState(buttonElement);
editorContainerElement.show();
if( !editorContainerElement.find('.wam-cleditor').length ) {
this.createConditionsEditor(editorContainerElement, function(e) {
function a() {
let loadMode = containerElement.find('.js-wam-select-plugin-load-mode').val();
if( "disable_plugin" === loadMode ) {
e.element.addClass('wam-cleditor__disable-plugin-mode');
} else {
e.element.removeClass('wam-cleditor__disable-plugin-mode');
}
}
containerElement.find('.js-wam-select-plugin-load-mode').change(function() {
a();
});
a();
});
}
}
closePluginSettings(buttonElement, destroyEditor = false) {
let containerElement = buttonElement.closest('.wam-plugin-settings'),
editorContainerElement = containerElement.find('.js-wam-plugin-settings__conditions');
if( destroyEditor ) {
this.destroyCoditionEditor(editorContainerElement);
}
if( !buttonElement.hasClass('js-wam-button--opened') ) {
return false;
}
this.setSettingsButtonOpenState(buttonElement);
editorContainerElement.hide();
}
disableAsset(selectElement) {
let containerElement = selectElement.closest('tr'),
settingsButtonElement = containerElement.find('.js-wam-open-asset-settings');
settingsButtonElement.removeClass('js-wam-button--hidden');
containerElement.addClass('js-wam-table__tr--disabled-section');
selectElement.removeClass('js-wam-select--enable').addClass('js-wam-select--disable');
this.openAssetSettings(settingsButtonElement);
this.updateStat();
}
enableAsset(selectElement) {
let containerElement = selectElement.closest('tr'),
settingsButtonElement = containerElement.find('.js-wam-open-asset-settings');
settingsButtonElement.addClass('js-wam-button--hidden');
selectElement.removeClass('js-wam-select--disable').addClass('js-wam-select--enable');
containerElement.removeClass('js-wam-table__tr--disabled-section');
this.closeAssetSettings(settingsButtonElement, true);
this.updateStat();
}
/**
* Toggle Asset Settings
* @param buttonElement Object settings button
* @returns {boolean}
*/
openAssetSettings(buttonElement) {
var placeID = buttonElement.closest('tr').attr('id'),
place = $('#' + placeID + '-conditions');
if( buttonElement.hasClass('js-wam-button--opened') ) {
return false;
}
this.setSettingsButtonCloseState(buttonElement);
place.show();
if( !place.find('.wam-cleditor').length ) {
this.createConditionsEditor(place.find(".wam-asset-conditions-builder"));
}
return true;
}
closeAssetSettings(buttonElement, destroyEditor = false) {
var placeID = buttonElement.closest('tr').attr('id'),
place = $('#' + placeID + '-conditions');
if( destroyEditor ) {
this.destroyCoditionEditor(place.find(".wam-asset-conditions-builder"));
}
if( !buttonElement.hasClass('js-wam-button--opened') ) {
return false;
}
this.setSettingsButtonOpenState(buttonElement);
place.hide();
return true;
}
saveSettings() {
var settings = {
save_mode: $('#js-wam-save-mode-checkbox').prop("checked"),
plugins: {},
theme: {},
misc: {}
};
$('.wam-nav-plugins__tab-content').each(function() {
let pluginGroupVisabilityConditionsElement = $(this).find('.js-wam-plugin-settings__conditions').find('.wam-conditions-builder__settings'),
pluginName = pluginGroupVisabilityConditionsElement.data('plugin-name'),
pluginGroupVisabilityConditionsVal = pluginGroupVisabilityConditionsElement.val(),
pluginGroupLoadMode = $('.js-wam-select-plugin-load-mode', $(this)).val();
if( pluginName ) {
if( !settings['plugins'][pluginName] ) {
settings['plugins'][pluginName] = {};
}
settings['plugins'][pluginName]['load_mode'] = pluginGroupLoadMode;
settings['plugins'][pluginName]['visability'] = pluginGroupVisabilityConditionsVal;
}
$('.wam-table__asset-settings', $(this)).each(function() {
let resourceType = $(this).data('resource-type'),
resourceHandle = $(this).data('resource-handle');
if( settings['plugins'][pluginName] ) {
if( !settings['plugins'][pluginName][resourceType] ) {
settings['plugins'][pluginName][resourceType] = {};
}
if( !settings['plugins'][pluginName][resourceType][resourceHandle] ) {
settings['plugins'][pluginName][resourceType][resourceHandle] = {};
}
settings['plugins'][pluginName][resourceType][resourceHandle]['move_to_footer'] = $(this).find('.wam-checkbox__move-to-footer').prop('checked');
}
});
$('.wam-table__asset-settings-conditions', $(this)).each(function() {
let resourceVisabilityConditionsElement = $(this).find('.wam-conditions-builder__settings'),
resourceVisabilityConditionsVal = resourceVisabilityConditionsElement.val(),
resourceType = resourceVisabilityConditionsElement.data('resource-type'),
resourceHandle = resourceVisabilityConditionsElement.data('resource-handle');
if( settings['plugins'][pluginName] ) {
if( !settings['plugins'][pluginName][resourceType] ) {
settings['plugins'][pluginName][resourceType] = {};
}
if( !settings['plugins'][pluginName][resourceType][resourceHandle] ) {
settings['plugins'][pluginName][resourceType][resourceHandle] = {};
}
if( 'enable' !== pluginGroupLoadMode ) {
resourceVisabilityConditionsVal = "";
}
settings['plugins'][pluginName][resourceType][resourceHandle]['visability'] = resourceVisabilityConditionsVal;
}
});
});
$('.wam-table__asset-settings', '#wam-assets-type-tab-content__theme,#wam-assets-type-tab-content__misc').each(function() {
let groupType = $(this).data('group-type'),
recourceType = $(this).data("resource-type"),
resourceHandle = $(this).data("resource-handle");
if( !settings[groupType] ) {
settings[groupType] = {};
}
if( !settings[groupType][recourceType] ) {
settings[groupType][recourceType] = {};
}
if( !settings[groupType][recourceType][resourceHandle] ) {
settings[groupType][recourceType][resourceHandle] = {};
}
settings[groupType][recourceType][resourceHandle]['move_to_footer'] = $(this).find('.wam-checkbox__move-to-footer').prop('checked');
});
$('.wam-conditions-builder__settings', '#wam-assets-type-tab-content__theme,#wam-assets-type-tab-content__misc').each(function() {
let groupType = $(this).data('group-type'),
recourceType = $(this).data("resource-type"),
resourceHandle = $(this).data("resource-handle");
if( !settings[groupType] ) {
settings[groupType] = {};
}
if( !settings[groupType][recourceType] ) {
settings[groupType][recourceType] = {};
}
if( !settings[groupType][recourceType][resourceHandle] ) {
settings[groupType][recourceType][resourceHandle] = {};
}
settings[groupType][recourceType][resourceHandle]['visability'] = $(this).val();
});
let stackBottomRight = {
'dir1': 'up',
'dir2': 'left',
'firstpos1': 25,
'firstpos2': 25
};
WamPnotify.closeAll();
WamPnotify.alert({
title: 'Saving settings!',
text: 'Please wait, saving settings ...',
stack: stackBottomRight,
hide: false
});
$.ajax(this.pluginVars.ajaxurl, {
type: 'post',
dataType: 'json',
data: {
action: 'wam-save-settings',
scope: this.pluginVars.scope,
settings: settings,
_wpnonce: $('#wam-save-button').data('nonce')
},
success: function(response) {
WamPnotify.closeAll();
if( !response || !response.success ) {
if( response.data ) {
WamPnotify.alert({
title: response.data.error_message_title,
text: response.data.error_message_content,
stack: stackBottomRight,
type: 'error',
delay: 15000,
hide: true
});
} else {
console.log(response);
}
return;
}
if( response.data ) {
WamPnotify.alert({
title: response.data.save_massage_title,
text: response.data.save_message_content,
stack: stackBottomRight,
type: 'success',
delay: 3000,
hide: true
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
WamPnotify.alert({
title: 'Unknown error',
text: thrownError,
stack: {
'dir1': 'up',
'dir2': 'left',
'firstpos1': 25,
'firstpos2': 25
},
type: 'error',
delay: 15000,
hide: true
});
}
});
}
createConditionsEditor(element, callback = null) {
element.wamConditionsEditor({
// where to get an editor template
templateSelector: '#wam-conditions-builder-template',
// where to put editor options
saveInputSelector: '.wam-conditions-builder__settings',
groups: [
{
"type": "group",
"conditions": [
{
"param": "current-url",
"operator": "equals",
"type": "default",
"value": this.getCurrentUrl()
}
]
}
],
callback: callback
});
}
/**
* Get current url
*
* if it is the admin area url would be with query string
*
* @returns {jQuery|*|*}
*/
getCurrentUrl() {
let path = $(location).attr('pathname'),
queryString = $(location).attr('search');
if( "admin" === this.pluginVars.scope || "networkadmin" === this.pluginVars.scope ) {
return path + queryString.replace(/[?&]{1}wbcr_assets_manager=1/g, '');
}
return path;
}
destroyCoditionEditor(element) {
element.find('.wam-cleditor').remove();
element.find('.wam-conditions-builder__settings').val('');
}
updateStat() {
let total_requests = 0,
total_size = 0,
optimized_size = 0,
disabled_js = 0,
disabled_css = 0;
$('.js-wam-asset').each(function() {
let size = $(this).data('size');
if( !$.isNumeric(size) ) {
return;
}
total_requests++;
total_size = total_size + size;
if( !$(this).hasClass('js-wam-table__tr--disabled-section') ) {
optimized_size = optimized_size + size;
} else {
if( $(this).hasClass('js-wam-js-asset') ) {
disabled_js++;
}
if( $(this).hasClass('js-wam-css-asset') ) {
disabled_css++;
}
}
});
$('.wam-float-panel__data-item.__info-request').find('.wam-float-panel__item_value').html(total_requests);
$('.wam-float-panel__data-item.__info-total-size').find('.wam-float-panel__item_value').html(Math.round(total_size) + ' KB');
$('.wam-float-panel__data-item.__info-reduced-total-size').find('.wam-float-panel__item_value').html(Math.round(optimized_size) + ' KB');
$('.wam-float-panel__data-item.__info-disabled-js').find('.wam-float-panel__item_value').html(disabled_js);
$('.wam-float-panel__data-item.__info-disabled-css').find('.wam-float-panel__item_value').html(disabled_css);
}
}
$(function() {
new AssetsManager();
});
})(jQuery);

View File

@@ -0,0 +1,54 @@
<?php
/**
* Этот файл инициализирует этот плагин, как аддон для плагина Clearfy.
*
* Файл будет подключен только в плагине Clearfy, используя особый вариант загрузки. Это более простое решение
* пришло на смену встроенной системы подключения аддонов в фреймворке.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'WGZ_PLUGIN_ACTIVE' ) ) {
define( 'WGZ_PLUGIN_VERSION', '2.1.9' );
define( 'WGZ_TEXT_DOMAIN', 'gonzales' );
define( 'WGZ_PLUGIN_ACTIVE', true );
// Этот плагин загружен, как аддон для плагина Clearfy
define( 'LOADING_ASSETS_MANAGER_AS_ADDON', true );
if ( ! defined( 'WGZ_PLUGIN_DIR' ) ) {
define( 'WGZ_PLUGIN_DIR', dirname( __FILE__ ) );
}
if ( ! defined( 'WGZ_PLUGIN_BASE' ) ) {
define( 'WGZ_PLUGIN_BASE', plugin_basename( __FILE__ ) );
}
if ( ! defined( 'WGZ_PLUGIN_URL' ) ) {
define( 'WGZ_PLUGIN_URL', plugins_url( '', __FILE__ ) );
}
try {
// Global scripts
require_once( WGZ_PLUGIN_DIR . '/includes/functions.php' );
require_once( WGZ_PLUGIN_DIR . '/includes/3rd-party/class-clearfy-plugin.php' );
new WGZ_Plugin();
} catch( Exception $e ) {
$wgnz_plugin_error_func = function () use ( $e ) {
$error = sprintf( "The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Assets Manager', $e->getMessage(), $e->getCode() );
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action( 'admin_notices', $wgnz_plugin_error_func );
add_action( 'network_admin_notices', $wgnz_plugin_error_func );
}
}

View File

@@ -0,0 +1,138 @@
<?php
/**
* Plugin Name: Webcraftic Assets manager
* Plugin URI: https://wordpress.org/plugins/gonzales/
* Description: Increase the speed of the pages by disabling unused scripts (.JS) and styles (.CSS). Make your website REACTIVE!
* Author: Webcraftic <wordpress.webraftic@gmail.com>
* Version: 2.1.9
* Text Domain: gonzales
* Domain Path: /languages/
* Author URI: https://webcraftic.com
* Framework Version: FACTORY_480_VERSION
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Developers who contributions in the development plugin:
*
* Alexander Kovalev
* ---------------------------------------------------------------------------------
* Full plugin development.
*
* Email: alex.kovalevv@gmail.com
* Personal card: https://alexkovalevv.github.io
* Personal repo: https://github.com/alexkovalevv
* ---------------------------------------------------------------------------------
*/
/**
* -----------------------------------------------------------------------------
* CHECK REQUIREMENTS
* Check compatibility with php and wp version of the user's site. As well as checking
* compatibility with other plugins from Webcraftic.
* -----------------------------------------------------------------------------
*/
require_once( dirname( __FILE__ ) . '/libs/factory/core/includes/class-factory-requirements.php' );
// @formatter:off
$wgnz_plugin_info = [
'prefix' => 'wbcr_gnz_',
'plugin_name' => 'wbcr_gonzales',
'plugin_title' => 'Webcraftic assets manager',
// PLUGIN SUPPORT
'support_details' => [
'url' => 'https://clearfy.pro',
'pages_map' => [
'support' => 'support', // {site}/support
'docs' => 'docs' // {site}/docs
]
],
// PLUGIN SUBSCRIBE FORM
'subscribe_widget' => true,
'subscribe_settings' => [ 'group_id' => '105408913' ],
// PLUGIN ADVERTS
'render_adverts' => true,
'adverts_settings' => [
'dashboard_widget' => true, // show dashboard widget (default: false)
'right_sidebar' => true, // show adverts sidebar (default: false)
'notice' => true, // show notice message (default: false)
],
// FRAMEWORK MODULES
'load_factory_modules' => [
[ 'libs/factory/bootstrap', 'factory_bootstrap_482', 'admin' ],
[ 'libs/factory/forms', 'factory_forms_480', 'admin' ],
[ 'libs/factory/pages', 'factory_pages_480', 'admin' ],
[ 'libs/factory/templates', 'factory_templates_134', 'all' ],
[ 'libs/factory/adverts', 'factory_adverts_159', 'admin' ]
]
];
$wgnz_compatibility = new Wbcr_Factory480_Requirements( __FILE__, array_merge( $wgnz_plugin_info, [
'plugin_already_activate' => defined( 'WGZ_PLUGIN_ACTIVE' ),
'required_php_version' => '7.0',
'required_wp_version' => '4.2.0',
'required_clearfy_check_component' => false
] ) );
/**
* If the plugin is compatible, then it will continue its work, otherwise it will be stopped,
* and the user will throw a warning.
*/
if ( ! $wgnz_compatibility->check() ) {
return;
}
/**
* -----------------------------------------------------------------------------
* CONSTANTS
* Install frequently used constants and constants for debugging, which will be
* removed after compiling the plugin.
* -----------------------------------------------------------------------------
*/
// This plugin is activated
define( 'WGZ_PLUGIN_ACTIVE', true );
define( 'WGZ_PLUGIN_VERSION', $wgnz_compatibility->get_plugin_version() );
define( 'WGZ_PLUGIN_DIR', dirname( __FILE__ ) );
define( 'WGZ_PLUGIN_BASE', plugin_basename( __FILE__ ) );
define( 'WGZ_PLUGIN_URL', plugins_url( '', __FILE__ ) );
/**
* -----------------------------------------------------------------------------
* PLUGIN INIT
* -----------------------------------------------------------------------------
*/
require_once( WGZ_PLUGIN_DIR . '/libs/factory/core/boot.php' );
require_once( WGZ_PLUGIN_DIR . '/includes/functions.php' );
require_once( WGZ_PLUGIN_DIR . '/includes/class-plugin.php' );
try {
new WGZ_Plugin( __FILE__, array_merge( $wgnz_plugin_info, [
'plugin_version' => WGZ_PLUGIN_VERSION,
'plugin_text_domain' => $wgnz_compatibility->get_text_domain(),
] ) );
} catch ( Exception $e ) {
// Plugin wasn't initialized due to an error
define( 'WGZ_PLUGIN_THROW_ERROR', true );
$wgnz_plugin_error_func = function () use ( $e ) {
$error = sprintf( "The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Assets Manager', $e->getMessage(), $e->getCode() );
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action( 'admin_notices', $wgnz_plugin_error_func );
add_action( 'network_admin_notices', $wgnz_plugin_error_func );
}
// @formatter:on

View File

@@ -0,0 +1,105 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Disable comments
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WGZ_Plugin {
/**
* @see self::app()
* @var WCL_Plugin
*/
private static $app;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct() {
if ( ! class_exists( 'WCL_Plugin' ) ) {
throw new Exception( 'Plugin Clearfy is not installed!' );
}
self::$app = WCL_Plugin::app();
$this->global_scripts();
if ( is_admin() ) {
require( WGZ_PLUGIN_DIR . '/admin/boot.php' );
}
add_action( 'plugins_loaded', [ $this, 'plugins_loaded' ] );
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return WCL_Plugin
*/
public static function app() {
return self::$app;
}
/**
* @throws \Exception
*/
public function plugins_loaded() {
}
/**
* Регистрирует классы страниц в плагине
*
* Мы указываем плагину, где найти файлы страниц и какое имя у их класса. Чтобы плагин
* выполнил подключение классов страниц. После регистрации, страницы будут доступные по url
* и в меню боковой панели администратора. Регистрируемые страницы будут связаны с текущим плагином
* все операции выполняемые внутри классов страниц, имеют отношение только текущему плагину.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
private function register_pages() {
$admin_path = WGZ_PLUGIN_DIR . '/admin/pages';
self::app()->registerPage( 'WGZ_AssetsManagerPage', $admin_path . '/class-pages-settings.php' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.1.0
*/
private function global_scripts() {
require_once( WGZ_PLUGIN_DIR . '/includes/classes/class-views.php' );
require_once WGZ_PLUGIN_DIR . '/includes/classes/class-assets-manager-global.php';
new WGZ_Assets_Manager_Public( self::$app );
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,104 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Assets manager core class
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 19.02.2018, Webcraftic
* @version 1.0
*/
class WGZ_Plugin extends Wbcr_Factory480_Plugin {
/**
* @see self::app()
* @var Wbcr_Factory480_Plugin
*/
private static $app;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct( $plugin_path, $data ) {
parent::__construct( $plugin_path, $data );
self::$app = $this;
$this->global_scripts();
if ( is_admin() ) {
$this->init_activation();
require( WGZ_PLUGIN_DIR . '/admin/boot.php' );
}
add_action( 'plugins_loaded', [ $this, 'plugins_loaded' ] );
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return \Wbcr_Factory480_Plugin|\WGZ_Plugin
*/
public static function app() {
return self::$app;
}
/**
* @throws \Exception
*/
public function plugins_loaded() {
}
protected function init_activation() {
include_once( WGZ_PLUGIN_DIR . '/admin/activation.php' );
self::app()->registerActivation( 'WGNZ_Activation' );
}
/**
* Регистрирует классы страниц в плагине
*
* Мы указываем плагину, где найти файлы страниц и какое имя у их класса. Чтобы плагин
* выполнил подключение классов страниц. После регистрации, страницы будут доступные по url
* и в меню боковой панели администратора. Регистрируемые страницы будут связаны с текущим плагином
* все операции выполняемые внутри классов страниц, имеют отношение только текущему плагину.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
private function register_pages() {
$admin_path = WGZ_PLUGIN_DIR . '/admin/pages';
self::app()->registerPage( 'WGZ_AssetsManagerPage', $admin_path . '/class-pages-settings.php' );
self::app()->registerPage( 'WGZ_MoreFeaturesPage', $admin_path . '/class-pages-more-features.php' );
}
private function global_scripts() {
require_once( WGZ_PLUGIN_DIR . '/includes/classes/class-views.php' );
require_once WGZ_PLUGIN_DIR . '/includes/classes/class-assets-manager-global.php';
new WGZ_Assets_Manager_Public( self::$app );
}
}

View File

@@ -0,0 +1,521 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Assets manager base class
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 10.09.20198, Webcraftic
* @since 2.0
*/
class WGZ_Check_Conditions {
protected $condition;
public function __construct($condition)
{
if( empty($condition) ) {
$this->condition = [];
} else {
$condition = @json_decode(stripslashes($condition));
$this->condition = $condition;
}
}
/**
* Проверяем в правильном ли формате нам передано условие
*
* @param \stdClass $condition
*
* @return bool
* @since 2.2.0
*
*/
protected function validate_condition_schema($condition)
{
$isset_attrs = !empty($condition->param) && !empty($condition->operator) && !empty($condition->type) && isset($condition->value);
$allow_params = in_array($condition->param, [
'user-role',
'user-mobile',
'user-cookie-name',
'current-url',
'query-string',
'location-page',
'regular-expression',
'location-some-page',
'location-post-type',
'location-taxonomy'
]);
$allow_operators = in_array($condition->operator, [
'equals',
'notequal',
'less',
'older',
'greater',
'younger',
'contains',
'notcontain',
'between'
]);
$allow_types = in_array($condition->type, ['select', 'text', 'default', 'regexp', 'equals']);
return $isset_attrs && $allow_params && $allow_operators && $allow_types;
}
/**
* @return bool
* @since 2.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
public function validate()
{
if( empty($this->condition) && !is_array($this->condition) ) {
return false;
}
$or = null;
foreach($this->condition as $group_OR) {
if( !empty($group_OR->conditions) && is_array($group_OR->conditions) ) {
$and = null;
foreach($group_OR->conditions as $condition) {
if( $this->validate_condition_schema($condition) ) {
$method_name = str_replace('-', '_', $condition->param);
if( is_null($and) ) {
$and = $this->call_method($method_name, $condition->operator, $condition->value);
} else {
$and = $and && $this->call_method($method_name, $condition->operator, $condition->value);
}
}
}
$or = is_null($or) ? $and : $or || $and;
}
}
return is_null($or) ? false : $or;
}
/**
* Call specified method
*
* @param $method_name
* @param $operator
* @param $value
*
* @return bool
*/
protected function call_method($method_name, $operator, $value)
{
if( method_exists($this, $method_name) ) {
return $this->$method_name($operator, $value);
} else {
return apply_filters('wam/conditions/call_method', false, $method_name, $operator, $value);
}
}
/**
* @param string $path
*
* @return string
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
*
*/
protected function get_admin_url_path($path)
{
return str_replace(site_url(), '', admin_url($path));
}
/**
* Get referer URL
*
* @return string
*/
protected function get_referer_url()
{
$out = "";
$url = explode('?', str_replace(site_url(), '', $_SERVER['HTTP_REFERER']), 2);
if( isset($url[0]) ) {
$out = trim($url[0], '/');
}
return $out ? urldecode($out) : '/';
}
/**
* Get current URL
*
* @return string
*/
protected function get_current_url_path($clear_query = false)
{
if( !is_admin() && !$clear_query ) {
$url = explode('?', $_SERVER['REQUEST_URI'], 2);
if( strlen($url[0]) > 1 ) {
$out = rtrim($url[0], '/');
} else {
$out = $url[0];
}
return "/" === $out ? "/" : untrailingslashit($out);
}
$removeble_args = array_merge(['wbcr_assets_manager'], wp_removable_query_args());
$url = remove_query_arg($removeble_args, $_SERVER['REQUEST_URI']);
return esc_url_raw(untrailingslashit($url));
}
/**
* Check by operator
*
* @param $operator
* @param $first
* @param $second
* @param $third
*
* @return bool
*/
public function apply_operator($operator, $first, $second, $third = false)
{
switch( $operator ) {
case 'equals':
return $first === $second;
case 'notequal':
return $first !== $second;
case 'less':
case 'older':
return $first > $second;
case 'greater':
case 'younger':
return $first < $second;
case 'contains':
return strpos($first, $second) !== false;
case 'notcontain':
return strpos($first, $second) === false;
case 'between':
return $first < $second && $second < $third;
default:
return $first === $second;
}
}
/**
* Get timestamp
*
* @param $units
* @param $count
*
* @return integer
*/
protected function get_timestamp($units, $count)
{
switch( $units ) {
case 'seconds':
return $count;
case 'minutes':
return $count * MINUTE_IN_SECONDS;
case 'hours':
return $count * HOUR_IN_SECONDS;
case 'days':
return $count * DAY_IN_SECONDS;
case 'weeks':
return $count * WEEK_IN_SECONDS;
case 'months':
return $count * MONTH_IN_SECONDS;
case 'years':
return $count * YEAR_IN_SECONDS;
default:
return $count;
}
}
/**
* Get date timestamp
*
* @param $value
*
* @return integer
*/
public function get_date_timestamp($value)
{
if( is_object($value) ) {
return (current_time('timestamp') - $this->get_timestamp($value->units, $value->unitsCount)) * 1000;
} else {
return $value;
}
}
/**
* A some selected page
*
* @param $operator
* @param $value
*
* @return boolean
*/
protected function location_some_page($operator, $value)
{
if( !is_admin() ) {
// For frontend area
switch( $value ) {
case 'base_web': // Basic - Entire Website
$result = !is_admin();
break;
case 'base_sing': // Basic - All Singulars
$result = is_singular();
break;
case 'base_arch': // Basic - All Archives
$result = is_archive();
break;
case 'spec_404': // Special Pages - 404 Page
$result = is_404();
break;
case 'spec_search': // Special Pages - Search Page
$result = is_search();
break;
case 'spec_blog': // Special Pages - Blog / Posts Page
$result = is_home();
break;
case 'spec_front': // Special Pages - Front Page
$result = is_front_page();
break;
case 'spec_date': // Special Pages - Date Archive
$result = is_date();
break;
case 'spec_auth': // Special Pages - Author Archive
$result = is_author();
break;
case 'post_all': // Posts - All Posts
case 'page_all': // Pages - All Pages
$result = false;
$post_id = (!is_404() && !is_search() && !is_archive() && !is_home()) ? get_the_ID() : false;
if( false !== $post_id ) {
$post_type = 'post_all' == $value ? 'post' : 'page';
$result = $post_type == get_post_type($post_id);
}
break;
case 'post_arch': // Posts - All Posts Archive
case 'page_arch': // Pages - All Pages Archive
$result = false;
if( is_archive() ) {
$post_type = 'post_arch' == $value ? 'post' : 'page';
$result = $post_type == get_post_type();
}
break;
case 'post_cat': // Posts - All Categories Archive
case 'post_tag': // Posts - All Tags Archive
$result = false;
if( is_archive() && 'post' == get_post_type() ) {
$taxonomy = 'post_tag' == $value ? 'post_tag' : 'category';
$obj = get_queried_object();
$current_taxonomy = '';
if( '' !== $obj && null !== $obj ) {
$current_taxonomy = $obj->taxonomy;
}
if( $current_taxonomy == $taxonomy ) {
$result = true;
}
}
break;
default:
$result = true;
}
} else {
// For admin area
switch( $value ) {
case 'all_admin_area':
$result = is_admin();
break;
case 'dashboard_home':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('index.php');
break;
case 'dashboard_wordpress_updates':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('update-core.php');
break;
case 'posts_all':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('edit.php');
break;
case 'posts_add_new':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('post-new.php');
break;
case 'posts_taxonomies':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('edit-tags.php');
break;
case 'media_library':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('upload.php');
break;
case 'media_library_add_new':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('media-new.php');
break;
case 'appearance_themes':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('themes.php');
break;
case 'appearance_customize':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('customize.php');
break;
case 'appearance_widgets':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('widgets.php');
break;
case 'appearance_menus':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('nav-menus.php');
break;
case 'appearance_theme_editor':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('theme-editor.php');
break;
case 'plugins_installed':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('plugins.php');
break;
case 'plugins_add_new':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('plugin-install.php');
break;
case 'plugins_editor':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('plugin-editor.php');
break;
case 'users_all':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('users.php');
break;
case 'users_add_new':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('user-new.php');
break;
case 'users_your_profile':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('profile.php');
break;
case 'tools_available':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('tools.php');
break;
case 'tools_import':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('import.php');
break;
case 'tools_export':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('export.php');
break;
case 'tools_site_health':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('site-health.php');
break;
case 'tools_export_personal_data':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('tools.php');
break;
case 'tools_erase_personal_data':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('tools.php');
break;
case 'settings_general':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('options-general.php');
break;
case 'settings_writing':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('options-writing.php');
break;
case 'settings_reading':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('options-reading.php');
break;
case 'settings_media':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('options-media.php');
break;
case 'settings_permalinks':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('options-permalink.php');
break;
case 'settings_privacy':
$result = $this->get_current_url_path(true) === $this->get_admin_url_path('privacy.php');
break;
default:
$result = true;
}
}
return $this->apply_operator($operator, $result, true);
}
/**
* Проверяет текущий URL страницы.
*
* Если url в условии и url текущей страницы совпадают,
* условие будет выполнено успешно.
*
* @param string $operator
* @param string $value
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
*
*/
protected function current_url($operator, $value)
{
$value = ("/" === $value) ? "/" : untrailingslashit($value);
$current_url = $this->get_current_url_path();
return $this->apply_operator($operator, $value, $current_url);
}
/**
* A post type of the current page
*
* @param $operator
* @param $value
*
* @return boolean
*/
protected function location_post_type($operator, $value)
{
if( is_singular() ) {
return $this->apply_operator($operator, $value, get_post_type());
}
return false;
}
/**
* A taxonomy of the current page
*
* @param $operator
* @param $value
*
* @return boolean
* @since 2.2.8 The bug is fixed, the condition was not checked
* for tachonomies, only posts.
*
*/
protected function location_taxonomy($operator, $value)
{
$taxonomy = null;
if( is_tax() || is_tag() || is_category() ) {
$taxonomy = get_queried_object()->taxonomy;
}
return $this->apply_operator($operator, $taxonomy, $value);
}
/**
* Checking for the existence of a variable in a query string
*
* @param $operator
* @param $value
*
* @return boolean
* @since 2.2.8 The bug is fixed, the condition was not checked
* for tachonomies, only posts.
*
*/
protected function query_string($operator, $value)
{
if( is_object($value) ) {
if( !empty($value->var_name) && isset($_GET[$value->var_name]) ) {
return $this->apply_operator($operator, $_GET[$value->var_name], $value->var_value);
}
}
return false;
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* Class that handles templates.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 05.04.2019, Webcraftic
* @version 1.0
*/
class WGZ_Views {
/**
* The single instance of the class.
*
* @since 1.3.0
* @access protected
* @var array
*/
protected static $_instance = [];
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.3.0
* @var string
*/
protected $plugin_dir;
/**
* WRIO_Views constructor.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*
* @param string $plugin_dir
*/
public function __construct( $plugin_dir ) {
$this->plugin_dir = $plugin_dir;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.3.6 - add instace id
* @since 1.3.0
*
* @param string $plugin_dir
*
* @return object|\WGZ_Views object Main instance.
*/
public static function get_instance( $plugin_dir ) {
$instance_id = md5( $plugin_dir );
if ( ! isset( self::$_instance[ $instance_id ] ) ) {
self::$_instance[ $instance_id ] = new self( $plugin_dir );
}
return self::$_instance[ $instance_id ];
}
/**
* Get a template contents.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.3.0
*
* @param string $template The template name.
* @param mixed $data Some data to pass to the template.
* @param WBCR\Factory_Templates_134\Pages\PageBase $page
*
* @return bool|string The page contents. False if the template doesn't exist.
*/
public function get_template( $template, $data = [], WBCR\Factory_Templates_134\Pages\PageBase $page = null ) {
$template = str_replace( '_', '-', $template );
$path = $this->plugin_dir . '/views/' . $template . '.php';
if ( ! file_exists( $path ) ) {
return false;
}
ob_start();
include $path;
$contents = ob_get_clean();
return trim( (string) $contents );
}
/**
* Print a template.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @access public
*
* @since 1.3.0
*
* @param string $template The template name.
* @param mixed $data Some data to pass to the template.
* @param WBCR\Factory_Templates_134\Pages\PageBase $page
*/
public function print_template( $template, $data = [], WBCR\Factory_Templates_134\Pages\PageBase $page = null ) {
echo $this->get_template( $template, $data, $page );
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Helpers functions
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 11.05.2019, Webcraftic
* @version 1.0
*/
/**
* Assets manager MU dynamically activated only plugins that you have selected in each page.
* This method installs the MU plugin if it does not exist or its current version does not
* match the current version.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
function wbcr_gnz_deploy_mu_plugin() {
if ( wp_mkdir_p( WPMU_PLUGIN_DIR ) ) {
if ( ! file_exists( WPMU_PLUGIN_DIR . "/assets-manager.php" ) ) {
@copy( WGZ_PLUGIN_DIR . '/mu-plugins/assets-manager.php', WPMU_PLUGIN_DIR . '/assets-manager.php' );
} else {
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$dp = get_plugin_data( WPMU_PLUGIN_DIR . "/assets-manager.php", false, false );
$sp = get_plugin_data( WGZ_PLUGIN_DIR . '/mu-plugins/assets-manager.php', false, false );
if ( version_compare( $dp['Version'], $sp['Version'], '!=' ) ) {
@copy( WGZ_PLUGIN_DIR . '/mu-plugins/assets-manager.php', WPMU_PLUGIN_DIR . '/assets-manager.php' );
}
}
}
}
/**
* Remove MU plugin
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
function wbcr_gnz_remove_mu_plugin() {
if ( file_exists( WPMU_PLUGIN_DIR . "/assets-manager.php" ) ) {
@unlink( WPMU_PLUGIN_DIR . '/assets-manager.php' );
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,466 @@
# Translation of Plugins - Clearfy in Spanish (Spain)
# This file is distributed under the same license as the Plugins - Clearfy WordPress optimization plugin and disable ultimate tweaker - Development (trunk) package.
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2019-04-28 06:23+0300\n"
"PO-Revision-Date: 2019-04-28 06:23+0300\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: es\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Poedit 2.1.1\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Poedit 2.1.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
"X-Poedit-SearchPathExcluded-0: libs\n"
"X-Poedit-SearchPathExcluded-1: components\n"
"X-Poedit-SearchPathExcluded-2: cache\n"
#: admin/boot.php:30
msgid ""
"We detected that you used the Assets manager plugin. Do you want to import "
"settings from this plugin to the Clearfy plugin?"
msgstr ""
"Configuración de activos detectada. ¿Desea importar esta configuración al "
"plugin Clearfy?"
#: admin/boot.php:31
msgid "Import options"
msgstr "Importar opciones"
#: admin/boot.php:48
msgid "Settings has been successfully imported!"
msgstr "¡Configuración importada exitosamente!"
#: admin/boot.php:140 admin/pages/assets-manager.php:96
msgid "Disable assets manager"
msgstr "Deshabilitar gestor de activos"
#: admin/boot.php:147 admin/pages/assets-manager.php:120
msgid "Disable assets manager panel"
msgstr "Deshabilitar el panel de Gestor de Activos"
#: admin/boot.php:153 admin/pages/assets-manager.php:129
msgid "Disable assets manager on front"
msgstr "Deshabilitar el administrador de activos en el frontend"
#: admin/boot.php:159 admin/pages/assets-manager.php:138
msgid "Disable assets manager on back-end"
msgstr "Deshabilitar el administrador de activos en el back-end"
#: admin/boot.php:165
msgid "Assets manager options"
msgstr "Opciiones del Gestor de Activos"
#: admin/boot.php:205 includes/class.configurate-assets.php:266
msgid "Disable plugins (groups of scripts)"
msgstr "Deshabilitar plugins (grupos de scripts)"
#: admin/boot.php:206 includes/class.configurate-assets.php:267
msgid "Conditions by the link template"
msgstr "Condiciones para enlace de plantilla."
#: admin/boot.php:207 includes/class.configurate-assets.php:268
msgid "Conditions by the regular expression"
msgstr "Condiciones para la expresión regular."
#: admin/boot.php:208 includes/class.configurate-assets.php:269
msgid "Safe mode"
msgstr "Modo seguro"
#: admin/boot.php:209 includes/class.configurate-assets.php:270
msgid "Statistics and optimization results"
msgstr "Estadísticas y resultados de optimización."
#: admin/boot.php:220
msgid "Get premium"
msgstr "Obtener premium"
#: admin/pages/assets-manager.php:48 admin/pages/assets-manager.php:67
#: admin/pages/assets-manager.php:75
msgid "Assets manager"
msgstr "Gestor de Activos"
#: admin/pages/assets-manager.php:67 admin/pages/assets-manager.php:75
msgid "General"
msgstr "General"
#: admin/pages/assets-manager.php:89
msgid "Disable unused scripts, styles, and fonts"
msgstr "Deshabilitar los scripts, estilos y fuentes no utilizados"
#: admin/pages/assets-manager.php:89
msgid ""
"There is a button in the adminbar called \"Script Manager\". If you click on "
"it you will see a list of loaded scripts, styles and fonts on the current "
"page of your site. If you think that one of the assets is superfluous on "
"this page, you can disable it individually, so that it does not create "
"unnecessary queries when page loading. Use the script manager very carefull "
"to non-corrupt your website. We recommend to test this function at a local "
"server."
msgstr ""
"Hay un botón en la barra de administración llamado \"Administrador de "
"secuencias de comandos\". Si hace clic en él, verá una lista de los scripts, "
"estilos y fuentes cargados en la página actual de su sitio. Si cree que uno "
"de los recursos es superfluo en esta página, puede deshabilitarlo "
"individualmente, para que no cree consultas innecesarias cuando se carga la "
"página. Utilice el administrador de scripts con mucho cuidado para no dañar "
"su sitio web. Recomendamos probar esta función en un servidor local."
#: admin/pages/assets-manager.php:98
msgid "Full disable of the module."
msgstr "Deshabilitación completa del módulo."
#: admin/pages/assets-manager.php:122
msgid ""
"By default in your admin bar there is a button for control the assets "
"scripts and styles. With this option, you can turn off the script manager on "
"front and back-end."
msgstr ""
"De forma predeterminada, en la barra de administración hay un botón para "
"controlar los scripts y estilos de activos. Con esta opción, puede "
"desactivar el administrador de secuencias de comandos en la parte frontal y "
"posterior."
#: admin/pages/assets-manager.php:131
msgid "Disables assets manager initialization for frontend."
msgstr "Desactiva el inicio del administrador de activos para el frontend."
#: admin/pages/assets-manager.php:140
msgid "Disables assets manager initialization for backend."
msgstr "Desactiva el inicio del administrador de activos para el backend."
#: gonzales.php:84
msgid "Webcraftic assets manager"
msgstr "Gestor de activos webcraftic"
#: includes/class.configurate-assets.php:128
#: includes/class.configurate-assets.php:147
msgid "Assets Manager"
msgstr "Gestor de Activos"
#: includes/class.configurate-assets.php:212
msgid "Total requests"
msgstr "Total de solicitudes"
#: includes/class.configurate-assets.php:213
msgid "Total size"
msgstr "Tamaño total"
#: includes/class.configurate-assets.php:214
msgid "Optimized size"
msgstr "Tamaño optimizado"
#: includes/class.configurate-assets.php:215
msgid "Disabled js"
msgstr "JS desactivado"
#: includes/class.configurate-assets.php:216
msgid "Disabled css"
msgstr "CSS desactivado"
#: includes/class.configurate-assets.php:218
msgid ""
"This is the general statistics to see the optimization result. Available in "
"the paid version only."
msgstr ""
"Esta es la estadística general para ver el resultado de la optimización. "
"Disponible solo en la versión de pago."
#: includes/class.configurate-assets.php:222
msgid "Reset"
msgstr "Resetear"
#: includes/class.configurate-assets.php:223
msgid "Save"
msgstr "Guardar"
#: includes/class.configurate-assets.php:224
msgid ""
"In test mode, you can experiment with disabling unused scripts safely for "
"your site. The resources that you disabled will be visible only to you (the "
"administrator), and all other users will receive an unoptimized version of "
"the site, until you remove this tick"
msgstr ""
"En el modo de prueba, puede experimentar con la desactivación segura de "
"scripts no utilizados para su sitio. Los recursos que desactivó solo serán "
"visibles para usted (el administrador), y todos los demás usuarios recibirán "
"una versión no optimizada del sitio, hasta que elimine esta marca"
#: includes/class.configurate-assets.php:225
msgid "Safe mode <b>PRO</b>"
msgstr "Modo seguro <b>PRO</b>"
#: includes/class.configurate-assets.php:227
msgid "Close"
msgstr "Cerrar"
#: includes/class.configurate-assets.php:257
msgid ""
"Important! Each page of your website has different sets of scripts and "
"styles files."
msgstr ""
"¡Importante! Cada página de su sitio web tiene diferentes conjuntos de "
"scripts y archivos de estilos."
#: includes/class.configurate-assets.php:258
msgid ""
"Use this feature to disable unwanted scripts and styles by setting up the "
"logic for different types of pages. We recommend working in \"Safe mode\" "
"because disabling any necessary system script file can corrupt the website. "
"All changes done in Safe mode are available for administrator only. This way "
"only you, as the administrator, can see the result of optimization. To "
"enable the changes for other users, uncheck Safe mode."
msgstr ""
"Utilice esta función para deshabilitar los scripts y estilos no deseados "
"configurando la mejor lógica para diferentes tipos de páginas. Recomendamos "
"trabajar en \"Safe mode\" ya que deshabilitar cualquier archivo importante "
"del script del sistema podría dañar el sitio web. Todos los cambios "
"realizados en Modo seguro están disponibles solo para el administrador. De "
"esta manera solo usted, como administrador, puede ver el resultado de la "
"optimización. Para habilitar los cambios para otros usuarios, desmarque Modo "
"seguro."
#: includes/class.configurate-assets.php:259
#, php-format
msgid ""
"For more details and user guides, check the plugins <a href=\"%s\" target="
"\"_blank\" rel=\"noreferrer noopener\">documentation</a>."
msgstr ""
"Para más detalles y guías de usuario del plugin, consulte la <a href=\"%s\" "
"target=\"_blank\" rel=\"noreferrer noopener\">documentación</a>."
#: includes/class.configurate-assets.php:262
msgid "Upgrade to Premium"
msgstr "Actualizar a Premium"
#: includes/class.configurate-assets.php:265
msgid "MORE IN CLEARFY BUSINESS"
msgstr "MÁS EN CLEARFY BUSINESS"
#: includes/class.configurate-assets.php:308
#: includes/class.configurate-assets.php:336
msgid "Loaded"
msgstr "Cargado"
#: includes/class.configurate-assets.php:309
msgid "Plugin"
msgstr "Plugin"
#: includes/class.configurate-assets.php:313
#: includes/class.configurate-assets.php:342
msgid "Load resource?"
msgstr "¿Cargar recurso?"
#: includes/class.configurate-assets.php:314
#: includes/class.configurate-assets.php:343
msgid "Conditions"
msgstr "Condiciones"
#: includes/class.configurate-assets.php:322
msgid "Author"
msgstr "Autor"
#: includes/class.configurate-assets.php:323
#: includes/class.configurate-assets.php:402
msgid "Version"
msgstr "Versión"
#: includes/class.configurate-assets.php:337
msgid "Size"
msgstr "Tamaño"
#: includes/class.configurate-assets.php:338
msgid "Resource"
msgstr "Recurso"
#: includes/class.configurate-assets.php:366
msgid "In use by"
msgstr "En uso por"
#: includes/class.configurate-assets.php:373
msgid "Requires"
msgstr "Requiere"
#: includes/class.configurate-assets.php:402
msgid "--"
msgstr "--"
#: includes/class.configurate-assets.php:559
#: includes/class.configurate-assets.php:1403
msgid "No"
msgstr "No"
#: includes/class.configurate-assets.php:559
#: includes/class.configurate-assets.php:1403
msgid "Yes"
msgstr "Sí"
#: includes/class.configurate-assets.php:575
msgid ""
"Click the switch in the <b>Load resource?</b> column to display the "
"conditions for loading the resource."
msgstr ""
"Haga clic en el switch de la columna <b>¿Cargar recurso?</b> para mostrar "
"las condiciones para cargar el recurso."
#: includes/class.configurate-assets.php:577
msgid ""
"Set the plugin logic to apply it to all plugins resources. This feature "
"available at the paid version."
msgstr ""
"Configure el \"plugin logic\" para aplicarlo a todos los recursos del "
"complemento. Esta característica está disponible en la versión de pago."
#: includes/class.configurate-assets.php:586
#: includes/class.configurate-assets.php:610
msgid "Current URL"
msgstr "URL actual"
#: includes/class.configurate-assets.php:587
msgid "Everywhere"
msgstr "Donde sea"
#: includes/class.configurate-assets.php:588
msgid "Custom URL (PRO)"
msgstr "URL personalizada (PRO)"
#: includes/class.configurate-assets.php:589
msgid "Regular expression (PRO)"
msgstr "Expresión regular (PRO)"
#: includes/class.configurate-assets.php:599
msgid "Exclude"
msgstr "Excluir"
#: includes/class.configurate-assets.php:599
msgid ""
"You can disable this resource for all pages, except sections and page types "
"listed below. Specify sections and page types with the enabled resource."
msgstr ""
"Puede deshabilitar este recurso para todas las páginas, excepto las "
"secciones y los tipos de página que se enumeran a continuación. Especifique "
"secciones y tipos de página con el recurso habilitado."
#: includes/class.configurate-assets.php:683
msgid "Example"
msgstr "Ejemplo"
#: includes/class.configurate-assets.php:683
msgid "Enter URL (set * for mask)"
msgstr "Ingrese URL (set * for mask)"
#: includes/class.configurate-assets.php:683
msgid ""
"You can disable the resource only for the pages with the matched to the "
"template address. For example, if you set the template for the link as "
"http://yoursite.test/profile/*, then the resource is disabled for the "
"following pages: http://yoursite.test/profile/12, http://yoursite.test/"
"profile/43, http://yoursite.test/profile/999. If you dont use the asterisk "
"symbol in the template then the plugin will disable the resource only for "
"the pages with 100% match in the specified link type. This feature is "
"available at the paid version."
msgstr ""
"Puede deshabilitar el recurso solo para las páginas que coincidan con la "
"dirección de la plantilla. Por ejemplo, si configura la plantilla para el "
"enlace como http://yoursite.test/profile/*, el recurso se deshabilita para "
"las siguientes páginas: http://yoursite.test/profile/12, http://yoursite."
"test/profile/43, http://yoursite.test/profile/999. Si no usa el símbolo de "
"asterisco en la plantilla, el complemento deshabilitará el recurso solo para "
"las páginas con una coincidencia del 100% en el tipo de enlace especificado. "
"Esta característica está disponible en la versión de pago."
#: includes/class.configurate-assets.php:686
msgid "Add field"
msgstr "Añadir campo"
#: includes/class.configurate-assets.php:696
msgid "Enter regular expression"
msgstr "Ingrese la expresión regular"
#: includes/class.configurate-assets.php:696
msgid ""
"Regular expressions can be used by experts. This tool creates flexible "
"conditions to disable the resource. For example, if you specify this "
"expression: ^([A-z0-9]+-)?gifts? then the resource will be disabled at the "
"following pages http://yoursite.test/get-gift/, http://yoursite.test/gift/, "
"http://yoursite.test/get-gifts/, http://yoursite.test/gifts/. The plugin "
"ignores the backslash at the beginning of the query string, so you can "
"dismiss it. Check your regular expressions in here: https://regex101.com, "
"this will prevent you from the mistakes. This feature is available at the "
"paid version."
msgstr ""
"Las expresiones regulares pueden ser utilizadas por expertos. Esta "
"herramienta crea condiciones flexibles para deshabilitar el recurso. Por "
"ejemplo, si especifica esta expresión: ^ ([A-z0-9] + -)?Gifts? significa que "
"el recurso se deshabilitará en las siguientes páginas http: //yoursite.test/"
"get-gift/, http: //yoursite.test/gift/, http: //yoursite.test/get-gifts/, "
"http: / /yoursite.test/gifts/. El plugin ignora la barra diagonal inversa al "
"principio de la cadena de consulta, por lo que puede descartarla. Verifique "
"sus expresiones regulares aquí: https://regex101.com, esto evitará que "
"cometa errores. Esta característica está disponible en la versión de pago."
#: includes/class.configurate-assets.php:715
msgid "Also disabled for pages"
msgstr "También deshabilitado para páginas"
#: includes/class.configurate-assets.php:729
msgid "You don't have enough capability to edit this information."
msgstr "No tienes suficiente permisos para editar esta información."
#: includes/class.configurate-assets.php:1293
msgid "Minify and Combine"
msgstr "Minificar y Combinar"
#: includes/class.configurate-assets.php:1314
msgid "remove version?"
msgstr "¿Eliminar versión?"
#: includes/class.configurate-assets.php:1314
msgid "optimize?"
msgstr "¿optimizar?"
#: includes/class.configurate-assets.php:1318
msgid ""
"Youve enabled &#34;Remove query strings&#34; from static resources in the "
"&#34;Clearfy&#34; plugin. This list of settings helps you to exclude the "
"necessary scripts and styles with remaining query strings. Press No to add a "
"file to the excluded list."
msgstr ""
"Has habilitado &#34;Eliminar cadenas de consulta&#34; de los recursos "
"estáticos en el &#34;Clearfy&#34; plugin. Esta lista de configuraciones le "
"ayuda a excluir los scripts y estilos necesarios con las cadenas de consulta "
"restantes. Presione No para agregar un archivo a la lista excluida."
#: includes/class.configurate-assets.php:1320
msgid ""
"Youve enabled the &#34;Optimize js scripts?&#34; and &#34;Optimize CSS "
"options&#34; in the &#34;Minify & Combine plugin&#34;. These settings "
"exclude scripts and styles that you dont want to optimize. Press No to add "
"a file to the excluded list."
msgstr ""
"Has habilitado &#34;Optimizar js scripts?&#34; y &#34;Optimizar CSS "
"options&#34; en el &#34;plugin Minify & Combine&#34;. Esta configuración "
"excluye los scripts y los estilos que no desea optimizar. Presione No para "
"agregar un archivo a la lista excluida."
#: includes/class.configurate-assets.php:1322
msgid ""
"Youve enabled the &#34;Optimize js scripts?&#34; and &#34;Optimize CSS "
"options&#34; in the &#34;Autoptimize&#34;. These settings exclude scripts "
"and styles that you dont want to optimize. Press No to add a file to the "
"excluded list."
msgstr ""
"Has habilitado &#34;Optimizar js scripts?&#34; y &#34;Optimizar CSS "
"options&#34; en el &#34;Autoptimize&#34;. Esta configuración excluye los "
"scripts y los estilos que no desea optimizar. Presione No para agregar un "
"archivo a la lista excluida."

View File

@@ -0,0 +1,194 @@
msgid ""
msgstr ""
"Project-Id-Version: Clearfy\n"
"POT-Creation-Date: 2018-09-06 18:24+0300\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: nl_BE\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.1.1\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Poedit 2.1.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
"X-Poedit-SearchPathExcluded-0: libs\n"
"X-Poedit-SearchPathExcluded-1: components\n"
"X-Poedit-SearchPathExcluded-2: cache\n"
#: admin/boot.php:32
msgid "Get ultimate plugin free"
msgstr "Krijg ultieme plugin gratis"
#: admin/boot.php:57 admin/pages/assets-manager.php:101
msgid "Disable assets manager"
msgstr "Schakel assets manager uit"
#: admin/boot.php:64 admin/pages/assets-manager.php:125
msgid "Disable assets manager panel"
msgstr "Schakel paneel van assets manager uit"
#: admin/boot.php:70 admin/pages/assets-manager.php:134
msgid "Disable assets manager on front"
msgstr "Schakel assets manager op front-end uit"
#: admin/boot.php:76 admin/pages/assets-manager.php:143
msgid "Disable assets manager on back-end"
msgstr "Schakel assets manager op back-end uit"
#: admin/boot.php:82
msgid "Assets manager options"
msgstr "Assets manager opties"
#: admin/pages/assets-manager.php:42 admin/pages/assets-manager.php:61
#: includes/class.configurate-assets.php:139
msgid "Assets manager"
msgstr "Assets manager"
#: admin/pages/assets-manager.php:62
msgid "General"
msgstr "Algemeen"
#: admin/pages/assets-manager.php:94
msgid "Disable unused scripts, styles, and fonts"
msgstr "Ongebruikte scripts, stijlen en lettertypen uitschakelen"
#: admin/pages/assets-manager.php:94
msgid ""
"There is a button in the adminbar called \"Script Manager\". If you click on "
"it you will see a list of loaded scripts, styles and fonts on the current page "
"of your site. If you think that one of the assets is superfluous on this page, "
"you can disable it individually, so that it does not create unnecessary "
"queries when page loading. Use the script manager very carefull to non-corrupt "
"your website. We recommend to test this function at a local server."
msgstr ""
"Er is een knop in de beheerbalk genaamd 'Script Manager'. Als u erop klikt, "
"ziet u een lijst met geladen scripts, stijlen en lettertypen op de huidige "
"pagina van uw site. Als u denkt dat een van de items op deze pagina overbodig "
"is, kunt u deze afzonderlijk uitschakelen, zodat er geen onnodige query's "
"ontstaan wanneer de pagina wordt geladen. Gebruik de script manager heel "
"voorzichtig om uw website niet te beschadigen. We raden aan om deze functie "
"bij een lokale server te testen."
#: admin/pages/assets-manager.php:103
msgid "Full disable of the module."
msgstr "De module volledig uitschakelen."
#: admin/pages/assets-manager.php:127
msgid ""
"By default in your admin bar there is a button for control the assets scripts "
"and styles. With this option, you can turn off the script manager on front and "
"back-end."
msgstr ""
"Standaard is er in je beheer balk een knop voor het beheren van de assets "
"scripts en -stijlen. Met deze optie kunt u de script manager aan frontend en "
"backend uitschakelen."
#: admin/pages/assets-manager.php:136
msgid "Disables assets manager initialization for frontend."
msgstr "Schakelt de opstart van assets manager voor de front-end uit."
#: admin/pages/assets-manager.php:145
msgid "Disables assets manager initialization for backend."
msgstr "Schakelt de opstart van assets manager voor de back-end uit."
#: gonzales.php:23
msgid ""
"We found that you use the plugin \"Clearfy - disable unused functions\", this "
"plugin already has the same functions as \"Assets manager\", so you can "
"disable the \"Assets manager\" plugin!"
msgstr ""
"We hebben vastgesteld dat u de plugin \"Clearfy - uitschakelen ongebruikte "
"functies\" gebruikt, deze plugin heeft al dezelfde functies als \"Assets "
"manager\", dus u kunt de plugin \"Assets manager\" uitschakelen!"
#: gonzales.php:80
msgid "Webcraftic assets manager"
msgstr "Webcraftic assets manager"
#: includes/class.configurate-assets.php:94
#: includes/class.configurate-assets.php:114
msgid "Script Manager"
msgstr "Script Manager"
#: includes/class.configurate-assets.php:141
msgid ""
"Below you can disable/enable CSS and JS files on a per page/post basis, as "
"well as by custom post types. We recommend testing this locally or on a "
"staging site first, as you could break the appearance of your live site. If "
"you aren't sure about a certain script, you can try clicking on it, as a lot "
"of authors will mention their plugin or theme in the header of the source code."
msgstr ""
"Hieronder kunt u CSS en JS bestanden per pagina/post uitschakelen en "
"inschakelen, evenals voor aangepaste bericht types. We raden aan dit eerst "
"lokaal of op een staging-site te testen, omdat je het uiterlijk van je live "
"site kunt breken. Als je niet zeker bent van een bepaald script, kun je "
"proberen erop te klikken, omdat veel auteurs hun plugin of thema zullen "
"vermelden in de hoofding van de broncode."
#: includes/class.configurate-assets.php:142
msgid ""
"If for some reason you run into trouble, you can always enable everything "
"again to reset the settings."
msgstr ""
"Als u om de één of andere reden in de problemen komt, kunt u altijd alles "
"opnieuw inschakelen om de instellingen opnieuw in te stellen."
#: includes/class.configurate-assets.php:151
msgid "Save settings"
msgstr "Bewaar instellingen"
#: includes/class.configurate-assets.php:158
msgid "Hide panel in adminbar?"
msgstr "Verberg paneel in beheer balk?"
#: includes/class.configurate-assets.php:169
msgid "State"
msgstr "Staat"
#: includes/class.configurate-assets.php:170
msgid "Size"
msgstr "Formaat"
#: includes/class.configurate-assets.php:171
msgid "Script"
msgstr "Script"
#: includes/class.configurate-assets.php:172
msgid "In use"
msgstr "In gebruik"
#: includes/class.configurate-assets.php:173
msgid "Disable"
msgstr "Uitschakelen"
#: includes/class.configurate-assets.php:174
msgid "Enable"
msgstr "Inschakelen"
#: includes/class.configurate-assets.php:221
msgid "In use by"
msgstr "In gebruik door"
#: includes/class.configurate-assets.php:248
msgid "Enabled"
msgstr "Ingeschakeld"
#: includes/class.configurate-assets.php:253
msgid "Everywhere"
msgstr "Overal"
#: includes/class.configurate-assets.php:260
#: includes/class.configurate-assets.php:283
msgid "Current URL"
msgstr "Huidige URL"
#: includes/class.configurate-assets.php:269
msgid "Disable everwhere to view enable settings."
msgstr "Overal uitschakelen om de instellingen voor inschakelen te bekijken."

View File

@@ -0,0 +1,194 @@
msgid ""
msgstr ""
"Project-Id-Version: clearfy\n"
"POT-Creation-Date: 2018-09-06 18:23+0300\n"
"PO-Revision-Date: 2018-09-06 18:23+0300\n"
"Last-Translator: alex.kovalevv@gmail.com <alex.kovalevv@gmail.com>\n"
"Language-Team: Alex Kovalev <alex.kovalevv@gmail.com>\n"
"Language: pt_BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.1.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
"X-Poedit-SearchPathExcluded-0: libs\n"
"X-Poedit-SearchPathExcluded-1: components\n"
"X-Poedit-SearchPathExcluded-2: cache\n"
#: admin/boot.php:32
msgid "Get ultimate plugin free"
msgstr "Obtenha o melhor plugin grátis"
#: admin/boot.php:57 admin/pages/assets-manager.php:101
msgid "Disable assets manager"
msgstr "Desativar gerente de ativos"
#: admin/boot.php:64 admin/pages/assets-manager.php:125
msgid "Disable assets manager panel"
msgstr "Desativar painel do gerenciador de ativos"
#: admin/boot.php:70 admin/pages/assets-manager.php:134
msgid "Disable assets manager on front"
msgstr "Desativar o gerente de ativos na frente"
#: admin/boot.php:76 admin/pages/assets-manager.php:143
msgid "Disable assets manager on back-end"
msgstr "Desativar gerenciador de ativos no back-end"
#: admin/boot.php:82
msgid "Assets manager options"
msgstr "Opções do gerente de ativos"
#: admin/pages/assets-manager.php:42 admin/pages/assets-manager.php:61
#: includes/class.configurate-assets.php:139
msgid "Assets manager"
msgstr "Gerente de Ativos"
#: admin/pages/assets-manager.php:62
msgid "General"
msgstr "Geral"
#: admin/pages/assets-manager.php:94
msgid "Disable unused scripts, styles, and fonts"
msgstr "Desativar scripts, estilos e fontes não utilizados"
#: admin/pages/assets-manager.php:94
msgid ""
"There is a button in the adminbar called \"Script Manager\". If you click on "
"it you will see a list of loaded scripts, styles and fonts on the current "
"page of your site. If you think that one of the assets is superfluous on "
"this page, you can disable it individually, so that it does not create "
"unnecessary queries when page loading. Use the script manager very carefull "
"to non-corrupt your website. We recommend to test this function at a local "
"server."
msgstr ""
"Existe um botão na barra de admin chamado \"Script Manager \". Se você "
"clicar nele, verá uma lista de scripts, estilos e fontes carregados na "
"página atual do seu site. Se você acha que um dos ativos é supérfluo nesta "
"página, você pode desativá-lo individualmente, para que ele não crie "
"consultas desnecessárias ao carregar a página. Use o gerenciador de scripts "
"com muito cuidado para não corromper seu site. Recomendamos testar essa "
"função em um servidor local."
#: admin/pages/assets-manager.php:103
msgid "Full disable of the module."
msgstr "Desabilitação total do módulo."
#: admin/pages/assets-manager.php:127
msgid ""
"By default in your admin bar there is a button for control the assets "
"scripts and styles. With this option, you can turn off the script manager on "
"front and back-end."
msgstr ""
"Por padrão, na barra de administração, existe um botão para controlar os "
"scripts e estilos de recursos. Com essa opção, você pode desativar o "
"gerenciador de scripts na frente e no final."
#: admin/pages/assets-manager.php:136
msgid "Disables assets manager initialization for frontend."
msgstr "Desativa a inicialização do gerenciador de ativos para o frontend."
#: admin/pages/assets-manager.php:145
msgid "Disables assets manager initialization for backend."
msgstr "Desativa a inicialização do gerenciador de ativos para o back-end."
#: gonzales.php:23
msgid ""
"We found that you use the plugin \"Clearfy - disable unused functions\", "
"this plugin already has the same functions as \"Assets manager\", so you can "
"disable the \"Assets manager\" plugin!"
msgstr ""
"Descobrimos que você usa o plugin \"Clearfy - desabilita funções não usadas "
"\", este plugin já tem as mesmas funções de \"Assets manager \", então você "
"pode desabilitar o plugin \"Assets manager \"!"
#: gonzales.php:80
msgid "Webcraftic assets manager"
msgstr "Gerente de ativos da webraftic"
#: includes/class.configurate-assets.php:94
#: includes/class.configurate-assets.php:114
msgid "Script Manager"
msgstr "Gerenciador de scripts"
#: includes/class.configurate-assets.php:141
msgid ""
"Below you can disable/enable CSS and JS files on a per page/post basis, as "
"well as by custom post types. We recommend testing this locally or on a "
"staging site first, as you could break the appearance of your live site. If "
"you aren't sure about a certain script, you can try clicking on it, as a lot "
"of authors will mention their plugin or theme in the header of the source "
"code."
msgstr ""
"Abaixo, você pode desativar / ativar arquivos CSS e JS em uma base por "
"página / postagem, bem como por tipos de postagem personalizados. "
"Recomendamos testar isso localmente ou em um site de teste primeiro, pois "
"você pode quebrar a aparência do site ao vivo. Se você não tem certeza sobre "
"um determinado script, pode tentar clicar nele, pois muitos autores "
"mencionarão seu plug-in ou tema no cabeçalho do código-fonte."
#: includes/class.configurate-assets.php:142
msgid ""
"If for some reason you run into trouble, you can always enable everything "
"again to reset the settings."
msgstr ""
"Se por algum motivo você tiver problemas, poderá sempre ativar tudo "
"novamente para redefinir as configurações."
#: includes/class.configurate-assets.php:151
msgid "Save settings"
msgstr "Salvar configurações"
#: includes/class.configurate-assets.php:158
msgid "Hide panel in adminbar?"
msgstr "Ocultar painel em adminbar?"
#: includes/class.configurate-assets.php:169
msgid "State"
msgstr "Estado"
#: includes/class.configurate-assets.php:170
msgid "Size"
msgstr "Tamanho"
#: includes/class.configurate-assets.php:171
msgid "Script"
msgstr "Roteiro"
#: includes/class.configurate-assets.php:172
msgid "In use"
msgstr "Em uso"
#: includes/class.configurate-assets.php:173
msgid "Disable"
msgstr "Desabilitar"
#: includes/class.configurate-assets.php:174
msgid "Enable"
msgstr "Habilitar"
#: includes/class.configurate-assets.php:221
msgid "In use by"
msgstr "Em uso por"
#: includes/class.configurate-assets.php:248
msgid "Enabled"
msgstr "ativado"
#: includes/class.configurate-assets.php:253
msgid "Everywhere"
msgstr "Em toda parte"
#: includes/class.configurate-assets.php:260
#: includes/class.configurate-assets.php:283
msgid "Current URL"
msgstr "URL atual"
#: includes/class.configurate-assets.php:269
msgid "Disable everwhere to view enable settings."
msgstr "Desative o everwhere para visualizar as configurações de ativação."

View File

@@ -0,0 +1,574 @@
msgid ""
msgstr ""
"Project-Id-Version: clearfy\n"
"POT-Creation-Date: 2018-10-16 15:56+0300\n"
"PO-Revision-Date: 2018-10-19 22:37+0300\n"
"Last-Translator: alex.kovalevv@gmail.com <alex.kovalevv@gmail.com>\n"
"Language-Team: Alex Kovalev <alex.kovalevv@gmail.com>\n"
"Language: ru_RU\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.1.1\n"
"X-Poedit-Basepath: ../..\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c\n"
"X-Poedit-SearchPath-0: assets-manager\n"
"X-Poedit-SearchPath-1: assets-manager-premium\n"
"X-Poedit-SearchPathExcluded-0: assets-manager/libs\n"
#: assets-manager-premium/admin/boot.php:46
msgid ""
"<strong>Assets manager Premium</strong><br>We did not find the installed "
"plugin \"Assets manager\". Please install the plugin \"Assets manager\" "
"first for premium functions!"
msgstr ""
"<strong>Менеджер скриптов премиум</strong><br> Мы не нашли установленный "
"копонент \"Менеджер скриптов\". Пожалуйста, установите копонент \"Менеджер "
"скриптов\" в первую очередь для премиум-функций!"
#: assets-manager-premium/assets-manager-premium.php:63
msgid "Webcraftic assets manager Premium"
msgstr "Webcraftic менеджер скриптов премиум"
#: assets-manager-premium/includes/class.configurate-assets.php:92
#: assets-manager/includes/class.configurate-assets.php:204
#: assets-manager/includes/class.configurate-assets.php:208
msgid "Total requests"
msgstr "Всего запросов"
#: assets-manager-premium/includes/class.configurate-assets.php:93
#: assets-manager/includes/class.configurate-assets.php:205
msgid "Total size"
msgstr "Общий вес"
#: assets-manager-premium/includes/class.configurate-assets.php:94
#: assets-manager/includes/class.configurate-assets.php:206
msgid "Optimized size"
msgstr "Оптим. вес"
#: assets-manager-premium/includes/class.configurate-assets.php:95
#: assets-manager/includes/class.configurate-assets.php:212
msgid "Disabled js"
msgstr "Отключено js"
#: assets-manager-premium/includes/class.configurate-assets.php:96
#: assets-manager/includes/class.configurate-assets.php:213
msgid "Disabled css"
msgstr "Отключено css"
#: assets-manager-premium/includes/class.configurate-assets.php:119
#: assets-manager/includes/class.configurate-assets.php:266
msgid "Safe mode"
msgstr "Безопасный режим"
#: assets-manager-premium/includes/class.configurate-assets.php:300
#: assets-manager/includes/class.configurate-assets.php:685
msgid "Example"
msgstr "Пример"
#: assets-manager-premium/includes/class.configurate-assets.php:300
#: assets-manager/includes/class.configurate-assets.php:685
msgid "Enter URL (set * for mask)"
msgstr "Введите URL (добавьте * для маски)"
#: assets-manager-premium/includes/class.configurate-assets.php:308
#: assets-manager-premium/includes/class.configurate-assets.php:316
#: assets-manager/includes/class.configurate-assets.php:688
msgid "Add field"
msgstr "Добавить"
#: assets-manager-premium/includes/class.configurate-assets.php:327
#: assets-manager/includes/class.configurate-assets.php:698
msgid "Enter regular expression"
msgstr "Введите регулярное выражение"
#: assets-manager-premium/includes/class.configurate-assets.php:532
msgid "Custom URL"
msgstr "Произвольный URL"
#: assets-manager-premium/includes/class.configurate-assets.php:533
msgid "Regular expression"
msgstr "Регулярное выражение"
#: assets-manager-premium/includes/class.configurate-assets.php:595
msgid "Set the plugin logic to apply it to all plugins resources."
msgstr ""
"Установите логику плагина, чтобы применить его ко всем ресурсам плагина."
#: assets-manager/admin/boot.php:48
#: assets-manager/admin/pages/assets-manager.php:89
msgid "Disable assets manager"
msgstr "Отключить менеджер скриптов"
#: assets-manager/admin/boot.php:55
#: assets-manager/admin/pages/assets-manager.php:113
msgid "Disable assets manager panel"
msgstr "Скрыть панель в админбаре"
#: assets-manager/admin/boot.php:61
#: assets-manager/admin/pages/assets-manager.php:122
msgid "Disable assets manager on front"
msgstr "Отключить менеджер скриптов на внешней стороне сайта"
#: assets-manager/admin/boot.php:67
#: assets-manager/admin/pages/assets-manager.php:131
msgid "Disable assets manager on back-end"
msgstr "Отключить менеджер скриптов в админпанели"
#: assets-manager/admin/boot.php:73
msgid "Assets manager options"
msgstr "Настройки менеджера скриптов"
#: assets-manager/admin/boot.php:86
msgid "Get ultimate plugin free"
msgstr "Получите полную версию плагина бесплатно"
#: assets-manager/admin/pages/assets-manager.php:48
#: assets-manager/admin/pages/assets-manager.php:67
msgid "Assets manager"
msgstr "Менеджер скриптов"
#: assets-manager/admin/pages/assets-manager.php:68
msgid "General"
msgstr "Основные"
#: assets-manager/admin/pages/assets-manager.php:82
msgid "Disable unused scripts, styles, and fonts"
msgstr "Отключите неиспользуемые скрипты, стили и шрифты"
#: assets-manager/admin/pages/assets-manager.php:82
msgid ""
"There is a button in the adminbar called \"Script Manager\". If you click on "
"it you will see a list of loaded scripts, styles and fonts on the current "
"page of your site. If you think that one of the assets is superfluous on "
"this page, you can disable it individually, so that it does not create "
"unnecessary queries when page loading. Use the script manager very carefull "
"to non-corrupt your website. We recommend to test this function at a local "
"server."
msgstr ""
"В админбаре есть кнопка под названием “Менеджер скриптов”, если на нее "
"нажать вы увидите список загружаемых скриптов, стилей и шрифтов на текущей "
"странице вашего сайта. Если вы считаете, что какой-то из ресурсов лишний на "
"этой странице, вы можете индивидуально его отключить, чтобы он не создавал "
"лишних запросов при загрузке. Используйте менеджер скриптов аккуратно, чтобы "
"не нарушить работу вашего сайта. Мы рекомендуем вам использовать локальный "
"сервер для тестирования этой функции."
#: assets-manager/admin/pages/assets-manager.php:91
msgid "Full disable of the module."
msgstr "Полностью отключает работу модуля."
#: assets-manager/admin/pages/assets-manager.php:115
msgid ""
"By default in your admin bar there is a button for control the assets "
"scripts and styles. With this option, you can turn off the script manager on "
"front and back-end."
msgstr ""
"По умолчанию в панели администратора есть кнопка для управления подключамыми "
"скриптами и стилями. Используя эту настроку вы можете скрыть эту панель из "
"админбара, чтобы она не занимала место."
#: assets-manager/admin/pages/assets-manager.php:124
msgid "Disables assets manager initialization for frontend."
msgstr "Отключает инициализацию менеджера лицензий на внешней стороне сайта."
#: assets-manager/admin/pages/assets-manager.php:133
msgid "Disables assets manager initialization for backend."
msgstr "Отключает инициализацию менеджера лицензий в админпанели сайта."
#: assets-manager/gonzales.php:63
msgid "Webcraftic assets manager"
msgstr "Webcraftic менеджер скриптов"
#: assets-manager/includes/class.configurate-assets.php:121
#: assets-manager/includes/class.configurate-assets.php:141
msgid "Script Manager"
msgstr "Менеджер скриптов"
#: assets-manager/includes/class.configurate-assets.php:208
msgid "Total weight"
msgstr "Общий вес"
#: assets-manager/includes/class.configurate-assets.php:208
msgid "Optimized weight"
msgstr "Оптим. вес"
#: assets-manager/includes/class.configurate-assets.php:215
msgid ""
"This is the general statistics to see the optimization result. Available in "
"the paid version only."
msgstr ""
"Это общая статистика, чтобы увидеть результат оптимизации. Доступно только в "
"платной версии."
#: assets-manager/includes/class.configurate-assets.php:219
msgid "Reset"
msgstr "Сбросить"
#: assets-manager/includes/class.configurate-assets.php:220
msgid "Save"
msgstr "Сохранить"
#: assets-manager/includes/class.configurate-assets.php:221
msgid ""
"In test mode, you can experiment with disabling unused scripts safely for "
"your site. The resources that you disabled will be visible only to you (the "
"administrator), and all other users will receive an unoptimized version of "
"the site, until you remove this tick"
msgstr ""
"В тестовом режиме можно поэкспериментировать с отключением неиспользуемых "
"скриптов безопасно для вашего сайта. Отключенные ресурсы будут видны только "
"вам (администратору), и все остальные пользователи получат "
"неоптимизированную версию сайта, пока вы не снимите галочку с этого элемента."
#: assets-manager/includes/class.configurate-assets.php:222
msgid "Safe mode <b>PRO</b>"
msgstr "Безопасный режим <b>PRO</b>"
#: assets-manager/includes/class.configurate-assets.php:224
msgid "Close"
msgstr "Закрыть"
#: assets-manager/includes/class.configurate-assets.php:254
msgid ""
"Important! Each page of your website has different sets of scripts and "
"styles files."
msgstr ""
"Важно! На каждой странице вашего сайта подключаются разные наборы файлов "
"скриптов и стилей. "
#: assets-manager/includes/class.configurate-assets.php:255
msgid ""
"Use this feature to disable unwanted scripts and styles by setting up the "
"logic for different types of pages. We recommend working in \"Safe mode\" "
"because disabling any necessary system script file can corrupt the website. "
"All changes done in Safe mode are available for administrator only. This way "
"only you, as the administrator, can see the result of optimization. To "
"enable the changes for other users, uncheck Safe mode."
msgstr ""
"Используйте этот инструмент для отключения неиспользуемых скриптов и стилей, "
"устанавливая логику для разных типов страниц. Мы рекомендуем вам работать в "
"“Безопасном режиме”, так как вы можете нарушить работу сайта, если отключите "
"системные файлы скриптов, без которых невозможна полноценная работа сайта. В "
"безопасном режиме, все ваши изменения будут работать только для "
"администратора, это необходимо для того, чтобы только вы могли увидеть "
"результат оптимизации. Чтобы изменения вступили в силу для всех остальных "
"пользователей, просто снимите галочку “Безопасный режим”. "
#: assets-manager/includes/class.configurate-assets.php:256
#, php-format
msgid ""
"For more details and user guides, check the plugins <a href=\"%s\" target="
"\"_blank\" rel=\"noreferrer noopener\">documentation</a>."
msgstr ""
"Более подробную информацию о работе с плагином можно найти в нашей <a href="
"\"%s\" target=\"_blank\" rel=\"noreferrer noopener\">документации</a>."
#: assets-manager/includes/class.configurate-assets.php:259
msgid "Upgrade to Premium"
msgstr "Обновить до премиум"
#: assets-manager/includes/class.configurate-assets.php:262
msgid "MORE IN CLEARFY BUSINESS"
msgstr "БОЛЬШЕ В CLEARFY БИЗНЕС"
#: assets-manager/includes/class.configurate-assets.php:263
msgid "Disable plugins (groups of scripts)"
msgstr "Отключить плагины (группы скриптов)"
#: assets-manager/includes/class.configurate-assets.php:264
msgid "Conditions by the link template"
msgstr "Условия по шаблону ссылки"
#: assets-manager/includes/class.configurate-assets.php:265
msgid "Conditions by the regular expression"
msgstr "Условия по регулярному выражению"
#: assets-manager/includes/class.configurate-assets.php:267
msgid "Statistics and optimization results"
msgstr "Статистика и результаты оптимизации"
#: assets-manager/includes/class.configurate-assets.php:304
#: assets-manager/includes/class.configurate-assets.php:332
msgid "Loaded"
msgstr "Загружен"
#: assets-manager/includes/class.configurate-assets.php:305
msgid "Plugin"
msgstr "Плагин"
#: assets-manager/includes/class.configurate-assets.php:309
#: assets-manager/includes/class.configurate-assets.php:338
msgid "Load resource?"
msgstr "Загружать ресурс?"
#: assets-manager/includes/class.configurate-assets.php:310
#: assets-manager/includes/class.configurate-assets.php:339
msgid "Conditions"
msgstr "Условия"
#: assets-manager/includes/class.configurate-assets.php:318
msgid "Author"
msgstr "Автор"
#: assets-manager/includes/class.configurate-assets.php:319
#: assets-manager/includes/class.configurate-assets.php:398
msgid "Version"
msgstr "Версия"
#: assets-manager/includes/class.configurate-assets.php:333
msgid "Size"
msgstr "Размер"
#: assets-manager/includes/class.configurate-assets.php:334
msgid "Resource"
msgstr "Ресурс"
#: assets-manager/includes/class.configurate-assets.php:362
msgid "In use by"
msgstr "Используется "
#: assets-manager/includes/class.configurate-assets.php:369
msgid "Requires"
msgstr "Зависимости"
#: assets-manager/includes/class.configurate-assets.php:398
msgid "--"
msgstr ""
#: assets-manager/includes/class.configurate-assets.php:561
#: assets-manager/includes/class.configurate-assets.php:1406
msgid "No"
msgstr "Нет"
#: assets-manager/includes/class.configurate-assets.php:561
#: assets-manager/includes/class.configurate-assets.php:1406
msgid "Yes"
msgstr "Да"
#: assets-manager/includes/class.configurate-assets.php:577
msgid ""
"Click the switch in the <b>Load resource?</b> column to display the "
"conditions for loading the resource."
msgstr ""
"Щелкните переключатель в этой колонке <b>Загрузить ресурс?</b>, чтобы "
"отобразить условия для загрузки ресурса."
#: assets-manager/includes/class.configurate-assets.php:579
msgid ""
"Set the plugin logic to apply it to all plugins resources. This feature "
"available at the paid version."
msgstr ""
"Устанавливая логику для плагина, она будет примена для всех его ресурсов. "
"Данная возможность доступна только в платной версии плагина."
#: assets-manager/includes/class.configurate-assets.php:588
#: assets-manager/includes/class.configurate-assets.php:612
msgid "Current URL"
msgstr "Текущий URL"
#: assets-manager/includes/class.configurate-assets.php:589
msgid "Everywhere"
msgstr "Повсюду"
#: assets-manager/includes/class.configurate-assets.php:590
msgid "Custom URL (PRO)"
msgstr "Произвольная ссылка (PRO)"
#: assets-manager/includes/class.configurate-assets.php:591
msgid "Regular expression (PRO)"
msgstr "Регулярное выражение (PRO)"
#: assets-manager/includes/class.configurate-assets.php:601
msgid "Exclude"
msgstr "Исключить"
#: assets-manager/includes/class.configurate-assets.php:601
msgid ""
"You can disable this resource for all pages, except sections and page types "
"listed below. Specify sections and page types with the enabled resource."
msgstr ""
"Вы можете отключить этот ресурс на всех страницах вашего сайта, кроме "
"нижеперечисленных разделов и типов страниц. Отметьте разделы и типы страниц, "
"в которых вы не хотите отключать ресурс"
#: assets-manager/includes/class.configurate-assets.php:685
msgid ""
"You can disable the resource only for the pages with the matched to the "
"template address. For example, if you set the template for the link as "
"http://yoursite.test/profile/*, then the resource is disabled for the "
"following pages: http://yoursite.test/profile/12, http://yoursite.test/"
"profile/43, http://yoursite.test/profile/999. If you dont use the asterisk "
"symbol in the template then the plugin will disable the resource only for "
"the pages with 100% match in the specified link type. This feature is "
"available at the paid version."
msgstr ""
"Вы можете отключить этот ресурс только на тех страницах, адрес которых будет "
"соответствовать установленному вами шаблону. К примеру, если вы установите "
"шаблон ссылки http://yoursite.test/profile/*, то ресурс будет отключен на "
"следующих страницах http://yoursite.test/profile/12, http://yoursite.test/"
"profile/43, http://yoursite.test/profile/999. Если вы не будете использовать "
"звездочку в вашем шаблоне, то плагин отключит ресурс, только на странице где "
"будет точное совпадение с установленной вами ссылкой. Эта функция доступна "
"только в платной версии плагина."
#: assets-manager/includes/class.configurate-assets.php:698
msgid ""
"Regular expressions can be used by experts. This tool creates flexible "
"conditions to disable the resource. For example, if you specify this "
"expression: ^([A-z0-9]+-)?gifts? then the resource will be disabled at the "
"following pages http://yoursite.test/get-gift/, http://yoursite.test/gift/, "
"http://yoursite.test/get-gifts/, http://yoursite.test/gifts/. The plugin "
"ignores the backslash at the beginning of the query string, so you can "
"dismiss it. Check your regular expressions in here: https://regex101.com, "
"this will prevent you from the mistakes. This feature is available at the "
"paid version."
msgstr ""
"Регулярные выражения используются экспертами. С помощью этого инструмента вы "
"можете создать более гибкие условия для отключения ресурса. К примеру, если "
"вы установите такое выражение: ^([A-z0-9]+-)?gifts?, то ресурс будет "
"отключен на страницах http://yoursite.test/get-gift/, http://yoursite.test/"
"gift/, http://yoursite.test/get-gifts/, http://yoursite.test/gifts/. Плагин "
"игнорирует обратный слеш в начале строки запроса, поэтому вы можете его "
"пропустить. Проверяйте свое регулярное выражение с помощью сервиса https://"
"regex101.com, чтобы вы были точно уверены, что в вашем регулярном выражении "
"нет ошибки. Эта функция доступна только в платной версии плагина."
#: assets-manager/includes/class.configurate-assets.php:718
msgid "Also disabled for pages"
msgstr "Также отключен для страниц"
#: assets-manager/includes/class.configurate-assets.php:1293
msgid "Minify and Combine"
msgstr "Минификация"
#: assets-manager/includes/class.configurate-assets.php:1315
msgid "remove version?"
msgstr "Удалить версию?"
#: assets-manager/includes/class.configurate-assets.php:1315
msgid "optimize?"
msgstr "оптимизировать?"
#: assets-manager/includes/class.configurate-assets.php:1319
msgid ""
"Youve enabled &#34;Remove query strings&#34; from static resources in the "
"&#34;Clearfy&#34; plugin. This list of settings helps you to exclude the "
"necessary scripts and styles with remaining query strings. Press No to add a "
"file to the excluded list."
msgstr ""
"Вы включили опцию &#34;Удалить переменные запроса для статических "
"ресурсов&#34; в плагине &#34;Clearfy&#34;, в этой колонке настроек вы можете "
"исключить скрипты и стили, для которых вы хотите оставить переменые запроса. "
"Просто выберите \"Нет\", чтобы добавить файл в исключения.."
#: assets-manager/includes/class.configurate-assets.php:1321
msgid ""
"Youve enabled the &#34;Optimize js scripts?&#34; and &#34;Optimize CSS "
"options&#34; in the &#34;Minify & Combine plugin&#34;. These settings "
"exclude scripts and styles that you dont want to optimize. Press No to add "
"a file to the excluded list."
msgstr ""
"Вы включили опцию &#34;Оптимизировать js скрипты?&#34; и &#34;Оптимизировать "
"css&#34; в плагине &#34;Сжатие и Объединения&#34;. С помощью этой колонки "
"настроек, вы можете исключить скрипты и стили, которые вы не хотите "
"оптимизировать. Чтобы добавить файл в исключения просто нажмите кнопку \"Нет"
"\"."
#: assets-manager/includes/class.configurate-assets.php:1323
msgid ""
"Youve enabled the &#34;Optimize js scripts?&#34; and &#34;Optimize CSS "
"options&#34; in the &#34;Autoptimize&#34;. These settings exclude scripts "
"and styles that you dont want to optimize. Press No to add a file to the "
"excluded list."
msgstr ""
"Вы включили опцию &#34;Оптимизировать js скрипты?&#34; и &#34;Оптимизировать "
"css&#34; в плагине &#34;Autoptimize&#34;. С помощью этой колонки настроек, "
"вы можете исключить скрипты и стили, которые вы не хотите оптимизировать. "
"Чтобы добавить файл в исключения просто нажмите кнопку \"Нет\"."
#~ msgid ""
#~ "We found that you use the plugin \"Clearfy - disable unused functions\", "
#~ "this plugin already has the same functions as \"Assets manager\", so you "
#~ "can disable the \"Assets manager\" plugin!"
#~ msgstr ""
#~ "Мы обнаружили, что вы используете плагин \"Clearfy - disable unused "
#~ "features\", этот плагин включает функционал \"WP Asset CleanUp\", вы "
#~ "можете деактивировать плагин \"Менеджер скриптов\"!"
#~ msgid ""
#~ "Below you can disable/enable CSS and JS files on a per page/post basis, "
#~ "as well as by custom post types. We recommend testing this locally or on "
#~ "a staging site first, as you could break the appearance of your live "
#~ "site. If you aren't sure about a certain script, you can try clicking on "
#~ "it, as a lot of authors will mention their plugin or theme in the header "
#~ "of the source code."
#~ msgstr ""
#~ "Ниже вы можете включить/отключить использование CSS и JS файлов в "
#~ "записях, произвольных типах записей или страницах. Мы рекомендуем вам "
#~ "эксперементировать со скриптами на локальном хостинге или тестом сайте, "
#~ "так как вы можете нарушить работу сайта, если отключите системные файлы "
#~ "скриптов, без которых невозможна полноценная работа сайта. Если вы не "
#~ "уверены, для чего используется тот или иной файл, попробуйте нажать на "
#~ "ссылку под его заголовком, в открывшемся файле вы можете увидеть "
#~ "комментарий разработчика с ссылкой на описание плагина. Получив "
#~ "достаточную информацию о функциях плагина, вы сможете более уверенно "
#~ "включать или отключать его стили и скрипты."
#~ msgid ""
#~ "If for some reason you run into trouble, you can always enable everything "
#~ "again to reset the settings."
#~ msgstr ""
#~ "Если по какой-то причине вы столкнулись с проблемами, вы всегда можете "
#~ "включить все опции, чтобы сбросить настройки."
#~ msgid "Save settings"
#~ msgstr "Сохранить"
#~ msgid "Hide panel in adminbar?"
#~ msgstr "Скрыть панель из админбара?"
#~ msgid "State"
#~ msgstr "Состояние"
#~ msgid "Script"
#~ msgstr "Скрипт"
#~ msgid "In use"
#~ msgstr "Используется"
#~ msgid "Disable"
#~ msgstr "Отключить"
#~ msgid "Enable"
#~ msgstr "Включить"
#~ msgid "Enabled"
#~ msgstr "Включить"
#~ msgid "Disable everwhere to view enable settings."
#~ msgstr ""
#~ "Нужно включить опцию \"повсюду\", чтобы увидеть дополнительные настройки."
#~ msgid ""
#~ "We found that you use the plugin \"Clearfy - disable unused functions\", "
#~ "this plugin already has the same functions as \"WP Asset CleanUp\", so "
#~ "you can disable the \"WP Asset CleanUp\" plugin!"
#~ msgstr ""
#~ "Мы обнаружили, что вы используете плагин \"Clearfy - disable unused "
#~ "features\", этот плагин включает функционал \"WP Asset CleanUp\", вы "
#~ "можете деактивировать плагин \"WP Asset CleanUp\"!"
#~ msgid "Webcraftic Assets manager"
#~ msgstr "Webcraftic менеджер скриптов"
#~ msgid ""
#~ "We found that you have the \"Clearfy - disable unused features\" plugin "
#~ "installed, this plugin already has disable comments functions, so you can "
#~ "deactivate plugin \"WP Asset CleanUp\"!"
#~ msgstr ""
#~ "Мы обнаружили, что вы используете плагин \"Clearfy - disable unused "
#~ "features\", этот плагин"

View File

@@ -0,0 +1,26 @@
<?php #comp-page builds: premium
/**
* Updates for altering the table used to store statistics data.
* Adds new columns and renames existing ones in order to add support for the new social buttons.
*/
class WGZUpdate010100 extends Wbcr_Factory480_Update {
public function install()
{
global $wpdb;
/*$request = $wpdb->get_results("SELECT option_id, option_name, option_value FROM {$wpdb->prefix}options WHERE option_name LIKE 'wbcr-clearfy_%'");
if( !empty($request) ) {
foreach($request as $option) {
$option_new_name = str_replace('wbcr-clearfy', WCL_Plugin::app()
->getPrefix(), $option->option_name);
if( !get_option($option_new_name, false) ) {
$wpdb->query("UPDATE {$wpdb->prefix}options SET option_name='$option_new_name' WHERE option_id='{$option->option_id}'");
} else {
delete_option($option->option_name);
}
}
}*/
}
}

View File

@@ -0,0 +1,226 @@
<?php #comp-page builds: premium
/**
* Updates for altering the table used to store statistics data.
* Adds new columns and renames existing ones in order to add support for the new social buttons.
*/
class WGZUpdate010108 extends Wbcr_Factory480_Update {
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
*/
public function install() {
$old_plugin_options = get_option( $this->plugin->getPrefix() . 'assets_manager_options', [] );
$save_mode = (int) get_option( $this->plugin->getPrefix() . 'for_admin_only', 0 );
$settings = get_option( $this->plugin->getPrefix() . 'assets_states', [] );
if ( ! empty( $old_plugin_options ) ) {
if ( ! function_exists( 'wbcr_gnz_deploy_mu_plugin' ) ) {
require_once WGZ_PLUGIN_DIR . '/includes/functions.php';
}
wbcr_gnz_deploy_mu_plugin();
}
if ( empty( $settings ) ) {
$settings['save_mode'] = (bool) $save_mode;
if ( ! empty( $old_plugin_options['disabled'] ) ) {
foreach ( $old_plugin_options['disabled'] as $type => $assets ) {
if ( ! empty( $assets ) ) {
foreach ( $assets as $handle => $where ) {
$group_settings = &$settings[ $type ][ $handle ];
$exclude = $this->get_enabled_from_options( $old_plugin_options, $type, $handle );
$this->where_to_condition( $where, $group_settings['visability'], $exclude );
if ( 'plugins' === $type ) {
$group_settings['load_mode'] = 'disable_assets';
}
$group_settings['visability'] = json_encode( $group_settings['visability'] );
}
}
}
$active_plugins = $this->get_active_plugins();
if ( ! empty( $active_plugins ) ) {
foreach ( (array) $active_plugins as $plugin_base ) {
$plugin_name_parts = explode( '/', $plugin_base );
if ( 2 === sizeof( $plugin_name_parts ) ) {
$plugin_name = $plugin_name_parts[0];
if ( empty( $settings['plugins'][ $plugin_name ]['load_mode'] ) ) {
$settings['plugins'][ $plugin_name ]['load_mode'] = 'enable';
}
if ( empty( $settings['plugins'][ $plugin_name ]['visability'] ) ) {
$settings['plugins'][ $plugin_name ]['visability'] = '';
}
if ( ! empty( $settings['js'] ) ) {
$settings['plugins'][ $plugin_name ]['js'] = $settings['js'];
}
if ( ! empty( $settings['css'] ) ) {
$settings['plugins'][ $plugin_name ]['css'] = $settings['css'];
}
}
}
}
if ( ! empty( $settings['js'] ) ) {
$settings['theme']['js'] = $settings['misc']['js'] = $settings['js'];
unset( $settings['js'] );
}
if ( ! empty( $settings['css'] ) ) {
$settings['theme']['css'] = $settings['misc']['css'] = $settings['css'];
unset( $settings['css'] );
}
}
}
//update_option( $this->plugin->getPrefix() . 'backend_assets_states', $settings );
update_option( $this->plugin->getPrefix() . 'assets_states', $settings );
}
/**
* Get a list of active plugins.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
* @return array
*/
private function get_active_plugins() {
if ( is_multisite() ) {
$active_network_plugins = (array) get_site_option( 'active_sitewide_plugins' );
$active_network_plugins = array_keys( $active_network_plugins );
$active_blog_plugins = (array) get_option( 'active_plugins' );
return array_unique( array_merge( $active_network_plugins, $active_blog_plugins ) );
}
return (array) get_option( 'active_plugins' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 2.0.0
*
* @param $where
* @param $settings
* @param $exclude
*/
private function where_to_condition( $where, &$settings, $exclude ) {
if ( ! empty( $where['current'] ) ) {
foreach ( (array) $where['current'] as $current_url ) {
$settings[] = [
'type' => 'OR',
'conditions' => [
[
'param' => 'current-url',
'operator' => 'equals',
'type' => 'default',
'value' => $current_url
]
]
];
}
}
if ( ! empty( $where['custom'] ) ) {
foreach ( (array) $where['custom'] as $custom_url ) {
$settings[] = [
'type' => 'OR',
'conditions' => [
[
'param' => 'location-page',
'operator' => 'equals',
'type' => 'text',
'value' => $custom_url
]
]
];
}
}
if ( ! empty( $where['regex'] ) ) {
$settings[] = [
'type' => 'OR',
'conditions' => [
[
'param' => 'regular-expression',
'operator' => 'equals',
'type' => 'regexp',
'value' => $where['regex']
]
]
];
}
if ( ! empty( $where['everywhere'] ) ) {
$everywhere = [
'type' => 'OR',
'conditions' => [
[
'param' => 'location-some-page',
'operator' => 'equals',
'type' => 'select',
'value' => 'base_web'
]
]
];
if ( ! empty( $exclude ) ) {
foreach ( (array) $exclude as $group_name => $group ) {
foreach ( (array) $group as $item_id ) {
if ( ! in_array( $group_name, [ 'post_type', 'taxonomies', 'current' ] ) ) {
continue;
}
switch ( $group_name ) {
case 'post_type':
$condition_param = 'location-post-type';
$value = $item_id;
break;
case 'taxonomies':
$condition_param = 'location-taxonomy';
$value = $item_id;
break;
case 'current':
$condition_param = 'current-url';
$value = $item_id;
break;
/*case 'categories':
$condition_param = 'location-taxonomy';
$value = '';
break;*/
}
$everywhere['conditions'][] = [
'param' => $condition_param,
'operator' => 'notequal',
'type' => 'select',
'value' => $value
];
}
}
}
$settings[] = $everywhere;
}
}
/**
* Get enabled from options
*
* @param $type
* @param $handle
*
* @return null
*/
private function get_enabled_from_options( $options, $type, $handle ) {
if ( isset( $options['enabled'] ) && isset( $options['enabled'][ $type ] ) && isset( $options['enabled'][ $type ][ $handle ] ) ) {
return $options['enabled'][ $type ][ $handle ];
}
return null;
}
}

View File

@@ -0,0 +1,20 @@
<?php #comp-page builds: premium
/**
* Updates for altering the table used to store statistics data.
* Adds new columns and renames existing ones in order to add support for the new social buttons.
*/
class WGZUpdate020005 extends Wbcr_Factory480_Update {
public function install() {
$settings = get_option( $this->plugin->getPrefix() . 'assets_states', [] );
if ( ! empty( $settings ) ) {
if ( ! function_exists( 'wbcr_gnz_deploy_mu_plugin' ) ) {
require_once WGZ_PLUGIN_DIR . '/includes/functions.php';
}
wbcr_gnz_deploy_mu_plugin();
}
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,534 @@
<?php
/**
* Webcraftic AM plugin load filter
* Dynamically activated only plugins that you have selected in each page. [Note] Webcraftic AM has been automatically installed/deleted by Activate/Deactivate of "load filter plugin".
* Version: 1.1.2
* Framework Version: FACTORY_480_VERSION
*/
// todo: проверить, как работает кеширование
// todo: замерить, скорость работы этого решения
defined('ABSPATH') || exit;
/**
* Stop optimizing scripts and caching the asset manager page.
*
* For some types of pages it is imperative to not be cached. Think of an e-commerce scenario:
* when a customer enters checkout, they wouldnt want to see a cached page with some previous
* customers payment data.
*
* Elaborate plugins like WooCommerce (and many others) use the DONOTCACHEPAGE constant to let
* caching plugins know about certain pages or endpoints that should not be cached in any case.
* Accordingly, all popular caching plugins, including WP Rocket, support the constant and would
* not cache a request for which DONOTCACHEPAGE is defined as true.
*/
if( isset($_GET['wbcr_assets_manager']) ) {
// Disable Query monitor plugin on the assets manager pages to avoid conflicts.
if( !defined('QM_DISABLED') ) {
define('QM_DISABLED', true);
}
// Disable Cache Plugins
if( !defined('DONOTCACHEPAGE') ) {
define('DONOTCACHEPAGE', true);
}
if( !defined('DONOTCACHCEOBJECT') ) {
define('DONOTCACHCEOBJECT', true);
}
if( !defined('DONOTMINIFY') ) {
define('DONOTMINIFY', true);
}
if( !defined('DONOTROCKETOPTIMIZE') ) {
define('DONOTROCKETOPTIMIZE', true);
}
if( !defined('DONOTMINIFYJS') ) {
define('DONOTMINIFYJS', true);
}
if( !defined('DONOTASYNCCSS') ) {
define('DONOTASYNCCSS', true);
}
if( !defined('DONOTMINIFYCSS') ) {
define('DONOTMINIFYCSS', true);
}
if( !defined('WHM_DO_NOT_HIDE_WP') ) {
define('WHM_DO_NOT_HIDE_WP', true);
}
}
if( defined('WP_SETUP_CONFIG') || defined('WP_INSTALLING') || isset($_GET['wbcr_assets_manager']) ) {
return;
}
// @formatter:off
//-------------------------------------------------------------------------------------------
// Plugins load filter
//-------------------------------------------------------------------------------------------
class WGNZ_Plugins_Loader {
const DEFAULT_OPTIONS_PREFIX = 'wbcr_gnz_';
const CLEARFY_OPTIONS_PREFIX = 'wbcr_clearfy_';
protected $parent_plugin_dir;
protected $settings;
protected $active_plugins = array();
public function __construct()
{
# We must always load the plugin if it is an ajax request, a cron
# task or a rest api request. Otherwise, the user may have problems
# with the work of plugins.
if( $this->doing_ajax() || $this->doing_cron() || $this->doing_rest_api() ) {
return;
}
$is_clearfy_active = false;
$this->active_plugins = $this->get_active_plugins();
add_filter('wam/conditions/call_method', [$this, 'check_conditions_method'], 10, 4);
if( $this->is_active_clearfy() ) {
$deactivate_components = $this->get_clearfy_deactivate_components();
if( empty($deactivate_components) || !in_array('assets_manager', $deactivate_components) ) {
$is_clearfy_active = true;
}
}
$parent_plugin_dir = $this->get_parent_plugin_dir();
if( empty($parent_plugin_dir) || !file_exists($parent_plugin_dir) ) {
return;
}
# Disable plugins only if Asset Manager and Clearfy are activated
if( $is_clearfy_active || $this->is_active_assets_manager_standalone() ) {
$this->settings = $this->get_assets_manager_options();
if( !empty($this->settings) ) {
if( is_multisite() ) {
add_filter('site_option_active_sitewide_plugins', array($this, 'disable_network_plugins'), 1);
}
add_filter('option_active_plugins', array($this, 'disable_plugins'), 1);
add_filter('option_hack_file', array($this, 'hack_file_filter'), 1);
add_action('plugins_loaded', array($this, 'remove_plugin_filters'), 1);
}
}
}
/**
* @param $hackFile
*
* @return mixed
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*
*/
public function hack_file_filter($hackFile)
{
$this->remove_plugin_filters();
return $hackFile;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
public function remove_plugin_filters()
{
remove_action('option_active_plugins', array($this, 'disable_plugins'), 1);
}
/**
* We control the disabling of plugins that are activated for the network.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
public function disable_network_plugins($plugins_list)
{
$new_plugin_list = $plugins_list;
if( is_array($plugins_list) && !empty($plugins_list) ) {
$temp_plugin_list = array_keys($plugins_list);
$temp_plugin_list = $this->disable_plugins($temp_plugin_list);
$new_plugin_list = array();
foreach((array)$temp_plugin_list as $plugin_file) {
$new_plugin_list[$plugin_file] = $plugins_list[$plugin_file];
}
}
return $new_plugin_list;
}
/**
* We control the disabling of plugins that are activated for blog.
*
* @param $plugins_list
*
* @return mixed
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*
*/
public function disable_plugins($plugins_list)
{
if( !is_array($plugins_list) || empty($plugins_list) ) {
return $plugins_list;
}
foreach((array)$plugins_list as $key => $plugin_base) {
if( $this->is_disabled_plugin($plugin_base) ) {
unset($plugins_list[$key]);
}
}
return $plugins_list;
}
/**
* Extra method for extend WGZ_Check_Conditions class.
*
* @param mixed $default
* @param string $method_name
* @param string $operator
* @param mixed $value
*
* @return mixed
* @since 1.0.7
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
public function check_conditions_method($default, $method_name, $operator, $value)
{
$premium_plugin_dir = $this->get_parent_premium_plugin_dir();
if( $premium_plugin_dir && file_exists($premium_plugin_dir) ) {
require_once $premium_plugin_dir . '/includes/class-check-conditions.php';
if( class_exists('WGNZP_Check_Conditions') ) {
$conditions = new WGNZP_Check_Conditions();
if( method_exists($conditions, $method_name) ) {
return $conditions->$method_name($operator, $value);
}
}
}
return $default;
}
/**
* Get a list of active plugins.
*
* @return array
* @since 1.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function get_active_plugins()
{
if( is_multisite() ) {
$active_network_plugins = (array)get_site_option('active_sitewide_plugins');
$active_network_plugins = array_keys($active_network_plugins);
$active_blog_plugins = (array)get_option('active_plugins');
return array_unique(array_merge($active_network_plugins, $active_blog_plugins));
}
return (array)get_option('active_plugins');
}
/**
* Determines whether the current plugin is disabled
*
* @param $plugin_base
*
* @return bool
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*
*/
private function is_disabled_plugin($plugin_base)
{
$white_plgins_list = array(
'clearfy', // prod
'wp-plugin-clearfy', // dev
'gonzales', // prod
'wp-plugin-gonzales', // dev
'clearfy_package' // premium package
);
$plugin_base_part = explode('/', $plugin_base);
# If plugin base is incorrect or plugin name in the white list
if( 2 !== sizeof($plugin_base_part) || in_array($plugin_base_part[0], $white_plgins_list) ) {
return false;
}
if( !empty($this->settings['plugins']) && isset($this->settings['plugins'][$plugin_base_part[0]]) && 'disable_plugin' === $this->settings['plugins'][$plugin_base_part[0]]['load_mode'] ) {
require_once $this->get_parent_plugin_dir() . '/includes/classes/class-check-conditions.php';
if( !empty($this->settings['plugins'][$plugin_base_part[0]]['visability']) ) {
$condition = new WGZ_Check_Conditions($this->settings['plugins'][$plugin_base_part[0]]['visability']);
if( $condition->validate() ) {
return true;
}
}
}
return false;
}
/**
* Checks if the current request is a WP REST API request.
*
* Case #1: After WP_REST_Request initialisation
* Case #2: Support "plain" permalink settings
* Case #3: URL Path begins with wp-json/ (your REST prefix)
* Also supports WP installations in subfolders
*
* @author matzeeable https://wordpress.stackexchange.com/questions/221202/does-something-like-is-rest-exist
* @since 1.0.0
* @return boolean
*/
private function doing_rest_api()
{
$prefix = rest_get_url_prefix();
$rest_route = isset($_GET['rest_route']) ? $_GET['rest_route'] : null;
if( defined('REST_REQUEST') && REST_REQUEST // (#1)
|| !is_null($rest_route) // (#2)
&& strpos(trim($rest_route, '\\/'), $prefix, 0) === 0 ) {
return true;
}
// (#3)
$rest_url = wp_parse_url(site_url($prefix));
$current_url = wp_parse_url(add_query_arg(array()));
return strpos($current_url['path'], $rest_url['path'], 0) === 0;
}
/**
* Determines whether the current request is a WordPress Ajax request.
*
* @return bool True if it's a WordPress Ajax request, false otherwise.
* @since 1.0.0
*/
private function doing_ajax()
{
if( function_exists('wp_doing_ajax') ) {
return wp_doing_ajax();
}
return defined('DOING_AJAX') && DOING_AJAX;
}
/**
* Determines whether the current request is a WordPress cron request.
*
* @return bool True if it's a WordPress cron request, false otherwise.
* @since 1.0.0
*/
private function doing_cron()
{
if( function_exists('wp_doing_cron') ) {
return wp_doing_cron();
}
return defined('DOING_CRON') && DOING_CRON;
}
/**
* Is Clearfy plugin actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_clearfy()
{
return $this->is_active_clearfy_dev() || $this->is_active_clearfy_prod();
}
/**
* Is Clearfy Dev plugin actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_clearfy_dev()
{
return in_array('wp-plugin-clearfy/clearfy.php', $this->active_plugins);
}
/**
* Is Clearfy Prod plugin actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_clearfy_prod()
{
return in_array('clearfy/clearfy.php', $this->active_plugins);
}
/**
* Is Assets Manager standalone actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_assets_manager_standalone()
{
return $this->is_active_assets_manager_standalone_prod() || $this->is_active_assets_manager_standalone_dev();
}
/**
* Is Assets Manager standalone prod actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_assets_manager_standalone_prod()
{
return in_array('gonzales/gonzales.php', $this->active_plugins);
}
/**
* Is Assets Manager standalone dev actives?
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function is_active_assets_manager_standalone_dev()
{
return in_array('wp-plugin-gonzales/gonzales.php', $this->active_plugins);
}
/**
* Get options prefix
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function get_options_prefix()
{
if( $this->is_active_clearfy() ) {
return self::CLEARFY_OPTIONS_PREFIX;
}
return self::DEFAULT_OPTIONS_PREFIX;
}
/**
* Get Clearfy deactivated components
*
* @return array|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function get_clearfy_deactivate_components()
{
if( is_multisite() ) {
return get_site_option($this->get_options_prefix() . 'deactive_preinstall_components', array());
}
return get_option($this->get_options_prefix() . 'deactive_preinstall_components', array());
}
/**
* Get Assets Manager options
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function get_assets_manager_options()
{
if( is_multisite() && is_network_admin() ) {
return get_site_option($this->get_options_prefix() . 'backend_assets_states', array());
} else if( is_admin() ) {
return get_option($this->get_options_prefix() . 'backend_assets_states', array());
}
return get_option($this->get_options_prefix() . 'assets_states', array());
}
/**
* Get parent plugin dir
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function get_parent_plugin_dir()
{
if( $this->is_active_clearfy() ) {
if( $this->is_active_clearfy_dev() ) {
return WP_PLUGIN_DIR . '/wp-plugin-clearfy/components/assets-manager/';
}
return WP_PLUGIN_DIR . '/clearfy/components/assets-manager/';
} else if( $this->is_active_assets_manager_standalone() ) {
if( $this->is_active_assets_manager_standalone_dev() ) {
return WP_PLUGIN_DIR . '/wp-plugin-gonzales/';
}
return WP_PLUGIN_DIR . '/gonzales/';
}
return null;
}
/**
* Get premium plugin dir in dependence on environment
*
* @return string|null
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.7
*/
private function get_parent_premium_plugin_dir()
{
$is_active_prod = in_array('clearfy_package/clearfy-package.php', $this->active_plugins);
$is_active_dev = in_array('wp-plugin-clearfy-package/clearfy-package.php', $this->active_plugins);
$is_active_stand_alone_prod = in_array('assets-manager-premium/assets-manager-premium.php', $this->active_plugins);
$is_active_stand_alone_dev = in_array('wp-plugin-assets-manager-premium/assets-manager-premium.php', $this->active_plugins);
if( $is_active_dev ) {
$premium_plugin_dir = WP_PLUGIN_DIR . '/wp-plugin-clearfy-package/plugins/assets-manager-premium';
} else if( $is_active_prod ) {
$premium_plugin_dir = WP_PLUGIN_DIR . '/clearfy_package/plugins/assets-manager-premium';
} else if( $is_active_stand_alone_prod ) {
$premium_plugin_dir = WP_PLUGIN_DIR . '/assets-manager-premium/';
} else if( $is_active_stand_alone_dev ) {
$premium_plugin_dir = WP_PLUGIN_DIR . '/wp-plugin-assets-manager-premium/';
} else {
return null;
}
return wp_normalize_path($premium_plugin_dir);
}
}
new WGNZ_Plugins_Loader();
// @formatter:on

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,162 @@
=== Wordpress Assets manager, dequeue scripts, dequeue styles ===
Tags: dequeue script, dequeue style, pagespeed, speed, unload style, gonzales, assets clean, assets, assets cleanup, page speed optimizer, perfmatters, disable script, disable style, disable jquery, disable jquery-migrate, disable fonts
Contributors: webcraftic, creativemotion, alexkovalevv
Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VDX7JNTQPNPFW
Requires at least: 5.6
Tested up to: 6.7
Requires PHP: 7.2
Stable tag: trunk
License: GPLv2
Increase the speed of the pages by disabling unused scripts (.JS) and styles (.CSS). Make your website REACTIVE!
== Description ==
You should know that, a lot of WordPress plugins developers forget performance when creating plugins. This means that a lot of them load self scripts/styles on every single post and or page of your site. This is not good, because it slows your site down.
That's why we created the WP Asset manager, with it, you can choose which scripts and styles should be loaded on the page, and which ones do not. One example of this would be with the Contact Form 7 plugin. With two clicks you can disable it everywhere except for on your contact page.
THIS PLUGINS BENEFITS INCLUDE
Decreases number of HTTP requests loaded (important for faster load)
Reduces the HTML code of the actual page (thats even better if GZIP compression is enabled)
Makes source code easier to scan in case youre a developer and want to search for something
Remove possible conflicts between plugins/theme (e.g. 2 JavaScript files that are loading from different plugins and they interfere one with another)
Better performance score if you test your URL on websites such as GTmetrix, PageSpeed Insights, Pingdom Website Speed Test
Google will love your website more as it would be faster and fast page load is nowadays a factor in search ranking
Your server access log files (e.g the Apache ones) will be easier to scan and would take less space on your server
We used some useful functions from plugins <strong>Asset Queue Manager</strong>, <strong>WP Asset CleanUp (Page Speed Optimizer)</strong>, <strong>Clearfy disable unused features</strong>, <strong>wp disable</strong>, <strong>Disabler</strong>, <strong>Admin Tweaks</strong>
== Translations ==
* English - default, always included
* French - Thank you very much to user (kingteamdunet)
* Russian
If you want to help with the translation, please contact me through this site or through the contacts inside the plugin.
#### Recommended separate modules ####
We invite you to check out a few other related free plugins that our team has also produced that you may find especially useful:
* [Clearfy WordPress optimization plugin and disable ultimate tweaker](https://wordpress.org/plugins/clearfy/)
* [Disable Comments for Any Post Types (Remove Comments)](https://wordpress.org/plugins/comments-plus/)
* [Cyrlitera transliteration of links and file names](https://wordpress.org/plugins/cyrlitera/)
* [Cyr-to-lat reloaded transliteration of links and file names](https://wordpress.org/plugins/cyr-and-lat/ "Cyr-to-lat reloaded")
* [Disable admin notices individually](https://wordpress.org/plugins/disable-admin-notices/ "Disable admin notices individually")
* [Hide login page](https://wordpress.org/plugins/hide-login-page/ "Hide login page")
* [Disable updates, Disable automatic updates, Updates manager](https://wordpress.org/plugins/webcraftic-updates-manager/)
== Installation ==
1. Upload the plugin folder to the `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. The plugin settings can be accessed via the 'Settings' menu in the administration area (either your site administration for single-site installs).
== Screenshots ==
1. Control panel
2. Assets manager
== Changelog ==
= 2.1.9 (05.12.2024) =
* Added: Compatibility with Wordpress 6.7
= 2.1.8 (21.03.2024) =
* Added: Compatibility with Wordpress 6.5
* Added: Compatibility with php 8.3
= 2.1.7 (21.11.2023) =
* Added: Compatibility with Wordpress 6.4
* Added: Compatibility with php 8.2
= 2.1.6 (22.03.2023) =
* Fixed: Freemius framework conflict
* Added: Compatibility with Wordpress 6.2
= 2.1.4 (27.05.2022) =
* Compatibility with Wordpress 6.0
= 2.1.3 (21.03.2022) =
* Fixed: Compatibility with Disable admin notices plugin
= 2.1.2 (21.03.2022) =
* Compatibility with Wordpress 5.2 - 5.9.x
* Fixed: Minor bug
= 2.1.0 (21.12.2020) =
* Added: Compatibility with Wordpress 5.8
* Fixed: Minor bugs
= 2.0.7 (21.12.2020) =
* Disabled search by options for a single plugin.
* Fixed: duplicate templates and scripts error when rendering html views of Assets manager.
= 2.0.6 (15.12.2020) =
* Added: Subscribe form
* Fixed: Minor bug
= 2.0.5 (12.02.2020) =
* Fixed: Minor bug
= 2.0.4 (10.12.2019) =
* Fixed: Bug "[Warning message when open the Customize](https://wordpress.org/support/topic/warning-message-when-open-the-customize/)".
* Fixed: Conditional logic in the premium plugin didn't work in previous version due an error.
* Added: You can control asset requires. Now if you disabled asset and it required for which other asset, you will get prompt with warning.
* Added: If you click on the "requires" tag, you will be gone to the asset for which require the current asset.
= 2.0.3 (13.11.2019) =
* Fixed: Minor bugs. Comment head of mu plugin determined as main.
= 2.0.2 (13.11.2019) =
* Fixed: Minor bugs. Added an admin notice about great release.
= 2.0.1 (12.10.2019) =
* Fixed: The bug with save mode.
* Fixed: Some conditions (entire website) didn't work. It could be due save mode.
* Fixed: Critical a php error which related "Call to undefined function wp_scripts_get_suffix".
= 2.0.0 (03.10.2019) =
* The interface has become more compact and friendly.
* The speed and productivity of the editor is increased, it loads faster and does not freeze, as it was before.
* Extended conditional logic has been added, now you can create complex conditions for disabling assets.
* An additional mode has appeared to completely disable the plugin (you can disable not only scripts, but also stop executing plugin scripts).
* Known bugs in the previous version are fixed.
= 1.1.0 =
* Added: Compatibility with Wordpress 4.2 - 5.x
* Added: Multisite support
* Fixed: Minor bugs
= 1.0.7 =
* Fixed: Added compatibility with ithemes sync
* Fixed: Minor style fixes
= 1.0.6 =
* Fixed: Fixed a bug when the interface did not open on the frontend.
= 1.0.5 =
Great update:
* We completely changed the interface design. Now it is more convenient for visual inspection of resource files.
* Fixed: All errors that users have reported about
* Added: Multisite support
* Added: New logic disabled scripts and styles
* Added: You can exclude assets from optimizing for Autoptimize and Clearfy plugins.
* Added: You can exclude resource files for which you do not need to remove the query string.
* Added: You can see which plugin the style file belongs to and the js file.
= 1.0.4 =
* Fixed: Update core
* Fixed: Compatibility with others plugin
= 1.0.3 =
* Fixed: Compatibility with Clearfy plugin
* Fixed: The plugin interface did not work and the styles were not loaded due to security settings
* ADDED: Plugin options caching to reduce database queries for 90%. Clearfy became lighter and faster.
* ADDED: Compress and cache the plugin core files, to reduce the load on the admin panel
= 1.0.2 =
* Fixed: Core bugs
* Fixed: Problems with the fonts in the assets manager
= 1.0.0 =
* Plugin release

View File

@@ -0,0 +1,52 @@
<?php
// if uninstall.php is not called by WordPress, die
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
die;
}
// remove plugin options
global $wpdb;
if ( ! defined( 'WGZ_PLUGIN_DIR' ) ) {
define( 'WGZ_PLUGIN_DIR', dirname( __FILE__ ) );
}
if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
}
function uninstall() {
// remove plugin options
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wbcr_gonzales_%';" );
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wbcr_gnz_%';" );
}
if ( is_multisite() ) {
global $wpdb, $wp_version;
$wpdb->query( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE 'wbcr_gonzales_%';" );
$wpdb->query( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE 'wbcr_gnz_%';" );
$blogs = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
if ( ! empty( $blogs ) ) {
foreach ( $blogs as $id ) {
switch_to_blog( $id );
uninstall();
restore_current_blog();
}
}
} else {
uninstall();
}
// Remove mu plugin
require_once WGZ_PLUGIN_DIR . '/includes/functions.php';
// todo: for the function require the constant WGZ_PLUGIN_DIR
wbcr_gnz_remove_mu_plugin();

View File

@@ -0,0 +1,37 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* @var array $data
* @var WGZ_Views $this
*/
?>
<div id="WBCR-AM" class="wam-wrapper" style="display: block;">
<?php $this->print_template( 'part-assets-manager-header', $data ); ?>
<main class="wam-content">
<?php $this->print_template( 'part-assets-manager-tabs-menu' ); ?>
<?php //$this->print_template( 'part-assets-manager-info-bar' ); ?>
<div id="wam-assets-type-tab-content__theme" data-category="theme" class="wam-assets-type-tab-content">
<?php $this->print_template( 'tab-content-assets', [
'type' => 'theme',
'assets' => $data['theme_assets']
] ); ?>
</div>
<div id="wam-assets-type-tab-content__misc" data-category="misc" class="wam-assets-type-tab-content">
<?php $this->print_template( 'tab-content-assets', [
'type' => 'misc',
'assets' => $data['misc_assets']
] ); ?>
</div>
<div id="wam-assets-type-tab-content__plugins" data-category="plugins" class="wam-assets-type-tab-content wam-assets-type-tab-content__active">
<?php $this->print_template( 'tab-content-assets-plugins', $data ); ?>
</div>
</main>
<!-- Html template Conditions Editor -->
<script type="text/html" id="wam-conditions-builder-template">
<?php $this->print_template( 'conditions-logic-editor-template', $data ); ?>
</script>
<!-- /End Html template -->
</div> <!-- /div2 -->

View File

@@ -0,0 +1,112 @@
<?php
defined('ABSPATH') || die('Cheatin uh?');
/**
* @var array $data
* @var WGZ_Views $this
*/
?>
<div class="wam-cleditor__empty wam-cleditor">
<div class="wam-cleditor__wrap">
<div class="wam-cleditor__when-empty">
<?php _e('No filters specified.', 'gonzales') ?>
<a href="#" class="js-wam-cleditor__add-group"><?php _e('Click here', 'gonzales') ?></a> <?php _e('to add one.', 'gonzales') ?>
</div>
<div class="wam-cleditor__groups"></div>
</div>
<div class="wam-cleditor__group">
<div class="wam-cleditor__point"></div>
<div class="wam-cleditor__head">
<div class="wam-cleditor__head-left">
<span class="wam-cleditor__first-group-title">
<?php _e('Disable If', 'gonzales') ?>
</span>
<span class="wam-cleditor__group-type"><?php _e('OR', 'gonzales') ?></span>
</div>
<div class="wam-cleditor__head-right">
<button type="button" class="wam-button wam-button--small wam-button--danger js-wam-cleditor__remove-group">
<?php _e('Delete', 'gonzales'); ?>
</button>
</div>
</div>
<div class="wam-cleditor__box">
<div class="wam-cleditor__when-empty">
<?php _e('No filters specified.', 'gonzales') ?>
<a href="#" class="js-wam-cleditor__add-condition"><?php _e('Click here', 'gonzales') ?></a> <?php _e('to add one.', 'gonzales') ?>
</div>
<div class="wam-cleditor__conditions"></div>
</div>
</div>
<div class="wam-cleditor__condition">
<div class="wam-cleditor__operator-and"><span><?php _e('and', 'gonzales') ?></span></div>
<span class="wam-cleditor__params">
<select class="wam-cleditor__param-select">
<?php if( !empty($data['conditions_logic_params']) ): ?>
<?php foreach((array)$data['conditions_logic_params'] as $filter_param) { ?>
<optgroup label="<?php echo $filter_param['title'] ?>">
<?php foreach((array)$filter_param['items'] as $param) { ?>
<?php
$option_attrs = [];
$option_attrs[] = 'data-type="' . esc_attr($param['type']) . '"';
if( isset($param['default_value']) ) {
$option_attrs[] = 'data-default-value="' . esc_attr($param['default_value']) . '"';
}
if( isset($param['placeholder']) ) {
$placeholder = is_array($param['placeholder']) ? @json_encode($param['placeholder'], JSON_UNESCAPED_UNICODE, JSON_HEX_QUOT) : $param['placeholder'];
$option_attrs[] = 'data-placeholder="' . esc_attr($placeholder) . '"';
}
if( isset($param['params']) ) {
$option_attrs[] = 'data-params="' . esc_attr(@json_encode($param['params'], JSON_UNESCAPED_UNICODE, JSON_HEX_QUOT)) . '"';
}
if( isset($param['only_equals']) ) {
$option_attrs[] = 'data-only-equals="' . intval($param['only_equals']) . '"';
}
if( isset($param['description']) ) {
$option_attrs[] = 'data-hint="' . esc_attr($param['description']) . '"';
}
$option_disabled = isset($param['disabled']) ? $param['disabled'] : false;
?>
<option<?php echo ' ' . implode(' ', $option_attrs) ?> value="<?php echo esc_attr($param['id']) ?>"<?php disabled($option_disabled) ?>>
<?php echo $param['title'] ?>
</option>
<?php } ?>
</optgroup>
<?php } ?>
<?php endif; ?>
</select>
<i class="wam-cleditor__hint">
<span class="wam-cleditor__hint-icon"></span>
<span class="wam-cleditor__hint-content"></span>
</i>
</span>
<span class="wam-cleditor__condition-operators">
<select class="wam-cleditor__operator-select">
<option value="equals"><?php _e('Equals', 'gonzales') ?></option>
<option value="notequal"><?php _e('Doesn\'t Equal', 'gonzales') ?></option>
<option value="greater"><?php _e('Greater Than', 'gonzales') ?></option>
<option value="less"><?php _e('Less Than', 'gonzales') ?></option>
<option value="older"><?php _e('Older Than', 'gonzales') ?></option>
<option value="younger"><?php _e('Younger Than', 'gonzales') ?></option>
<option value="contains"><?php _e('Contains', 'gonzales') ?></option>
<option value="notcontain"><?php _e('Doesn\'t Сontain', 'gonzales') ?></option>
<option value="between"><?php _e('Between', 'gonzales') ?></option>
</select>
</span>
<span class="wam-cleditor__condition-value"></span>
<span class="wam-cleditor__condition-actions">
<a href="#" class="wam-button wam-button--danger button-sm js-wam-cleditor__condition-remove"><?php _e('X', 'gonzales') ?></a>
<a href="#" class="wam-button wam-button--yellow button-sm js-wam-cleditor__condition-add-and"><?php _e('AND', 'gonzales') ?></a>
</span>
</div>
<div class="wam-cleditor__buttons-group">
<button type="button" class="wam-button wam-button--default wam-cleditor__button-left js-wam-cleditor__add-group">
<?php _e('Add new group', 'gonzales') ?>
</button>
</div>
</div>

View File

@@ -0,0 +1,41 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* @var array $data
* @var WGZ_Views $this
*/
?>
<header class="wam-float-panel">
<div class="wam-float-panel__left">
<div class="wam-float-panel__logo"></div>
<ul class="wam-float-panel__data panel__data-main">
<li class="wam-float-panel__data-item __info-request">
<?php _e( 'Total requests', 'gonzales' ) ?>:
<b class="wam-float-panel__item_value">--</b>
</li>
<li class="wam-float-panel__data-item __info-total-size">
<?php _e( 'Total size', 'gonzales' ) ?>:
<b class="wam-float-panel__item_value">--</b>
</li>
<li class="wam-float-panel__data-item __info-reduced-total-size"><?php _e( 'Optimized size', 'gonzales' ) ?>
:
<b class="wam-float-panel__item_value">--</b>
</li>
<li class="wam-float-panel__data-item __info-disabled-js"><?php _e( 'Disabled js', 'gonzales' ) ?>:
<b class="wam-float-panel__item_value">-- </b>
</li>
<li class="wam-float-panel__data-item __info-disabled-css"><?php _e( 'Disabled css', 'gonzales' ) ?>:
<b class="wam-float-panel__item_value">-- </b>
</li>
</ul>
</div>
<div class="wam-float-panel__right">
<a class="wam-float-panel__reset wbcr-reset-button js-wam-reset-settings" href="<?php echo esc_url( wp_nonce_url( add_query_arg( [ 'wam_reset_settings' => 1 ] ), 'wam_reset_settings' ) ); ?>">
<?php _e( 'Reset', 'gonzales' ) ?>
</a>
<button id="wam-save-button" class="wam-float-panel__save js-wam-top-panel__save-button" data-nonce="<?php echo wp_create_nonce( 'wam_save_settigns' ); ?>"><?php _e( 'Save', 'gonzales' ) ?></button>
<?php do_action( 'wam/views/safe_mode_checkbox', $data ); ?>
<a class="wam-float-panel__close wbcr-close-button" href="<?php echo esc_url(remove_query_arg( 'wbcr_assets_manager' )); ?>" aria-label="<?php _e( 'Close', 'gonzales' ) ?>"></a>
</div>
</header>

View File

@@ -0,0 +1,44 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* @var array $data
* @var WGZ_Views $this
*/
?>
<div class="wam-info-section">
<div class="wam-info-section__warning">
<p>
<b>
<?php _e( 'Important! Each page of your website has different sets of scripts and styles files.', 'gonzales' ) ?>
</b>
</p>
<p>
<?php _e( 'Use this feature to disable unwanted scripts and styles by setting up the logic for
different types of pages. We recommend working in "Safe mode" because disabling any necessary
system script file can corrupt the website. All changes done in Safe mode are available for
administrator only. This way only you, as the administrator, can see the result of optimization.
To enable the changes for other users, uncheck Safe mode.', 'gonzales' ) ?>
</p>
<p>
<?php echo sprintf( __( 'For more details and user guides, check the plugins <a href="%s" target="_blank" rel="noreferrer noopener">documentation</a>.', 'gonzales' ), WGZ_Plugin::app()->get_support()->get_docs_url( true, 'docs' ) ) ?>
</p>
</div>
<a class="wbcr-gnz-button__pro"
href="<?php echo WGZ_Plugin::app()->get_support()->get_tracking_page_url( 'assets-manager', 'assets-manager' ) ?>"
target="_blank" rel="noreferrer noopener">'
<?php _e( 'Upgrade to Premium', 'gonzales' ) ?></a>
<div class="wam-info-section__go-to-premium">
<h3>
<span><?php _e( 'MORE IN CLEARFY BUSINESS', 'gonzales' ) ?></span>
</h3>
<ul>
<li><?php _e( 'Disable plugins (groups of scripts)', 'gonzales' ) ?></li>
<li><?php _e( 'Conditions by the link template', 'gonzales' ) ?></li>
<li><?php _e( 'Conditions by the regular expression', 'gonzales' ) ?></li>
<li><?php _e( 'Safe mode', 'gonzales' ) ?></li>
<li><?php _e( 'Statistics and optimization results', 'gonzales' ) ?></li>
</ul>
</div>
</div>

View File

@@ -0,0 +1,16 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* @var array $data
* @var WGZ_Views $this
*/
?>
<ul class="wam-assets-type-tabs">
<li class="wam-assets-type-tabs__item">
<div class="wam-assets-type-tabs__button js-wam-assets-type-tabs__button wam-assets-type-tabs__button--plugins wam-assets-type-tab__active" data-type="plugins"></div>
<div class="wam-assets-type-tabs__button js-wam-assets-type-tabs__button wam-assets-type-tabs__button--misc" data-type="misc"></div>
<div class="wam-assets-type-tabs__button js-wam-assets-type-tabs__button wam-assets-type-tabs__button--theme" data-type="theme"></div>
</li>
</ul>

View File

@@ -0,0 +1,111 @@
<?php
defined('ABSPATH') || die('Cheatin uh?');
/**
* @var array $data
* @var WGZ_Views $this
*/
$plugin_name = $data['name'];
?>
<div class="wam-plugin-settings">
<div class="wam-plugin-settings__controls">
<select class="wam-select<?php echo $data['select_control_classes']; ?> js-wam-select-plugin-load-mode" data-plugin-name="<?php echo esc_attr($plugin_name) ?>">
<option value="enable"<?php selected('enable', $data['load_mode']) ?>>
<?php _e("Load plugin and its assets", 'gonzales') ?>
</option>
<option value="disable_assets"<?php selected('disable_assets', $data['load_mode']) ?>>
<?php _e("Don't load plugin assets", 'gonzales') ?>
</option>
<option value="disable_plugin"<?php selected('disable_plugin', $data['load_mode']) ?>>
<?php _e("Don't load plugin", 'gonzales') ?>
</option>
</select>
<button class="wam-button wam-button--default wam-button__icon js-wam-button__icon--cogs js-wam-open-plugin-settings<?php echo esc_attr($data['settings_button_classes']) ?>"></button>
</div>
<div class="js-wam-plugin-settings__conditions">
<input type="hidden" data-plugin-name="<?php echo esc_attr($plugin_name) ?>" class="wam-conditions-builder__settings" value="<?php echo esc_attr($data['visability']) ?>">
</div>
</div>
<div class="wam-plugin-assets wam-plugin-<?php echo esc_attr($plugin_name) ?>-assets">
<h2><?php _e('Loaded resourses on current page', 'gonzales') ?>:</h2>
<table class="wam-table wam-plugin-assets__table" style="margin:0;">
<tr>
<th class="wam-table__th-actions"><?php _e('Actions', 'gonzales') ?></th>
<th class="wam-table__th-type"><?php _e('Type', 'gonzales') ?></th>
<th class="wam-table__th-handle"><?php _e('Handle/Source', 'gonzales') ?></th>
<th class="wam-table__th-version"><?php _e('Version', 'gonzales') ?></th>
<th class="wam-table__th-size"><?php _e('Size', 'gonzales') ?></th>
</tr>
<?php if( !empty($data['assets']) ): ?>
<?php foreach((array)$data['assets'] as $resource_type => $assets): ?>
<?php foreach((array)$assets as $resource_handle => $item): ?>
<tr data-size="<?php echo esc_attr($item['size']); ?>" data-resource-type="<?php echo esc_attr($resource_type) ?>" data-resource-handle="<?php echo esc_attr($resource_handle) ?>" data-asset-handle="<?php echo esc_attr($resource_handle . '-' . $resource_type); ?>" class="js-wam-asset js-wam-<?php echo esc_attr($resource_type); ?>-asset wam-table__asset-settings<?php echo $item['row_classes']; ?>" id="wam-table__loaded-resourse-<?php echo md5($resource_handle . $resource_type . $item['url_full']); ?>">
<td class="wam-table__td-actions">
<select class="wam-select<?php echo $item['select_control_classes']; ?> js-wam-select-asset-load-mode"<?php disabled('enable' !== $data['load_mode']) ?>>
<option value="enable"<?php selected('enable', $item['load_mode']) ?>>
<?php _e('Enable', 'gonzales') ?>
</option>
<option value="disable"<?php selected('disable', $item['load_mode']) ?>>
<?php _e('Disable', 'gonzales') ?>
</option>
</select>
<button class="wam-button wam-button--default wam-button__icon js-wam-button__icon--cogs js-wam-open-asset-settings<?php echo esc_attr($item['settings_button_classes']); ?>"></button>
</td>
<td class="wam-table__td-type">
<span class="wam-asset-type wam-asset-type--<?php echo esc_attr($resource_type); ?>">
<?php echo esc_attr($resource_type); ?>
</span>
</td>
<td class="wam-table__td-handle">
<?php echo esc_html($resource_handle); ?><br>
<a href="<?php echo esc_url($item['url_full']); ?>">
<?php echo esc_html($item['url_short']); ?>
</a>
<?php do_action('wam/views/assets/handle_column/after_url', $item); ?>
<div class="wam-table__handle-deps">
<?php if( !empty($item['deps']) ): ?>
<span class="wam-colors--grey"><?php _e('Dependency by', 'gonzales') ?></span>:
<span class="wam-table__asset-deps js-wam-table__asset-deps">
<?php echo implode(', ', $item['deps']); ?>
</span><br>
<?php endif; ?>
<?php if( !empty($item['requires']) ): ?>
<span class="wam-colors--red"><?php _e('Requires for', 'gonzales') ?></span>:
<span class="wam-table__asset-requires js-wam-table__asset-requires">
<?php echo implode(', ', $item['requires']); ?>
</span>
<?php endif; ?>
</div>
</td>
<td class="wam-table__td-version"><?php echo esc_html($item['ver']); ?></td>
<td class="wam-table__td-size"><?php echo esc_html($item['size']); ?> KB</td>
</tr>
<tr id="wam-table__loaded-resourse-<?php echo md5($resource_handle . $resource_type . $item['url_full']); ?>-conditions" class="wam-table__asset-settings-conditions">
<td colspan="5">
<!--<p>
<input type="checkbox" class="wam-checkbox wam-table__checkbox">
<?php _e('Don\'t optimize file', 'gonzales') ?>
<i class="wam-help-hint wam-tooltip wam-tooltip--bottom" data-tooltip="<?php _e('Youve enabled the &#34;Optimize js scripts?&#34; and &#34;Optimize CSS options&#34; in the &#34;Minify & Combine plugin&#34;. These settings exclude scripts and styles that you dont want to optimize. Press No to add a file to the excluded list.', 'gonzales') ?>"></i>
</p>
<p>
<input type="checkbox" class="wam-checkbox wam-table__checkbox">
<?php _e('Don\'t remove query string (version)', 'gonzales') ?>
<i class="wam-help-hint wam-tooltip wam-tooltip--bottom" data-tooltip="<?php _e('Youve enabled &#34;Remove query strings&#34; from static resources in the &#34;Clearfy&#34; plugin. This list of settings helps you to exclude the necessary scripts and styles with remaining query strings. Press No to add a file to the excluded list.', 'gonzales') ?>"></i>
</p>-->
<p>
<?php _e('<strong> You must set rules to disable the resource.</strong>
For example, if you select Page -> Equals -> All posts, then the script or style will not
loaded on all pages of type post.', 'gonzales') ?>
</p>
<div class="wam-asset-conditions-builder">
<input type="hidden" data-plugin-name="<?php echo esc_attr($plugin_name) ?>" data-resource-type="<?php echo esc_attr($resource_type) ?>" data-resource-handle="<?php echo esc_attr($resource_handle) ?>" class="wam-conditions-builder__settings" value="<?php echo esc_attr($item['visability']) ?>">
</div>
</td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
</table>
</div>

View File

@@ -0,0 +1,48 @@
<?php
defined( 'ABSPATH' ) || die( 'Cheatin uh?' );
/**
* @var array $data
* @var WGZ_Views $this
*/
if ( empty( $data['loaded_plugins'] ) ) {
echo 'Plugins is not found!';
return;
}
$active_plugin = reset( $data['loaded_plugins'] );
?>
<table class="wam-table">
<thead>
<tr>
<th class="wam-table__th-plugins-list"><?php _e( "Plugins", 'gonzales' ) ?></th>
<th class="wam-table__th-plugins-settings"><?php echo $active_plugin['info']['Title']; ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="wam-table__td-plugins-list">
<ul class="wam-nav-plugins">
<?php foreach ( (array) $data['loaded_plugins'] as $plugin_name => $plugin ): ?>
<li class="wam-nav-plugins__tab wam-nav-plugins__tab-load-mode--<?php echo esc_attr( str_replace( '_', '-', $plugin['load_mode'] ) ); ?> js-wam-nav-plugins__tab-switch<?php echo( $active_plugin['name'] == $plugin_name ? ' wam-nav-plugins__tab--active' : '' ) ?>">
<a href="#wam-<?php echo esc_attr( $plugin_name ); ?>">
<strong class="wam-plugin-name"><?php echo $plugin['info']['Title']; ?></strong>
<span><?php _e( 'Author', 'gonzales' ) ?>: <?php echo $plugin['info']['Author']; ?></span>
<span><?php _e( 'Version', 'gonzales' ) ?>: <?php echo $plugin['info']['Version']; ?></span>
</a>
</li>
<?php endforeach; ?>
</ul>
</td>
<td class="wam-table__td-plugins-settings">
<?php foreach ( (array) $data['loaded_plugins'] as $plugin_name => $plugin ): ?>
<div id="wam-<?php echo esc_attr( $plugin_name ); ?>" class="wam-nav-plugins__tab-content<?php echo( $active_plugin['name'] == $plugin_name ? ' js-wam-nav-plugins__tab-content--active' : '' ) ?>">
<?php $this->print_template( 'part-tab-content-assets-plugins-settings', $plugin ); ?>
</div>
<?php endforeach; ?>
</td>
</tr>
</tbody>
</table> <!-- /end .wam-table -->

View File

@@ -0,0 +1,88 @@
<?php
defined('ABSPATH') || die('Cheatin uh?');
/**
* @var array $data
* @var WGZ_Views $this
*/
if( empty($data['assets']) ) {
echo 'Assets is not found!';
return;
}
?>
<table class="wam-table">
<tr>
<th class="wam-table__th-actions"><?php _e('Actions', 'gonzales') ?></th>
<th class="wam-table__th-type"><?php _e('Type', 'gonzales') ?></th>
<th class="wam-table__th-handle"><?php _e('Handle/Source', 'gonzales') ?></th>
<th class="wam-table__th-version"><?php _e('Version', 'gonzales') ?></th>
<th class="wam-table__th-size"><?php _e('Size', 'gonzales') ?></th>
</tr>
<?php if( !empty($data['assets']) ): ?>
<?php foreach((array)$data['assets'] as $resource_type => $assets): ?>
<?php foreach((array)$assets as $resource_handle => $item): ?>
<tr data-size="<?php echo esc_attr($item['size']); ?>" data-group-type="<?php echo esc_attr($data['type']) ?>" data-resource-type="<?php echo esc_attr($resource_type) ?>" data-resource-handle="<?php echo esc_attr($resource_handle) ?>" data-asset-handle="<?php echo esc_attr($resource_handle . '-' . $resource_type); ?>" class="js-wam-asset js-wam-<?php echo esc_attr($resource_type); ?>-asset wam-table__asset-settings<?php echo $item['row_classes']; ?>" id="wam-table__loaded-resourse-<?php echo md5($resource_handle . $resource_type . $item['url_full']); ?>">
<td class="wam-table__td-actions">
<select class="wam-select<?php echo $item['select_control_classes']; ?> js-wam-select-asset-load-mode">
<option value="enable"<?php selected('enable', $item['load_mode']) ?>>
<?php _e('Enable', 'gonzales') ?>
</option>
<option value="disable"<?php selected('disable', $item['load_mode']) ?>>
<?php _e('Disable', 'gonzales') ?>
</option>
</select>
<button class="wam-button wam-button--default wam-button__icon js-wam-button__icon--cogs js-wam-open-asset-settings<?php echo esc_attr($item['settings_button_classes']); ?>"></button>
</td>
<td class="wam-table__td-type">
<span class="wam-asset-type wam-asset-type--<?php echo esc_attr($resource_type); ?>">
<?php echo esc_attr($resource_type); ?>
</span>
</td>
<td class="wam-table__td-handle">
<?php echo esc_html($resource_handle); ?><br>
<a href="<?php echo esc_url($item['url_full']); ?>">
<?php echo esc_html($item['url_short']); ?>
</a>
<?php do_action('wam/views/assets/handle_column/after_url', $item); ?>
<div class="wam-table__handle-deps">
<?php if( !empty($item['deps']) ): ?>
<span class="wam-colors--grey"><?php _e('Dependency by', 'gonzales') ?></span>:
<span class="wam-table__asset-deps js-wam-table__asset-deps">
<?php echo implode(', ', $item['deps']); ?>
</span><br>
<?php endif; ?>
<?php if( !empty($item['requires']) ): ?>
<span class="wam-colors--red"><?php _e('Requires for', 'gonzales') ?></span>:
<span class="wam-table__asset-requires js-wam-table__asset-requires">
<?php echo implode(', ', $item['requires']); ?>
</span>
<?php endif; ?>
</div>
</td>
<td class="wam-assets__table-td-version"><?php echo esc_html($item['ver']); ?></td>
<td class="wam-assets__table-td-size"><?php echo esc_html($item['size']); ?> KB</td>
</tr>
<tr id="wam-table__loaded-resourse-<?php echo md5($resource_handle . $resource_type . $item['url_full']); ?>-conditions" class="wam-table__asset-settings-conditions">
<td colspan="5">
<!-- <p>
<input type="checkbox" class="wam-checkbox wam-table__checkbox">
<?php _e('Don\'t remove query string (version)', 'gonzales') ?>
<i class="wam-help-hint wam-tooltip wam-tooltip--bottom" data-tooltip="<?php _e('Youve enabled &#34;Remove query strings&#34; from static resources in the &#34;Clearfy&#34; plugin. This list of settings helps you to exclude the necessary scripts and styles with remaining query strings. Press No to add a file to the excluded list.', 'gonzales') ?>"></i>
</p>-->
<p>
<?php _e('<strong> You must set rules to disable the resource.</strong>
For example, if you select Page -> Equals -> All posts, then the script or style will not
loaded on all pages of type post.', 'gonzales') ?>
</p>
<div class="wam-asset-conditions-builder">
<input type="hidden" data-group-type="<?php echo esc_attr($data['type']) ?>" data-resource-type="<?php echo esc_attr($resource_type) ?>" data-resource-handle="<?php echo esc_attr($resource_handle) ?>" class="wam-conditions-builder__settings" value="<?php echo esc_attr($item['visability']) ?>">
</div>
</td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
</table>

View File

@@ -0,0 +1,43 @@
<?php
/**
* Activator for the cyrlitera
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 09.03.2018, Webcraftic
* @see Wbcr_Factory480_Activator
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class WCACHE_Activation extends Wbcr_Factory480_Activator {
/**
* Runs activation actions.
*
* @since 1.0.0
*/
public function activate()
{
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
try {
WCL_Cache::activate();
} catch( Exception $e ) {
//nothing
}
}
public function deactivate()
{
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
try {
WCL_Cache::deactivate();
} catch( Exception $e ) {
//nothing
}
}
}

View File

@@ -0,0 +1,238 @@
<?php
/**
* Clearfy quick start options
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright (c) 03.06.2020, Webcraftic
* @version 1.0
*/
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
add_filter("wbcr_clearfy_group_options", function ($options) {
$options[] = [
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'dont_cache_for_logged_in_users',
'title' => __('Don\'t cache for logged-in users', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'cache_reject_uri',
'title' => __('Never Cache URL(s)', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'preload_cache',
'title' => __('Preload cache', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'clear_cache_for_newpost',
'title' => __('Clear cache for new post', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'exclude_files',
'title' => __('Filenames that can be cached', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'exclude_pages',
'title' => __('Rejected User Agents', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'cache_mobile',
'title' => __('Mobile', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'cache_mobile_theme',
'title' => __('Create cache for mobile theme', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'widget_cache',
'title' => __('Widget Cache', 'clearfy'),
'tags' => ['optimize_performance']
];
return $options;
});
add_action('wclearfy/setup_wizard/speed_optimize_step/continue_step', function () {
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
try {
\WCL_Cache_Helpers::modifyHtaccess();
} catch( \Exception $e ) {
}
});
add_filter('wclearfy/setup_wizard/speed_optimize_step/form_options', function ($options) {
array_unshift($options, [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('This option enable cache to generates static html files from your dynamic WordPress blog. After a html file is generated your webserver will serve that file instead of processing the comparatively heavier and more expensive WordPress PHP scripts.', 'clearfy'),
'default' => true
], [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the size of page decrease the page load time a lot. You can reduce the size of page with GZIP compression feature.
If the size of requested files are big, loading takes time so in this case there is needed to reduce the size of files. Gzip Compression feature compresses the pages and resources before sending so the transfer time is reduced.', 'clearfy'),
'default' => false
], [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the load times of pages by storing commonly used files from your website on your visitors browser.
A browser loads the css, js, images resources to display the web page to the visitors. This process is always performed.
If the commonly used files are cached by browser, the visitors browsers do not have to load them evert time so the load times of pages are reduced.', 'clearfy'),
'default' => false
]);
return $options;
});
add_action('wclearfy/cache/settings_page/after_form_save', function () {
if( WCL_Cache_Helpers::is_nginx() && WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
wp_redirect(WCL_Plugin::app()->getPluginPageUrl('clearfy_cache_nginx_rules'));
exit;
}
}, 10);
add_action('wbcr/factory/pages/impressive/print_all_notices', function ($plugin, $page) {
if( "clearfy_cache" === $page->id ) {
if( WCL_Cache_Helpers::is_nginx() && WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
$button = '<br><a class="btn btn-default" href="' . WCL_Plugin::app()->getPluginPageUrl('clearfy_cache_nginx_rules') . '">NGINX configuration</a>';
$page->printWarningNotice("<p>" . __("Clearfy will work out of the box on NGINX servers. But if you want to get the best performance results, place the NGINX rules we generated in your server config. It enables NGINX to directly serve previously cached files without calling WordPress or any PHP. It also adds headers to cached CSS, JS, and images via browser cache.", 'wbcr_factory_pages_480') . "</p>" . $button);
}
}
}, 10, 2);
add_filter('wclearfy/cache/htaccess_rules', function ($htaccess) {
$gzip = WCL_Plugin::app()->getPopulateOption('gzip');
if( $gzip ) {
$data = "# BEGIN GzipWClearfyCache" . "\n" . "<IfModule mod_deflate.c>" . "\n" . "AddType x-font/woff .woff" . "\n" . "AddType x-font/ttf .ttf" . "\n" . "AddOutputFilterByType DEFLATE image/svg+xml" . "\n" . "AddOutputFilterByType DEFLATE text/plain" . "\n" . "AddOutputFilterByType DEFLATE text/html" . "\n" . "AddOutputFilterByType DEFLATE text/xml" . "\n" . "AddOutputFilterByType DEFLATE text/css" . "\n" . "AddOutputFilterByType DEFLATE text/javascript" . "\n" . "AddOutputFilterByType DEFLATE application/xml" . "\n" . "AddOutputFilterByType DEFLATE application/xhtml+xml" . "\n" . "AddOutputFilterByType DEFLATE application/rss+xml" . "\n" . "AddOutputFilterByType DEFLATE application/javascript" . "\n" . "AddOutputFilterByType DEFLATE application/x-javascript" . "\n" . "AddOutputFilterByType DEFLATE application/x-font-ttf" . "\n" . "AddOutputFilterByType DEFLATE x-font/ttf" . "\n" . "AddOutputFilterByType DEFLATE application/vnd.ms-fontobject" . "\n" . "AddOutputFilterByType DEFLATE font/opentype font/ttf font/eot font/otf" . "\n" . "</IfModule>" . "\n";
if( defined("WCLEARFY_GZIP_FOR_COMBINED_FILES") && WCLEARFY_GZIP_FOR_COMBINED_FILES ) {
$data = $data . "\n" . '<FilesMatch "\d+index\.(css|js)(\.gz)?$">' . "\n" . "# to zip the combined css and js files" . "\n\n" . "RewriteEngine On" . "\n" . "RewriteCond %{HTTP:Accept-encoding} gzip" . "\n" . "RewriteCond %{REQUEST_FILENAME}\.gz -s" . "\n" . "RewriteRule ^(.*)\.(css|js) $1\.$2\.gz [QSA]" . "\n\n" . "# to revent double gzip and give the correct mime-type" . "\n\n" . "RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1,E=FORCE_GZIP]" . "\n" . "RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1,E=FORCE_GZIP]" . "\n" . "Header set Content-Encoding gzip env=FORCE_GZIP" . "\n" . "</FilesMatch>" . "\n";
}
$data = $data . "# END GzipWClearfyCache" . "\n";
$htaccess = preg_replace("/\s*\#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache\s*/s", "", $htaccess);
return $data . $htaccess;
} else {
//delete gzip rules
$htaccess = preg_replace("/\s*\#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache\s*/s", "", $htaccess);
return $htaccess;
}
});
add_filter('wclearfy/cache/htaccess_rules', function ($htaccess) {
$browser_caching = WCL_Plugin::app()->getPopulateOption('browser_caching');
if( $browser_caching ) {
$data = "
# BEGIN LBCWClearfyCache
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault 'access plus 1 month'
ExpiresByType text/cache-manifest 'access plus 0 seconds'
ExpiresByType text/html 'access plus 0 seconds'
ExpiresByType text/xml 'access plus 0 seconds'
ExpiresByType application/xml 'access plus 0 seconds'
ExpiresByType application/json 'access plus 0 seconds'
ExpiresByType application/rss+xml 'access plus 1 hour'
ExpiresByType application/atom+xml 'access plus 1 hour'
ExpiresByType image/x-icon 'access plus 1 week'
ExpiresByType image/gif 'access plus 4 months'
ExpiresByType image/png 'access plus 4 months'
ExpiresByType image/jpeg 'access plus 4 months'
ExpiresByType image/webp 'access plus 4 months'
ExpiresByType video/ogg 'access plus 4 months'
ExpiresByType audio/ogg 'access plus 4 months'
ExpiresByType video/mp4 'access plus 4 months'
ExpiresByType video/webm 'access plus 4 months'
ExpiresByType text/x-component 'access plus 1 month'
ExpiresByType font/ttf 'access plus 4 months'
ExpiresByType font/otf 'access plus 4 months'
ExpiresByType font/woff 'access plus 4 months'
ExpiresByType font/woff2 'access plus 4 months'
ExpiresByType image/svg+xml 'access plus 1 month'
ExpiresByType application/vnd.ms-fontobject 'access plus 1 month'
ExpiresByType text/css 'access plus 1 year'
ExpiresByType application/javascript 'access plus 1 year'
</IfModule>
# END LBCWClearfyCache";
if( !preg_match("/BEGIN\s*LBCWClearfyCache/", $htaccess) ) {
return $data . $htaccess;
} else {
return $htaccess;
}
} else {
//delete levere browser caching
$htaccess = preg_replace("/#\s?BEGIN\s?LBCWClearfyCache.*?#\s?END\s?LBCWClearfyCache/s", "", $htaccess);
return $htaccess;
}
});
//add_action('wfactory/activated_' . WCL_Plugin::app()->getPluginName() . '_component', function ($component_name) {
//todo: Проверить совместимость с плагинами, включить или отключить компонент в зависимсти от результатов
//});

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,221 @@
<?php
/**
* The page Settings.
*
* @since 1.0.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WBCR\Factory_Templates_134\Pages\PageBase' ) ) {
return;
}
class WCL_CacheProNginxRulesPage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* The id of the page in the admin menu.
*
* Mainly used to navigate between pages.
*
* @see FactoryPages480_AdminPage
*
* @since 1.0.0
* @var string
*/
public $id = "clearfy_cache_nginx_rules";
/**
* @var string
*/
public $page_parent_page = "none";
/**
* @var string
*/
public $page_menu_dashicon = 'dashicons-clock';
/**
* @var bool
*/
//public $internal = false;
/**
* @var string
*/
public $type = 'page';
public $available_for_multisite = true;
/**
* Show on the page a search form for search options of plugin?
*
* @since 2.2.0 - Added
* @var bool - true show, false hide
*/
public $show_search_options_form = false;
/**
* @param WCL_Plugin $plugin
*/
public function __construct(WCL_Plugin $plugin)
{
$this->menu_title = __('Nginx Rules', 'clearfy');
parent::__construct($plugin);
$this->plugin = $plugin;
}
public function getPageTitle()
{
return __('Nginx Rules', 'clearfy');
}
public function showPageContent()
{
?>
<div class="form-group">
<h2><?php
_e('Nginx Configuration Rules', 'clearfy') ?></h2>
<p>
<?php
_e('It enables NGINX to directly serve previously cached files without calling WordPress or any PHP. It also adds headers to cached CSS, JS, and images via browser cache.', 'clearfy') ?>
</p>
<p>
<?php
_e('Unfortunately, our plugin does not have the ability to automatically configure the nginx server. You have to copy the rules below and paste into your server config file.', 'clearfy') ?>
</p>
<p>
<?php
_e('Copy and paste the following code snippet in the server { } block of “default” file (or whatever the file is being used) located in /etc/nginx/sites-enabled/. Make sure to remove the existing location / { } block before using the one in the following code snippet.', 'clearfy') ?>
</p>
<div class="control-group">
<textarea row="50" cols="100" style="height: 500px;">
<?php
echo $this->generate_base_nginx_rules();
echo $this->generate_browser_cache_rules();
echo $this->generate_gzip_rules();
?>
</textarea>
</div>
</div>
<?php
}
protected function generate_base_nginx_rules()
{
$rules = "
#####
#CLEARFY CACHE RULES
#
set \$clearfy_bypass 1; # Should NGINX bypass WordPress and call cache file directly ?
set \$condition '';
# Do not bypass if it's a POST request
if (\$request_method = POST) {
set \$clearfy_bypass 0;
set \$clearfy_reason \"POST request\";
set \$condition \"null\";
}
# Do not bypass if arguments are found (e.g. ?page=2)
if (\$is_args) {
set \$clearfy_bypass 0;
set \$clerfy_reason \"Arguments found\";
set \$condition \"null\";
}
# Do not bypass if the site is in maintenance mode
if (-f \"\$document_root/.maintenance\") {
set \$clearfy_bypass 0;
set \$clearfy_reason \"Maintenance mode\";
set \$condition \"null\";
}
# Do not bypass if one of those cookie if found
# wordpress_logged_in_[hash] : When a user is logged in, this cookie is created (we'd rather let WP-Rocket handle that)
# wp-postpass_[hash] : When a protected post requires a password, this cookie is created.
if (\$http_cookie ~* \"(wordpress_logged_in_|wp\-postpass_|woocommerce_items_in_cart|woocommerce_cart_hash|wptouch_switch_toogle|comment_author_|comment_author_email_)\") {
set \$clearfy_bypass 0;
set \$clearfy_reason \"Cookie\";
set \$condition \"null\";
}
set \$fullurl '/wp-content/cache/all\${condition}';
#CACHE ENDING
location / {
set \$serve_url \$fullurl\${uri}index.html;
add_header X-Clearfy-Cache-Location \$serve_URL;
try_files \$serve_url \$uri \$uri/ /index.php\$is_args\$args;
}
# Debug header (when file is not cached)
add_header X-Clearfy-Nginx-Serving-Static \$clearfy_is_bypassed;
add_header X-Clearfy-Nginx-Reason \$clearfy_reason;
add_header X-Clearfy-Nginx-File \$clearfy_file;
";
return $rules;
}
private function generate_gzip_rules()
{
$rules = '
#####
# BROWSER CSS CACHE
#
location ~ /wp-content/cache/all/.*html$ {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types image/svg+xml text/plain text/html text/xml text/css text/javascript application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript application/x-font-ttf application/vnd.ms-fontobject font/opentype font/ttf font/eot font/otf;
}
';
return $rules;
}
private function generate_browser_cache_rules()
{
$rules = '
#####
# BROWSER CSS CACHE
#
location ~* \.css$ {
etag on;
gzip_vary on;
expires 30d;
}';
$rules .= '
####
# BROWSER JS CACHE
#
location ~* \.js$ {
etag on;
gzip_vary on;
expires 30d;
}';
$rules .= '
####
# BROWSER MEDIA CACHE
#
location ~* \.(ico|gif|jpe?g|png|svg|eot|otf|woff|woff2|ttf|ogg)$ {
etag on;
expires 30d;
}';
return $rules;
}
}

View File

@@ -0,0 +1,328 @@
<?php
/**
* The page Settings.
*
* @since 1.0.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class WCACHE_CachePage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* @see {@inheritDoc}
*
* @var string
*/
public $id = "clearfy_cache";
/**
* @var string
*/
public $page_parent_page = 'performance';
/**
* @see {@inheritDoc}
*
* @var string
*/
public $page_menu_dashicon = 'dashicons-performance';
/**
* @see {@inheritDoc}
*
* @var int
*/
public $page_menu_position = 20;
/**
* @see {@inheritDoc}
*
* @var bool
*/
//public $available_for_multisite = true;
protected $errors = [
98 => "<label>.htaccess was not found</label> <a target='_blank' href='http://www.wpfastestcache.com/warnings/htaccess-was-not-found/'>Read More</a>",
99 => "define('WP_CACHE', true); is needed to be added into wp-config.php",
100 => "You have to set <strong><u><a href=" . "'/wp-admin/options-permalink.php'>permalinks</a></u></strong>",
101 => "Fast Velocity Minify needs to be deactivated",
102 => 'Far Future Expiration Plugin needs to be deactivated',
103 => "SG Optimizer needs to be deactived",
104 => "AdRotate needs to be deactived",
105 => "MobilePress needs to be deactived",
106 => "Speed Booster Pack needs to be deactived",
107 => "WP Performance Score Booster needs to be deactivated<br>This plugin has aldready Gzip, Leverage Browser Caching features",
109 => "Check and Enable GZIP compression needs to be deactivated<br>This plugin has aldready Gzip feature",
110 => "GZippy needs to be deactivated<br>This plugin has aldready Gzip feature",
111 => "GZip Ninja Speed Compression needs to be deactivated<br>This plugin has aldready Gzip feature",
112 => "WordPress Gzip Compression needs to be deactivated<br>This plugin has aldready Gzip feature",
113 => "GZIP Output needs to be deactivated<br>This plugin has aldready Gzip feature",
114 => "Head Cleaner needs to be deactivated",
115 => "Far Future Expiration Plugin needs to be deactivated",
];
/**
* @param WCL_Plugin $plugin
*/
public function __construct(WCL_Plugin $plugin)
{
$this->menu_title = __('Cache', 'clearfy');
$this->page_menu_short_description = __('Cache pages', 'clearfy');
if( $plugin->premium->is_activate() && $plugin->premium->is_install_package() ) {
$this->available_for_multisite = true;
}
parent::__construct($plugin);
$this->plugin = $plugin;
}
/**
* We register notifications for some actions
*
* @param $notices
* @param \Wbcr_Factory480_Plugin $plugin
*
* @return array
* @see libs\factory\pages\themplates\FactoryPages480_ImpressiveThemplate
*/
public function getActionNotices($notices)
{
$notices[] = [
'conditions' => [
'wclearfy-cache-cleared' => 1
],
'type' => 'success',
'message' => 'Cache has been cleared!'
];
foreach($this->errors as $key => $error_message) {
$notices[] = [
'conditions' => [
'wclearfy-cache-error' => $key
],
'type' => 'danger',
'message' => $error_message
];
}
return $notices;
}
/**
* Permalinks options.
*
* @return mixed[]
* @since 1.0.0
*/
public function getPageOptions()
{
$options = [];
$options[] = [
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header">' . __('<strong>Cache settings</strong>', 'clearfy') . '<p>' . __('A very fast caching engine for WordPress that produces static html files. You can configure caching in this section.', 'clearfy') . '</p></div>'
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('This option enable cache to generates static html files from your dynamic WordPress blog. After a html file is generated your webserver will serve that file instead of processing the comparatively heavier and more expensive WordPress PHP scripts.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'dont_cache_for_logged_in_users',
'title' => __('Don\'t cache for logged-in users', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Don\'t show the cached version for logged-in users', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the size of page decrease the page load time a lot. You can reduce the size of page with GZIP compression feature.
If the size of requested files are big, loading takes time so in this case there is needed to reduce the size of files. Gzip Compression feature compresses the pages and resources before sending so the transfer time is reduced.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the load times of pages by storing commonly used files from your website on your visitors browser.
A browser loads the css, js, images resources to display the web page to the visitors. This process is always performed.
If the commonly used files are cached by browser, the visitors browsers do not have to load them evert time so the load times of pages are reduced.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_uri',
'title' => __('Never Cache URL(s)', 'clearfy'),
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Specify URLs of pages or posts that should never be cached (one per line). The domain part of the URL will be stripped automatically.
Use (.*) wildcards to address multiple URLs under a given path.', 'clearfy'),
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_user_agents',
'title' => __('Rejected User Agents', 'clearfy'),
'default' => "facebookexternalhit\nTwitterbot\nLinkedInBot\nWhatsApp\nMediatoolkitbot",
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Strings in the HTTP User Agent header that prevent WP-Cache from caching bot, spiders, and crawlers requests. Note that super cached files are still sent to these agents if they already exists.', 'clearfy'),
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_cookies',
'title' => __('Rejected Cookies', 'clearfy'),
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Do not cache pages when these cookies are set. Add the cookie names here, one per line. Matches on fragments, so "test" will match "WordPress_test_cookie". (Simple caching only)', 'clearfy'),
];
$options[] = [
'type' => 'more-link',
'name' => 'cache-group',
'title' => __('Advanced options', 'clearfy'),
'count' => 8,
'items' => [
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'cache_mobile',
'title' => __('Mobile', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __("Don't show the cached version for desktop to mobile devices", 'clearfy'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'cache_mobile_theme',
'title' => __('Create cache for mobile theme', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('If you use a mobile theme, you should enable both “Mobile” and “Create cache for mobile theme” options. If you use a responsive theme, no need to use the mobile cache feature. You should disable “Mobile” and “Create cache for mobile theme” options.', 'clearfy'),
'default' => false,
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'widget_cache',
'title' => __('Widget Cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('You can reduce the number of sql queries with this feature.
When “Cache System” is enabled, the page is saved as a static html file, thus PHP and MySQL does not work for the page which has been cached. MySQL and PHP work to generate the html of the other pages which have not been cached yet.
Every time before the cache is created, the same widgets are generated again and again. This feature avoids generating the widgets again and again to reduce the sql queries.', 'clearfy'),
'default' => true,
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'preload_cache',
'title' => __('Preload cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('The preload feature stars to work after delete cache.
When the Preload feature calls the urls, the cache of urls are created automatically. When all the pages are cached, the preload stops working. When the cache is clear, it starts working again.
The Preload runs every 5 minutes. If you want set a specific interval. Note: The preload feature works with the WP_CRON system.', 'clearfy'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'clear_cache_for_newpost',
'title' => __('Clear cache for new post', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clear cache files when a post or page is published', 'clearfy'),
'default' => true
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'clear_cache_for_updated_post',
'title' => __('Clear cache for updated Post', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clear cache files when a post or page is updated', 'clearfy'),
'default' => true
],
[
'type' => 'textarea',
'name' => 'exclude_files',
'title' => __('Filenames that can be cached', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Add here those filenames that can be cached, even if they match one of the rejected substring specified above.', 'clearfy'),
'default' => 'wp-comments-popup.php
wp-links-opml.php
wp-locations.php
'
],
[
'type' => 'textarea',
'name' => 'exclude_pages',
'title' => __('Rejected User Agents', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Strings in the HTTP User Agent header that prevent WP-Cache from caching bot, spiders, and crawlers requests. Note that super cached files are still sent to these agents if they already exists.', 'clearfy'),
'default' => 'bot
ia_archive
slurp
crawl
spider
Yandex
'
]
]
];
$form_options = [];
$form_options[] = [
'type' => 'form-group',
'items' => $options,
//'cssClass' => 'postbox'
];
return apply_filters('wclearfy_cache_form_options', $form_options, $this);
}
public function afterFormSave()
{
try {
do_action("wclearfy/cache/settings_page/after_form_save");
WCL_Cache_Helpers::modifyHtaccess();
} catch( Exception $e ) {
if( !empty($e->getCode()) && isset($this->errors[$e->getCode()]) ) {
$this->redirectToAction('index', ['wclearfy-cache-error' => $e->getCode()]);
}
}
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Plugin Name: Webcraftic Clearfy Cache
* Plugin URI: https://webcraftic.com
* Description: Webcraftic Clearfy Cache
* Author: Webcraftic <wordpress.webraftic@gmail.com>
* Version: 1.0.3
* Text Domain: clearfy_cache
* Domain Path: /languages/
* Author URI: https://webcraftic.com
* Framework Version: FACTORY_480_VERSION
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Developers who contributions in the development plugin:
*
* Alexander Kovalev
* ---------------------------------------------------------------------------------
* Full plugin development.
*
* Email: alex.kovalevv@gmail.com
* Personal card: https://alexkovalevv.github.io
* Personal repo: https://github.com/alexkovalevv
* ---------------------------------------------------------------------------------
*/
/**
* -----------------------------------------------------------------------------
* CHECK REQUIREMENTS
* Check compatibility with php and wp version of the user's site. As well as checking
* compatibility with other plugins from Webcraftic.
* -----------------------------------------------------------------------------
*/
//todo: Fill the file if need release alone plugin

View File

@@ -0,0 +1,52 @@
<?php
/**
* Этот файл инициализирует этот плагин, как аддон для плагина Clearfy.
*
* Файл будет подключен только в плагине Clearfy, используя особый вариант загрузки. Это более простое решение
* пришло на смену встроенной системы подключения аддонов в фреймворке.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
if( !defined('WCACHE_PLUGIN_ACTIVE') ) {
define('WCACHE_PLUGIN_VERSION', '1.0.3');
define('WCACHE_TEXT_DOMAIN', 'clearfy_cache');
define('WCACHE_PLUGIN_ACTIVE', true);
// Этот плагин загружен, как аддон для плагина Clearfy
define('LOADING_CLEARFY_CACHE_AS_ADDON', true);
if( !defined('WCACHE_PLUGIN_DIR') ) {
define('WCACHE_PLUGIN_DIR', dirname(__FILE__));
}
if( !defined('WCACHE_PLUGIN_BASE') ) {
define('WCACHE_PLUGIN_BASE', plugin_basename(__FILE__));
}
if( !defined('WCACHE_PLUGIN_URL') ) {
define('WCACHE_PLUGIN_URL', plugins_url('', __FILE__));
}
try {
// Global scripts
require_once(WCACHE_PLUGIN_DIR . '/includes/3rd-party/class-clearfy-plugin.php');
new WCACHE_Plugin();
} catch( Exception $e ) {
$wcache_plugin_error_func = function () use ($e) {
$error = sprintf("The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Clearfy Cache', $e->getMessage(), $e->getCode());
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action('admin_notices', $wcache_plugin_error_func);
add_action('network_admin_notices', $wcache_plugin_error_func);
}
}

View File

@@ -0,0 +1,135 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Clearfy cache
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
* @version 1.0
*/
class WCACHE_Plugin {
/**
* @see self::app()
* @var WCL_Plugin
*/
private static $app;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct()
{
if( !class_exists('WCL_Plugin') ) {
throw new Exception('Plugin Clearfy is not installed!');
}
self::$app = WCL_Plugin::app();
$this->global_scripts();
if( is_admin() ) {
$this->admin_scripts();
}
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return WCL_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
protected function init_activation()
{
include_once(WCACHE_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WCACHE_Activation');
}
/**
* @throws \Exception
* @since 1.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function register_pages()
{
self::app()->registerPage('WCACHE_CachePage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-performance-cache.php');
self::app()->registerPage('WCL_CacheProNginxRulesPage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-nginx-rules.php');
}
/**
* @throws \Exception
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
require(WCACHE_PLUGIN_DIR . '/admin/boot.php');
$this->init_activation();
}
private function global_scripts()
{
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
if( self::app()->getPopulateOption('enable_cache') ) {
if( self::app()->getPopulateOption('widget_cache') ) {
require_once WCACHE_PLUGIN_DIR . "/includes/widget-cache.php";
WCL_WidgetCache::action();
}
}
if( self::app()->getPopulateOption('cache_mobile_theme') ) {
require_once WCACHE_PLUGIN_DIR . '/includes/mobile-cache.php';
}
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,100 @@
<?php
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/create-cache.php';
class WCL_Cache {
public function __construct()
{
add_action('transition_post_status', array($this, 'on_all_status_transitions'), 10, 3);
add_action('init', function () {
if (current_user_can('manage_options') && isset($_GET['wclearfy_cache_delete'])) {
check_admin_referer('wclearfy_cache_delete_action');
WCL_Cache_Helpers::deleteCache();
wp_redirect(esc_url_raw(remove_query_arg(['wclearfy_cache_delete', '_wpnonce'])));
die();
}
});
if( !is_admin() ) {
if( isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] ) {
$cache = new WCL_Create_Cache();
$cache->createCache();
}
}
}
public function on_all_status_transitions($new_status, $old_status, $post)
{
if( !WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
return false;
}
if( !wp_is_post_revision($post->ID) ) {
if( isset($post->post_type) ) {
if( $post->post_type == "nf_sub" ) {
return false;
}
}
if( WCL_Plugin::app()->getPopulateOption('clear_cache_for_newpost') ) {
if( $new_status == "publish" && $old_status != "publish" ) {
WCL_Cache_Helpers::deleteHomePageCache();
//to clear category cache and tag cache
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
//to clear widget cache
WCL_Cache_Helpers::deleteWidgetCache();
}
}
if( WCL_Plugin::app()->getPopulateOption('clear_cache_for_updated_post') ) {
if( $new_status == "publish" && $old_status == "publish" ) {
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
//to clear widget cache
WCL_Cache_Helpers::deleteWidgetCache();
}
}
if( $new_status == "trash" && $old_status == "publish" ) {
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
} else if( ($new_status == "draft" || $new_status == "pending" || $new_status == "private") && $old_status == "publish" ) {
WCL_Cache_Helpers::deleteCache();
}
}
}
public static function activate()
{
if( WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
WCL_Cache_Helpers::modifyHtaccess();
}
}
public static function deactivate()
{
$path = ABSPATH;
if( WCL_Cache_Helpers::is_subdirectory_install() ) {
$path = WCL_Cache_Helpers::getABSPATH();
}
if( is_file($path . ".htaccess") && is_writable($path . ".htaccess") ) {
$htaccess = file_get_contents($path . ".htaccess");
$htaccess = preg_replace("/#\s?BEGIN\s?WClearfyCache.*?#\s?END\s?WClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?LBCWClearfyCache.*?#\s?END\s?LBCWClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?WEBPWClearfyCache.*?#\s?END\s?WEBPWClearfyCache/s", "", $htaccess);
@file_put_contents($path . ".htaccess", $htaccess);
}
//$wclearfy->deleteCache();
}
}
new WCL_Cache();

View File

@@ -0,0 +1,132 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Transliteration core class
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 19.02.2018, Webcraftic
*/
class WCACHE_Plugin extends Wbcr_Factory480_Plugin {
/**
* @see self::app()
* @var Wbcr_Factory480_Plugin
*/
private static $app;
/**
* @since 1.1.0
* @var array
*/
private $plugin_data;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct($plugin_path, $data)
{
parent::__construct($plugin_path, $data);
self::$app = $this;
$this->plugin_data = $data;
$this->global_scripts();
if( is_admin() ) {
$this->admin_scripts();
}
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return \Wbcr_Factory480_Plugin|\WCTR_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
protected function init_activation()
{
include_once(WCACHE_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WCACHE_Activation');
}
/**
* @throws \Exception
* @since 1.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function register_pages()
{
$this->registerPage('WCACHE_CachePage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-performance-cache.php');
}
/**
* @throws \Exception
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
$this->init_activation();
}
private function global_scripts()
{
require_once WCACHE_PLUGIN_DIR . '/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
if( is_admin() ) {
require(WCACHE_PLUGIN_DIR . '/admin/boot.php');
if( class_exists('WCL_CachePage') ) {
WCL_Plugin::app()->registerPage('WCL_CacheProPage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-cache.php');
}
}
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
}
}

View File

@@ -0,0 +1,921 @@
<?php
class WCL_Create_Cache {
public $options = [];
public $cdn;
private $startTime;
private $blockCache = false;
private $err = "";
public $cacheFilePath = "";
public $exclude_rules = false;
public $preload_user_agent = false;
public $current_page_type = false;
public $current_page_content_type = false;
public $exclude_current_page_text = false;
public function __construct()
{
//to fix: PHP Notice: Undefined index: HTTP_USER_AGENT
$_SERVER['HTTP_USER_AGENT'] = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] ? strip_tags($_SERVER['HTTP_USER_AGENT']) : "Empty User Agent";
if( preg_match("/(WP\sFastest\sCache\sPreload(\siPhone\sMobile)?\s*Bot)/", $_SERVER['HTTP_USER_AGENT']) ) {
$this->preload_user_agent = true;
} else {
$this->preload_user_agent = false;
}
//$this->set_cdn();
$this->set_cache_file_path();
}
public function detect_current_page_type()
{
if( preg_match("/\?/", $_SERVER["REQUEST_URI"]) ) {
return true;
}
if( preg_match("/^\/wp-json/", $_SERVER["REQUEST_URI"]) ) {
return true;
}
if( is_front_page() ) {
echo "<!--WCLEARFY_PAGE_TYPE_homepage-->";
} else if( is_category() ) {
echo "<!--WCLEARFY_PAGE_TYPE_category-->";
} else if( is_tag() ) {
echo "<!--WCLEARFY_PAGE_TYPE_tag-->";
} else if( is_singular('post') ) {
echo "<!--WCLEARFY_PAGE_TYPE_post-->";
} else if( is_page() ) {
echo "<!--WCLEARFY_PAGE_TYPE_page-->";
} else if( is_attachment() ) {
echo "<!--WCLEARFY_PAGE_TYPE_attachment-->";
} else if( is_archive() ) {
echo "<!--WCLEARFY_PAGE_TYPE_archive-->";
}
}
public function set_exclude_rules()
{
if( $json_data = get_option("WClearfyCacheExclude") ) {
$this->exclude_rules = json_decode($json_data);
}
}
public function set_cache_file_path()
{
$type = "all";
if( WCL_Cache_Helpers::isMobile() && WCL_Plugin::app()->getPopulateOption('cache_mobile') ) {
if( class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$type = "wclearfy-mobile-cache";
}
}
if( WCL_Cache_Helpers::isPluginActive('gtranslate/gtranslate.php') ) {
if( isset($_SERVER["HTTP_X_GT_LANG"]) ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["HTTP_X_GT_LANG"] . $_SERVER["REQUEST_URI"];
} else if( isset($_SERVER["REDIRECT_URL"]) && $_SERVER["REDIRECT_URL"] != "/index.php" ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REDIRECT_URL"];
} else if( isset($_SERVER["REQUEST_URI"]) ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REQUEST_URI"];
}
} else {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REQUEST_URI"];
// for /?s=
$this->cacheFilePath = preg_replace("/(\/\?s\=)/", "$1/", $this->cacheFilePath);
}
$this->cacheFilePath = $this->cacheFilePath ? rtrim($this->cacheFilePath, "/") . "/" : "";
$this->cacheFilePath = preg_replace("/\/cache\/(all|wclearfy-mobile-cache)\/\//", "/cache/$1/", $this->cacheFilePath);
if( strlen($_SERVER["REQUEST_URI"]) > 1 ) { // for the sub-pages
if( !preg_match("/\.html/i", $_SERVER["REQUEST_URI"]) ) {
if( WCL_Cache_Helpers::is_trailing_slash() ) {
if( !preg_match("/\/$/", $_SERVER["REQUEST_URI"]) ) {
if( defined('WCACHE_QUERYSTRING') && WCACHE_QUERYSTRING ) {
} else if( preg_match("/gclid\=/i", $this->cacheFilePath) ) {
} else if( preg_match("/fbclid\=/i", $this->cacheFilePath) ) {
} else if( preg_match("/utm_(source|medium|campaign|content|term)/i", $this->cacheFilePath) ) {
} else {
$this->cacheFilePath = false;
}
}
} else {
//toDo
}
}
}
$this->remove_url_paramters();
// to decode path if it is not utf-8
if( $this->cacheFilePath ) {
$this->cacheFilePath = urldecode($this->cacheFilePath);
}
// for security
if( preg_match("/\.{2,}/", $this->cacheFilePath) ) {
$this->cacheFilePath = false;
}
if( WCL_Cache_Helpers::isMobile() ) {
if( WCL_Plugin::app()->getPopulateOption('cache_mobile') ) {
if( !class_exists("WCL_MobileCache") ) {
$this->cacheFilePath = false;
} else {
if( !WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$this->cacheFilePath = false;
}
}
}
}
}
public function remove_url_paramters()
{
$action = false;
//to remove query strings for cache if Google Click Identifier are set
if( preg_match("/gclid\=/i", $this->cacheFilePath) ) {
$action = true;
}
//to remove query strings for cache if facebook parameters are set
if( preg_match("/fbclid\=/i", $this->cacheFilePath) ) {
$action = true;
}
//to remove query strings for cache if google analytics parameters are set
if( preg_match("/utm_(source|medium|campaign|content|term)/i", $this->cacheFilePath) ) {
$action = true;
}
if( $action ) {
if( strlen($_SERVER["REQUEST_URI"]) > 1 ) { // for the sub-pages
$this->cacheFilePath = preg_replace("/\/*\?.+/", "", $this->cacheFilePath);
$this->cacheFilePath = $this->cacheFilePath . "/";
define('WCACHE_QUERYSTRING', true);
}
}
}
public function set_cdn()
{
$cdn_values = get_option("WClearfyCacheCDN");
if( $cdn_values ) {
$std_obj = json_decode($cdn_values);
$arr = [];
if( is_array($std_obj) ) {
$arr = $std_obj;
} else {
array_push($arr, $std_obj);
}
foreach($arr as $key => &$std) {
$std->originurl = trim($std->originurl);
$std->originurl = trim($std->originurl, "/");
$std->originurl = preg_replace("/http(s?)\:\/\/(www\.)?/i", "", $std->originurl);
$std->cdnurl = trim($std->cdnurl);
$std->cdnurl = trim($std->cdnurl, "/");
if( !preg_match("/https\:\/\//", $std->cdnurl) ) {
$std->cdnurl = "//" . preg_replace("/http(s?)\:\/\/(www\.)?/i", "", $std->cdnurl);
}
}
$this->cdn = $arr;
}
}
public function checkShortCode($content)
{
if( preg_match("/\[wclearfyNOT\]/", $content) ) {
if( !is_home() || !is_archive() ) {
$this->blockCache = true;
}
$content = str_replace("[wclearfyNOT]", "", $content);
}
return $content;
}
public function createCache()
{
if( !WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
return 0;
}
// to exclude static pdf files
if( preg_match("/\.pdf$/i", $_SERVER["REQUEST_URI"]) ) {
return 0;
}
// to check logged-in user
if( WCL_Plugin::app()->getPopulateOption('dont_cache_for_logged_in_users') ) {
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/wordpress_logged_in/i", $cookie_key) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
// to exclude admin users
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/wordpress_logged_in/i", $cookie_key) ) {
$users_groups = get_users(["role" => "administrator", "fields" => ["user_login"]]);
foreach($users_groups as $user_key => $user_value) {
if( preg_match("/^" . preg_quote($user_value->user_login, "/") . "/", $cookie_value) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
}
// to check comment author
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/comment_author_/i", $cookie_key) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
if( isset($_COOKIE) && isset($_COOKIE['safirmobilswitcher']) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
if( isset($_COOKIE) && isset($_COOKIE["wptouch-pro-view"]) ) {
if( WCL_Cache_Helpers::is_wptouch_smartphone() ) {
if( $_COOKIE["wptouch-pro-view"] == "desktop" ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
if( preg_match("/\?/", $_SERVER["REQUEST_URI"]) && !preg_match("/\/\?fdx\_switcher\=true/", $_SERVER["REQUEST_URI"]) ) { // for WP Mobile Edition
if( preg_match("/\?amp(\=1)?/i", $_SERVER["REQUEST_URI"]) ) {
//
} else if( defined('WCACHE_QUERYSTRING') && WCACHE_QUERYSTRING ) {
//
} else {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
if( preg_match("/(" . WCL_Cache_Helpers::get_excluded_useragent() . ")/", $_SERVER['HTTP_USER_AGENT']) ) {
return 0;
}
if( isset($_SERVER['REQUEST_URI']) && preg_match("/(\/){2}$/", $_SERVER['REQUEST_URI']) ) {
return 0;
}
// to check permalink if it does not end with slash
if( isset($_SERVER['REQUEST_URI']) && preg_match("/[^\/]+\/$/", $_SERVER['REQUEST_URI']) ) {
if( !preg_match("/\/$/", get_option('permalink_structure')) ) {
return 0;
}
}
if( isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "POST" ) {
return 0;
}
if( preg_match("/^https/i", get_option("home")) && !is_ssl() ) {
//Must be secure connection
return 0;
}
if( !preg_match("/^https/i", get_option("home")) && is_ssl() ) {
//must be normal connection
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl/rlrsssl-really-simple-ssl.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl-pro/really-simple-ssl-pro.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl-on-specific-pages/really-simple-ssl-on-specific-pages.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('ssl-insecure-content-fixer/ssl-insecure-content-fixer.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('https-redirection/https-redirection.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('better-wp-security/better-wp-security.php') ) {
return 0;
}
}
}
}
}
}
}
if( preg_match("/www\./i", get_option("home")) && !preg_match("/www\./i", $_SERVER['HTTP_HOST']) ) {
return 0;
}
if( !preg_match("/www\./i", get_option("home")) && preg_match("/www\./i", $_SERVER['HTTP_HOST']) ) {
return 0;
}
if( $this->exclude_page() ) {
echo "<!-- Clearfy Cache: Exclude Page -->"."\n";
return 0;
}
// http://mobiledetect.net/ does not contain the following user-agents
if( preg_match("/Nokia309|Casper_VIA/i", $_SERVER['HTTP_USER_AGENT']) ) {
return 0;
}
if( preg_match("/Empty\sUser\sAgent/i", $_SERVER['HTTP_USER_AGENT']) ) { // not to show the cache for command line
return 0;
}
//to show cache version via php if htaccess rewrite rule does not work
if( !$this->preload_user_agent && $this->cacheFilePath && (@file_exists($this->cacheFilePath . "index.html") || @file_exists($this->cacheFilePath . "index.json") || @file_exists($this->cacheFilePath . "index.xml")) ) {
$via_php = "";
if( @file_exists($this->cacheFilePath . "index.json") ) {
$file_extension = "json";
header('Content-type: application/json');
} else if( @file_exists($this->cacheFilePath . "index.xml") ) {
$file_extension = "xml";
header('Content-type: text/xml');
} else {
$file_extension = "html";
$via_php = "<!-- via php -->";
}
if( $content = @file_get_contents($this->cacheFilePath . "index." . $file_extension) ) {
if( defined('WCLEARFY_REMOVE_VIA_FOOTER_COMMENT') && WCLEARFY_REMOVE_VIA_FOOTER_COMMENT ) {
$via_php = "";
}
$content = $content . $via_php;
die($content);
}
} else {
if( WCL_Cache_Helpers::isMobile() ) {
if( class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
if( WCL_Plugin::app()->getPopulateOption('cache_mobile_theme_name') ) {
$create_cache = true;
} else if( WCL_Cache_Helpers::isPluginActive('wptouch/wptouch.php') || WCL_Cache_Helpers::isPluginActive('wptouch-pro/wptouch-pro.php') ) {
//to check that user-agent exists in wp-touch's list or not
if( WCL_Cache_Helpers::is_wptouch_smartphone() ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else if( WCL_Cache_Helpers::isPluginActive('any-mobile-theme-switcher/any-mobile-theme-switcher.php') ) {
if( WCL_Cache_Helpers::is_anymobilethemeswitcher_mobile() ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else {
if( (preg_match('/iPhone/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Mobile/', $_SERVER['HTTP_USER_AGENT'])) || (preg_match('/Android/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Mobile/', $_SERVER['HTTP_USER_AGENT'])) ) {
$create_cache = true;
} else {
$create_cache = false;
}
}
} else if( !WCL_Plugin::app()->getPopulateOption('cache_mobile') && !WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else {
$create_cache = true;
}
if( $create_cache ) {
$this->startTime = microtime(true);
add_action('wp', [$this, "detect_current_page_type"]);
add_action('get_footer', [$this, "detect_current_page_type"]);
add_action('get_footer', [$this, "wp_print_scripts_action"]);
// to exclude current page hook
add_action("wclearfy_exclude_current_page", [$this, 'exclude_current_page'], 10, 0);
ob_start([$this, "callback"]);
}
}
}
public function exclude_current_page($some = true)
{
$via = debug_backtrace();
if( isset($via) && is_array($via) ) {
foreach($via as $key => $value) {
if( $value["function"] == "wclearfy_exclude_current_page" ) {
if( defined('WCLEARFY_DEBUG') && (WCLEARFY_DEBUG === true) ) {
if( preg_match("/wp-content\/themes/", $value["file"]) ) {
$this->exclude_current_page_text = "<!-- This page has been excluded by " . basename($value["file"]) . " of the Theme -->";
} else if( preg_match("/wp-content\/plugins/", $value["file"]) ) {
$this->exclude_current_page_text = "<!-- This page has been excluded by " . basename($value["file"]) . " of " . preg_replace("/([^\/]+)\/.+/", "$1", plugin_basename($value["file"])) . " -->";
}
} else {
$this->exclude_current_page_text = "<!-- This page has been excluded -->";
}
break;
}
}
}
}
public function wp_print_scripts_action()
{
echo "<!--WCLEARFY_FOOTER_START-->";
}
public function ignored($buffer)
{
$list = [
"\/wp\-comments\-post\.php",
"\/wp\-login\.php",
"\/robots\.txt",
"\/wp\-cron\.php",
"\/wp\-content",
"\/wp\-admin",
"\/wp\-includes",
"\/index\.php",
"\/xmlrpc\.php",
"\/wp\-api\/",
"leaflet\-geojson\.php",
"\/clientarea\.php"
];
if( WCL_Cache_Helpers::isPluginActive('woocommerce/woocommerce.php') ) {
if( $this->current_page_type != "homepage" ) {
global $post;
if( isset($post->ID) && $post->ID ) {
if( function_exists("wc_get_page_id") ) {
$woocommerce_ids = [];
array_push($woocommerce_ids, wc_get_page_id('cart'), wc_get_page_id('checkout'), wc_get_page_id('receipt'), wc_get_page_id('confirmation'), wc_get_page_id('myaccount'));
if( in_array($post->ID, $woocommerce_ids) ) {
return true;
}
}
}
array_push($list, "\/cart\/?$", "\/checkout", "\/receipt", "\/confirmation", "\/wc-api\/");
}
}
if( WCL_Cache_Helpers::isPluginActive('wp-easycart/wpeasycart.php') ) {
array_push($list, "\/cart");
}
if( WCL_Cache_Helpers::isPluginActive('easy-digital-downloads/easy-digital-downloads.php') ) {
array_push($list, "\/cart", "\/checkout");
}
if( preg_match("/" . implode("|", $list) . "/i", $_SERVER["REQUEST_URI"]) ) {
return true;
}
return false;
}
public function exclude_page()
{
$preg_match_rule = "";
$request_url = urldecode(trim($_SERVER["REQUEST_URI"], "/"));
$excluded_uris = WCL_Plugin::app()->getPopulateOption('cache_reject_uri');
if( !empty($excluded_uris) ) {
$excluded_uris = array_map(function ($value) {
$site_url = site_url();
$value = trim(rtrim($value));
// http://clearfy.pro/members/ -> /members/
$value = str_replace($site_url, "", $value);
// /members/(.*) -> members/(.*)
$value = preg_replace("/^\//", "", $value);
// members/ -> members
$value = untrailingslashit($value);
return $value;
}, preg_split('/\r\n|\n|\r/', $excluded_uris));
} else {
$excluded_uris = [];
}
foreach($excluded_uris as $uri) {
if( $uri === $request_url ) {
return true;
}
if( !empty($uri) && @preg_match('/' . $uri . '/i', $request_url) ) {
return true;
}
}
return false;
}
public function is_json()
{
return $this->current_page_content_type == "json" ? true : false;
}
public function is_xml()
{
return $this->current_page_content_type == "xml" ? true : false;
}
public function is_html()
{
return $this->current_page_content_type == "html" ? true : false;
}
public function set_current_page_type($buffer)
{
preg_match('/<\!--WCLEARFY_PAGE_TYPE_([a-z]+)-->/i', $buffer, $out);
$this->current_page_type = isset($out[1]) ? $out[1] : false;
}
public function set_current_page_content_type($buffer)
{
$content_type = false;
if( function_exists("headers_list") ) {
$headers = headers_list();
foreach($headers as $header) {
if( preg_match("/Content-Type\:/i", $header) ) {
$content_type = preg_replace("/Content-Type\:\s(.+)/i", "$1", $header);
}
}
}
if( preg_match("/xml/i", $content_type) ) {
$this->current_page_content_type = "xml";
} else if( preg_match("/json/i", $content_type) ) {
$this->current_page_content_type = "json";
} else {
$this->current_page_content_type = "html";
}
}
public function last_error($buffer = false)
{
if( function_exists("http_response_code") && (http_response_code() === 404) ) {
return true;
}
if( is_404() ) {
return true;
}
if( preg_match("/<body id\=\"error-page\">\s*<p>[^\>]+<\/p>\s*<\/body>/i", $buffer) ) {
return true;
}
}
public function callback($buffer)
{
$this->set_current_page_type($buffer);
$this->set_current_page_content_type($buffer);
$buffer = $this->checkShortCode($buffer);
// for Wordfence: not to cache 503 pages
if( defined('DONOTCACHEPAGE') && WCL_Cache_Helpers::isPluginActive('wordfence/wordfence.php') ) {
if( function_exists("http_response_code") && http_response_code() == 503 ) {
return $buffer . "<!-- DONOTCACHEPAGE is defined as TRUE -->";
}
}
// for iThemes Security: not to cache 403 pages
if( defined('DONOTCACHEPAGE') && WCL_Cache_Helpers::isPluginActive('better-wp-security/better-wp-security.php') ) {
if( function_exists("http_response_code") && http_response_code() == 403 ) {
return $buffer . "<!-- DONOTCACHEPAGE is defined as TRUE -->";
}
}
if( $this->exclude_page($buffer) ) {
$buffer = preg_replace('/<\!--WCLEARFY_PAGE_TYPE_[a-z]+-->/i', '', $buffer);
return $buffer;
}
$buffer = preg_replace('/<\!--WCLEARFY_PAGE_TYPE_[a-z]+-->/i', '', $buffer);
if( $this->exclude_current_page_text ) {
return $buffer . $this->exclude_current_page_text;
} else if( $this->is_json() && (!defined('WCACHE_JSON') || (defined('WCACHE_JSON') && WCACHE_JSON !== true)) ) {
return $buffer;
} else if( preg_match("/Mediapartners-Google|Google\sWireless\sTranscoder/i", $_SERVER['HTTP_USER_AGENT']) ) {
return $buffer;
} else if( is_user_logged_in() || $this->isCommenter() ) {
return $buffer;
} else if( $this->isPasswordProtected($buffer) ) {
return $buffer . "<!-- Password protected content has been detected -->";
} else if( WCL_Cache_Helpers::isWpLogin($buffer) ) {
return $buffer . "<!-- wp-login.php -->";
} else if( WCL_Cache_Helpers::hasContactForm7WithCaptcha($buffer) ) {
return $buffer . "<!-- This page was not cached because ContactForm7's captcha -->";
} else if( $this->last_error($buffer) ) {
return $buffer;
} else if( $this->ignored($buffer) ) {
return $buffer;
} else if( $this->blockCache === true ) {
return $buffer . "<!-- wclearfyNOT has been detected -->";
} else if( isset($_GET["preview"]) ) {
return $buffer . "<!-- not cached -->";
} else if( $this->checkHtml($buffer) ) {
return $buffer . "<!-- html is corrupted -->";
} else if( (function_exists("http_response_code")) && (http_response_code() == 301 || http_response_code() == 302) ) {
return $buffer;
} else if( !$this->cacheFilePath ) {
return $buffer . "<!-- permalink_structure ends with slash (/) but REQUEST_URI does not end with slash (/) -->";
} else {
$content = $buffer;
if( $this->err ) {
return $buffer . "<!-- " . $this->err . " -->";
} else {
$content = $this->cacheDate($content);
$content = str_replace("<!--WCLEARFY_FOOTER_START-->", "", $content);
$content = $this->cdn_rewrite($content);
$content = $this->fix_pre_tag($content, $buffer);
if( $this->cacheFilePath ) {
if( $this->is_html() ) {
$this->createFolder($this->cacheFilePath, $content);
do_action('wclearfy_is_cacheable_action');
} else if( $this->is_xml() ) {
if( preg_match("/<link><\/link>/", $buffer) ) {
if( preg_match("/\/feed$/", $_SERVER["REQUEST_URI"]) ) {
return $buffer . time();
}
}
$this->createFolder($this->cacheFilePath, $buffer, "xml");
do_action('wclearfy_is_cacheable_action');
return $buffer;
} else if( $this->is_json() ) {
$this->createFolder($this->cacheFilePath, $buffer, "json");
do_action('wclearfy_is_cacheable_action');
return $buffer;
}
}
return $content . "<!-- need to refresh to see cached version -->";
}
}
}
public function fix_pre_tag($content, $buffer)
{
if( preg_match("/<pre[^\>]*>/i", $buffer) ) {
preg_match_all("/<pre[^\>]*>((?!<\/pre>).)+<\/pre>/is", $buffer, $pre_buffer);
preg_match_all("/<pre[^\>]*>((?!<\/pre>).)+<\/pre>/is", $content, $pre_content);
if( isset($pre_content[0]) && isset($pre_content[0][0]) ) {
foreach($pre_content[0] as $key => $value) {
/*
location ~ / {
set $path /path/$1/index.html;
}
*/
if( isset($pre_buffer[0][$key]) ) {
$pre_buffer[0][$key] = preg_replace('/\$(\d)/', '\\\$$1', $pre_buffer[0][$key]);
$content = preg_replace("/" . preg_quote($value, "/") . "/", $pre_buffer[0][$key], $content);
}
}
}
}
return $content;
}
public function cdn_rewrite($content)
{
if( $this->cdn ) {
$content = preg_replace_callback("/(srcset|src|href|data-vc-parallax-image|data-bg|data-fullurl|data-mobileurl|data-img-url|data-cvpsrc|data-cvpset|data-thumb|data-bg-url|data-large_image|data-lazyload|data-lazy|data-source-url|data-srcsmall|data-srclarge|data-srcfull|data-slide-img|data-lazy-original)\s{0,2}\=\s{0,2}[\'\"]([^\'\"]+)[\'\"]/i", [
$this,
'cdn_replace_urls'
], $content);
//url()
$content = preg_replace_callback("/(url)\(([^\)\>]+)\)/i", [$this, 'cdn_replace_urls'], $content);
//{"concatemoji":"http:\/\/your_url.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.7"}
$content = preg_replace_callback("/\{\"concatemoji\"\:\"[^\"]+\"\}/i", [
$this,
'cdn_replace_urls'
], $content);
//<script>var loaderRandomImages=["https:\/\/www.site.com\/wp-content\/uploads\/2016\/12\/image.jpg"];</script>
$content = preg_replace_callback("/[\"\']([^\'\"]+)[\"\']\s*\:\s*[\"\']https?\:\\\\\/\\\\\/[^\"\']+[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <script>
// jsFileLocation:"//domain.com/wp-content/plugins/revslider/public/assets/js/"
// </script>
$content = preg_replace_callback("/(jsFileLocation)\s*\:[\"\']([^\"\']+)[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <form data-product_variations="[{&quot;src&quot;:&quot;//domain.com\/img.jpg&quot;}]">
// <div data-siteorigin-parallax="{&quot;backgroundUrl&quot;:&quot;https:\/\/domain.com\/wp-content\/TOR.jpg&quot;,&quot;backgroundSize&quot;:[830,467],&quot;}" data-stretch-type="full">
$content = preg_replace_callback("/(data-product_variations|data-siteorigin-parallax)\=[\"\'][^\"\']+[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <object data="https://site.com/source.swf" type="application/x-shockwave-flash"></object>
$content = preg_replace_callback("/<object[^\>]+(data)\s{0,2}\=[\'\"]([^\'\"]+)[\'\"][^\>]+>/i", [
$this,
'cdn_replace_urls'
], $content);
}
return $content;
}
public function get_header($content)
{
$head_first_index = strpos($content, "<head");
$head_last_index = strpos($content, "</head>");
return substr($content, $head_first_index, ($head_last_index - $head_first_index + 1));
}
public function checkHtml($buffer)
{
if( !$this->is_html() ) {
return false;
}
if( preg_match('/<html[^\>]*>/si', $buffer) && preg_match('/<body[^\>]*>/si', $buffer) ) {
return false;
}
// if(strlen($buffer) > 10){
// return false;
// }
return true;
}
public function cacheDate($buffer)
{
if( WCL_Cache_Helpers::isMobile() && class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile') && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$comment = "<!-- Mobile: Clearfy Cache file was created in " . $this->creationTime() . " seconds, on " . date("d-m-y G:i:s", current_time('timestamp')) . " -->";
} else {
$comment = "<!-- Clearfy Cache file was created in " . $this->creationTime() . " seconds, on " . date("d-m-y G:i:s", current_time('timestamp')) . " -->";
}
if( defined('WCLEARFY_REMOVE_FOOTER_COMMENT') && WCLEARFY_REMOVE_FOOTER_COMMENT ) {
return $buffer;
} else {
return $buffer . $comment;
}
}
public function creationTime()
{
return microtime(true) - $this->startTime;
}
public function isCommenter()
{
$commenter = wp_get_current_commenter();
return isset($commenter["comment_author_email"]) && $commenter["comment_author_email"] ? true : false;
}
public function isPasswordProtected($buffer)
{
if( preg_match("/action\=[\'\"].+postpass.*[\'\"]/", $buffer) ) {
return true;
}
foreach($_COOKIE as $key => $value) {
if( preg_match("/wp\-postpass\_/", $key) ) {
return true;
}
}
return false;
}
public function create_name($list)
{
$arr = is_array($list) ? $list : [["href" => $list]];
$name = "";
foreach($arr as $tag_key => $tag_value) {
$tmp = preg_replace("/(\.css|\.js)\?.*/", "$1", $tag_value["href"]); //to remove version number
$name = $name . $tmp;
}
return base_convert(crc32($name), 20, 36);
}
public function createFolder($cachFilePath, $buffer, $extension = "html", $prefix = false)
{
$create = false;
$file_name = "index.";
$update_db_statistic = true;
if( $buffer && strlen($buffer) > 100 && preg_match("/html|xml|json/i", $extension) ) {
if( !preg_match("/^\<\!\-\-\sMobile\:\sWP\sFastest\sCache/i", $buffer) ) {
if( !preg_match("/^\<\!\-\-\sWP\sFastest\sCache/i", $buffer) ) {
$create = true;
}
}
if( $this->preload_user_agent ) {
if( file_exists($cachFilePath . "/" . "index." . $extension) ) {
$update_db_statistic = false;
@unlink($cachFilePath . "/" . "index." . $extension);
}
}
}
if( ($extension == "svg" || $extension == "woff" || $extension == "css" || $extension == "js") && $buffer && strlen($buffer) > 5 ) {
$create = true;
$file_name = base_convert(substr(time(), -6), 20, 36) . ".";
$buffer = trim($buffer);
if( $extension == "js" ) {
if( substr($buffer, -1) != ";" ) {
$buffer .= ";";
}
}
}
if( $create ) {
if( !is_user_logged_in() && !$this->isCommenter() ) {
if( !is_dir($cachFilePath) ) {
if( is_writable(WCL_Cache_Helpers::getWpContentDir()) || ((is_dir(WCL_Cache_Helpers::getWpContentDir() . "/cache")) && (is_writable(WCL_Cache_Helpers::getWpContentDir() . "/cache"))) ) {
if( @mkdir($cachFilePath, 0755, true) ) {
$buffer = (string)apply_filters('wclearfy_buffer_callback_filter', $buffer, $extension);
file_put_contents($cachFilePath . "/" . $file_name . $extension, $buffer);
if( $extension == "html" ) {
if( !file_exists(WP_CONTENT_DIR . "/cache/index.html") ) {
@file_put_contents(WP_CONTENT_DIR . "/cache/index.html", "");
}
} else {
if( !file_exists(WP_CONTENT_DIR . "/cache/wclearfy-minified/index.html") ) {
@file_put_contents(WP_CONTENT_DIR . "/cache/wclearfy-minified/index.html", "");
}
}
} else {
}
} else {
}
} else {
if( file_exists($cachFilePath . "/" . $file_name . $extension) ) {
} else {
$buffer = (string)apply_filters('wclearfy_buffer_callback_filter', $buffer, $extension);
file_put_contents($cachFilePath . "/" . $file_name . $extension, $buffer);
}
}
}
} else if( $extension == "html" ) {
$this->err = "Buffer is empty so the cache cannot be created";
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,45 @@
<?php
class WCL_MobileCache {
private $folder_name = "wclearfy-mobile-cache";
private $wptouch = false;
public function __construct()
{
}
public function set_wptouch($status)
{
$this->wptouch = $status;
}
public function update_htaccess($data)
{
preg_match("/RewriteEngine\sOn(.+)/is", $data, $out);
$htaccess = "\n##### mobile #####\n";
$htaccess .= $out[0];
if( $this->wptouch ) {
$wptouch_rule = "RewriteCond %{HTTP:Cookie} !wptouch-pro-view=desktop";
$htaccess = str_replace("RewriteCond %{HTTP:Profile}", $wptouch_rule . "\n" . "RewriteCond %{HTTP:Profile}", $htaccess);
}
$htaccess = str_replace("RewriteCond %{HTTP:Cookie} !safirmobilswitcher=mobil", "RewriteCond %{HTTP:Cookie} !safirmobilswitcher=masaustu", $htaccess);
$htaccess = str_replace("RewriteCond %{HTTP_USER_AGENT} !^.*", "RewriteCond %{HTTP_USER_AGENT} ^.*", $htaccess);
$htaccess = preg_replace("/\/cache\/all\//", "/cache/" . $this->get_folder_name() . "/", $htaccess);
//$htaccess = preg_replace("/(\/cache\/)[^\/]+(\/.{1}1\/index\.html)/","$1".$this->get_folder_name()."$2", $htaccess);
$htaccess .= "\n##### mobile #####\n";
return $htaccess;
}
public function get_folder_name()
{
return $this->folder_name;
}
}
?>

View File

@@ -0,0 +1,504 @@
<?php
class WCL_Preload_Cache {
private static $exclude_rules = false;
public static function set_preload($slug)
{
$preload_arr = array();
if( !empty($_POST) && isset($_POST["wpFastestCachePreload"]) ) {
foreach($_POST as $key => $value) {
$key = esc_attr($key);
$value = esc_attr($value);
preg_match("/wpFastestCachePreload_(.+)/", $key, $type);
if( !empty($type) ) {
if( $type[1] == "restart" ) {
//to need to remove "restart" value
} else if( $type[1] == "number" ) {
$preload_arr[$type[1]] = $value;
} else {
$preload_arr[$type[1]] = 0;
}
}
}
}
if( $data = get_option("WClearfyCachePreLoad") ) {
$preload_std = json_decode($data);
if( !empty($preload_arr) ) {
foreach($preload_arr as $key => &$value) {
if( !empty($preload_std->$key) ) {
if( $key != "number" ) {
$value = $preload_std->$key;
}
}
}
$preload_std = $preload_arr;
} else {
foreach($preload_std as $key => &$value) {
if( $key != "number" ) {
$value = 0;
}
}
}
update_option("WClearfyCachePreLoad", json_encode($preload_std));
if( !wp_next_scheduled($slug . "_Preload") ) {
wp_schedule_event(time() + 5, 'everyfiveminute', $slug . "_Preload");
}
} else {
if( !empty($preload_arr) ) {
add_option("WClearfyCachePreLoad", json_encode($preload_arr), null, "yes");
if( !wp_next_scheduled($slug . "_Preload") ) {
wp_schedule_event(time() + 5, 'everyfiveminute', $slug . "_Preload");
}
} else {
//toDO
}
}
}
public static function statistic($pre_load = false)
{
$total = new stdClass();
if( isset($pre_load->homepage) ) {
$total->homepage = 1;
}
if( isset($pre_load->customposttypes) ) {
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach($post_types as $post_type_key => $post_type_value) {
if( !in_array($post_type_key, array("post", "page", "attachment")) ) {
$where_query = $where_query . $wpdb->prefix . "posts.post_type = '" . $post_type_value . "' OR ";
}
}
if( $where_query ) {
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS COUNT(" . $wpdb->prefix . "posts.ID) as total FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $where_query . ") AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID", ARRAY_A);
$total->customposttypes = $recent_custom_posts[0]["total"];
}
}
if( isset($pre_load->post) ) {
$count_posts = wp_count_posts("post", array('post_status' => 'publish', 'suppress_filters' => true));
$total->post = $count_posts->publish;
}
if( isset($pre_load->attachment) ) {
$total_attachments = wp_count_attachments();
$total->attachment = array_sum((array)$total_attachments) - $total_attachments->trash;
}
if( isset($pre_load->page) ) {
$count_pages = wp_count_posts("page", array('post_status' => 'publish', 'suppress_filters' => true));
$total->page = $count_pages->publish;
}
if( isset($pre_load->category) ) {
$total->category = wp_count_terms("category", array('hide_empty' => false));
}
if( isset($pre_load->tag) ) {
$total->tag = wp_count_terms("post_tag", array('hide_empty' => false));
}
if( isset($pre_load->customTaxonomies) ) {
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if( count($taxo) > 0 ) {
$total->customTaxonomies = wp_count_terms($taxo, array('hide_empty' => false));
}
}
foreach($total as $key => $value) {
$pre_load->$key = $pre_load->$key == -1 ? $value : $pre_load->$key;
echo $key . ": " . $pre_load->$key . "/" . $value . "<br>";
}
}
public static function create_preload_cache($options)
{
if( $data = get_option("WClearfyCachePreLoad") ) {
if( !isset($options->wpFastestCacheStatus) ) {
die("Cache System must be enabled");
}
$pre_load = json_decode($data);
if( defined("WCLEARFY_PRELOAD_NUMBER") && WCLEARFY_PRELOAD_NUMBER ) {
$number = WCLEARFY_PRELOAD_NUMBER;
} else {
$number = $pre_load->number;
}
$urls_limit = isset($options->wpFastestCachePreload_number) ? $options->wpFastestCachePreload_number : 4; // must be even
$urls = array();
if( isset($options->wpFastestCacheMobileTheme) && $options->wpFastestCacheMobileTheme ) {
$mobile_theme = true;
$number = round($number / 2);
} else {
$mobile_theme = false;
}
// HOME
if( isset($pre_load->homepage) && $pre_load->homepage > -1 ) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_option("home"), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_option("home"), "user-agent" => "desktop"));
$number--;
$pre_load->homepage = -1;
}
// CUSTOM POSTS
if( $number > 0 && isset($pre_load->customposttypes) && $pre_load->customposttypes > -1 ) {
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach($post_types as $post_type_key => $post_type_value) {
if( !in_array($post_type_key, array("post", "page", "attachment")) ) {
$where_query = $where_query . $wpdb->prefix . "posts.post_type = '" . $post_type_value . "' OR ";
}
}
if( $where_query ) {
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $where_query . ") AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->customposttypes . ", " . $number, ARRAY_A);
if( count($recent_custom_posts) > 0 ) {
foreach($recent_custom_posts as $key => $post) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->customposttypes = $pre_load->customposttypes + 1;
}
} else {
$pre_load->customposttypes = -1;
}
}
}
// POST
if( $number > 0 && isset($pre_load->post) && $pre_load->post > -1 ) {
// $recent_posts = wp_get_recent_posts(array(
// 'numberposts' => $number,
// 'offset' => $pre_load->post,
// 'orderby' => 'ID',
// 'order' => 'DESC',
// 'post_type' => 'post',
// 'post_status' => 'publish',
// 'suppress_filters' => true
// ), ARRAY_A);
global $wpdb;
$recent_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'post') AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->post . ", " . $number, ARRAY_A);
if( count($recent_posts) > 0 ) {
foreach($recent_posts as $key => $post) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->post = $pre_load->post + 1;
}
} else {
$pre_load->post = -1;
}
}
// ATTACHMENT
if( $number > 0 && isset($pre_load->attachment) && $pre_load->attachment > -1 ) {
global $wpdb;
$recent_attachments = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'attachment') ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->attachment . ", " . $number, ARRAY_A);
if( count($recent_attachments) > 0 ) {
foreach($recent_attachments as $key => $attachment) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_permalink($attachment["ID"]),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array("url" => get_permalink($attachment["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->attachment = $pre_load->attachment + 1;
}
} else {
$pre_load->attachment = -1;
}
}
// PAGE
if( $number > 0 && isset($pre_load->page) && $pre_load->page > -1 ) {
global $wpdb;
$pages = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'page') AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->page . ", " . $number, ARRAY_A);
if( count($pages) > 0 ) {
foreach($pages as $key => $page) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->page = $pre_load->page + 1;
}
} else {
$pre_load->page = -1;
}
}
// CATEGORY
if( $number > 0 && isset($pre_load->category) && $pre_load->category > -1 ) {
$categories = get_terms(array(
'taxonomy' => array('category'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->category
));
if( count($categories) > 0 ) {
foreach($categories as $key => $category) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($category->slug, $category->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($category->slug, $category->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->category = $pre_load->category + 1;
}
} else {
$pre_load->category = -1;
}
}
// TAG
if( $number > 0 && isset($pre_load->tag) && $pre_load->tag > -1 ) {
$tags = get_terms(array(
'taxonomy' => array('post_tag'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->tag
));
if( count($tags) > 0 ) {
foreach($tags as $key => $tag) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($tag->slug, $tag->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($tag->slug, $tag->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->tag = $pre_load->tag + 1;
}
} else {
$pre_load->tag = -1;
}
}
// Custom Taxonomies
if( $number > 0 && isset($pre_load->customTaxonomies) && $pre_load->customTaxonomies > -1 ) {
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if( count($taxo) > 0 ) {
$custom_taxos = get_terms(array(
'taxonomy' => array_values($taxo),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->customTaxonomies
));
if( count($custom_taxos) > 0 ) {
foreach($custom_taxos as $key => $custom_tax) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->customTaxonomies = $pre_load->customTaxonomies + 1;
}
} else {
$pre_load->customTaxonomies = -1;
}
} else {
$pre_load->customTaxonomies = -1;
}
}
if( count($urls) > 0 ) {
foreach($urls as $key => $arr) {
$user_agent = "";
if( $arr["user-agent"] == "desktop" ) {
$user_agent = "Clearfy Cache Preload Bot";
} else if( $arr["user-agent"] == "mobile" ) {
$user_agent = "Clearfy Cache Preload iPhone Mobile Bot";
}
if( self::is_excluded($arr["url"]) ) {
$status = "<strong style=\"color:blue;\">Excluded</strong>";
} else {
if( $GLOBALS["wp_fastest_cache"]->wclearfy_remote_get($arr["url"], $user_agent) ) {
$status = "<strong style=\"color:lightgreen;\">OK</strong>";
} else {
$status = "<strong style=\"color:red;\">ERROR</strong>";
}
}
echo $status . " " . $arr["url"] . " (" . $arr["user-agent"] . ")<br>";
}
echo "<br>";
echo count($urls) . " page have been cached";
update_option("WClearfyCachePreLoad", json_encode($pre_load));
echo "<br><br>";
self::statistic($pre_load);
} else {
if( isset($options->wpFastestCachePreload_restart) ) {
foreach($pre_load as $pre_load_key => &$pre_load_value) {
if( $pre_load_key != "number" ) {
$pre_load_value = 0;
}
}
update_option("WClearfyCachePreLoad", json_encode($pre_load));
echo "Preload Restarted";
include_once('cdn.php');
CdnWCLEARFY::cloudflare_clear_cache();
} else {
echo "Completed";
wp_clear_scheduled_hook("wp_fastest_cache_Preload");
}
}
}
if( isset($_GET) && isset($_GET["type"]) && $_GET["type"] == "preload" ) {
die();
}
}
public static function is_excluded($url)
{
if( !is_string($url) ) {
return false;
}
$request_url = parse_url($url, PHP_URL_PATH);
$request_url = urldecode(trim($request_url, "/"));
if( !$request_url ) {
return false;
}
if( self::$exclude_rules === false ) {
if( $json_data = get_option("WClearfyCacheExclude") ) {
self::$exclude_rules = json_decode($json_data);
} else {
self::$exclude_rules = array();
}
}
foreach((array)self::$exclude_rules as $key => $value) {
if( $value->prefix == "exact" ) {
if( strtolower($value->content) == strtolower($request_url) ) {
return true;
}
} else {
if( $value->prefix == "startwith" ) {
$preg_match_rule = "^" . preg_quote($value->content, "/");
} else if( $value->prefix == "contain" ) {
$preg_match_rule = preg_quote($value->content, "/");
}
if( isset($preg_match_rule) ) {
if( preg_match("/" . $preg_match_rule . "/i", $request_url) ) {
return true;
}
}
}
}
return false;
}
}
?>

View File

@@ -0,0 +1,208 @@
<?php
class WCL_SinglePreload_Cache {
public static $id = 0;
public static $urls = array();
public static function init()
{
SinglePreloadWCLEARFY::set_id();
SinglePreloadWCLEARFY::set_urls();
SinglePreloadWCLEARFY::set_urls_with_terms();
}
public static function set_id()
{
if( isset($_GET["post"]) && $_GET["post"] ) {
static::$id = esc_sql($_GET["post"]);
if( get_post_status(static::$id) != "publish" ) {
static::$id = 0;
}
}
}
public static function create_cache()
{
$res = $GLOBALS["wp_fastest_cache"]->wclearfy_remote_get($_GET["url"], $_GET["user_agent"]);
if( $res ) {
die("true");
}
}
public static function is_mobile_active()
{
if( isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobile) && isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobileTheme) ) {
return true;
} else {
return false;
}
}
public static function set_term_urls($term_taxonomy_id)
{
$term = get_term_by("term_taxonomy_id", $term_taxonomy_id);
if( $term && !is_wp_error($term) ) {
$url = get_term_link($term->term_id, $term->taxonomy);
array_push(static::$urls, array("url" => $url, "user-agent" => "Clearfy Cache Preload Bot"));
if( self::is_mobile_active() ) {
array_push(static::$urls, array(
"url" => $url,
"user-agent" => "Clearfy Cache Preload iPhone Mobile Bot"
));
}
if( $term->parent > 0 ) {
$parent = get_term_by("id", $term->parent, $term->taxonomy);
static::set_term_urls($parent->term_taxonomy_id);
}
}
}
public static function set_urls_with_terms()
{
global $wpdb;
$terms = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "term_relationships` WHERE `object_id`=" . static::$id, ARRAY_A);
foreach($terms as $term_key => $term_val) {
static::set_term_urls($term_val["term_taxonomy_id"]);
}
}
public static function set_urls()
{
if( static::$id ) {
$permalink = get_permalink(static::$id);
array_push(static::$urls, array("url" => $permalink, "user-agent" => "Clearfy Cache Preload Bot"));
if( self::is_mobile_active() ) {
array_push(static::$urls, array(
"url" => $permalink,
"user-agent" => "Clearfy Cache Preload iPhone Mobile Bot"
));
}
}
}
public static function put_inline_js()
{
$screen = get_current_screen();
if( $screen->parent_base == "edit" && $screen->base == "post" ) {
?>
<div id="wclearfy-single-preload" class="notice notice-info is-dismissible" style="display: none;">
<p id="wclearfy-single-preload-info"><?php _e('Cache is generated for this content', 'wp-fastest-cache'); ?>
<label style="display: none;" id="wclearfy-single-preload-error">0</label><label id="wclearfy-single-preload-process" style="padding-left: 5px;"><span>0</span>/<span><?php echo count(static::$urls); ?></span></label>
</p>
<script type="text/javascript">
var WclearfySinglePreload = {
error_message: "",
init: function() {
},
change_status: function() {
var type = "";
var cached_number = parseInt(jQuery("#wclearfy-single-preload-process span").first().text());
var total = parseInt(jQuery("#wclearfy-single-preload-process span").last().text());
var error_number = parseInt(jQuery("#wclearfy-single-preload-error").text());
if( cached_number == total ) {
type = "success";
}
if( (error_number + cached_number) == total ) {
if( error_number > cached_number ) {
type = "error";
} else {
type = "success";
}
}
if( type ) {
var class_name = jQuery("#wclearfy-single-preload").attr("class");
class_name = class_name.replace("notice-info", "notice-" + type);
jQuery("#wclearfy-single-preload").attr("class", class_name);
if( type == "success" ) {
jQuery("#wclearfy-single-preload p").text("<?php _e('Cache has been generated for this content successfully', 'wp-fastest-cache');?>");
} else {
if( this.error_message ) {
this.error_message = "<?php _e('Cache has NOT been generated for this content successfully', 'wp-fastest-cache');?>" + "<br>" + "<?php _e('Reason:', 'wp-fastest-cache');?>" + " " + this.error_message;
jQuery("#wclearfy-single-preload p").html(this.error_message);
}
}
}
},
increase_error: function() {
var error_number = jQuery("#wclearfy-single-preload-error").text();
error_number = parseInt(error_number) + 1;
jQuery("#wclearfy-single-preload-error").text(error_number);
this.change_status();
},
create_cache: function(url, user_agent) {
var self = this;
jQuery("#wclearfy-single-preload").show();
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {
"action": "wclearfy_preload_single",
"url": url,
"user_agent": user_agent
},
dataType: "html",
timeout: 10000,
cache: false,
success: function(data) {
if( data == "true" ) {
var number = jQuery("#wclearfy-single-preload-process span").first().text();
number = parseInt(number) + 1;
jQuery("#wclearfy-single-preload-process span").first().text(number);
} else {
self.error_message = data;
WclearfySinglePreload.increase_error();
}
self.change_status();
},
error: function(error) {
self.error_message = error.statusText;
WclearfySinglePreload.increase_error();
}
});
}
};
jQuery(document).ready(function() {
if( jQuery("#message").find("a").attr("href") ) {
WclearfySinglePreload.init();
<?php
foreach (self::$urls as $key => $value) {
?>
setTimeout(function() {
WclearfySinglePreload.create_cache("<?php echo $value["url"]; ?>", "<?php echo $value["user-agent"]; ?>");
}, <?php echo $key * 500;?>);
<?php
}
?>
}
});
</script>
</div>
<?php
}
}
}
?>

View File

@@ -0,0 +1,462 @@
<?php
class CdnWCLEARFY{
public static function cloudflare_clear_cache($email = false, $key = false, $zoneid = false){
if(!$email && !$key && !$zoneid){
if($cdn_values = get_option("WClearfyCacheCDN")){
$std_obj = json_decode($cdn_values);
foreach ($std_obj as $key => $value) {
if($value->id == "cloudflare"){
$email = $value->cdnurl;
$key = $value->originurl;
break;
}
}
if($email && $key){
$zone = self::cloudflare_get_zone_id($email, $key, false);
if($zone["success"]){
$zoneid = $zone["zoneid"];
}
}
}
}
if($email && $key && $zoneid){
$header = array("method" => "DELETE",
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
"body" => '{"purge_everything":true}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/purge_cache', $header);
}
}
public static function cloudflare_disable_rocket_loader($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":"off"}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/rocket_loader', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable rocket loader option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_set_browser_caching($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":16070400}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/browser_cache_ttl', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to set the browser caching option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_disable_minify($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":{"css":"off","html":"off","js":"off"}}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/minify', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable minify options");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}else{
wp_die("bad request");
}
}
public static function cloudflare_get_zone_id($email = false, $key = false){
$hostname = preg_replace("/^(https?\:\/\/)?(www\d*\.)?/", "", $_SERVER["HTTP_HOST"]);
if(function_exists("idn_to_utf8")){
$hostname = idn_to_utf8($hostname);
}
$header = array("method" => "GET",
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
);
/*
status=active has been removed because status may be "pending"
*/
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/?page=1&per_page=1000', $header);
if(!$response || is_wp_error($response)){
$res = array("success" => false, "error_message" => $response->get_error_message());
}else{
$zone = json_decode(wp_remote_retrieve_body($response));
if(isset($zone->errors) && isset($zone->errors[0])){
$res = array("success" => false, "error_message" => $zone->errors[0]->message);
}else{
if(isset($zone->result) && isset($zone->result[0])){
foreach ($zone->result as $zone_key => $zone_value) {
if(preg_match("/".$zone_value->name."/", $hostname)){
$res = array("success" => true,
"zoneid" => $zone_value->id,
"plan" => $zone_value->plan->legacy_id);
}
}
if(!$res["success"]){
$res = array("success" => false, "error_message" => "No zone name ".$hostname);
}
}else{
$res = array("success" => false, "error_message" => "There is no zone");
}
}
}
return $res;
}
public static function cloudflare_remove_webp(){
$path = ABSPATH.".htaccess";
if(file_exists($path)){
if(is_writable($path)){
$htaccess = file_get_contents($path);
$htaccess = preg_replace("/#\s?BEGIN\s?WEBPWClearfyCache.*?#\s?END\s?WEBPWClearfyCache/s", "", $htaccess);
file_put_contents($path, $htaccess);
}
}
}
public static function cloudflare_change_settings(){
//admin OR author OR editor
if(current_user_can('manage_options') || current_user_can('delete_published_posts') || current_user_can('edit_published_posts')){
if(isset($_GET["url"]) && isset($_GET["origin_url"])){
$email = $_GET["url"];
$key = $_GET["origin_url"];
}
$zone = CdnWCLEARFY::cloudflare_get_zone_id($email, $key);
if($zone["success"]){
$minify = CdnWCLEARFY::cloudflare_disable_minify($email, $key, $zone["zoneid"]);
$rocket_loader = CdnWCLEARFY::cloudflare_disable_rocket_loader($email, $key, $zone["zoneid"]);
$purge_cache = CdnWCLEARFY::cloudflare_clear_cache($email, $key, $zone["zoneid"]);
$browser_caching = CdnWCLEARFY::cloudflare_set_browser_caching($email, $key, $zone["zoneid"]);
if($zone["plan"] == "free"){
CdnWCLEARFY::cloudflare_remove_webp();;
}
if($minify["success"]){
if($rocket_loader["success"]){
if($browser_caching["success"]){
$res = array("success" => true);
}else{
$res = array("success" => false, "error_message" => $browser_caching["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $rocket_loader["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $minify["error_message"]);
}
}else{
$res = $zone;
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function check_url(){
if(current_user_can('manage_options')){
if(isset($_GET["type"]) && $_GET["type"] == "cloudflare"){
CdnWCLEARFY::cloudflare_change_settings();
}
if(preg_match("/wp\.com/", $_GET["url"]) || $_GET["url"] == "random"){
wp_send_json(array("success" => true));
}
$host = str_replace("www.", "", $_SERVER["HTTP_HOST"]);
$_GET["url"] = esc_url_raw($_GET["url"]);
if(!preg_match("/^http/", $_GET["url"])){
$_GET["url"] = "http://".$_GET["url"];
}
if(preg_match("/^https/i", site_url()) && preg_match("/^https/i", home_url())){
$_GET["url"] = preg_replace("/http\:\/\//i", "https://", $_GET["url"]);
}
$response = wp_remote_get($_GET["url"], array('timeout' => 20, 'user-agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:64.0) Gecko/20100101 Firefox/64.0"));
$header = wp_remote_retrieve_headers($response);
if ( !$response || is_wp_error( $response ) ) {
$res = array("success" => false, "error_message" => $response->get_error_message());
if($response->get_error_code() == "http_request_failed"){
if($response->get_error_message() == "Failure when receiving data from the peer"){
$res = array("success" => true);
}else if(preg_match("/cURL\serror\s60/i", $response->get_error_message())){
//cURL error 60: SSL: no alternative certificate subject name matches target host name
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/' target='_blank'>Please Read: https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/</a>");
}else if(preg_match("/cURL\serror\s6/i", $response->get_error_message())){
//cURL error 6: Couldn't resolve host
if(preg_match("/".preg_quote($host, "/")."/i", $_GET["url"])){
$res = array("success" => true);
}
}
}
}else{
$response_code = wp_remote_retrieve_response_code( $response );
if($response_code == 200){
$res = array("success" => true);
}else{
if(method_exists($response, "get_error_message")){
$res = array("success" => false, "error_message" => $response->get_error_message());
}else{
$res = array("success" => false, "error_message" => wp_remote_retrieve_response_message($response));
}
if(isset($header["server"]) && preg_match("/squid/i", $header["server"])){
$res = array("success" => true);
}
if(($response_code == 401) && (preg_match("/res\.cloudinary\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/stackpathdns\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/cloudfront\.net/i", $_GET["url"]))){
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/warnings/amazon-s3-cloudfront-access-denied-403-forbidden/' target='_blank'>Please Read: https://www.wpfastestcache.com/warnings/amazon-s3-cloudfront-access-denied-403-forbidden</a>");
}
}
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function cdn_options(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WClearfyCacheCDN");
if($cdn_values){
echo $cdn_values;
}else{
echo json_encode(array("success" => false));
}
exit;
}else{
wp_die("Must be admin");
}
}
public static function remove_cdn_integration(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WClearfyCacheCDN");
if($cdn_values){
$std_obj = json_decode($cdn_values);
$cdn_values_arr = array();
if(is_array($std_obj)){
$cdn_values_arr = $std_obj;
}else{
array_push($cdn_values_arr, $std_obj);
}
foreach ($cdn_values_arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "amazonaws" || $cdn_value->id == "keycdn" || $cdn_value->id == "cdn77"){
$cdn_value->id = "other";
}
if($cdn_value->id == $_POST["id"]){
unset($cdn_values_arr[$cdn_key]);
}
}
$cdn_values_arr = array_values($cdn_values_arr);
}
if(count($cdn_values_arr) > 0){
update_option("WClearfyCacheCDN", json_encode($cdn_values_arr));
}else{
delete_option("WClearfyCacheCDN");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
public static function cdn_template(){
if(current_user_can('manage_options')){
if($_POST["id"] == "maxcdn"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/maxcdn.php";
}else if($_POST["id"] == "other"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/other.php";
}else if($_POST["id"] == "photon"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/photon.php";
}else if($_POST["id"] == "cloudflare"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/cloudflare.php";
}else{
die("Wrong cdn");
}
ob_start();
include_once($path);
$content = ob_get_contents();
ob_end_clean();
$res = array("success" => false, "content" => "");
if($data = @file_get_contents($path)){
$res["success"] = true;
$res["content"] = $content;
}
echo json_encode($res);
exit;
}else{
wp_die("Must be admin");
}
}
public static function save_cdn_integration(){
if(current_user_can('manage_options')){
if(isset($_POST) && isset($_POST["values"])){
foreach ($_POST["values"] as $val_key => &$val_value) {
$val_value = sanitize_text_field($val_value);
}
}
if($data = get_option("WClearfyCacheCDN")){
$cdn_exist = false;
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => &$cdn_value) {
if($cdn_value->id == $_POST["values"]["id"]){
$cdn_value = $_POST["values"];
$cdn_exist = true;
}
}
if(!$cdn_exist){
array_push($arr, $_POST["values"]);
}
update_option("WClearfyCacheCDN", json_encode($arr));
}else{
$tmp_arr = array();
if($arr->id == $_POST["values"]["id"]){
array_push($tmp_arr, $_POST["values"]);
}else{
array_push($tmp_arr, $arr);
array_push($tmp_arr, $_POST["values"]);
}
update_option("WClearfyCacheCDN", json_encode($tmp_arr));
}
}else{
$arr = array();
array_push($arr, $_POST["values"]);
add_option("WClearfyCacheCDN", json_encode($arr), null, "yes");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
}
?>

View File

@@ -0,0 +1,160 @@
<?php
class WCL_WidgetCache {
public static function action()
{
add_filter('widget_display_callback', array("WCL_WidgetCache", "create_cache"), 10, 3);
}
public static function add_filter_admin()
{
add_filter('widget_update_callback', array("WCL_WidgetCache", "widget_update"), 5, 3);
add_action('in_widget_form', array("WCL_WidgetCache", 'in_widget_form'), 5, 3);
}
public static function in_widget_form($widget, $return, $instance)
{
$wclearfynot = isset($instance['wclearfynot']) ? $instance['wclearfynot'] : '';
?>
<p>
<input class="checkbox" type="checkbox" id="<?php echo $widget->get_field_id('wclearfynot'); ?>" name="<?php echo $widget->get_field_name('wclearfynot'); ?>" <?php checked(true, $wclearfynot); ?> />
<label for="<?php echo $widget->get_field_id('wclearfynot'); ?>">
<?php _e('Don\'t cache this widget'); ?>
</label>
</p>
<?php
}
public static function widget_update($instance, $new_instance)
{
WCL_Cache_Helpers::rm_folder_recursively(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache/"));
if( isset($new_instance['wclearfynot']) ) {
$instance['wclearfynot'] = 1;
} else {
if( isset($instance['wclearfynot']) ) {
unset($instance['wclearfynot']);
}
}
return $instance;
}
public static function create_cache($instance, $widget, $args)
{
if( !isset($args["widget_id"]) || !$args["widget_id"] ) {
return $instance;
}
if( $instance === false ) {
return $instance;
}
// to return instance if not to cache widget
if( isset($instance["wclearfynot"]) ) {
return $instance;
}
// to exclude WooCommerce Product Categories automatically if show_children_only has been set
if( isset($instance["show_children_only"]) ) {
return $instance;
}
// to exclude fixed widget Q2W3 Fixed Widget
if( isset($instance["q2w3_fixed_widget"]) ) {
return $instance;
}
// to exclude Ninja Forms
if( preg_match("/^ninja_forms_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude WPML Multilingual Language Switcher
if( preg_match("/^icl_lang_sel_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Yuzo Related Posts
if( preg_match("/^yuzo_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Amazon Affiliate for WordPress
if( preg_match("/^aawp_widget_/i", $args["widget_id"]) ) {
return $instance;
}
// Flagman theme
if( preg_match("/^ct_slider_widget_/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
if( preg_match("/^woof_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
if( preg_match("/^woocommerce_price_filter/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Bridge Woocommerce Dropdown Cart
if( preg_match("/^woocommerce-dropdown-cart/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
// https://mihajlovicnenad.com/product-filter/
if( preg_match("/^prdctfltr/i", $args["widget_id"]) ) {
return $instance;
}
$create_cache = false;
$path = WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache/" . $args["widget_id"] . ".html");
//to get cache
if( file_exists($path) ) {
if( $data = @file_get_contents($path) ) {
echo $data;
return false;
}
}
//to get the content of Widget
ob_start();
$widget->widget($args, $instance);
$cached_widget = ob_get_clean();
//to create cache
if( $cached_widget ) {
if( !is_dir(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache")) ) {
if( @mkdir(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache"), 0755, true) ) {
$create_cache = true;
}
} else {
$create_cache = true;
}
//to exclude the widgets which contains nonce value
//<input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="fdd28cece7" />
if( preg_match("/<input[^\>]+hidden[^\>]+nonce[^\>]+>/", $cached_widget) || preg_match("/<input[^\>]+nonce[^\>]+hidden[^\>]+>/", $cached_widget) ) {
$create_cache = false;
}
if( $create_cache ) {
@file_put_contents($path, $cached_widget);
}
}
echo $cached_widget;
return false;
}
}
?>

View File

@@ -0,0 +1,178 @@
<?php
/**
* Admin boot
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright Webcraftic 25.05.2017
* @version 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Массово проходится по комментарием в базе данных и отключает, какждый индивидуально.
*/
function wbcr_cmp_enter_permanent_mode() {
global $wpdb;
if ( ! WCM_Plugin::app()->getPopulateOption( 'disable_comments_permanent' ) ) {
return;
}
$types = wbcr_cmp_get_disabled_post_types();
if ( empty( $types ) ) {
return;
}
if ( WCM_Plugin::app()->isNetworkActive() ) {
// NOTE: this can be slow on large networks!
$blogs = $wpdb->get_col( $wpdb->prepare( "SELECT blog_id
FROM $wpdb->blogs
WHERE site_id = %d
AND public = '1'
AND archived = '0'
AND deleted = '0'", $wpdb->siteid ) );
foreach ( $blogs as $id ) {
switch_to_blog( $id );
wbcr_close_comments_in_db( $types );
restore_current_blog();
}
} else {
wbcr_close_comments_in_db( $types );
}
}
add_action( 'wbcr/factory/pages/impressive/after_form_save', 'wbcr_cmp_enter_permanent_mode' );
add_action( 'wbcr_clearfy_configurated_quick_mode', 'wbcr_cmp_enter_permanent_mode' );
/**
* Закрывает комментарии в базе данных
*
* @param $types
*/
function wbcr_close_comments_in_db( $types ) {
global $wpdb;
$bits = implode( ', ', array_pad( [], count( $types ), '%s' ) );
$wpdb->query( $wpdb->prepare( "UPDATE `$wpdb->posts`
SET `comment_status` = 'closed', ping_status = 'closed'
WHERE `post_type`
IN ( $bits )", $types ) );
}
if ( ! defined( 'LOADING_COMMENTS_PLUS_AS_ADDON' ) ) {
function wbcr_cmp_set_plugin_meta( $links, $file ) {
if ( $file == WCM_PLUGIN_BASE ) {
$url = 'https://clearfy.pro';
if ( get_locale() == 'ru_RU' ) {
$url = 'https://ru.clearfy.pro';
}
$url .= '?utm_source=wordpress.org&utm_campaign=' . WCM_Plugin::app()->getPluginName();
$links[] = '<a href="' . $url . '" style="color: #FF5722;font-weight: bold;" target="_blank">' . __( 'Get ultimate plugin free', 'comments-plus' ) . '</a>';
}
return $links;
}
add_filter( 'plugin_row_meta', 'wbcr_cmp_set_plugin_meta', 10, 2 );
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*
* @param string $page_url
* @param string $plugin_name
*
* @return string
*/
function wbcr_cmp_rating_widget_url( $page_url, $plugin_name ) {
if ( ! defined( 'LOADING_COMMENTS_PLUS_AS_ADDON' ) && ( $plugin_name == WCM_Plugin::app()->getPluginName() ) ) {
return 'https://goo.gl/v4QkW5';
}
return $page_url;
}
add_filter( 'wbcr_factory_pages_480_imppage_rating_widget_url', 'wbcr_cmp_rating_widget_url', 10, 2 );
/**
* Удаляем лишние виджеты из правого сайдбара в интерфейсе плагина
*
* - Виджет с премиум рекламой
* - Виджет с рейтингом
* - Виджет с маркерами информации
*/
add_filter( 'wbcr/factory/pages/impressive/widgets', function ( $widgets, $position, $plugin ) {
if ( WCM_Plugin::app()->getPluginName() == $plugin->getPluginName() && 'right' == $position ) {
unset( $widgets['business_suggetion'] );
unset( $widgets['rating_widget'] );
unset( $widgets['info_widget'] );
}
return $widgets;
}, 20, 3 );
} else {
function wbcr_cmp_group_options( $options ) {
$options[] = [
'name' => 'disable_comments',
'title' => __( 'Disable comments on the entire site', 'comments-plus' ),
'tags' => [ 'disable_all_comments' ],
'values' => [ 'disable_all_comments' => 'disable_comments' ]
];
$options[] = [
'name' => 'disable_comments_for_post_types',
'title' => __( 'Select post types', 'comments-plus' ),
'tags' => []
];
$options[] = [
'name' => 'disable_comments_extra_post_types',
'title' => __( 'Custom post types', 'comments-plus' ),
'tags' => []
];
$options[] = [
'name' => 'disable_comments_permanent',
'title' => __( 'Use persistent mode', 'comments-plus' ),
'tags' => []
];
$options[] = [
'name' => 'comment_text_convert_links_pseudo',
'title' => __( 'Replace external links in comments on the JavaScript code', 'comments-plus' ),
'tags' => [ 'recommended', 'seo_optimize' ]
];
$options[] = [
'name' => 'pseudo_comment_author_link',
'title' => __( 'Replace external links from comment authors on the JavaScript code', 'comments-plus' ),
'tags' => [ 'recommended', 'seo_optimize' ]
];
$options[] = [
'name' => 'remove_url_from_comment_form',
'title' => __( 'Remove field "site" in comment form', 'comments-plus' ),
'tags' => []
];
return $options;
}
add_filter( "wbcr_clearfy_group_options", 'wbcr_cmp_group_options' );
function wbcr_cmp_allow_quick_mods( $mods ) {
$mods['disable_all_comments'] = [
'title' => __( 'One click disable all comments', 'comments-plus' ),
'icon' => 'dashicons-testimonial'
];
return $mods;
}
add_filter( "wbcr_clearfy_allow_quick_mods", 'wbcr_cmp_allow_quick_mods' );
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,233 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Страница общих настроек для этого плагина.
*
* Может быть использована только, если этот плагин используется как отдельный плагин, а не как аддон
* дя плагина Clearfy. Если плагин загружен, как аддон для Clearfy, эта страница не будет подключена.
*
* Поддерживает режим работы с мультисаймами. Вы можете увидеть эту страницу в панели настройки сети.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WbcrCmp_CommentsPage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* {@inheritDoc}
*
* @var string
*/
public $id = "comments";
/**
* {@inheritDoc}
*
* @var string
*/
public $page_menu_dashicon = 'dashicons-testimonial';
/**
* {@inheritDoc}
*
* @var bool
*/
public $available_for_multisite = true;
/**
* {@inheritDoc}
*
* @since 1.1.0
* @var bool
*/
public $show_right_sidebar_in_options = true;
/**
* WbcrCmp_CommentsPage constructor.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*
* @param \Wbcr_Factory480_Plugin $plugin
*/
public function __construct( Wbcr_Factory480_Plugin $plugin ) {
$this->menu_title = __( 'Disable comments', 'comments-plus' );
$this->page_menu_short_description = __( 'Manage site comments', 'comments-plus' );
if ( ! defined( 'LOADING_COMMENTS_PLUS_AS_ADDON' ) ) {
$this->internal = false;
$this->menu_target = 'options-general.php';
$this->add_link_to_plugin_actions = true;
$this->show_search_options_form = false;
}
parent::__construct( $plugin );
}
/*public function getMenuTitle() {
return defined( 'LOADING_COMMENTS_PLUS_AS_ADDON' ) ? __( 'Comments', 'comments-plus' ) : __( 'General', 'comments-plus' );
}*/
/**
* {@inheritDoc}
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @return string
*/
public function getPageTitle() {
return defined( 'LOADING_COMMENTS_PLUS_AS_ADDON' ) ? __( 'Comments', 'comments-plus' ) : __( 'General', 'comments-plus' );
}
/**
* {@inheritDoc}
*
* @since 1.0.0
* @return mixed[]
*/
public function getPageOptions() {
$options = [];
$options[] = [
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header"><strong>' . __( 'Global disabling of comments', 'comments-plus' ) . '</strong><p>' . __( 'What is the difference between these and native WordPress functions? WordPress disables comments only for new posts! Using the functions below, you can disable comments globally, even for old posts, and you can choose which post types comments to disable. The plugin also disables the comment functionality itself, which creates a certain load on the site.', 'comments-plus' ) . '</p></div>'
];
$args = [ 'public' => true ];
if ( $this->plugin->isNetworkActive() ) {
$args['_builtin'] = true;
}
$types = get_post_types( $args, 'objects' );
/*foreach( array_keys( $types ) as $type ) {
if( ! in_array( $type, $this->modified_types ) && ! post_type_supports( $type, 'comments' ) ) // the type doesn't support comments anyway
unset( $types[$type] );
}*/
$post_types = [];
foreach ( $types as $type_name => $type ) {
$post_types[] = [ $type_name, $type->label ];
}
$options[] = [
'type' => 'dropdown',
'name' => 'disable_comments',
'way' => 'buttons',
'title' => __( 'Disable comments', 'comments-plus' ),
'data' => [
[ 'enable_comments', __( 'Not disable', 'comments-plus' ) ],
[
'disable_comments',
__( 'Everywhere', 'comments-plus' ),
sprintf( __( 'You can delete all comments in the database by clicking on this link (<a href="%s">cleaning comments in database</a>).', 'comments-plus' ), admin_url( 'admin.php?page=delete_comments-' . $this->plugin->getPluginName() ) )
],
[
'disable_certain_post_types_comments',
__( 'On certain post types', 'comments-plus' ),
sprintf( __( 'You can delete all comments for the selected post types. Select the post types below and save the settings. After that, click the link (<a href="%s">delete all comments for the selected post types in database</a>).', 'comments-plus' ), admin_url( 'admin.php?page=delete_comments-' . $this->plugin->getPluginName() ) )
]
],
'layout' => [ 'hint-type' => 'icon', 'hint-icon-color' => 'grey' ],
'hint' => __( 'Everywhere - Warning: This option is global and will affect your entire site. Use it only if you want to disable comments everywhere. A complete description of what this option does is available here', 'comments-plus' ) . '<br><br>' . __( 'On certain post types - Disabling comments will also disable trackbacks and pingbacks. All comment-related fields will also be hidden from the edit/quick-edit screens of the affected posts. These settings cannot be overridden for individual posts.', 'comments-plus' ),
'default' => 'enable_comments',
'events' => [
'disable_certain_post_types_comments' => [
'show' => '.factory-control-disable_comments_for_post_types, #wbcr-clearfy-comments-base-options,.factory-control-disable_comments_permanent,.factory-control-disable_comments_extra_post_types'
],
'enable_comments' => [
'show' => '#wbcr-clearfy-comments-base-options',
'hide' => '.factory-control-disable_comments_for_post_types,.factory-control-disable_comments_permanent,.factory-control-disable_comments_extra_post_types'
],
'disable_comments' => [
'show' => '.factory-control-disable_comments_permanent',
'hide' => '.factory-control-disable_comments_for_post_types, #wbcr-clearfy-comments-base-options,.factory-control-disable_comments_extra_post_types'
]
]
];
$options[] = [
'type' => 'list',
'way' => 'checklist',
'name' => 'disable_comments_for_post_types',
'title' => __( 'Select post types', 'comments-plus' ),
'data' => $post_types,
'layout' => [ 'hint-type' => 'icon', 'hint-icon-color' => 'grey' ],
'hint' => __( 'Select the post types for which comments will be disabled', 'comments-plus' ),
'default' => 'post,page,attachment'
];
if ( $this->plugin->isNetworkActive() ) {
$options[] = [
'type' => 'textbox',
'name' => 'disable_comments_extra_post_types',
'title' => __( 'Custom post types', 'comments-plus' ),
'data' => $post_types,
'layout' => [ 'hint-type' => 'icon', 'hint-icon-color' => 'grey' ],
'hint' => __( 'Only the built-in post types appear above. If you want to disable comments on other custom post types on the entire network, you can supply a comma-separated list of post types below (use the slug that identifies the post type).', 'comments-plus' ),
'default' => ''
];
}
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'disable_comments_permanent',
'title' => __( 'Use persistent mode', 'comments-plus' ),
'layout' => [ 'hint-type' => 'icon', 'hint-icon-color' => 'grey' ],
'hint' => __( 'This will make persistent changes to your database &mdash; comments will remain closed even if you later disable the plugin! You should not use it if you only want to disable comments temporarily.', 'comments-plus' ),
'default' => false
];
$options[] = [
'type' => 'div',
'id' => 'wbcr-clearfy-comments-base-options',
'items' => [
[
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header"><strong>' . __( 'General settings for comments', 'comments-plus' ) . '</strong><p>' . __( 'These settings will help you improve SEO and reduce the amount of spam.', 'comments-plus' ) . '</p></div>'
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'remove_url_from_comment_form',
'title' => __( 'Remove field "site" in comment form', 'comments-plus' ),
'layout' => [ 'hint-type' => 'icon', 'hint-icon-color' => 'grey' ],
'hint' => __( 'Tired of spam in the comments? Do visitors leave "blank" comments for the sake of a link to their site?', 'comments-plus' ) . '<br><b>Clearfy: </b>' . __( 'Removes the "Site" field from the comment form.', 'comments-plus' ) . '<br>--<br><span class="wbcr-factory-light-orange-color"> *' . __( 'Works with the standard comment form, if the form is manually written in your theme-it probably will not work!', 'comments-plus' ) . '</span>',
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'comment_text_convert_links_pseudo',
'title' => __( 'Replace external links in comments on the JavaScript code', 'comments-plus' ),
'layout' => [ 'hint-type' => 'icon' ],
'hint' => __( 'Superfluous external links from comments, which can be typed from a dozen and more for one article, do not bring anything good for promotion.', 'comments-plus' ) . '<br><br><b>Clearfy: </b>' . sprintf( __( 'Replaces the links of this kind of %s, on links of this kind %s', 'comments-plus' ), '<code>a href="http://yourdomain.com" rel="nofollow"</code>', '<code>span data-uri="http://yourdomain.com"</code>' ),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'pseudo_comment_author_link',
'title' => __( 'Replace external links from comment authors on the JavaScript code', 'comments-plus' ),
'layout' => [ 'hint-type' => 'icon' ],
'hint' => __( 'Up to 90 percent of comments in the blog can be left for the sake of an external link. Even nofollow from page weight loss here does not help.', 'comments-plus' ) . '<br><br><b>Clearfy: </b>' . __( 'Replaces the links of the authors of comments on the JavaScript code, it is impossible to distinguish it from usual links.', 'comments-plus' ) . '<br>--<br><i>' . __( 'In some Wordpress topics this may not work.', 'comments-plus' ) . '</i>',
'default' => false
]
]
];
$formOptions = [];
$formOptions[] = [
'type' => 'form-group',
'items' => $options,
//'cssClass' => 'postbox'
];
return apply_filters( 'wbcr_cmp_comments_form_options', $formOptions );
}
}

View File

@@ -0,0 +1,513 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Страница общих настроек для этого плагина.
*
* Может быть использована только, если этот плагин используется как отдельный плагин, а не как аддон
* дя плагина Clearfy. Если плагин загружен, как аддон для Clearfy, эта страница не будет подключена.
*
* Поддерживает режим работы с мультисаймами. Вы можете увидеть эту страницу в панели настройки сети.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WbcrCmp_DeleteCommentsPage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* {@inheritDoc}
*
* @var string
*/
public $id = "delete_comments";
/**
* {@inheritDoc}
*
* @var string
*/
public $type = "page";
/**
* {@inheritDoc}
*
* @var string
*/
public $page_parent_page = "comments";
/**
* {@inheritDoc}
*
* @var string
*/
public $page_menu_dashicon = 'dashicons-testimonial';
/**
* {@inheritDoc}
*
* @var bool
*/
public $available_for_multisite = true;
/**
* {@inheritDoc}
*
* @since 1.1.0
* @var bool
*/
public $show_right_sidebar_in_options = true;
/**
* WbcrCmp_DeleteCommentsPage constructor.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*
* @param \Wbcr_Factory480_Plugin $plugin
*/
public function __construct( Wbcr_Factory480_Plugin $plugin ) {
$this->menu_title = __( 'Comments cleaner', 'comments-plus' );
parent::__construct( $plugin );
}
/**
* {@inheritDoc}
*
* @param $notices
* @param Wbcr_Factory480_Plugin $plugin
*
* @return array
* @see libs\factory\pages\themplates\FactoryPages480_ImpressiveThemplate
*/
public function getActionNotices( $notices ) {
$notices[] = [
'conditions' => [
'wbcr_cmp_clear_comments' => 1
],
'type' => 'success',
'message' => __( 'All comments have been deleted.', 'comments-plus' )
];
$notices[] = [
'conditions' => [
'wbcr_cmp_clear_comments_error' => 1,
'wbcr_cmp_code' => 'interal_error'
],
'type' => 'danger',
'message' => __( 'An error occurred while trying to delete comments. Internal error occured. Please try again later.', 'comments-plus' )
];
return $notices;
}
public function getStats() {
if ( WCM_Plugin::app()->isNetworkActive() ) {
$stats = $this->getMultisiteStats();
} else {
$stats = $this->getSiteStats();
}
return $stats;
}
public function getMultisiteStats() {
$stats = [];
foreach ( WCM_Plugin::app()->getActiveSites() as $site ) {
switch_to_blog( $site->blog_id );
$site_stats = $this->getSiteStats();
$stats = $this->mergeStats( $stats, $site_stats );
restore_current_blog();
}
return $stats;
}
public function mergeStats( $current_stats, $new_stats ) {
if ( ! isset( $current_stats['stat_data'] ) ) {
$current_stats['stat_data'] = $new_stats['stat_data'];
} else {
$comment_fields = [ 'total_comments', 'order_notes_count', 'spamcount', 'unpcount', 'trashcount' ];
foreach ( $comment_fields as $comment_field ) {
if ( is_null( $current_stats['stat_data'][0]->$comment_field ) ) {
$current_stats['stat_data'][0]->$comment_field = 0;
}
if ( is_null( $new_stats['stat_data'][0]->$comment_field ) ) {
$new_stats['stat_data'][0]->$comment_field = 0;
}
if ( $new_stats['stat_data'][0]->$comment_field ) {
$current_stats['stat_data'][0]->$comment_field = $current_stats['stat_data'][0]->$comment_field + $new_stats['stat_data'][0]->$comment_field;
}
}
}
if ( ! isset( $current_stats['post_types'] ) ) {
$current_stats['post_types'] = $new_stats['post_types'];
} else {
foreach ( $new_stats['post_types'] as $post_type_key => $post_type ) {
if ( array_key_exists( $post_type_key, $current_stats['post_types'] ) ) {
$current_stats['post_types'][ $post_type_key ]['comments_count'] += $new_stats['post_types'][ $post_type_key ]['comments_count'];
} else {
$current_stats['post_types'][ $post_type_key ] = $new_stats['post_types'][ $post_type_key ];
}
}
}
return $current_stats;
}
public function getSiteStats() {
global $wpdb;
$stat_data = $wpdb->get_results( "SELECT count(*) as total_comments,
SUM(comment_type='order_note') as order_notes_count,
SUM(comment_approved='spam') as spamcount,
SUM(comment_approved='0') as unpcount,
SUM(comment_approved='trash') as trashcount
FROM {$wpdb->prefix}comments" );
$stat_data_by_post_type = $wpdb->get_results( "SELECT
SUM(comment_count) as type_comments_count, post_type
FROM $wpdb->posts
GROUP BY post_type" );
$types = get_post_types( [ 'public' => true ], 'objects' );
$post_types = [];
foreach ( (array) $types as $type_name => $type ) {
$comments_count = 0;
if ( ! empty( $stat_data_by_post_type ) ) {
foreach ( (array) $stat_data_by_post_type as $post_type_stat_value ) {
if ( $post_type_stat_value->post_type == $type_name ) {
$comments_count = $post_type_stat_value->type_comments_count;
}
}
}
$post_types[ $type_name ] = [ 'label' => $type->label, 'comments_count' => $comments_count ];
}
return [
'stat_data' => $stat_data,
'post_types' => $post_types
];
}
/**
* Prints the content of the page
*
* @see libs\factory\pages\themplates\FactoryPages480_ImpressiveThemplate
*/
public function showPageContent() {
$stats = $this->getStats();
$stat_data = $stats['stat_data'];
$post_types = $stats['post_types'];
?>
<script>
/**
* Select all types by one click.
*/
jQuery(document).ready(function($) {
updateCommentsCounter();
var allTypesCheckbox = $('#wbcr-cmp-all-types-checkbox');
allTypesCheckbox.click(function() {
$('.wbcr-cmp-post-type-checkbox').prop("checked", $(this).prop("checked"));
updateCommentsCounter()
});
$('.wbcr-cmp-post-type-checkbox').click(function() {
if( !$(this).prop("checked") ) {
allTypesCheckbox.prop("checked", false);
}
updateCommentsCounter();
});
$('input[name="wbcr_cmp_delete_order_notes"]').click(function() {
updateCommentsCounter();
});
$('.wbcr-cmp-delete-comments-button').click(function() {
var confrimDelete = confirm('<?php _e( 'Are you sure you want to delete comments from the database without restoring?', 'comments-plus' ); ?>');
if( !confrimDelete ) {
return false;
}
$(this).submit();
});
function updateCommentsCounter() {
var commentsCount = 0;
$('.wbcr-cmp-post-type-checkbox:checked, input[name="wbcr_cmp_delete_order_notes"]:checked').each(function() {
commentsCount += $(this).data('comments-number');
});
$('.wbcr-cmp-delete-comments-button').val('<?php _e( 'Delete ', 'comments-plus' ) ?>(' + commentsCount + ')');
}
});
</script>
<div class="wbcr-factory-page-group-header" style="margin-top:0;">
<strong><?php _e( 'Comments clearing tools', 'comments-plus' ) ?></strong>
<p>
<?php _e( 'These functions can be useful for global disabling comments or bulk cleaning spam comments.', 'comments-plus' ) ?>
</p>
</div>
<form method="post" action="<?= $this->getActionUrl( 'delete-all-comments' ) ?>" style="padding: 20px;">
<h5><?php _e( 'Remove all comments', 'comments-plus' ); ?></h5>
<p><?php _e( 'You can delete all comments in your database with one click.', 'comments-plus' ); ?></p>
<p><strong><?php _e( 'Choose post types', 'comments-plus' ); ?></strong>
<div style="height:150px; width:400px; padding:10px 10px 0; background: #fff; border:1px solid #ccc; overflow-y: scroll; overflow-x:hidden;">
<p>
<label>
<input type="checkbox" id="wbcr-cmp-all-types-checkbox" name="wbcr_cmp_post_type[]" value="all" checked/> <?php _e( 'Select all', 'comments-plus' ); ?>
</label>
</p>
<?php foreach ( (array) $post_types as $key => $type ): ?>
<p>
<label>
<input type="checkbox" data-comments-number="<?= $type['comments_count'] ?>" class="wbcr-cmp-post-type-checkbox" name="wbcr_cmp_post_type[]" value="<?= esc_attr( $key ) ?>" checked/> <?= $type['label'] ?>
(<?= $type['comments_count'] ?>)
</label>
</p>
<?php endforeach; ?>
</div>
<?php if ( class_exists( 'WooCommerce' ) ):
?>
<p style="margin:15px 0 0">
<label>
<input type="checkbox" data-comments-number="<?= $stat_data[0]->order_notes_count ?>" name="wbcr_cmp_delete_order_notes" value="1"/> <?php printf( __( 'Delete Woocommerce order notices? (%d)', 'comments-plus' ), $stat_data[0]->order_notes_count ); ?>
</label>
</p>
<?php endif;
?>
<p style="margin-top:15px;">
<input type="submit" name="wbcr_cmp_delete_all" class="button button-default wbcr-cmp-delete-comments-button" value="<?php printf( __( 'Delete (%s)', 'comments-plus' ), $stat_data[0]->total_comments ); ?>">
</p>
<?php wp_nonce_field( $this->getResultId() . '_delete_all_comments' ) ?>
</form>
<div style="padding: 20px;">
<hr/>
<h5><?php _e( 'Remove spam comments', 'comments-plus' ); ?></h5>
<p><?php _e( 'You can remove only spam comments from the database with one click.', 'comments-plus' ); ?></p>
<a href="<?= wp_nonce_url( $this->getActionUrl( 'delete-spam-comments' ), $this->getResultId() . '_delete_spam_comments' ) ?>" class="button button-default wbcr-cmp-delete-comments-button">
<?php printf( __( 'Delete (%d)', 'comments-plus' ), $stat_data[0]->spamcount ); ?>
</a>
<hr/>
<h5><?php _e( 'Remove unapproved comments', 'comments-plus' ); ?></h5>
<p><?php _e( 'You can remove only unapproved comments from the database with one click.', 'comments-plus' ); ?></p>
<a href="<?= wp_nonce_url( $this->getActionUrl( 'delete-unaproved-comments' ), $this->getResultId() . '_delete_unaproved_comments' ) ?>" class="button button-default wbcr-cmp-delete-comments-button">
<?php printf( __( 'Delete (%d)', 'comments-plus' ), $stat_data[0]->unpcount ); ?>
</a>
<hr/>
<h5><?php _e( 'Remove trashed comments', 'comments-plus' ); ?></h5>
<p><?php _e( 'You can remove only trashed comments from the database with one click.', 'comments-plus' ); ?></p>
<a href="<?= wp_nonce_url( $this->getActionUrl( 'delete-trash-comments' ), $this->getResultId() . '_delete_trash_comments' ) ?>" class="button button-default wbcr-cmp-delete-comments-button">
<?php printf( __( 'Delete (%d)', 'comments-plus' ), $stat_data[0]->trashcount ); ?>
</a>
</div>
<?php
}
/**
* @return bool
*/
protected function deleteAllComments() {
global $wpdb;
$delete_order_notes = $this->request->post( 'wbcr_cmp_delete_order_notes', false, 'intval' );
if ( $wpdb->query( "TRUNCATE $wpdb->commentmeta" ) != false ) {
$delete_all_sql = "TRUNCATE $wpdb->comments";
if ( class_exists( 'WooCommerce' ) ) {
if ( ! $delete_order_notes ) {
$delete_all_sql = "DELETE FROM $wpdb->comments WHERE comment_type != 'order_note'";
}
}
if ( $wpdb->query( $delete_all_sql ) != false ) {
$wpdb->query( "UPDATE $wpdb->posts SET comment_count = 0 WHERE post_author != 0" );
$wpdb->query( "OPTIMIZE TABLE $wpdb->commentmeta" );
$wpdb->query( "OPTIMIZE TABLE $wpdb->comments" );
return true;
}
}
return false;
}
/**
* @param string $post_type
*
* @return bool
*/
protected function deleteCommentsByPostType( $post_type = 'post' ) {
global $wpdb;
$delete_order_notes = $this->request->post( 'wbcr_cmp_delete_order_notes', false, 'intval' );
$wpdb->query( "DELETE cmeta FROM $wpdb->commentmeta cmeta INNER JOIN $wpdb->comments comments ON cmeta.comment_id=comments.comment_ID INNER JOIN $wpdb->posts posts ON comments.comment_post_ID=posts.ID WHERE posts.post_type = '%s'" );
$delete_certain_sql = "DELETE comments FROM $wpdb->comments comments INNER JOIN $wpdb->posts posts ON comments.comment_post_ID=posts.ID WHERE posts.post_type = '%s'";
if ( class_exists( 'WooCommerce' ) ) {
if ( ! $delete_order_notes ) {
$delete_certain_sql .= " and comment_type != 'order_note'";
}
}
$wpdb->query( $wpdb->prepare( $delete_certain_sql, $post_type ) );
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET comment_count = 0 WHERE post_author != 0 AND post_type = '%s'", $post_type ) );
return true;
}
/**
* @param $post_types
*
* @return bool
*/
protected function deleteCommentsByPostTypes( $post_types ) {
global $wpdb;
if ( empty( $post_types ) || ! is_array( $post_types ) ) {
return false;
}
foreach ( $post_types as $post_type ) {
$this->deleteCommentsByPostType( $post_type );
}
$wpdb->query( "OPTIMIZE TABLE $wpdb->commentmeta" );
$wpdb->query( "OPTIMIZE TABLE $wpdb->comments" );
return true;
}
/**
* This action deletes all comments from the database without restoring.
*/
public function deleteAllCommentsAction() {
check_admin_referer( $this->getResultId() . '_delete_all_comments' );
if ( isset( $_POST['wbcr_cmp_delete_all'] ) ) {
$post_types = $this->request->post( 'wbcr_cmp_post_type', [], true );
$result = false;
if ( empty( $post_types ) || in_array( 'all', $post_types ) ) {
if ( WCM_Plugin::app()->isNetworkActive() ) {
foreach ( WCM_Plugin::app()->getActiveSites() as $site ) {
switch_to_blog( $site->blog_id );
$result = $this->deleteAllComments();
restore_current_blog();
}
} else {
$result = $this->deleteAllComments();
}
} else {
if ( WCM_Plugin::app()->isNetworkActive() ) {
foreach ( WCM_Plugin::app()->getActiveSites() as $site ) {
switch_to_blog( $site->blog_id );
$result = $this->deleteCommentsByPostTypes( $post_types );
restore_current_blog();
}
} else {
$result = $this->deleteCommentsByPostTypes( $post_types );
}
}
if ( $result ) {
$this->redirectToAction( 'index', [
'wbcr_cmp_clear_comments' => '1'
] );
} else {
$this->redirectToAction( 'index', [
'wbcr_cmp_clear_comments_error' => '1',
'wbcr_cmp_code' => 'interal_error',
] );
}
}
$this->redirectToAction( 'index' );
}
/**
* The basic function of deleting comments.
*
* @param int|string $type
*/
public function deleteComments( $type = 0 ) {
if ( in_array( $type, [ 'spam', 'trash', 0 ] ) ) {
if ( WCM_Plugin::app()->isNetworkActive() ) {
foreach ( WCM_Plugin::app()->getActiveSites() as $site ) {
switch_to_blog( $site->blog_id );
$this->deleteCommentsByType( $type );
restore_current_blog();
}
} else {
$this->deleteCommentsByType( $type );
}
$this->redirectToAction( 'index', [
'wbcr_cmp_clear_comments' => '1'
] );
}
}
/**
* @param int $type
*
* @return false|int
*/
private function deleteCommentsByType( $type = 0 ) {
global $wpdb;
$wpdb->query( "DELETE cmeta
FROM $wpdb->commentmeta cmeta
INNER JOIN {$wpdb->comments} comments ON cmeta.comment_id=comments.comment_ID
WHERE comment_approved='{$type}'" );
$res = $wpdb->query( "DELETE FROM {$wpdb->comments} WHERE comment_approved='{$type}'" );
if ( $res ) {
$wpdb->query( "OPTIMIZE TABLE {$wpdb->comments}" );
$wpdb->query( "OPTIMIZE TABLE {$wpdb->commentmeta}" );
}
return $res;
}
/**
* This action deletes spam comments
*/
public function deleteSpamCommentsAction() {
check_admin_referer( $this->getResultId() . '_delete_spam_comments' );
$this->deleteComments( 'spam' );
}
/**
* This action deletes unaproved comments
*/
public function deleteUnaprovedCommentsAction() {
check_admin_referer( $this->getResultId() . '_delete_unaproved_comments' );
$this->deleteComments();
}
/**
* This action deletes trash comments
*/
public function deleteTrashCommentsAction() {
check_admin_referer( $this->getResultId() . '_delete_trash_comments' );
$this->deleteComments( 'trash' );
}
}

View File

@@ -0,0 +1,24 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Рекламная страница.
*
* Используется для рекламы плагина Clearfy. Пользователь может изучить все возможности плагина Clearfy
* и перейти на лендинг плагина, чтобы скачать и попробовать его.
*
* Может быть использована только, если этот плагин используется как отдельный плагин, а не как аддон
* для плагина Clearfy. Если плагин загружен, как аддон для Clearfy, эта страница не будет подключена.
*
* НЕ поддерживает режим работы с мультисаймами!
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WbcrCmp_MoreFeaturesPage extends \WBCR\Factory_Templates_134\Pages\MoreFeatures {
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,16 @@
/**
* Url span
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 17.11.2017, Webcraftic
* @version 1.0
*/
.wbcr-clearfy-pseudo-link {
color: #008acf;
cursor: pointer;
text-decoration: underline;
}
.wbcr-clearfy-pseudo-link:hover {
text-decoration: none;
}

View File

@@ -0,0 +1,18 @@
/**
* Url span
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 17.11.2017, Webcraftic
* @version 1.0
*/
(function($) {
'use strict';
$(function() {
$(document).on("click", ".wbcr-clearfy-pseudo-link", function() {
window.open($(this).data("uri"));
});
})
})(jQuery);

View File

@@ -0,0 +1,52 @@
<?php
/**
* Этот файл инициализирует этот плагин, как аддон для плагина Clearfy.
*
* Файл будет подключен только в плагине Clearfy, используя особый вариант загрузки. Это более простое решение
* пришло на смену встроенной системы подключения аддонов в фреймворке.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'WCM_PLUGIN_ACTIVE' ) ) {
define( 'WCM_PLUGIN_VERSION', '1.2.0' );
define( 'WCM_TEXT_DOMAIN', 'comments-plus' );
define( 'WCM_PLUGIN_ACTIVE', true );
// Этот плагин загружен, как аддон для плагина Clearfy
define( 'LOADING_COMMENTS_PLUS_AS_ADDON', true );
if ( ! defined( 'WCM_PLUGIN_DIR' ) ) {
define( 'WCM_PLUGIN_DIR', dirname( __FILE__ ) );
}
if ( ! defined( 'WCM_PLUGIN_BASE' ) ) {
define( 'WCM_PLUGIN_BASE', plugin_basename( __FILE__ ) );
}
if ( ! defined( 'WCM_PLUGIN_URL' ) ) {
define( 'WCM_PLUGIN_URL', plugins_url( '', __FILE__ ) );
}
try {
// Global scripts
require_once( WCM_PLUGIN_DIR . '/includes/3rd-party/class-clearfy-plugin.php' );
new WCM_Plugin();
} catch( Exception $e ) {
$wcm_plugin_error_func = function () use ( $e ) {
$error = sprintf( "The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Disable Comments', $e->getMessage(), $e->getCode() );
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action( 'admin_notices', $wcm_plugin_error_func );
add_action( 'network_admin_notices', $wcm_plugin_error_func );
}
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* Plugin Name: Webcraftic Disable Comments
* Plugin URI: https://webcraftic.com
* Description: Allows administrators to globally disable comments on their site. Comments can be disabled for individual record types.
* Author: Webcraftic <wordpress.webraftic@gmail.com>
* Version: 1.2.0
* Text Domain: comments-plus
* Domain Path: /languages/
* Author URI: https://webcraftic.com
* Framework Version: FACTORY_480_VERSION
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Developers who contributions in the development plugin:
*
* Alexander Kovalev
* ---------------------------------------------------------------------------------
* Full plugin development.
*
* Email: alex.kovalevv@gmail.com
* Personal card: https://alexkovalevv.github.io
* Personal repo: https://github.com/alexkovalevv
* ---------------------------------------------------------------------------------
*/
/**
* -----------------------------------------------------------------------------
* CHECK REQUIREMENTS
* Check compatibility with php and wp version of the user's site. As well as checking
* compatibility with other plugins from Webcraftic.
* -----------------------------------------------------------------------------
*/
require_once( dirname( __FILE__ ) . '/libs/factory/core/includes/class-factory-requirements.php' );
// @formatter:off
$wcm_plugin_info = [
'prefix' => 'wbcr_comments_plus_', // wbcr_cmp
'plugin_name' => 'wbcr_comments_plus',
'plugin_title' => 'Webcraftic Disable comments',
// PLUGIN SUPPORT
'support_details' => [
'url' => 'https://webcraftic.com',
'pages_map' => [
'support' => 'support', // {site}/support
'docs' => 'docs' // {site}/docs
]
],
// PLUGIN SUBSCRIBE FORM
'subscribe_widget' => true,
'subscribe_settings' => [ 'group_id' => '105408898' ],
// PLUGIN ADVERTS
'render_adverts' => true,
'adverts_settings' => [
'dashboard_widget' => true, // show dashboard widget (default: false)
'right_sidebar' => true, // show adverts sidebar (default: false)
'notice' => true, // show notice message (default: false)
],
// FRAMEWORK MODULES
'load_factory_modules' => [
[ 'libs/factory/bootstrap', 'factory_bootstrap_482', 'admin' ],
[ 'libs/factory/forms', 'factory_forms_480', 'admin' ],
[ 'libs/factory/pages', 'factory_pages_480', 'admin' ],
[ 'libs/factory/templates', 'factory_templates_134', 'all' ],
[ 'libs/factory/adverts', 'factory_adverts_159', 'admin' ]
]
];
$wcm_compatibility = new Wbcr_Factory480_Requirements( __FILE__, array_merge( $wcm_plugin_info, [
'plugin_already_activate' => defined( 'WCM_PLUGIN_ACTIVE' ),
'required_php_version' => '5.4',
'required_wp_version' => '4.2.0',
'required_clearfy_check_component' => false
] ) );
/**
* If the plugin is compatible, then it will continue its work, otherwise it will be stopped,
* and the user will throw a warning.
*/
if ( ! $wcm_compatibility->check() ) {
return;
}
/**
* -----------------------------------------------------------------------------
* CONSTANTS
* Install frequently used constants and constants for debugging, which will be
* removed after compiling the plugin.
* -----------------------------------------------------------------------------
*/
// This plugin is activated
define( 'WCM_PLUGIN_ACTIVE', true );
define( 'WCM_PLUGIN_VERSION', $wcm_compatibility->get_plugin_version() );
define( 'WCM_PLUGIN_DIR', dirname( __FILE__ ) );
define( 'WCM_PLUGIN_BASE', plugin_basename( __FILE__ ) );
define( 'WCM_PLUGIN_URL', plugins_url( '', __FILE__ ) );
/**
* -----------------------------------------------------------------------------
* PLUGIN INIT
* -----------------------------------------------------------------------------
*/
require_once( WCM_PLUGIN_DIR . '/libs/factory/core/boot.php' );
require_once( WCM_PLUGIN_DIR . '/includes/class-plugin.php' );
try {
new WCM_Plugin( __FILE__, array_merge( $wcm_plugin_info, [
'plugin_version' => WCM_PLUGIN_VERSION,
'plugin_text_domain' => $wcm_compatibility->get_text_domain(),
] ) );
} catch ( Exception $e ) {
// Plugin wasn't initialized due to an error
define( 'WCM_PLUGIN_THROW_ERROR', true );
$wcm_plugin_error_func = function () use ( $e ) {
$error = sprintf( "The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Disable Comments', $e->getMessage(), $e->getCode() );
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action( 'admin_notices', $wcm_plugin_error_func );
add_action( 'network_admin_notices', $wcm_plugin_error_func );
}
// @formatter:on

View File

@@ -0,0 +1,112 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Disable comments
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2018 Webraftic Ltd
*/
class WCM_Plugin {
/**
* @see self::app()
* @var WCL_Plugin
*/
private static $app;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct() {
if ( ! class_exists( 'WCL_Plugin' ) ) {
throw new Exception( 'Plugin Clearfy is not installed!' );
}
self::$app = WCL_Plugin::app();
$this->global_scripts();
if ( is_admin() ) {
$this->admin_scripts();
}
add_action( 'plugins_loaded', [ $this, 'plugins_loaded' ] );
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return WCL_Plugin
*/
public static function app() {
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
public function plugins_loaded() {
}
/**
* Регистрирует классы страниц в плагине
*
* Мы указываем плагину, где найти файлы страниц и какое имя у их класса. Чтобы плагин
* выполнил подключение классов страниц. После регистрации, страницы будут доступные по url
* и в меню боковой панели администратора. Регистрируемые страницы будут связаны с текущим плагином
* все операции выполняемые внутри классов страниц, имеют отношение только текущему плагину.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
private function register_pages() {
$admin_path = WCM_PLUGIN_DIR . '/admin/pages';
self::app()->registerPage( 'WbcrCmp_CommentsPage', $admin_path . '/class-page-comments.php' );
self::app()->registerPage( 'WbcrCmp_DeleteCommentsPage', $admin_path . '/class-page-delete-comments.php' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts() {
require( WCM_PLUGIN_DIR . '/admin/boot.php' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function global_scripts() {
require( WCM_PLUGIN_DIR . '/includes/boot.php' );
require( WCM_PLUGIN_DIR . '/includes/classes/class-configurate-comments.php' );
new WbcrCmp_ConfigComments( self::$app );
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,51 @@
<?php
/**
* Admin boot
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright Webcraftic 25.05.2017
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Получает список отключенных типов записей
*
* @return array|bool|mixed|void
*/
function wbcr_cmp_get_disabled_post_types() {
$post_types = WCM_Plugin::app()->getPopulateOption( 'disable_comments_for_post_types' );
if ( WCM_Plugin::app()->getPopulateOption( 'disable_comments', 'enable_comments' ) == 'disable_comments' ) {
$args = [ 'public' => true ];
if ( WCM_Plugin::app()->isNetworkActive() ) {
$args['_builtin'] = true;
}
$all_post_types = get_post_types( $args, 'objects' );
return array_keys( $all_post_types );
}
// Not all extra_post_types might be registered on this particular site
/*if( $this->networkactive ) {
foreach( (array) $this->options['extra_post_types'] as $extra ) {
if( post_type_exists( $extra ) ) {
$types[] = $extra;
}
}
}*/
if ( is_array( $post_types ) ) {
return $post_types;
}
return explode( ',', $post_types );
}

View File

@@ -0,0 +1,119 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Plugin class
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright (c) 19.02.2018, Webcraftic
*/
class WCM_Plugin extends Wbcr_Factory480_Plugin {
/**
* @see self::app()
* @var Wbcr_Factory480_Plugin
*/
private static $app;
/**
* @since 3.1.0
* @var array
*/
private $plugin_data;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct( $plugin_path, $data ) {
parent::__construct( $plugin_path, $data );
self::$app = $this;
$this->plugin_data = $data;
$this->global_scripts();
if ( is_admin() ) {
$this->admin_scripts();
}
add_action( 'plugins_loaded', [ $this, 'plugins_loaded' ] );
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return \Wbcr_Factory480_Plugin|\WCM_Plugin
*/
public static function app() {
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
public function plugins_loaded() {
}
/**
* Регистрирует классы страниц в плагине
*
* Мы указываем плагину, где найти файлы страниц и какое имя у их класса. Чтобы плагин
* выполнил подключение классов страниц. После регистрации, страницы будут доступные по url
* и в меню боковой панели администратора. Регистрируемые страницы будут связаны с текущим плагином
* все операции выполняемые внутри классов страниц, имеют отношение только текущему плагину.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @throws \Exception
*/
private function register_pages() {
$admin_path = WCM_PLUGIN_DIR . '/admin/pages';
self::app()->registerPage( 'WbcrCmp_CommentsPage', $admin_path . '/class-page-comments.php' );
self::app()->registerPage( 'WbcrCmp_DeleteCommentsPage', $admin_path . '/class-page-delete-comments.php' );
self::app()->registerPage( 'WbcrCmp_MoreFeaturesPage', $admin_path . '/class-page-more-features.php' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts() {
require( WCM_PLUGIN_DIR . '/admin/boot.php' );
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function global_scripts() {
require( WCM_PLUGIN_DIR . '/includes/boot.php' );
require( WCM_PLUGIN_DIR . '/includes/classes/class-configurate-comments.php' );
new WbcrCmp_ConfigComments( self::$app );
}
}

View File

@@ -0,0 +1,338 @@
<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This class configures the parameters advanced
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
*
* @copyright (c) 2017 Webraftic Ltd
*/
class WbcrCmp_ConfigComments extends WBCR\Factory_Templates_134\Configurate {
private $modified_types = [];
/**
* @param Wbcr_Factory480_Plugin $plugin
*/
public function __construct( Wbcr_Factory480_Plugin $plugin ) {
parent::__construct( $plugin );
$this->plugin = $plugin;
}
public function registerActionsAndFilters() {
// These need to happen now
if ( $this->isDisabledAllPosts() ) {
add_action( 'widgets_init', [ $this, 'disableRcWidget' ] );
add_action( 'template_redirect', [ $this, 'filterQuery' ], 9 ); // before redirect_canonical
// Admin bar filtering has to happen here since WP 3.6
add_action( 'template_redirect', [ $this, 'filterAdminBar' ] );
add_action( 'admin_init', [ $this, 'filterAdminBar' ] );
} else {
if ( $this->getPopulateOption( 'comment_text_convert_links_pseudo' ) || $this->getPopulateOption( 'pseudo_comment_author_link' ) ) {
add_action( 'wp_enqueue_scripts', [ $this, 'assetsUrlSpanScripts' ] );
}
if ( $this->getPopulateOption( 'comment_text_convert_links_pseudo' ) ) {
add_filter( 'comment_text', [ $this, 'commentTextConvertLinksPseudo' ] );
}
if ( $this->getPopulateOption( 'pseudo_comment_author_link' ) ) {
add_filter( 'get_comment_author_link', [ $this, 'pseudoCommentAuthorLink' ], 100, 3 );
}
if ( $this->getPopulateOption( 'remove_url_from_comment_form' ) ) {
add_filter( 'comment_form_default_fields', [ $this, 'removeUrlFromCommentForm' ] );
}
}
// These can happen later
//add_action('plugins_loaded', array($this, 'register_text_domain'));
add_action( 'wp_loaded', [ $this, 'initWploadedFilters' ] );
}
/*
* Remove comment links from the admin bar in a multisite network.
*/
public function removeNetworkCommentLinks( $wp_admin_bar ) {
if ( $this->plugin->isNetworkActive() && is_user_logged_in() ) {
foreach ( (array) $wp_admin_bar->user->blogs as $blog ) {
$wp_admin_bar->remove_menu( 'blog-' . $blog->userblog_id . '-c' );
}
} else {
// We have no way to know whether the plugin is active on other sites, so only remove this one
$wp_admin_bar->remove_menu( 'blog-' . get_current_blog_id() . '-c' );
}
}
private function isDisabledAllPosts() {
return $this->getPopulateOption( 'disable_comments', 'enable_comments' ) == 'disable_comments';
}
private function isDisabledCertainPostTypes() {
return $this->getPopulateOption( 'disable_comments', 'enable_comments' ) == 'disable_certain_post_types_comments';
}
private function isEnabledComments() {
return $this->getPopulateOption( 'disable_comments', 'enable_comments' ) == 'enable_comments';
}
/*
* Get an array of disabled post type.
*/
private function getDisabledPostTypes() {
return wbcr_cmp_get_disabled_post_types();
}
/*
* Check whether comments have been disabled on a given post type.
*/
private function isPostTypeDisabled( $type ) {
return $this->isDisabledCertainPostTypes() && in_array( $type, $this->getDisabledPostTypes() );
}
public function initWploadedFilters() {
$disabled_post_types = $this->getDisabledPostTypes();
if ( ! empty( $disabled_post_types ) && ! $this->isEnabledComments() ) {
foreach ( $disabled_post_types as $type ) {
// we need to know what native support was for later
if ( post_type_supports( $type, 'comments' ) ) {
$this->modified_types[] = $type;
remove_post_type_support( $type, 'comments' );
remove_post_type_support( $type, 'trackbacks' );
}
}
add_filter( 'comments_array', [ $this, 'filterExistingComments' ], 20, 2 );
add_filter( 'comments_open', [ $this, 'filterCommentStatus' ], 20, 2 );
add_filter( 'pings_open', [ $this, 'filterCommentStatus' ], 20, 2 );
}
// Filters for the admin only
if ( is_admin() ) {
add_action( 'admin_print_footer_scripts', [ $this, 'discussionNotice' ] );
// if only certain types are disabled, remember the original post status
if ( ! $this->isDisabledAllPosts() ) {
add_action( 'edit_form_advanced', [ $this, 'editFormInputs' ] );
add_action( 'edit_page_form', [ $this, 'editFormInputs' ] );
} else {
add_action( 'admin_menu', [ $this, 'filterAdminMenu' ], 9999 ); // do this as late as possible
add_action( 'admin_print_footer_scripts-index.php', [ $this, 'dashboardJs' ] );
add_action( 'wp_dashboard_setup', [ $this, 'filterDashboard' ] );
add_filter( 'pre_option_default_pingback_flag', '__return_zero' );
}
} // Filters for front end only
else {
add_action( 'template_redirect', [ $this, 'checkCommentTemplate' ] );
if ( $this->isDisabledAllPosts() ) {
add_filter( 'feed_links_show_comments_feed', '__return_false' );
}
}
}
/*
* Replace the theme's comment template with a blank one.
* To prevent this, define DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE
* and set it to True
*/
public function checkCommentTemplate() {
if ( is_singular() && ( $this->isDisabledAllPosts() || $this->isPostTypeDisabled( get_post_type() ) ) ) {
if ( ! defined( 'DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE' ) || DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE == true ) {
// Kill the comments template.
add_filter( 'comments_template', [ $this, 'dummyCommentsTemplate' ], 20 );
}
// Remove comment-reply script for themes that include it indiscriminately
wp_deregister_script( 'comment-reply' );
// feed_links_extra inserts a comments RSS link
remove_action( 'wp_head', 'feed_links_extra', 3 );
}
}
public function dummyCommentsTemplate() {
return WCM_PLUGIN_DIR . '/includes/comments-template.php';
}
/*
* Issue a 403 for all comment feed requests.
*/
public function filterQuery() {
if ( is_comment_feed() ) {
wp_die( __( 'Comments are closed.' ), '', [ 'response' => 403 ] );
}
}
/*
* Remove comment links from the admin bar.
*/
public function filterAdminBar() {
if ( is_admin_bar_showing() ) {
// Remove comments links from admin bar
remove_action( 'admin_bar_menu', 'wp_admin_bar_comments_menu', 60 );
}
if ( is_multisite() ) {
add_action( 'admin_bar_menu', [ $this, 'removeNetworkCommentLinks' ], 500 );
}
}
public function editFormInputs() {
global $post;
// Without a dicussion meta box, comment_status will be set to closed on new/updated posts
if ( in_array( $post->post_type, $this->modified_types ) ) {
echo '<input type="hidden" name="comment_status" value="' . $post->comment_status . '" /><input type="hidden" name="ping_status" value="' . $post->ping_status . '" />';
}
}
public function discussionNotice() {
$disabled_post_types = $this->getDisabledPostTypes();
if ( get_current_screen()->id == 'options-discussion' && ! empty( $disabled_post_types ) ) {
$names = [];
foreach ( $disabled_post_types as $type ) {
$type_object = get_post_type_object( $type );
if ( empty( $type_object ) ) {
continue;
}
$names[ $type ] = $type_object->labels->name;
}
?>
<script>
jQuery(document).ready(function($) {
$(".wrap h2").first().after(<?php echo json_encode( '<div style="color: #900"><p>' . sprintf( __( 'Note: The <em>%s</em> plugin is currently active, and comments are completely disabled on: %s. Many of the settings below will not be applicable for those post types.', 'comments-plus' ), $this->plugin->getPluginTitle(), implode( ', ', $names ) ) . '</p></div>' );?>);
});
</script>
<?php
}
}
public function filterAdminMenu() {
global $pagenow;
if ( $pagenow == 'comment.php' || $pagenow == 'edit-comments.php' || $pagenow == 'options-discussion.php' ) {
wp_die( __( 'Comments are closed.' ), '', [ 'response' => 403 ] );
}
remove_menu_page( 'edit-comments.php' );
remove_submenu_page( 'options-general.php', 'options-discussion.php' );
}
public function filterDashboard() {
remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );
}
public function dashboardJs() {
echo '<script>
jQuery(function($){
$("#dashboard_right_now .comment-count, #latest-comments").hide();
$("#welcome-panel .welcome-comments").parent().hide();
});
</script>';
}
public function filterExistingComments( $comments, $post_id ) {
$post = get_post( $post_id );
return ( $this->isDisabledAllPosts() || $this->isPostTypeDisabled( $post->post_type ) ) ? [] : $comments;
}
public function filterCommentStatus( $open, $post_id ) {
$post = get_post( $post_id );
return ( $this->isDisabledAllPosts() || $this->isPostTypeDisabled( $post->post_type ) ) ? false : $open;
}
public function disableRcWidget() {
unregister_widget( 'WP_Widget_Recent_Comments' );
}
/**
* Convert links in comment text into span pseudo links
*
* @param $comment_text
*
* @return mixed
*/
public function commentTextConvertLinksPseudo( $comment_text ) {
return $this->convertLinksPseudo( $comment_text );
}
/**
* Convert links into span pseudo links
*
* @param $text
*
* @return mixed
*/
public function convertLinksPseudo( $text ) {
return preg_replace_callback( '/<a[^>]+href=[\'"](https?:\/\/[^"\']+)[\'"][^>]+>(.*?)<\/a>/i', [
$this,
'replaceLinks'
], $text );
}
public function replaceLinks( $matches ) {
if ( $matches[1] == get_home_url() ) {
return $matches[0];
}
return '<span class="wbcr-clearfy-pseudo-link" data-uri="' . $matches[1] . '" > ' . $matches[2] . '</span>';
}
/**
* Convert author link to pseudo link
*
* @return string
*/
public function pseudoCommentAuthorLink( $return, $author, $comment_ID ) {
$url = get_comment_author_url( $comment_ID );
$author = get_comment_author( $comment_ID );
if ( empty( $url ) || 'http://' == $url ) {
$return = $author;
} else {
$return = '<span class="wbcr-clearfy-pseudo-link" data-uri="' . $url . '">' . $author . '</span>';
}
return $return;
}
/**
* Remove url field from comment form
*
* @param $fields
*
* @return mixed
*/
public function removeUrlFromCommentForm( $fields ) {
if ( isset( $fields['url'] ) ) {
unset( $fields['url'] );
}
return $fields;
}
// todo: Убрать это грязное решение со скриптами.
public function assetsUrlSpanScripts() {
if ( ! is_singular() ) {
return;
}
wp_enqueue_style( 'wbcr-comments-plus-url-span', WCM_PLUGIN_URL . '/assets/css/url-span.css', [], $this->plugin->getPluginVersion() );
wp_enqueue_script( 'wbcr-comments-plus-url-span', WCM_PLUGIN_URL . '/assets/js/url-span.js', [ 'jquery' ], $this->plugin->getPluginVersion(), true );
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,4 @@
<?php
/* Dummy comments template file.
* This replaces the theme's comment template when comments are disabled everywhere
*/

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

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