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,46 @@
<?php
/**
* Activator for the GA cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 09.09.2017, Webcraftic
* @see Factory480_Activator
* @version 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WGA_Activation extends Wbcr_Factory480_Activator {
/**
* Runs activation actions.
*
* @since 1.0.0
*/
public function activate() {
$ga_cache = WGA_Plugin::app()->getPopulateOption( 'ga_cache' );
if ( $ga_cache ) {
wp_clear_scheduled_hook( 'wbcr/gac/update_analytic_library' );
if ( ! wp_next_scheduled( 'wbcr/gac/update_analytic_library' ) ) {
wp_schedule_event( time(), 'daily', 'wbcr/gac/update_analytic_library' );
}
}
}
/**
* Runs activation actions.
*
* @since 1.0.0
*/
public function deactivate() {
if ( wp_next_scheduled( 'wbcr/gac/update_analytic_library' ) ) {
wp_clear_scheduled_hook( 'wbcr/gac/update_analytic_library' );
}
}
}

View File

@@ -0,0 +1,274 @@
<?php
/**
* The boot file is needed to connect backend files, as well as register hooks.
* Some hooks are so small that it does not make sense to put them into a file
* or put them into a specific group of code.
*
* I usually register administrator notifications, create handlers before saving
* plugin settings or after, register options in the Clearfy plugin.
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright Webcraftic
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* After saving the settings in the plugin, we check whether the
* options for analytic caching are enabled or not. If enabled,
* add cron task.
*
* @param Wbcr_FactoryPages480_ImpressiveThemplate $page
*
* @param Wbcr_Factory480_Plugin $plugin
*
* @return void
* @since 3.0.1
*
*/
add_action('wbcr/factory/pages/impressive/after_form_save', function ($plugin, $page) {
if( WGA_Plugin::app()->getPluginName() != $plugin->getPluginName() ) {
return;
}
$ga_cache = WGA_Plugin::app()->getPopulateOption('ga_cache');
if( $ga_cache ) {
if( !wp_next_scheduled('wbcr/gac/update_analytic_library') ) {
wp_schedule_event(time(), 'daily', 'wbcr/gac/update_analytic_library');
}
} else {
if( wp_next_scheduled('wbcr/gac/update_analytic_library') ) {
wp_clear_scheduled_hook('wbcr/gac/update_analytic_library');
}
}
}, 10, 2);
if( !defined('LOADING_GA_CACHE_AS_ADDON') ) {
/**
* Notice that the plugin has been seriously updated!
*
* @param string $plugin_name
*
* @param array $notices all registered notices
*
* @return array all notices
* @since 3.0.1
*
*/
function wbcr_ga_admin_conflict_notices_error($notices, $plugin_name)
{
if( $plugin_name != WGA_Plugin::app()->getPluginName() ) {
return $notices;
}
$text = '<p>' . __('The <b>Simple Google Analytics</b> plugin has some major changes!', 'simple-google-analytics') . '</p>';
$text .= '<p>' . __('Unfortunately, the old version of the plugin (2.2.2) is no longer supported, but you still can download it from the WordPress repository in case if the new release doesnt work for you.', 'simple-google-analytics') . '</p>';
$text .= '<p>' . __('Weve updated the code and fixed the compatibility issue for the latest WordPress and PHP versions. Weve also added additional feature of the Local Google Analytics this way your website will load faster. The plugins name has been changed to Local Google Analytics, but all features remained the same.', 'simple-google-analytics') . '</p>';
$text .= '<p>' . sprintf(__('Please, check <a href="%s">plugin settings</a> and its performance on your website. We do care about you and want to avoid any problems with the new version.', 'simple-google-analytics') . '</p>', admin_url('options-general.php?page=ga_cache-' . WGA_Plugin::app()->getPluginName())) . '</p>';
$text .= '<p>' . sprintf(__('We are aimed to pay more attention to the speed and security aspects of your website. Thats why you should definitely try our basic WordPress optimization plugin as well. Clearfy includes functionality of this plugin and has many additional features for the website optimization:
<a href="%s">Donwload Clearfy for free</a>', 'simple-google-analytics'), 'https://clearfy.pro?utm_source=wordpress.org&utm_campaign=' . WGA_Plugin::app()->getPluginName()) . '</p>';
$notices[] = [
'id' => 'ga_plugin_upgrade_notice1',
'type' => 'warning',
'dismissible' => true,
'dismiss_expires' => 0,
'text' => $text
];
return $notices;
}
add_filter('wbcr/factory/admin_notices', 'wbcr_ga_admin_conflict_notices_error', 10, 2);
/**
* Migrate settings from the old plugin to the new one.
*
* @return void
* @since 3.0.1
*/
add_action('init', function () {
global $wpdb;
if( defined('LOADING_GA_CACHE_AS_ADDON') ) {
return;
}
$is_migrate_up_to_230 = WGA_Plugin::app()->getPopulateOption('is_migrate_up_to_230', false);
if( !$is_migrate_up_to_230 ) {
$old_plugin_tracking_id = get_option('sga_analytics_id');
$old_plugin_code_location = get_option('sga_code_location');
$old_plugin_demographic_and_interest = (int)get_option('sga_demographic_and_interest');
$old_plugin_sga_render_when_loggedin = (int)get_option('sga_render_when_loggedin');
if( !empty($old_plugin_tracking_id) ) {
WGA_Plugin::app()->updatePopulateOption('ga_cache', 1);
WGA_Plugin::app()->updatePopulateOption('ga_tracking_id', $old_plugin_tracking_id);
$script_position = 'footer';
if( $old_plugin_code_location == 'head' ) {
$script_position = 'header';
}
WGA_Plugin::app()->updatePopulateOption('ga_script_position', $script_position);
WGA_Plugin::app()->updatePopulateOption('ga_anonymize_ip', $old_plugin_demographic_and_interest);
WGA_Plugin::app()->updatePopulateOption('ga_track_admin', $old_plugin_sga_render_when_loggedin);
$wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE option_name LIKE 'sga_%';");
}
WGA_Plugin::app()->updatePopulateOption('is_migrate_up_to_230', 1);
}
});
/**
* Add a link to plugin meta. You can find this link in admin panel on
* the page plugins.php. Look under plugin short description.
*
* @param array $links An array of the plugin's metadata, including the version,
* author, author URI, and plugin URI.
* @param string $file path to the plugin file, relative to the plugins directory.
*
* @return array
*/
add_filter('plugin_row_meta', function ($links, $file) {
if( $file == WGA_PLUGIN_BASE ) {
$url = 'https://clearfy.pro';
if( get_locale() == 'ru_RU' ) {
$url = 'https://ru.clearfy.pro';
}
$url .= '?utm_source=wordpress.org&utm_campaign=' . WGA_Plugin::app()->getPluginName();
$links[] = '<a href="' . $url . '" style="color: #FF5722;font-weight: bold;" target="_blank">' . __('Get ultimate plugin free', 'simple-google-analytics') . '</a>';
}
return $links;
}, 10, 2);
/**
* Rating widget url
*
* @param string $page_url
* @param string $plugin_name
*
* @return string
*/
add_filter('wbcr_factory_imppage_rating_widget_url', function ($page_url, $plugin_name) {
if( $plugin_name == WGA_Plugin::app()->getPluginName() ) {
return 'https://wordpress.org/support/plugin/simple-google-analytics/reviews/#new-post';
}
return $page_url;
}, 10, 2);
/**
* Удаляем лишние виджеты из правого сайдбара в интерфейсе плагина
*
* - Виджет с премиум рекламой
* - Виджет с рейтингом
* - Виджет с маркерами информации
*/
add_filter('wbcr/factory/pages/impressive/widgets', function ($widgets, $position, $plugin) {
if( WGA_Plugin::app()->getPluginName() == $plugin->getPluginName() && 'right' == $position ) {
unset($widgets['business_suggetion']);
unset($widgets['rating_widget']);
unset($widgets['info_widget']);
}
return $widgets;
}, 20, 3);
} else {
/**
* This action is executed when the component of the Clearfy plugin
* is activate and if this component is name ga_cache
*
* @return void
* @since 3.0.1
*/
add_action('wbcr/clearfy/activated_component', function ($component_name) {
if( $component_name == 'ga_cache' ) {
require_once WGA_PLUGIN_DIR . '/admin/activation.php';
$plugin = new WGA_Activation(WGA_Plugin::app());
$plugin->activate();
}
});
/**
* This action is executed when the component of the Clearfy plugin
* is deactivated and if this component is name ga_cache
*
* @return void
* @since 3.0.1
*/
add_action('wbcr_clearfy_pre_deactivate_component', function ($component_name) {
if( $component_name == 'ga_cache' ) {
require_once WGA_PLUGIN_DIR . '/admin/activation.php';
$plugin = new WGA_Activation(WGA_Plugin::app());
$plugin->deactivate();
}
});
/**
* We register options of this plugin in global Clearfy options. Clearfy later can automatically
* set default values for this options or completely delete it from site database.
*
* In more detail you can read about it here: wp-plugin-clearfy\admin\includes\options.php
*
* @param array $options all available component options plugin clearfy
*
* @return array
*/
function wbcr_ga_group_options($options)
{
$options[] = [
'name' => 'ga_cache',
'title' => __('Google Analytics Cache', 'simple-google-analytics'),
'tags' => []
];
$options[] = [
'name' => 'ga_tracking_id',
'title' => __('Google analytic Code', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'ga_adjusted_bounce_rate',
'title' => __('Use adjusted bounce rate?', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'ga_enqueue_order',
'title' => __('Change enqueue order?', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'ga_disable_display_features',
'title' => __('Disable all display features functionality?', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'ga_anonymize_ip',
'title' => __('Use Anonymize IP? (Required by law for some countries)', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'ga_track_admin',
'title' => __('Track logged in Administrators?', 'clearfy'),
'tags' => []
];
return $options;
}
add_filter("wbcr_clearfy_group_options", 'wbcr_ga_group_options');
}

View File

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

View File

@@ -0,0 +1,174 @@
<?php
/**
* Options for additionally form
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 21.01.2018, Webcraftic
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* @return array
*/
function wbcr_ga_get_plugin_options()
{
$options = [];
$options[] = [
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header">' . __('<strong>Improve browser caching for 3rd-party services</strong>.', 'simple-google-analytics') . '<p>' . __('To improve Google Page Speed indicators Analytics caching is needed. However, it can also slightly increase your website loading speed, because Analytics js files will load locally. The second case that you might need these settings is the usual Google Analytics connection to your website. You do not need to do this with other plugins or insert the tracking code into your theme.', 'simple-google-analytics') . '</p></div>'
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'facebook_cache',
'title' => __('Improve browser caching for Facebook Pixel', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clearfy will host these Facebook Pixels locally on your server to help satisfy the PageSpeed recommendation for Leverage browser caching.', 'simple-google-analytics') . '<br>--<br><span class="wbcr-factory-light-orange-color">' . __('ATTENTION! Before using this option, remove the previously installed Google Analytics code inside your theme or plugins associated with this feature!', 'simple-google-analytics') . '</span>',
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'google_analytics_cache',
'title' => __('Improve browser caching for Google Analytics', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clearfy will host these Google scripts locally on your server to help satisfy the PageSpeed recommendation for Leverage browser caching.', 'simple-google-analytics') . (WGA_Plugin::app()->getPopulateOption('ga_cache') ? '<br>--<br><span class="wbcr-factory-light-orange-color">' . __('ATTENTION! Before using this option, please disable the option "Add Google Analytics code and Cache"!', 'simple-google-analytics') . '</span>' : ''),
'cssClass' => WGA_Plugin::app()->getPopulateOption('ga_cache') ? ['factory-checkbox-disabled'] : [],
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'yandex_metrika_cache',
'title' => __('Improve browser caching for Yandex metrika', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clearfy will host these Yandex metrika scripts locally on your server to help satisfy the PageSpeed recommendation for Leverage browser caching..', 'simple-google-analytics') . (WGA_Plugin::app()->getPopulateOption('ga_cache') ? '<br>--<br><span class="wbcr-factory-light-orange-color">' . __('ATTENTION! Before using this option, please disable the option "Add Google Analytics code and Cache"!', 'simple-google-analytics') . '</span>' : ''),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'ga_cache',
'title' => __('Add Google Analytics code and Cache', 'simple-google-analytics'),
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('If you enable this option, the plugin will begin to save a local copy of Google Analytics to speed up the loading of your website and improve Google Page Speed.', 'simple-google-analytics') . '<br>--<br><span class="wbcr-factory-red-color">' . __('ATTENTION! This option is deprecated and cannot be used since plugin version 1.9.0! Use the new option "Improve browser caching for Google Analytics", you will have to insert the google analytics code yourself without the Clearfy plugin.', 'simple-google-analytics') . '</span>',
'default' => false,
'cssClass' => !WGA_Plugin::app()->getPopulateOption('ga_cache') ? ['factory-checkbox-disabled'] : [],
'eventsOn' => [
'show' => '#wbcr-clearfy-performance-ga-block'
],
'eventsOff' => [
'hide' => '#wbcr-clearfy-performance-ga-block'
]
];
$options[] = [
'type' => 'div',
'id' => 'wbcr-clearfy-performance-ga-block',
'items' => [
[
'type' => 'textbox',
'way' => 'buttons',
'name' => 'ga_tracking_id',
'title' => __('Google analytic Code', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Set the Google Analytics tracking code.', 'simple-google-analytics'),
'placeholder' => 'UA-XXXXX-Y'
],
[
'type' => 'dropdown',
'way' => 'buttons',
'name' => 'ga_script_position',
'data' => [
['header', 'Header'],
['footer', 'Footer'],
],
'title' => __('Save GA in', 'simple-google-analytics'),
'hint' => __('Select location for the Google Analytics code.', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'default' => 'footer'
],
[
'type' => 'integer',
'name' => 'ga_adjusted_bounce_rate',
'title' => __('Use adjusted bounce rate?', 'simple-google-analytics'),
'default' => 0,
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Essentially, you set up an event which is triggered after a user spends a certain amount of time on the landing page, telling Google Analytics not to count these users as bounces. A user may come to your website, find all of the information they need (a phone number, for example) and then leave the site without visiting another page. Without adjusted bounce rate, such a user would be considered a bounce, even though they had a successful experience. By defining a time limit after which you can consider a user to be "engaged," that user would no longer count as a bounce, and you\'d get a more accurate idea of whether they found what they were looking for.', 'simple-google-analytics')
],
[
'type' => 'integer',
'way' => 'buttons',
'name' => 'ga_enqueue_order',
'title' => __('Change enqueue order?', 'simple-google-analytics'),
'default' => 0,
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('By default, Google Analytics code is loaded before other scripts and javasscript code, but if you set the value to 100, the GA code will be loaded after all other scripts. By changing the priority, you can set code position on the page.', 'simple-google-analytics')
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'ga_disable_display_features',
'title' => __('Disable all display features functionality?', 'simple-google-analytics'),
//'layout' => array('hint-type' => 'icon', 'hint-icon-color' => 'grey'),
'hint' => sprintf(__('Disable all <a href="%s">display features functionality?</a>', 'simple-google-analytics'), 'https://developers.google.com/analytics/devguides/collection/analyticsjs/display-features'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'ga_anonymize_ip',
'title' => __('Use Anonymize IP? (Required by law for some countries)', 'simple-google-analytics'),
//'layout' => array('hint-type' => 'icon', 'hint-icon-color' => 'grey'),
'hint' => sprintf(__('Use <a href="%s">Anonymize IP?</a> (Required by law for some countries)', 'simple-google-analytics'), 'https://support.google.com/analytics/answer/2763052'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'ga_track_admin',
'title' => __('Track logged in Administrators?', 'simple-google-analytics'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Track logged in Administrators?', 'simple-google-analytics'),
'default' => false
]
]
];
return $options;
}
/**
* @param $form
* @param $page Wbcr_FactoryPages480_ImpressiveThemplate
*
* @return mixed
*/
function wbcr_ga_additionally_form_options($form, $page)
{
if( empty($form) ) {
return $form;
}
$options = wbcr_ga_get_plugin_options();
foreach($options as $option) {
$form[0]['items'][] = $option;
}
return $form;
}
add_filter('wbcr_clr_code_clean_form_options', 'wbcr_ga_additionally_form_options', 10, 2);

View File

@@ -0,0 +1,97 @@
<?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
* @version 1.0
*/
class WGA_CachePage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* {@inheritDoc}
*
* @var string
*/
public $id = "ga_cache";
/**
* {@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;
/**
* @param Wbcr_Factory480_Plugin $plugin
*/
public function __construct( Wbcr_Factory480_Plugin $plugin ) {
$this->menu_title = __( 'Local Google Analytics', 'simple-google-analytics' );
if ( ! defined( 'LOADING_GA_CACHE_AS_ADDON' ) ) {
$this->internal = false;
$this->menu_target = 'options-general.php';
$this->add_link_to_plugin_actions = true;
}
parent::__construct( $plugin );
$this->plugin = $plugin;
}
/**
* {@inheritDoc}
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.1.0
* @return string|void
*/
public function getPageTitle() {
return __( 'General', 'simple-google-analytics' );
}
/**
* Permalinks options.
*
* @since 1.0.0
* @return mixed[]
*/
public function getPageOptions() {
$options = wbcr_ga_get_plugin_options();
$formOptions = [];
$formOptions[] = [
'type' => 'form-group',
'items' => $options,
//'cssClass' => 'postbox'
];
return apply_filters( 'wbcr_ga_notices_form_options', $formOptions, $this );
}
}

View File

@@ -0,0 +1,21 @@
<?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 WGA_MoreFeaturesPage extends \WBCR\Factory_Templates_134\Pages\MoreFeatures {
}

View File

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

View File

@@ -0,0 +1,56 @@
<?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('WGA_PLUGIN_ACTIVE') ) {
define('WGA_PLUGIN_VERSION', '3.2.9');
define('WGA_TEXT_DOMAIN', 'simple-google-analytics');
define('WGA_PLUGIN_ACTIVE', true);
// Этот плагин загружен, как аддон для плагина Clearfy
define('LOADING_GA_CACHE_AS_ADDON', true);
if( !defined('WGA_PLUGIN_DIR') ) {
define('WGA_PLUGIN_DIR', dirname(__FILE__));
}
if( !defined('WGA_PLUGIN_BASE') ) {
define('WGA_PLUGIN_BASE', plugin_basename(__FILE__));
}
if( !defined('WGA_PLUGIN_URL') ) {
define('WGA_PLUGIN_URL', plugins_url('', __FILE__));
}
if( !defined('WGA_PLUGIN_CACHE_FOLDER') ) {
define('WGA_PLUGIN_CACHE_FOLDER', 'wga-cache');
}
try {
// Global scripts
require_once(WGA_PLUGIN_DIR . '/includes/3rd-party/class-clearfy-plugin.php');
new WGA_Plugin();
} catch( Exception $e ) {
$wga_plugin_error_func = function () use ($e) {
$error = sprintf("The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Local Google Analytic', $e->getMessage(), $e->getCode());
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action('admin_notices', $wga_plugin_error_func);
add_action('network_admin_notices', $wga_plugin_error_func);
}
}

View File

@@ -0,0 +1,100 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Local Google Analytic
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
* @version 1.0
*/
class WGA_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->init_activation();
$this->admin_scripts();
}
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return WCL_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.0.0
*/
private function init_activation()
{
require_once(WGA_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WGA_Activation');
}
/**
* @throws \Exception
* @since 3.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
require(WGA_PLUGIN_DIR . '/admin/options.php');
require(WGA_PLUGIN_DIR . '/admin/boot.php');
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.0.0
*/
private function global_scripts()
{
require(WGA_PLUGIN_DIR . '/includes/classes/class-configurate-ga.php');
new WGA_ConfigGACache(self::$app);
add_action('plugins_loaded', function () {
require(WGA_PLUGIN_DIR . '/includes/classes/class-scheduler.php');
new \WGA\Busting\Sheduller();
});
}
}

View File

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

View File

@@ -0,0 +1,135 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Plugin class
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 19.02.2018, Webcraftic
*/
class WGA_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->init_activation();
$this->admin_scripts();
}
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return \Wbcr_Factory480_Plugin|\WGA_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.0.0
*/
private function init_activation()
{
require_once(WGA_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WGA_Activation');
}
/**
* Регистрирует классы страниц в плагине
*
* Мы указываем плагину, где найти файлы страниц и какое имя у их класса. Чтобы плагин
* выполнил подключение классов страниц. После регистрации, страницы будут доступные по url
* и в меню боковой панели администратора. Регистрируемые страницы будут связаны с текущим плагином
* все операции выполняемые внутри классов страниц, имеют отношение только текущему плагину.
*
* @throws \Exception
* @since 3.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function register_pages()
{
if( $this->as_addon ) {
return;
}
if( $this->isNetworkActive() and !is_network_admin() ) {
return;
}
self::app()->registerPage('WGA_CachePage', WGA_PLUGIN_DIR . '/admin/pages/class-pages-general-settings.php');
self::app()->registerPage('WGA_MoreFeaturesPage', WGA_PLUGIN_DIR . '/admin/pages/class-pages-more-features.php');
}
/**
* @throws \Exception
* @since 3.1.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
require(WGA_PLUGIN_DIR . '/admin/options.php');
require(WGA_PLUGIN_DIR . '/admin/boot.php');
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.0.0
*/
private function global_scripts()
{
require(WGA_PLUGIN_DIR . '/includes/classes/class-configurate-ga.php');
new WGA_ConfigGACache(self::$app);
require(WGA_PLUGIN_DIR . '/includes/classes/class-scheduler.php');
new \WGA\Busting\Sheduller();
}
}

View File

@@ -0,0 +1,562 @@
<?php
namespace WGA\Busting;
use FilesystemIterator;
use IteratorIterator;
use RegexIterator;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2020 CreativeMotion Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
abstract class Abstract_Cache {
/**
* Cache busting files base path
*
* @var string
*/
protected $busting_path;
/**
* Cache busting base URL
*
* @var string
*/
protected $busting_url;
/**
* Filename for the cache busting file.
*
* @var string
*/
protected $filename;
/**
* Filesystem object.
*
* @var object
* @since 3.2.0
*/
protected $filesystem = false;
/**
* Constructor.
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @since 3.2.0
*/
public function __construct($busting_path, $busting_url)
{
/*
* Define the timeouts for the connections. Only available after the constructor is called
* to allow for per-transport overriding of the default.
*/
if( !defined('FS_CONNECT_TIMEOUT') ) {
define('FS_CONNECT_TIMEOUT', 30);
}
if( !defined('FS_TIMEOUT') ) {
define('FS_TIMEOUT', 30);
}
// Set the permission constants if not already set.
if( !defined('FS_CHMOD_DIR') ) {
define('FS_CHMOD_DIR', (fileperms(ABSPATH) & 0777 | 0755));
}
if( !defined('FS_CHMOD_FILE') ) {
define('FS_CHMOD_FILE', (fileperms(ABSPATH . 'index.php') & 0777 | 0644));
}
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
$this->filesystem = new \WP_Filesystem_Direct(new \StdClass());
}
/**
* Tell if the cache busting should happen.
*
* @return bool
* @since 3.2.0
*
*/
private function is_allowed()
{
//if( defined('DONOTROCKETOPTIMIZE') && DONOTROCKETOPTIMIZE ) {
//return false;
//}
return true;
}
/**
* Saves the content of the URL to bust to the busting file.
*
* @param string $url URL to get the content from.
* @return bool
* @since 3.2.0
*/
public function refresh_save($url)
{
// Before doing anything, make sure the busting file can be created.
if( !$this->is_busting_dir_writable() ) {
return false;
}
// Get remote content.
$content = $this->get_remote_contents($url);
if( !$content ) {
// Could not get the remote contents.
return false;
}
$version = md5($content);
$path = $this->get_busting_file_path($version);
return $this->update_file_contents($path, $content);
}
/**
* Performs the replacement process.
*
* @param string $html HTML content.
* @return string
* @since 3.2.0
*/
abstract public function replace_url($html);
/**
* Searches for element(s) in the DOM
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
* @since 3.2.0
*/
abstract protected function find($pattern, $html);
/**
* Saves the content of the URL to bust to the busting file if it doesn't exist yet.
*
* @param string $url URL to get the content from.
* @return bool
* @since 3.2.0
*/
public function save($url)
{
if( $this->get_busting_version() ) {
// We have a local copy.
\WGA_Plugin::app()->logger->info('Found local file. Busting path ' . $this->get_busting_path());
return true;
}
if( $this->refresh_save($url) ) {
// We downloaded a fresh copy.
\WGA_Plugin::app()->logger->info('New copy downloaded. Busting path ' . $this->get_busting_path());
return true;
}
return false;
}
/**
* Deletes the busting file.
*
* @return bool True on success. False on failure.
* @since 3.2.0
*/
public function delete()
{
$files = $this->get_all_files();
if( false === $files ) {
// Error.
return false;
}
$this->file_version = null;
if( !$files ) {
// No local files yet.
return true;
}
return $this->delete_files(array_keys($files));
}
/**
* Get the version of the current busting file.
*
* @return string|bool Version of the file. False if the file does not exist.
*
*
* @since 3.2.0
*/
protected function get_busting_version()
{
if( !empty($this->file_version) ) {
return $this->file_version;
}
$files = $this->get_all_files();
if( !$files ) {
return false;
}
$this->file_version = reset($files);
return $this->file_version;
}
/**
* Get all cached files in the directory.
* In a perfect world, there should be only one.
*
* @return bool|array A list of file names (as array keys) and versions (as array values). False on failure.
* @since 3.2.0
* @access private
*
*/
private function get_all_files()
{
$dir_path = rtrim($this->busting_path, '\\/');
if( !$this->filesystem->exists($dir_path) ) {
return [];
}
if( !$this->filesystem->is_readable($dir_path) ) {
\WGA_Plugin::app()->logger->error('Directory is not readable. Path ' . $dir_path);
return false;
}
$pattern = '/' . sprintf($this->escape_file_name($this->filename_pattern), '([a-f0-9]{32}|local)') . '/';
$entries = $this->get_dir_files_by_regex($dir_path, $pattern);
$list = [];
foreach($entries as $entry) {
$filename = $entry->getFilename();
preg_match($pattern, $filename, $file_details_match);
if( !empty($file_details_match[1]) ) {
$list[$filename] = $file_details_match[1];
}
}
return $list;
}
/**
* Get the final URL for the current cache busting file.
*
* @return string|bool URL of the file. False if the file does not exist.
* @since 3.2.0
* @access protected
*
*/
public function get_busting_url()
{
return $this->get_busting_file_url($this->get_busting_version());
}
/**
* Get the path to the current cache busting file.
*
* @return string|bool URL of the file. False if the file does not exist.
*
*
* @since 3.2.0
* @access protected
*/
protected function get_busting_path()
{
return $this->get_busting_file_path($this->get_busting_version());
}
/**
* Get the final URL for a cache busting file.
*
* @param string $version The file version.
* @return string|bool URL of the file with this version. False if no versions are provided.
* @since 3.2.0
* @access private
*
*
*/
private function get_busting_file_url($version)
{
if( !$version ) {
return false;
}
$filename = $this->get_busting_file_name($version);
return $this->busting_url . $filename;
}
/**
* Get the local file name.
*
* @param string $version The file version.
* @return string|bool The name of the file with this version. False if no versions are provided.
* @since 3.2.0
* @access private
*/
private function get_busting_file_name($version)
{
if( !$version ) {
return false;
}
return sprintf($this->filename_pattern, $version);
}
/**
* Get the local file path.
*
* @param string $version The file version.
* @return string|bool Path to the file with this version. False if no versions are provided.
* @since 3.2.0
* @access private
*/
private function get_busting_file_path($version)
{
if( !$version ) {
return false;
}
return $this->busting_path . $this->get_busting_file_name($version);
}
/**
* Escape a file name, to be used in a regex pattern (delimiter is `/`).
* `%s` conversion specifications are protected.
*
* @param string $filename_pattern The file name.
* @return string
* @since 3.2.0
* @access private
*
*/
private function escape_file_name($filename_pattern)
{
return preg_quote($filename_pattern, '/');
}
/**
* Delete busting files.
*
* @param array $files A list of file names.
* @return bool True if files have been deleted (or no files have been provided). False on failure.
* @since 3.2.0
*/
private function delete_files($files)
{
if( !$files ) {
return true;
}
$has_deleted = false;
$error_paths = [];
foreach($files as $file_name) {
if( !$this->filesystem->delete($this->busting_path . $file_name, false, 'f') ) {
$error_paths[] = $this->busting_path . $file_name;
} else {
$has_deleted = true;
}
}
if( $error_paths ) {
\WGA_Plugin::app()->logger->error('Local file(s) could not be deleted. Path ' . $error_paths);
}
return $has_deleted;
}
/**
* Add new contents to a file. If the file doesn't exist, it is created.
*
* @param string $file_path Path to the file to update.
* @param string $file_contents New contents.
* @return string|bool The file contents on success. False on failure.
*
*
* @since 3.2.0
* @access private
*/
private function update_file_contents($file_path, $file_contents)
{
if( !$this->is_busting_dir_writable() ) {
return false;
}
if( !$this->filesystem->put_contents($file_path, $file_contents) ) {
\WGA_Plugin::app()->logger->error('Contents could not be written into file. Path ' . $file_path);
return false;
}
return $file_contents;
}
/**
* Tell if the directory containing the busting file is writable.
*
* @return bool
*
*
* @since 3.2
* @access private
*/
private function is_busting_dir_writable()
{
if( !$this->filesystem->exists($this->busting_path) ) {
wp_mkdir_p($this->busting_path);
}
if( !$this->filesystem->is_writable($this->busting_path) ) {
\WGA_Plugin::app()->logger->error('Directory is not writable. Paths ' . $this->busting_path);
return false;
}
return true;
}
/** ----------------------------------------------------------------------------------------- */
/** GET LOCAL/REMOTE CONTENTS =============================================================== */
/** ----------------------------------------------------------------------------------------- */
/**
* Get a file contents. If the file doesn't exist, new contents are fetched remotely.
*
* @param string $file_path Path to the file.
* @param string $file_url URL to the remote file.
* @return string|bool The contents on success, false on failure.
*
* @since 3.2.0
*/
private function get_file_or_remote_contents($file_path, $file_url)
{
$content = $this->get_file_contents($file_path);
if( $content ) {
// We have a local file.
return $content;
}
return $this->get_remote_contents($file_url);
}
/**
* Get a file contents.
*
* @param string $file_path Path to the file.
* @return string|bool The contents on success, false on failure.
* @since 3.2.0
* @access private
*
*
*/
private function get_file_contents($file_path)
{
if( !$this->filesystem->exists($file_path) ) {
\WGA_Plugin::app()->logger->error('Local file does not exist. Path ' . $file_path);
return false;
}
if( !$this->filesystem->is_readable($file_path) ) {
\WGA_Plugin::app()->logger->error('Local file is not readable. Path' . $file_path);
return false;
}
$content = $this->filesystem->get_contents($file_path);
if( !$content ) {
\WGA_Plugin::app()->logger->error('Local file is empty. Path' . $file_path);
return false;
}
return $content;
}
/**
* Get the contents of a URL.
*
* @param string $url The URL to request.
* @return string|bool The contents on success. False on failure.
* @since 3.2.0
* @access private
*
*
*/
private function get_remote_contents($url)
{
try {
$response = wp_remote_get($url);
} catch( \Exception $e ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $e->getMessage());
return false;
}
if( is_wp_error($response) ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $response->get_error_message());
return false;
}
$contents = wp_remote_retrieve_body($response);
if( !$contents ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $response->get_error_message());
return false;
}
return $contents;
}
/**
* Gets Directory files matches regex.
*
* @param string $dir Directory to search for files inside it.
* @param string $regex Regular expression for files need to be searched for.
*
* @return array|RegexIterator List of files matches this regular expression.
* @since 3.6.3
* @access private
*
*/
function get_dir_files_by_regex($dir, $regex)
{ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
try {
$iterator = new IteratorIterator(new FilesystemIterator($dir));
return new RegexIterator($iterator, $regex);
} catch( \Exception $e ) {
return [];
}
}
}

View File

@@ -0,0 +1,207 @@
<?php
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WGA_ConfigGACache extends WBCR\Factory_Templates_134\Configurate {
public function registerActionsAndFilters() {
if ( $this->getPopulateOption( 'ga_cache' ) ) {
add_filter( 'cron_schedules', [ $this, 'cron_additions' ] );
// Load update script to schedule in wp_cron.
add_action( 'wbcr/gac/update_analytic_library', [ $this, 'update_local_analytic' ] );
if ( ! is_admin() ) {
$this->add_google_analitics_script();
}
}
}
/**
* Extends the recurrence interval of cron tasks. In the core,
* the number of recurrence intervals for cron tasks is limited.
* Therefore, we create 3 additional recurrences weekly,
* twicemonthly, monthly.
*
* @param array $schedules an array of already recorded recurrences
*
* @return mixed
*/
public function cron_additions( $schedules ) {
$schedules['weekly'] = [
'interval' => DAY_IN_SECONDS * 7,
'display' => __( 'Once Weekly' ),
];
$schedules['twicemonthly'] = [
'interval' => DAY_IN_SECONDS * 14,
'display' => __( 'Twice Monthly' ),
];
$schedules['monthly'] = [
'interval' => DAY_IN_SECONDS * 30,
'display' => __( 'Once Monthly' ),
];
return $schedules;
}
/**
* Enables update-local-ga.php, which creates and updates
* the Google analytics library locally on the user's site.
* This method performs via cron and manually if the library
* file has not yet been created.
*
* @since 3.0.1
* @return void
*/
public function update_local_analytic() {
include( WGA_PLUGIN_DIR . '/includes/update-local-ga.php' );
}
/**
* Generates tracking code based on the user options set. Then it just
* prints this code on the page. The code can be printed to the header
* or footer, depending on which action called this method.
*
* @since 3.0.1
* @return void
*/
public function print_google_analytics() {
$tracking_id = $this->getPopulateOption( 'ga_tracking_id' );
$track_admin = (int) $this->getPopulateOption( 'ga_track_admin' );
// If user is admin we don't want to render the tracking code, when option is disabled.
if ( empty( $tracking_id ) || ( current_user_can( 'manage_options' ) && ( ! $track_admin ) ) ) {
return;
}
$adjusted_bounce_rate = (int) $this->getPopulateOption( 'ga_adjusted_bounce_rate', 0 );
$anonymize_ip = (int) $this->getPopulateOption( 'ga_anonymize_ip', 0 );
$disable_display_features = (int) $this->getPopulateOption( 'ga_disable_display_features', 0 );
echo "<!-- Google Analytics Local by " . $this->plugin->getPluginTitle() . " -->" . PHP_EOL;
echo "<script>" . PHP_EOL;
echo "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','" . esc_url( $this->get_local_analytic_file_url() ) . "','ga');" . PHP_EOL;
/**
* Allows you to complement the current configuration analytics.
* For example, one of the users wanted to add google adwords ID
* to this code.
*
* When using this action, you must enter only javascript code,
* without opening and closing tags.
*
* @since 3.0.1
*/
do_action( 'wbcr/gac/print_analytic_options', [
'tracking_id' => $tracking_id,
'track_admin' => $track_admin,
'adjusted_bounce_rate' => $adjusted_bounce_rate,
'anonymize_ip' => $anonymize_ip,
'disable_display_features' => $disable_display_features
] );
echo "ga('create', '" . esc_attr( $tracking_id ) . "', 'auto');" . PHP_EOL;
echo $disable_display_features ? "ga('set', 'displayFeaturesTask', null);" . PHP_EOL : '';
echo $anonymize_ip ? "ga('set', 'anonymizeIp', true);" . PHP_EOL : '';
echo "ga('send', 'pageview');";
echo $adjusted_bounce_rate ? PHP_EOL . 'setTimeout("ga(' . "'send','event','adjusted bounce rate','" . $adjusted_bounce_rate . " seconds')" . '"' . ',' . $adjusted_bounce_rate * 1000 . ');' : '';
echo PHP_EOL . '</script>' . PHP_EOL;
echo "<!-- end Google Analytics Local by " . $this->plugin->getPluginTitle() . " -->" . PHP_EOL;
}
/**
* Inserts tracking code in header and footer. Before insertion,
* it executes the wbcr_ga_update_local_script action to update
* Google local analytics library.
*
* @since 3.0.1
* @return void
*/
private function add_google_analitics_script() {
$tracking_id = $this->getPopulateOption( 'ga_tracking_id' );
if ( ! empty( $tracking_id ) ) {
$local_ga_file = $this->get_local_analytic_file_path();
// If file is not created yet, create now!
if ( $local_ga_file && ! file_exists( $local_ga_file ) ) {
ob_start();
$this->update_local_analytic();
ob_end_clean();
}
$enqueue_order = $this->getPopulateOption( 'ga_enqueue_order', 0 );
if ( $this->getPopulateOption( 'ga_script_position', 'footer' ) == 'header' ) {
add_action( 'wp_head', [ $this, 'print_google_analytics' ], $enqueue_order );
} else {
add_action( 'wp_footer', [ $this, 'print_google_analytics' ], $enqueue_order );
}
}
}
/**
* Get uploads dir
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.1.1
*/
private function get_uploads_dir() {
$upload_dir = wp_upload_dir();
if ( true === $upload_dir['error'] ) {
return null;
}
return (object) $upload_dir;
}
/**
* Get the path to an encrypted google analytics file
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.1.1
* @return string|null
*/
private function get_local_analytic_file_url() {
if ( $this->get_uploads_dir() ) {
return untrailingslashit( $this->get_uploads_dir()->baseurl ) . '/wga-cache/local-ga.js';
}
return null;
}
/**
* Get the url to an encrypted google analytics file
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 3.1.1
* @return string|null
*/
private function get_local_analytic_file_path() {
if ( $this->get_uploads_dir() ) {
return untrailingslashit( $this->get_uploads_dir()->basedir ) . '/wga-cache/local-ga.js';
}
return null;
}
}

View File

@@ -0,0 +1,555 @@
<?php
namespace WGA\Busting;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class Facebook_SDK {
/**
* Facebook SDK URL.
* %s is a locale like "en_US".
*
* @var string
* @since 3.2.0
*/
protected $url = 'https://connect.facebook.net/%s/sdk.js';
/**
* Filename for the cache busting file.
* %s is a locale like "en_US".
*
* @var string
* @since 3.2.0
*/
protected $filename = 'fbsdk-%s.js';
/**
* Flag to track the replacement.
*
* @var bool
* @since 3.2.0
*/
protected $is_replaced = false;
/**
* Filesystem object.
*
* @var object
* @since 3.2.0
*/
protected $filesystem = false;
/**
* Constructor.
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @since 3.2.0
*
*/
public function __construct($busting_path, $busting_url)
{
/** Warning: the file name and script URL are dynamic, and must be run through sprintf(). */
$this->busting_path = $busting_path . 'facebook-tracking/';
$this->busting_url = $busting_url . 'facebook-tracking/';
/*
* Define the timeouts for the connections. Only available after the constructor is called
* to allow for per-transport overriding of the default.
*/
if( !defined('FS_CONNECT_TIMEOUT') ) {
define('FS_CONNECT_TIMEOUT', 30);
}
if( !defined('FS_TIMEOUT') ) {
define('FS_TIMEOUT', 30);
}
// Set the permission constants if not already set.
if( !defined('FS_CHMOD_DIR') ) {
define('FS_CHMOD_DIR', (fileperms(ABSPATH) & 0777 | 0755));
}
if( !defined('FS_CHMOD_FILE') ) {
define('FS_CHMOD_FILE', (fileperms(ABSPATH . 'index.php') & 0777 | 0644));
}
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
$this->filesystem = new \WP_Filesystem_Direct(new \StdClass());
}
/**
* Perform the URL replacement process.
*
* @param string $html HTML contents.
* @return string HTML contents.
* @since 3.2.0
*
*/
public function replace_url($html)
{
$this->is_replaced = false;
$tag = $this->find('<script[^>]*?>(.*)<\/script>', $html);
if( !$tag ) {
return $html;
}
\WGA_Plugin::app()->logger->info('FACEBOOK SDK CACHING PROCESS STARTED. Tag ' . $tag);
$locale = $this->get_locale_from_url($tag);
$remote_url = $this->get_url($locale);
if( !$this->save($remote_url) ) {
return $html;
}
$file_url = $this->get_busting_file_url($locale);
$replace_tag = preg_replace('@(?:https?:)?//connect\.facebook\.net/[a-zA-Z_-]+/sdk\.js@i', $file_url, $tag, -1, $count);
if( !$count || false === strpos($html, $tag) ) {
\WGA_Plugin::app()->logger->error('The facebook sdk local file URL could not be replaced in the page contents.');
return $html;
}
$html = str_replace($tag, $replace_tag, $html);
$file_path = $this->get_busting_file_path($locale);
$xfbml = $this->get_xfbml_from_url($tag); // Default value should be set to false.
$app_id = $this->get_appId_from_url($tag); // APP_ID is the only required value.
$url_version = $this->get_version_from_url($tag);
$version = false === $url_version ? 'v5.0' : $url_version; // If version is not available set it to the latest: v.5.0.
if( false !== $app_id ) {
// Add FB async init.
$fb_async_script = '<script>window.fbAsyncInit = function fbAsyncInit () {FB.init({appId: \'' . $app_id . '\',xfbml: ' . $xfbml . ',version: \'' . $version . '\'})}</script>';
$html = str_replace('</body>', $fb_async_script . '</body>', $html);
}
$this->is_replaced = true;
\WGA_Plugin::app()->logger->info('Facebook SDK caching process succeeded. File ' . $file_path);
return $html;
}
/**
* Tell if the replacement was sucessful or not.
*
* @return bool
* @since 3.2.0
*
*/
public function is_replaced()
{
return $this->is_replaced;
}
/**
* Search for an element in the DOM.
*
* @param string $pattern Pattern to match.
* @param string $html HTML contents.
* @return string|bool The matched HTML on success. False if nothing is found.
* @since 3.2.0
*
*/
protected function find($pattern, $html)
{
preg_match_all('/' . $pattern . '/Umsi', $html, $matches, PREG_SET_ORDER);
if( empty($matches) ) {
return false;
}
foreach($matches as $match) {
if( trim($match[1]) && preg_match('@//connect\.facebook\.net/[a-zA-Z_-]+/sdk\.js@i', $match[1]) ) {
return $match[0];
}
}
return false;
}
/**
* Save the contents of a URL into a local file if it doesn't exist yet.
*
* @param string $url URL to get the contents from.
* @return bool True on success. False on failure.
* @since 3.2.0
*
*/
public function save($url)
{
$locale = $this->get_locale_from_url($url);
$path = $this->get_busting_file_path($locale);
if( $this->filesystem->exists($path) ) {
// If a previous version is present, keep it.
return true;
}
return $this->refresh_save($url);
}
/**
* Save the contents of a URL into a local file.
*
* @param string $url URL to get the contents from.
* @return bool True on success. False on failure.
* @since 3.2.0
*
*/
public function refresh_save($url)
{
$content = $this->get_file_content($url);
if( !$content ) {
// Error, we couldn't fetch the file contents.
return false;
}
$locale = $this->get_locale_from_url($url);
$path = $this->get_busting_file_path($locale);
return (bool)$this->update_file_contents($path, $content);
}
/**
* Add new contents to a file. If the file doesn't exist, it is created.
*
* @param string $file_path Path to the file to update.
* @param string $file_contents New contents.
* @return string|bool The file contents on success. False on failure.
* @since 3.2.0
*
*/
private function update_file_contents($file_path, $file_contents)
{
if( !$this->filesystem->exists($this->busting_path) ) {
wp_mkdir_p($this->busting_path);
}
if( !$this->filesystem->put_contents($file_path, $file_contents) ) {
\WGA_Plugin::app()->logger->error('Contents could not be written into file. File path ' . $file_path);
return false;
}
return $file_contents;
}
/**
* Look for existing local files and update their contents if there's a new version available.
* Actually, if a more recent version exists on the FB side, it will delete all local files and hit the home page to recreate them.
*
* @return bool True on success. False on failure.
* @since 3.2.0
*
*/
public function refresh()
{
$files = $this->get_files();
if( !$files ) {
// No files (or there's an error).
return false !== $files;
}
$error_paths = [];
$pattern = $this->escape_file_name($this->filename);
$pattern = sprintf($pattern, '(?<locale>[a-zA-Z_-]+)');
foreach($files as $file) {
preg_match('/^' . $pattern . '$/', $file, $matches);
$remote_url = $this->get_url($matches['locale']);
if( !$this->refresh_save($remote_url) ) {
$error_paths[] = $this->get_busting_file_path($matches['locale']);
}
}
if( $error_paths ) {
\WGA_Plugin::app()->logger->error('Local file(s) could not be updated. Paths ' . $error_paths);
}
return !$error_paths;
}
/**
* Delete all Facebook SDK busting files.
*
* @return bool True on success. False on failure.
* @since 3.2.0
*
*/
public function delete()
{
$filesystem = $this->filesystem;
$files = $this->get_files();
if( !$files ) {
// No files (or there's an error).
return false !== $files;
}
$error_paths = [];
foreach($files as $file_name) {
if( !$filesystem->delete($this->busting_path . $file_name, false, 'f') ) {
$error_paths[] = $this->busting_path . $file_name;
}
}
if( $error_paths ) {
\WGA_Plugin::app()->logger->error('Local file(s) could not be deleted. Paths ' . $error_paths);
}
return !$error_paths;
}
/**
* Get all cached files in the directory.
*
* @return array|bool A list of file names. False on failure.
* @since 3.2.0
*
*/
private function get_files()
{
$filesystem = $this->filesystem;
$dir_path = rtrim($this->busting_path, '\\/');
if( !$filesystem->exists($dir_path) ) {
return [];
}
if( !$filesystem->is_writable($dir_path) ) {
\WGA_Plugin::app()->logger->error('Facebook sdk: Directory is not writable. Path ' . $dir_path);
return false;
}
$dir = $filesystem->dirlist($dir_path);
if( false === $dir ) {
\WGA_Plugin::app()->logger->error('Facebook sdk: Could not get the directory contents. Path ' . $dir_path);
return false;
}
if( !$dir ) {
return [];
}
$list = [];
$pattern = $this->escape_file_name($this->filename);
$pattern = sprintf($pattern, '[a-zA-Z_-]+');
foreach($dir as $entry) {
if( 'f' !== $entry['type'] ) {
continue;
}
if( preg_match('/^' . $pattern . '$/', $entry['name'], $matches) ) {
$list[$entry['name']] = $entry['name'];
}
}
return $list;
}
/**
* Get the remote Facebook SDK URL.
*
* @param string $locale A locale string, like 'en_US'.
* @return string
* @since 3.2.0
*
*/
public function get_url($locale)
{
return sprintf($this->url, $locale);
}
/**
* Extract the locale from a URL to bust.
*
* @param string $url Any string containing the URL to bust.
* @return string|bool The locale on success. False on failure.
* @since 3.2.0
*
*/
private function get_locale_from_url($url)
{
$pattern = '@//connect\.facebook\.net/(?<locale>[a-zA-Z_-]+)/sdk\.js@i';
if( !preg_match($pattern, $url, $matches) ) {
return false;
}
return $matches['locale'];
}
/**
* Extract XFBML from a URL to bust.
*
* @param string $url Any string containing the URL to bust.
* @return string|bool The XFBML on success. False on failure.
* @since 3.4.3
*
*/
private function get_xfbml_from_url($url)
{
$pattern = '@//connect\.facebook\.net/(?<locale>[a-zA-Z_-]+)/sdk\.js#(?:.+&)?xfbml=(?<xfbml>[0-9]+)@i';
if( !preg_match($pattern, $url, $matches) ) {
return false;
}
return $matches['xfbml'];
}
/**
* Extract appId from a URL to bust.
*
* @param string $url Any string containing the URL to bust.
* @return string|bool The appId on success. False on failure.
* @since 3.4.3
*
*/
private function get_appId_from_url($url)
{
$pattern = '@//connect\.facebook\.net/(?<locale>[a-zA-Z_-]+)/sdk\.js#(?:.+&)?appId=(?<appId>[0-9]+)@i';
if( !preg_match($pattern, $url, $matches) ) {
return false;
}
return $matches['appId'];
}
/**
* Extract version from a URL to bust.
*
* @param string $url Any string containing the URL to bust.
* @return string|bool The version on success. False on failure.
* @since 3.4.3
*
*/
private function get_version_from_url($url)
{
$pattern = '@//connect\.facebook\.net/(?<locale>[a-zA-Z_-]+)/sdk\.js#(?:.+&)?version=(?<version>[a-zA-Z0-9.]+)@i';
if( !preg_match($pattern, $url, $matches) ) {
return false;
}
return $matches['version'];
}
/**
* Get the local Facebook SDK URL.
*
* @param string $locale A locale string, like 'en_US'.
* @return string
* @since 3.2.0
*
*/
private function get_busting_file_url($locale)
{
$filename = $this->get_busting_file_name($locale);
return $this->busting_url . $filename;
}
/**
* Get the local Facebook SDK file name.
*
* @param string $locale A locale string, like 'en_US'.
* @return string
* @since 3.2.0
*
*/
private function get_busting_file_name($locale)
{
return sprintf($this->filename, $locale);
}
/**
* Get the local Facebook SDK file path.
*
* @param string $locale A locale string, like 'en_US'.
* @return string
* @since 3.2.0
*
*/
private function get_busting_file_path($locale)
{
return $this->busting_path . $this->get_busting_file_name($locale);
}
/**
* Get the contents of a URL.
*
* @param string $url The URL to request.
* @return string|bool The contents on success. False on failure.
* @since 3.2.0
*
*/
protected function get_file_content($url)
{
try {
$response = wp_remote_get($url);
} catch( \Exception $e ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $e->getMessage());
return false;
}
if( is_wp_error($response) ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $response->get_error_message());
return false;
}
$contents = wp_remote_retrieve_body($response);
if( !$contents ) {
\WGA_Plugin::app()->logger->error('Remote file could not be fetched. Response ' . $response->get_error_message());
return false;
}
return $contents;
}
/**
* Escape a file name, to be used in a regex pattern (delimiter is `/`).
* `%s` conversion specifications are protected.
*
* @param string $file_name The file name.
* @return string
* @since 3.2.0
*
*/
private function escape_file_name($file_name)
{
$file_name = explode('%s', $file_name);
$file_name = array_map('preg_quote', $file_name);
return implode('%s', $file_name);
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace WGA\Busting;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class Google_Analytics_Cache extends Abstract_Cache {
/**
* Google Analytics URL.
*
* @var string
* @since 3.2.0
*/
protected $url = 'https://www.google-analytics.com/analytics.js';
/**
* File name (local).
* %s is a "version": a md5 hash of the file contents.
*
* @var string
* @since 3.2.0
*/
protected $filename_pattern = 'ga-%s.js';
/**
* Current file version (local): a md5 hash of the file contents.
*
* @var string
* @since 3.2.0
*/
protected $file_version;
/**
* Flag to track the replacement.
*
* @var bool
* @since 3.2.0
*/
protected $is_replaced = false;
/**
* Constructor.
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @since 3.1
* @access public
*
*/
public function __construct($busting_path, $busting_url)
{
parent::__construct($busting_path, $busting_url);
$this->busting_path = $busting_path . 'google-tracking/';
$this->busting_url = $busting_url . 'google-tracking/';
}
/**
* Performs the replacement process.
*
* @param string $html HTML content.
* @return string
* @since 3.2.0
*
*/
public function replace_url($html)
{
$this->is_replaced = false;
$tag = $this->find('<script\s*(?<attr>[^>]*)?>(?<content>[^<]+)?<\/script>', $html);
if( !$tag ) {
return $html;
}
\WGA_Plugin::app()->logger->info('GOOGLE ANALYTICS CACHING PROCESS STARTED. TAG #' . $tag);
if( !$this->save($this->url) ) {
return $html;
}
$replace_tag = preg_replace('/(?:https?:)?\/\/www\.google-analytics\.com\/analytics\.js/i', $this->get_busting_url(), $tag);
$html = str_replace($tag, $replace_tag, $html);
$this->is_replaced = true;
\WGA_Plugin::app()->logger->info('Google Analytics caching process succeeded. Busting path ' . $this->get_busting_path());
return $html;
}
/**
* Tell if the replacement was sucessful or not.
*
* @return bool
*
* @since 3.2.0
*/
public function is_replaced()
{
return $this->is_replaced;
}
/**
* Get the Google Analytics URL.
*
* @return string
* @author Remy Perona
*
* @since 3.1
* @access public
*/
public function get_url()
{
return $this->url;
}
/**
* Searches for element(s) in the DOM.
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
* @author Remy Perona
*
* @since 3.1
* @access public
*/
protected function find($pattern, $html)
{
preg_match_all('/' . $pattern . '/is', $html, $all_matches, PREG_SET_ORDER);
$matches = array_map(function ($match) {
if( empty($match['content']) || (!preg_match('/src\s*=\s*[\'"]\s*(?:https?:)?\/\/www\.google-analytics\.com\/analytics\.js\s*[\'"]/i', $match['attr'] . $match['content']) && false === strpos($match['content'], 'GoogleAnalyticsObject')) ) {
return;
}
return $match[0];
}, $all_matches);
$matches = array_values(array_filter($matches));
if( !$matches ) {
return false;
}
return $matches[0];
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace WGA\Busting;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class Google_Tag_Manager_Cache extends Abstract_Cache {
/**
* Context used for the logger.
*
* @var string
* @since 3.2.4
*/
const LOGGER_CONTEXT = 'gg tag manager';
/**
* File name (local).
* %s is a "version": a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
*/
protected $filename_pattern = 'gtm-%s.js';
/**
* Current file version (local): a md5 hash of the file contents.
*
* @var string
* @since 3.2.4
* @access protected
*/
protected $file_version;
/**
* Filesystem object.
*
* @var object
* @since 3.2.4
* @access protected
*/
protected $filesystem = false;
/**
* Google Analytics object.
*
* @var object
* @since 3.2.4
* @access protected
*/
protected $ga_busting = false;
/**
* Constructor.
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @param Google_Analytics_Cache $ga_busting A GoogleAnalytics instance.
* @since 3.1
* @access public
*
*/
public function __construct($busting_path, $busting_url, Google_Analytics_Cache $ga_busting)
{
parent::__construct($busting_path, $busting_url);
$blog_id = get_current_blog_id();
$this->busting_path = $busting_path . $blog_id . '/';
$this->busting_url = $busting_url . $blog_id . '/';
$this->ga_busting = $ga_busting;
}
/**
* Performs the replacement process.
*
* @param string $html HTML content.
* @return string
* @since 3.1
* @access public
*
*/
public function replace_url($html)
{
$script = $this->find('<script(\s+[^>]+)?\s+src\s*=\s*[\'"]\s*?((?:https?:)?\/\/www\.googletagmanager\.com(?:.+)?)\s*?[\'"]([^>]+)?\/?>', $html);
if( !$script ) {
return $html;
}
// replace relative protocol // with full https://.
$gtm_url = preg_replace('/^\/\//', 'https://', $script[2]);
\WGA_Plugin::app()->logger->info('GOOGLE TAG MANAGER CACHING PROCESS STARTED. Script ' . $script);
if( !$this->save($gtm_url) ) {
return $html;
}
$replace_script = str_replace($script[2], $this->get_busting_url(), $script[0]);
$replace_script = str_replace('<script', '<script data-no-minify="1"', $replace_script);
$html = str_replace($script[0], $replace_script, $html);
\WGA_Plugin::app()->logger->info('Google Tag Manager caching process succeeded. Path ' . $this->get_busting_path());
return $html;
}
/**
* Searches for element(s) in the DOM.
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
* @since 3.1
* @access public
*
*/
protected function find($pattern, $html)
{
preg_match_all('/' . $pattern . '/Umsi', $html, $matches, PREG_SET_ORDER);
if( empty($matches) ) {
return false;
}
return $matches[0];
}
/**
* Replaces the Google Analytics URL by the local copy inside the gtm-local.js file content
*
* @param string $content JavaScript content.
* @return string
* @since 3.1
*
*/
protected function replace_ga_url($content)
{
if( !$this->ga_busting->save($this->ga_busting->get_url()) ) {
return $content;
}
return str_replace($this->ga_busting->get_url(), $this->ga_busting->get_busting_url(), $content);
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace WGA\Busting;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class Sheduller {
protected $ga_processor;
protected $gtm_processor;
protected $fbpix_processor;
protected $fbsdk_processor;
/**
* Constructor
*/
public function __construct()
{
require_once WGA_PLUGIN_DIR . '/includes/classes/class-abstract-cache.php';
require_once WGA_PLUGIN_DIR . '/includes/classes/class-google-analytics-cache.php';
require_once WGA_PLUGIN_DIR . '/includes/classes/class-yandex-metrika-cache.php';
require_once WGA_PLUGIN_DIR . '/includes/classes/class-google-tag-manager-cache.php';
require_once WGA_PLUGIN_DIR . '/includes/classes/class-facebook-sdk.php';
require_once WGA_PLUGIN_DIR . '/includes/classes/class-facebook-cache.php';
$uploads_dir = wp_get_upload_dir();
if( !$uploads_dir ) {
return false;
}
$busting_path = trailingslashit($uploads_dir['basedir']) . WGA_PLUGIN_CACHE_FOLDER . '/';
$busting_url = trailingslashit($uploads_dir['baseurl']) . WGA_PLUGIN_CACHE_FOLDER . '/';
if( \WGA_Plugin::app()->getPopulateOption('yandex_metrika_cache') ) {
$this->ym_processor = new Yandex_Metrika_Cache($busting_path, $busting_url);
}
if( \WGA_Plugin::app()->getPopulateOption('google_analytics_cache') ) {
$this->ga_processor = new Google_Analytics_Cache($busting_path, $busting_url);
$this->gtm_processor = new Google_Tag_Manager_Cache($busting_path, $busting_url, $this->ga_processor);
}
if( \WGA_Plugin::app()->getPopulateOption('facebook_cache') ) {
$this->fbpix_processor = new Facebook_Pixel_Cache($busting_path, $busting_url);
$this->fbsdk_processor = new Facebook_SDK($busting_path, $busting_url);
}
add_action('cron_schedules', [$this, 'add_schedule']);
add_action('wclearfy/google_tracking_cache_update', [$this, 'update_tracking_cache']);
add_action('init', [$this, 'schedule_tracking_cache_update']);
add_action('template_redirect', function () {
ob_start([$this, 'cache_busting_google_tracking']);
}, 1);
add_action('wclearfy_delete_cache', [$this, 'delete_tracking_cache']);
}
/**
* Processes the cache busting on the HTML content
*
* Google Analytics replacement is performed first, and if no replacement occured, Google Tag Manager replacement is performed.
*
* @param string $html HTML content.
* @return string
* @since 3.1
*
*/
public function cache_busting_google_tracking($html)
{
if( !$this->is_busting_active() ) {
return $html;
}
if( \WGA_Plugin::app()->getPopulateOption('yandex_metrika_cache') ) {
$html = $this->ym_processor->replace_url($html);
}
if( \WGA_Plugin::app()->getPopulateOption('google_analytics_cache') ) {
$html = $this->ga_processor->replace_url($html);
$html = $this->gtm_processor->replace_url($html);
}
if( \WGA_Plugin::app()->getPopulateOption('facebook_cache') ) {
$html = $this->fbpix_processor->replace_url($html);
$html = $this->fbsdk_processor->replace_url($html);
}
return $html;
}
/**
* Adds weekly interval to cron schedules
*
* @param $schedules array An array of intervals used by cron jobs.
* @return []
* @since 3.2.0
*
*/
public function add_schedule($schedules)
{
if( !$this->is_busting_active() ) {
return $schedules;
}
$schedules['weekly'] = [
'interval' => 604800,
'display' => __('weekly', 'clearfy'),
];
return $schedules;
}
/**
* Schedules the auto-update of Google Analytics cache busting file
*
* @return void
* @since 3.2.0
*/
public function schedule_tracking_cache_update()
{
if( !$this->is_busting_active() ) {
return;
}
if( !wp_next_scheduled('wclearfy/google_tracking_cache_update') ) {
wp_schedule_event(time(), 'weekly', 'wclearfy/google_tracking_cache_update');
}
}
/**
* Updates Google Analytics cache busting file
*
* @return bool
* @since 3.2.0
*/
public function update_tracking_cache()
{
if( !$this->is_busting_active() ) {
return false;
}
if( \WGA_Plugin::app()->getPopulateOption('yandex_metrika_cache') ) {
$this->ym_processor->refresh_save($this->ym_processor->get_url());
}
if( \WGA_Plugin::app()->getPopulateOption('google_analytics_cache') ) {
$this->ga_processor->refresh_save($this->ga_processor->get_url());
}
if( \WGA_Plugin::app()->getPopulateOption('facebook_cache') ) {
$this->fbsdk_processor->refresh();
$this->fbpix_processor->refresh_all();
}
return true;
}
/**
* Deletes the GA busting file.
*
* @return bool
* @since 3.2.0
*/
public function delete_tracking_cache()
{
if( !$this->is_busting_active() ) {
return false;
}
$result = false;
if( \WGA_Plugin::app()->getPopulateOption('facebook_cache') ) {
$result = $this->fbsdk_processor->delete() && $this->fbpix_processor->delete_all();
}
if( \WGA_Plugin::app()->getPopulateOption('google_analytics_cache') ) {
$result = $result && $this->ga_processor->delete() && $this->gtm_processor->delete();
}
if( \WGA_Plugin::app()->getPopulateOption('yandex_metrika_cache') ) {
$result = $result && $this->ym_processor->delete();
}
return $result;
}
/**
* Tell if the cache busting option is active.
*
* @return bool
* @since 3.2.0
*
*/
private function is_busting_active()
{
return (\WGA_Plugin::app()->getPopulateOption('yandex_metrika_cache') || \WGA_Plugin::app()->getPopulateOption('google_analytics_cache') || \WGA_Plugin::app()->getPopulateOption('facebook_cache'));
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace WGA\Busting;
/**
* This class configures the google analytics cache
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2017 Webraftic Ltd
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class Yandex_Metrika_Cache extends Abstract_Cache {
/**
* Google Analytics URL.
*
* @var string
* @since 3.2.0
*/
protected $url = 'https://mc.yandex.ru/metrika/tag.js';
/**
* File name (local).
* %s is a "version": a md5 hash of the file contents.
*
* @var string
* @since 3.2.0
*/
protected $filename_pattern = 'ym-tag-%s.js';
/**
* Current file version (local): a md5 hash of the file contents.
*
* @var string
* @since 3.2.0
*/
protected $file_version;
/**
* Flag to track the replacement.
*
* @var bool
* @since 3.2.0
*/
protected $is_replaced = false;
/**
* Constructor.
*
* @param string $busting_path Path to the busting directory.
* @param string $busting_url URL of the busting directory.
* @since 3.1
* @access public
*
*/
public function __construct($busting_path, $busting_url)
{
parent::__construct($busting_path, $busting_url);
$this->busting_path = $busting_path . 'yandex-tracking/';
$this->busting_url = $busting_url . 'yandex-tracking/';
}
/**
* Performs the replacement process.
*
* @param string $html HTML content.
* @return string
* @since 3.2.0
*
*/
public function replace_url($html)
{
$this->is_replaced = false;
$tag = $this->find('<script\s*(?<attr>[^>]*)?>(?<content>[^<]+)?<\/script>', $html);
if( !$tag ) {
return $html;
}
\WGA_Plugin::app()->logger->info('YANDEX METRIKA CACHING PROCESS STARTED. TAG #' . $tag);
if( !$this->save($this->url) ) {
return $html;
}
$replace_tag = preg_replace('/(?:https?:)?\/\/mc\.yandex\.ru\/metrika\/tag\.js/i', $this->get_busting_url(), $tag);
$html = str_replace($tag, $replace_tag, $html);
$this->is_replaced = true;
\WGA_Plugin::app()->logger->info('Yandex metrika caching process succeeded. Busting path ' . $this->get_busting_path());
return $html;
}
/**
* Tell if the replacement was sucessful or not.
*
* @return bool
*
* @since 3.2.0
*/
public function is_replaced()
{
return $this->is_replaced;
}
/**
* Get the Google Analytics URL.
*
* @return string
* @author Remy Perona
*
* @since 3.1
* @access public
*/
public function get_url()
{
return $this->url;
}
/**
* Searches for element(s) in the DOM.
*
* @param string $pattern Pattern to match.
* @param string $html HTML content.
* @return string
* @author Remy Perona
*
* @since 3.1
* @access public
*/
protected function find($pattern, $html)
{
preg_match_all('/' . $pattern . '/is', $html, $all_matches, PREG_SET_ORDER);
$matches = array_map(function ($match) {
if( empty($match['content']) || (!preg_match('/\"script\",\s*[\'"](?:https?:)?\/\/mc\.yandex\.ru\/metrika\/tag\.js[\'"]/i', $match['attr'] . $match['content'])) ) {
return false;
}
return $match[0];
}, $all_matches);
$matches = array_values(array_filter($matches));
if( !$matches ) {
return false;
}
return $matches[0];
}
}

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,92 @@
<?php
/**
* Script to update local-ga.js-file
* Credits go to: Matthew Horne | http://diywpblog.com/leverage-browser-cache-optimize-google-analytics/
* I adjusted this script to work with wp-cron. It will still run in crontab, though.
* To run the script in crontab, remove the code on lines 8 and 9.
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Remote file to download.
$remote_file = 'https://www.google-analytics.com/analytics.js';
$upload_dir = wp_upload_dir();
if ( true === $upload_dir['error'] ) {
return;
}
$cache_dir = untrailingslashit( $upload_dir['basedir'] ) . '/wga-cache';
if ( ! file_exists( $cache_dir ) ) {
if ( ! wp_mkdir_p( $cache_dir ) ) {
return;
}
}
$local_file = $cache_dir . '/local-ga.js';
// Connection time out.
$conn_timeout = 10;
$url = wp_parse_url( $remote_file );
$host = $url['host'];
$path = isset( $url['path'] ) ? $url['path'] : '/';
if ( isset( $url['query'] ) ) {
$path .= '?' . $url['query'];
}
$port = isset( $url['port'] ) ? $url['port'] : '80';
$fp = @fsockopen( $host, '80', $errno, $errstr, $conn_timeout );
if ( ! $fp ) {
// On connection failure return the cached file (if exists).
if ( file_exists( $local_file ) ) {
readfile( $local_file );
}
} else {
// Send the header information
$header = "GET $path HTTP/1.0\r\n";
$header .= "Host: $host\r\n";
$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n";
$header .= "Accept: */*\r\n";
$header .= "Accept-Language: en-us,en;q=0.5\r\n";
$header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$header .= "Keep-Alive: 300\r\n";
$header .= "Connection: keep-alive\r\n";
$header .= "Referer: http://$host\r\n\r\n";
fputs( $fp, $header );
$response = '';
// Get the response from the remote server.
while( $line = fread( $fp, 4096 ) ) {
$response .= $line;
}
// Close the connection.
fclose( $fp );
// Remove the headers.
$pos = strpos( $response, "\r\n\r\n" );
$response = substr( $response, $pos + 4 );
// Return the processed response.
echo $response;
// Save the response to the local file.
if ( ! file_exists( $local_file ) ) {
// Try to create the file, if doesn't exist.
fopen( $local_file, 'w' );
}
if ( is_writable( $local_file ) ) {
$fp = fopen( $local_file, 'w' );
if ( $fp ) {
fwrite( $fp, $response );
fclose( $fp );
}
}
}// End if().

View File

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

View File

@@ -0,0 +1,234 @@
# 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:27+0300\n"
"PO-Revision-Date: 2019-04-28 06:27+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:34
msgid "The <b>Simple Google Analytics</b> plugin has some major changes!"
msgstr "El plugin <b>Simple Google Analytics</b> tiene cambios importantes."
#: admin/boot.php:35
msgid ""
"Unfortunately, the old version of the plugin (2.2.2) is no longer supported, "
"but you still can download it from the WordPress repository in case if the "
"new release doesnt work for you."
msgstr ""
"Desafortunadamente, la versión anterior del complemento (2.2.2) ya no aplica "
"soporte, pero aún puede descargarlo del repositorio de WordPress en caso de "
"que la nueva versión no funcione para usted."
#: admin/boot.php:36
msgid ""
"Weve updated the code and fixed the compatibility issue for the latest "
"WordPress and PHP versions. Weve also added additional feature of the Local "
"Google Analytics this way your website will load faster. The plugins name "
"has been changed to Local Google Analytics, but all features remained the "
"same."
msgstr ""
"Hemos actualizado el código y hemos solucionado el problema de "
"compatibilidad para las últimas versiones de WordPress y PHP. También hemos "
"agregado una función adicional de Local Google Analytics, de esta manera su "
"sitio web cargará más rápido. El nombre del plugin se ha cambiado a Local "
"Google Analytics, pero todas las características siguen siendo las mismas."
#: admin/boot.php:37
#, php-format
msgid ""
"Please, check <a href=\"%s\">plugin settings</a> and its performance on your "
"website. We do care about you and want to avoid any problems with the new "
"version."
msgstr ""
"Verifique <a href=\"%s\">configuraciónes de plugins</a> y el rendimiento de "
"su Website. Nos preocupamos por usted, queremos evitar problemas con la "
"nueva versión."
#: admin/boot.php:38
#, php-format
msgid ""
"We are aimed to pay more attention to the speed and security aspects of your "
"website. Thats why you should definitely try our basic WordPress "
"optimization plugin as well. Clearfy includes functionality of this plugin "
"and has many additional features for the website optimization:\n"
"<a href=\"%s\">Donwload Clearfy for free</a>"
msgstr ""
"Nuestro meta es prestar más atención a los aspectos de velocidad y seguridad "
"de su sitio web. Por eso prueba nuestro plugin básico de optimización "
"WordPress. Clearfy incluye funcionalidades de este plugin y posee "
"características adicionales para optimización de sitios web:\n"
"<a href=\"%s\">Descargue Clearfy de forma gratuita</a>"
#: admin/boot.php:170 admin/options.php:29 admin/pages/ga_cache.php:54
msgid "Google Analytics Cache"
msgstr "Cache de Google Analytics"
#: admin/boot.php:176 admin/options.php:49
msgid "Google analytic Code"
msgstr "Código de Google Analytics"
#: admin/boot.php:181 admin/options.php:70
msgid "Use adjusted bounce rate?"
msgstr "¿Usar tasa de rebote ajustada?"
#: admin/boot.php:186 admin/options.php:79
msgid "Change enqueue order?"
msgstr "¿Cambiar orden del turno?"
#: admin/boot.php:191 admin/options.php:88
msgid "Disable all display features functionality?"
msgstr "¿Desactivar todas las funciones de la pantalla?"
#: admin/boot.php:196 admin/options.php:97
msgid "Use Anonymize IP? (Required by law for some countries)"
msgstr "¿Usar IP Anónima? (Requerimiento legal en algunos países)"
#: admin/boot.php:201 admin/options.php:106 admin/options.php:108
msgid "Track logged in Administrators?"
msgstr "¿Registrados en Administradores?"
#: admin/boot.php:232
msgid "Get ultimate plugin free"
msgstr "Obtener el ultimate plugin gratis"
#: admin/options.php:22
msgid "<strong>Google Analytics cache</strong>."
msgstr "<strong>Google Analytics cache</strong>."
#: admin/options.php:22
msgid ""
"To improve Google Page Speed indicators Analytics caching is needed. "
"However, it can also slightly increase your website loading speed, because "
"Analytics js files will load locally. The second case that you might need "
"these settings is the usual Google Analytics connection to your website. You "
"do not need to do this with other plugins or insert the tracking code into "
"your theme."
msgstr ""
"Para mejorar el ranking en Google Page Speed, es necesario el almacenamiento "
"en caché de Analytics. con esto, aumentará ligeramente la velocidad de carga "
"de su sitio web, ya que los archivos de Analytics js se cargarán localmente. "
"El segundo caso en el que puede necesitar estos ajustes, es con la conexión "
"habitual de Google Analytics a su sitio web. No necesita hacer esto con "
"otros plugins ni insertar el código de seguimiento en su tema."
#: admin/options.php:31
msgid ""
"If you enable this option, the plugin will begin to save a local copy of "
"Google Analytics to speed up the loading of your website and improve Google "
"Page Speed."
msgstr ""
"Si habilita esta opción, el complemento comenzará a guardar una copia local "
"de Google Analytics acelerando la carga de su sitio web y mejorando el "
"ranking en Google Page Speed ."
#: admin/options.php:31
msgid ""
"ATTENTION! Before using this option, remove the previously installed Google "
"Analytics code inside your theme or plugins associated with this feature!"
msgstr ""
"¡ATENCIÓN! ¡Antes de usar esta opción, elimine el código de Google Analytics "
"instalado previamente dentro de su tema o los complementos asociados con "
"esta función!"
#: admin/options.php:51
msgid "Set the Google Analytics tracking code."
msgstr "Configure el código de seguimiento de Google Analytics."
#: admin/options.php:62
msgid "Save GA in"
msgstr "Guardar GA en"
#: admin/options.php:63
msgid "Select location for the Google Analytics code."
msgstr "Seleccione la ubicación para el código de Google Analytics."
#: admin/options.php:73
msgid ""
"Essentially, you set up an event which is triggered after a user spends a "
"certain amount of time on the landing page, telling Google Analytics not to "
"count these users as bounces. A user may come to your website, find all of "
"the information they need (a phone number, for example) and then leave the "
"site without visiting another page. Without adjusted bounce rate, such a "
"user would be considered a bounce, even though they had a successful "
"experience. By defining a time limit after which you can consider a user to "
"be \"engaged,\" that user would no longer count as a bounce, and you'd get a "
"more accurate idea of whether they found what they were looking for."
msgstr ""
"Básicamente, configura un evento que se activa después de que un usuario "
"pasa una cierta cantidad de tiempo en la página de destino, diciéndole a "
"Google Analytics que no cuente a estos usuarios como rebotes. Un usuario "
"puede ir a su sitio web, buscar toda la información que necesita (un número "
"de teléfono, por ejemplo) y luego abandonar el sitio sin visitar otra "
"página. Sin una tasa de rebote ajustada, dicho usuario se consideraría un "
"rebote aunque tuviera una experiencia exitosa. Al definir un límite de "
"tiempo, un usuario se consideraría \"comprometido\", ese usuario ya no se "
"contaría como un rebote ya que sería obvio que encontró lo que buscó."
#: admin/options.php:82
msgid ""
"By default, Google Analytics code is loaded before other scripts and "
"javasscript code, but if you set the value to 100, the GA code will be "
"loaded after all other scripts. By changing the priority, you can set code "
"position on the page."
msgstr ""
"Por defecto, el código de Google Analytics se carga antes que otros scripts "
"y el código javasscript, pero si establece el valor a 100, el código GA se "
"cargará después de todos los demás scripts. Al cambiar la prioridad, puede "
"establecer la posición del código en la página."
#: admin/options.php:90
#, php-format
msgid "Disable all <a href=\"%s\">display features functionality?</a>"
msgstr ""
"Deshabilitar todas las <a href=\"%s\">¿Características de funciones?</a>"
#: admin/options.php:99
#, php-format
msgid ""
"Use <a href=\"%s\">Anonymize IP?</a> (Required by law for some countries)"
msgstr ""
"Use <a href=\"%s\">¿Anonimizar IP?</a> (Requisito legal para algunos países)"
#: admin/pages/ga_cache.php:38
msgid "Local Google Analytics"
msgstr "Google Analytics local"
#: admin/pages/ga_cache.php:55
msgid "General"
msgstr "General"
#: includes/classes/class.configurate-ga.php:44
msgid "Once Weekly"
msgstr "Una vez a la semana"
#: includes/classes/class.configurate-ga.php:49
msgid "Twice Monthly"
msgstr "Dos veces al mes"
#: includes/classes/class.configurate-ga.php:54
msgid "Once Monthly"
msgstr "Una vez al mes"
#: simple_google_analytics.php:83
msgid "Webcraftic Local Google Analytics"
msgstr "Webcraftic Local Google Analytics"

View File

@@ -0,0 +1,243 @@
msgid ""
msgstr ""
"Project-Id-Version: Clearfy\n"
"POT-Creation-Date: 2018-09-06 18:33+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:27
msgid "The <b>Simple Google Analytics</b> plugin has some major changes!"
msgstr ""
#: admin/boot.php:28
msgid ""
"Unfortunately, the old version of the plugin (2.2.2) is no longer supported, "
"but you still can download it from the WordPress repository in case if the new "
"release doesnt work for you."
msgstr ""
#: admin/boot.php:29
msgid ""
"Weve updated the code and fixed the compatibility issue for the latest "
"WordPress and PHP versions. Weve also added additional feature of the Local "
"Google Analytics this way your website will load faster. The plugins name "
"has been changed to Local Google Analytics, but all features remained the same."
msgstr ""
#: admin/boot.php:30
#, php-format
msgid ""
"Please, check <a href=\"%s\">plugin settings</a> and its performance on your "
"website. We do care about you and want to avoid any problems with the new "
"version."
msgstr ""
#: admin/boot.php:32
#, php-format
msgid ""
"We are aimed to pay more attention to the speed and security aspects of your "
"website. Thats why you should definitely try our basic WordPress optimization "
"plugin as well. Clearfy includes functionality of this plugin and has many "
"additional features for the website optimization:\n"
"<a href=\"%s\">Donwload Clearfy for free</a>"
msgstr ""
#: admin/boot.php:121 admin/options.php:30 admin/pages/ga_cache.php:49
msgid "Google Analytics Cache"
msgstr ""
#: admin/boot.php:127 admin/options.php:50
msgid "Google analytic Code"
msgstr "Google analytics Code"
#: admin/boot.php:132 admin/options.php:71
msgid "Use adjusted bounce rate?"
msgstr "Aangepast bounce percentage gebruiken?"
#: admin/boot.php:137 admin/options.php:80
msgid "Change enqueue order?"
msgstr "Enqueue volgorde wijzigen?"
#: admin/boot.php:142 admin/options.php:89
msgid "Disable all display features functionality?"
msgstr "Alle weergave functionaliteit uitschakelen?"
#: admin/boot.php:147 admin/options.php:98
msgid "Use Anonymize IP? (Required by law for some countries)"
msgstr "Gebruik anonimiseren IP? (Voor sommige landen wettelijk verplicht)"
#: admin/boot.php:152 admin/options.php:107 admin/options.php:109
msgid "Track logged in Administrators?"
msgstr "Track ingelogde Beheerders?"
#: admin/boot.php:157 admin/options.php:116
msgid "Remove script from wp-cron?"
msgstr "Verwijder script van wp-cron?"
#: admin/boot.php:185
msgid "Get ultimate plugin free"
msgstr "Krijg ultieme plugin gratis"
#: admin/options.php:23
msgid "<strong>Google Analytics cache</strong>."
msgstr "<strong>Google Analytics cache</strong>."
#: admin/options.php:23
msgid ""
"To improve Google Page Speed indicators Analytics caching is needed. However, "
"it can also slightly increase your website loading speed, because Analytics js "
"files will load locally. The second case that you might need these settings is "
"the usual Google Analytics connection to your website. You do not need to do "
"this with other plugins or insert the tracking code into your theme."
msgstr ""
"Om de pagina snelheid indicatoren van Google te verbeteren, is caching in "
"Analytics nodig. Het kan echter ook de laadsnelheid van uw website enigszins "
"verhogen, omdat de Analytics js bestanden lokaal worden geladen. Het tweede "
"geval waarvoor u deze instellingen nodig heeft, is de gebruikelijke Google "
"Analytics verbinding met uw website. U hoeft dit niet met andere plugins te "
"doen of de tracking code in uw thema in te voegen."
#: admin/options.php:32
msgid ""
"If you enable this option, the plugin will begin to save a local copy of "
"Google Analytics to speed up the loading of your website and improve Google "
"Page Speed."
msgstr ""
"Als u deze optie inschakelt, zal de plugin beginnen met het opslaan van een "
"lokale kopie van Google Analytics om het laden van uw website te versnellen en "
"de Google Page Speed te verbeteren."
#: admin/options.php:32
msgid ""
"ATTENTION! Before using this option, remove the previously installed Google "
"Analytics code inside your theme or plugins associated with this feature!"
msgstr ""
"AANDACHT! Voordat u deze optie gebruikt, verwijdert u de eerder geïnstalleerde "
"Google Analytics code in uw thema of plugins die aan deze functie zijn "
"gekoppeld!"
#: admin/options.php:52
msgid "Set the Google Analytics tracking code."
msgstr "Stel de Google Analytics tracking code in."
#: admin/options.php:63
msgid "Save GA in"
msgstr "Bewaar GA in"
#: admin/options.php:64
msgid "Select location for the Google Analytics code."
msgstr "Selecteer een locatie voor de Google Analytics code."
#: admin/options.php:74
msgid ""
"Essentially, you set up an event which is triggered after a user spends a "
"certain amount of time on the landing page, telling Google Analytics not to "
"count these users as bounces. A user may come to your website, find all of the "
"information they need (a phone number, for example) and then leave the site "
"without visiting another page. Without adjusted bounce rate, such a user would "
"be considered a bounce, even though they had a successful experience. By "
"defining a time limit after which you can consider a user to be \"engaged,\" "
"that user would no longer count as a bounce, and you'd get a more accurate "
"idea of whether they found what they were looking for."
msgstr ""
"In essentie stelt u een gebeurtenis in die wordt geactiveerd nadat een "
"gebruiker een bepaalde hoeveelheid tijd op de bestemmingspagina heeft "
"doorgebracht, waarmee u Google Analytics vertelt om deze gebruikers niet als "
"bounces te tellen. Een gebruiker kan naar uw website komen, alle benodigde "
"informatie vinden (bijvoorbeeld een telefoonnummer) en vervolgens de website "
"verlaten zonder een andere pagina te bezoeken. Zonder aangepast bounce "
"percentage zou een dergelijke gebruiker als een bounce worden beschouwd, ook "
"al hadden ze een succesvolle ervaring. Door een tijdslimiet te definiëren "
"waarna u kunt concluderen dat een gebruiker \"geëngageerd\" is, telt die "
"gebruiker niet mee als een bounce en krijgt u een beter beeld van het feit of "
"ze hebben gevonden waarnaar ze op zoek waren."
#: admin/options.php:83
msgid ""
"By default, Google Analytics code is loaded before other scripts and "
"javasscript code, but if you set the value to 100, the GA code will be loaded "
"after all other scripts. By changing the priority, you can set code position "
"on the page."
msgstr ""
"Standaard wordt de Google Analytics code geladen voor andere scripts en "
"javasscript code, maar als u de waarde instelt op 100, wordt de GA code "
"geladen na alle andere scripts. Door de prioriteit te wijzigen, kunt u de "
"codepositie op de pagina instellen."
#: admin/options.php:91
#, php-format
msgid "Disable all <a href=\"%s\">display features functionality?</a>"
msgstr "Alle <a href=\"%s\">van weergave functies uitschakelen?</a>"
#: admin/options.php:100
#, php-format
msgid "Use <a href=\"%s\">Anonymize IP?</a> (Required by law for some countries)"
msgstr ""
"Gebruik <a href=\"%s\">Anoniem maken van IP?</a> (Wettelijk vereist voor "
"sommige landen)"
#: admin/options.php:118
msgid ""
"Clearfy creates a cron job to daily update Google Analytics cache scripts. "
"After enabling this option, the plugin will not update Google Analytics cache "
"file. Do not use this option if you do not understand why you need it!"
msgstr ""
"Clearfy maakt een cron-taak om dagelijks de cache scripts van Google Analytics "
"bij te werken. Nadat u deze optie hebt ingeschakeld, werkt de plugin het cache "
"bestand van Google Analytics niet bij. Gebruik deze optie niet als u niet "
"begrijpt waarom u het nodig hebt!"
#: admin/pages/ga_cache.php:33
msgid "Local Google Analytics"
msgstr ""
#: admin/pages/ga_cache.php:50
msgid "General"
msgstr "Algemeen"
#: includes/classes/class.configurate-ga.php:37
msgid "Once Weekly"
msgstr "Eénmaal per week"
#: includes/classes/class.configurate-ga.php:42
msgid "Twice Monthly"
msgstr "Tweemaal per maand"
#: includes/classes/class.configurate-ga.php:47
msgid "Once Monthly"
msgstr "Eénmaal per maand"
#: simple_google_analytics.php:32
msgid ""
"We found that you have the \"Clearfy - disable unused features\" plugin "
"installed, this plugin already has Google Analytics cache functions, so you "
"can deactivate plugin \"Google Analytics Cache\"!"
msgstr ""
#: simple_google_analytics.php:40
msgid ""
"You use the old version of Wordpress to use the <b>Webcraftic Local Google "
"Analytics (Old name: Simple Google Analytics)</b> plugin, you must upgrade "
"your Wordpress to the minimum version 4.2!"
msgstr ""
#: simple_google_analytics.php:65
msgid "Webcraftic Local Google Analytics"
msgstr ""

View File

@@ -0,0 +1,247 @@
msgid ""
msgstr ""
"Project-Id-Version: clearfy\n"
"POT-Creation-Date: 2018-09-06 18:33+0300\n"
"PO-Revision-Date: 2018-09-06 18:33+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:27
msgid "The <b>Simple Google Analytics</b> plugin has some major changes!"
msgstr ""
#: admin/boot.php:28
msgid ""
"Unfortunately, the old version of the plugin (2.2.2) is no longer supported, "
"but you still can download it from the WordPress repository in case if the "
"new release doesnt work for you."
msgstr ""
#: admin/boot.php:29
msgid ""
"Weve updated the code and fixed the compatibility issue for the latest "
"WordPress and PHP versions. Weve also added additional feature of the Local "
"Google Analytics this way your website will load faster. The plugins name "
"has been changed to Local Google Analytics, but all features remained the "
"same."
msgstr ""
#: admin/boot.php:30
#, php-format
msgid ""
"Please, check <a href=\"%s\">plugin settings</a> and its performance on your "
"website. We do care about you and want to avoid any problems with the new "
"version."
msgstr ""
#: admin/boot.php:32
#, php-format
msgid ""
"We are aimed to pay more attention to the speed and security aspects of your "
"website. Thats why you should definitely try our basic WordPress "
"optimization plugin as well. Clearfy includes functionality of this plugin "
"and has many additional features for the website optimization:\n"
"<a href=\"%s\">Donwload Clearfy for free</a>"
msgstr ""
#: admin/boot.php:121 admin/options.php:30 admin/pages/ga_cache.php:49
msgid "Google Analytics Cache"
msgstr "Cache analítico do Google"
#: admin/boot.php:127 admin/options.php:50
msgid "Google analytic Code"
msgstr "Código analítico do Google"
#: admin/boot.php:132 admin/options.php:71
msgid "Use adjusted bounce rate?"
msgstr "Use taxa de rejeição ajustada?"
#: admin/boot.php:137 admin/options.php:80
msgid "Change enqueue order?"
msgstr "Alterar ordem de enfileiramento?"
#: admin/boot.php:142 admin/options.php:89
msgid "Disable all display features functionality?"
msgstr "Desativar todas as funcionalidades dos recursos de exibição?"
#: admin/boot.php:147 admin/options.php:98
msgid "Use Anonymize IP? (Required by law for some countries)"
msgstr "Use Anonymize IP? (Obrigatório por lei para alguns países)"
#: admin/boot.php:152 admin/options.php:107 admin/options.php:109
msgid "Track logged in Administrators?"
msgstr "Track logado em Administradores?"
#: admin/boot.php:157 admin/options.php:116
msgid "Remove script from wp-cron?"
msgstr "Remover script do wp-cron?"
#: admin/boot.php:185
msgid "Get ultimate plugin free"
msgstr "Obtenha o melhor plugin grátis"
#: admin/options.php:23
msgid "<strong>Google Analytics cache</strong>."
msgstr "<strong>cache do Google Analytics</strong>."
#: admin/options.php:23
msgid ""
"To improve Google Page Speed indicators Analytics caching is needed. "
"However, it can also slightly increase your website loading speed, because "
"Analytics js files will load locally. The second case that you might need "
"these settings is the usual Google Analytics connection to your website. You "
"do not need to do this with other plugins or insert the tracking code into "
"your theme."
msgstr ""
"Para melhorar os indicadores do Google Page Speed, é necessário o "
"armazenamento em cache do Analytics. No entanto, também pode aumentar "
"ligeiramente a velocidade de carregamento do seu site, porque os arquivos do "
"Google Analytics js serão carregados localmente. O segundo caso em que você "
"pode precisar dessas configurações é a conexão normal do Google Analytics "
"com seu website. Você não precisa fazer isso com outros plug-ins ou inserir "
"o código de acompanhamento em seu tema."
#: admin/options.php:32
msgid ""
"If you enable this option, the plugin will begin to save a local copy of "
"Google Analytics to speed up the loading of your website and improve Google "
"Page Speed."
msgstr ""
"Se você ativar essa opção, o plug-in começará a salvar uma cópia local do "
"Google Analytics para acelerar o carregamento de seu website e melhorar a "
"velocidade da página do Google."
#: admin/options.php:32
msgid ""
"ATTENTION! Before using this option, remove the previously installed Google "
"Analytics code inside your theme or plugins associated with this feature!"
msgstr ""
"ATENÇÃO! Antes de usar essa opção, remova o código do Google Analytics "
"instalado anteriormente no seu tema ou plug-ins associados a esse recurso."
#: admin/options.php:52
msgid "Set the Google Analytics tracking code."
msgstr "Definir o código de acompanhamento do Google Analytics."
#: admin/options.php:63
msgid "Save GA in"
msgstr "Salvar o GA em"
#: admin/options.php:64
msgid "Select location for the Google Analytics code."
msgstr "Selecione o local para o código do Google Analytics."
#: admin/options.php:74
msgid ""
"Essentially, you set up an event which is triggered after a user spends a "
"certain amount of time on the landing page, telling Google Analytics not to "
"count these users as bounces. A user may come to your website, find all of "
"the information they need (a phone number, for example) and then leave the "
"site without visiting another page. Without adjusted bounce rate, such a "
"user would be considered a bounce, even though they had a successful "
"experience. By defining a time limit after which you can consider a user to "
"be \"engaged,\" that user would no longer count as a bounce, and you'd get a "
"more accurate idea of whether they found what they were looking for."
msgstr ""
"Essencialmente, você configura um evento que é acionado depois que um "
"usuário passa um determinado período de tempo na página de destino, dizendo "
"ao Google Analytics para não contabilizar esses usuários como rejeições. Um "
"usuário pode acessar seu site, encontrar todas as informações necessárias "
"(um número de telefone, por exemplo) e sair do site sem visitar outra "
"página. Sem a taxa de rejeição ajustada, esse usuário seria considerado uma "
"rejeição, mesmo que tivesse uma experiência bem-sucedida. Ao definir um "
"limite de tempo após o qual você pode considerar um usuário \"engajado\", "
"esse usuário não será mais considerado uma rejeição, e você terá uma ideia "
"mais precisa sobre se encontrou o que estava procurando."
#: admin/options.php:83
msgid ""
"By default, Google Analytics code is loaded before other scripts and "
"javasscript code, but if you set the value to 100, the GA code will be "
"loaded after all other scripts. By changing the priority, you can set code "
"position on the page."
msgstr ""
"Por padrão, o código do Google Analytics é carregado antes de outros scripts "
"e código javasscript, mas se você definir o valor como 100, o código do GA "
"será carregado depois de todos os outros scripts. Ao alterar a prioridade, "
"você pode definir a posição do código na página."
#: admin/options.php:91
#, php-format
msgid "Disable all <a href=\"%s\">display features functionality?</a>"
msgstr ""
"Desativar todas as <a href=\"%s\"> funcionalidades dos recursos de exibição? "
"</a>"
#: admin/options.php:100
#, php-format
msgid ""
"Use <a href=\"%s\">Anonymize IP?</a> (Required by law for some countries)"
msgstr ""
"Usar <a href=\"%s\">Anonimizar IP?</a> (exigido por lei para alguns países)"
#: admin/options.php:118
msgid ""
"Clearfy creates a cron job to daily update Google Analytics cache scripts. "
"After enabling this option, the plugin will not update Google Analytics "
"cache file. Do not use this option if you do not understand why you need it!"
msgstr ""
"O Clearfy cria uma tarefa cron para atualizar diariamente os scripts de "
"cache do Google Analytics. Depois de ativar essa opção, o plug-in não "
"atualizará o arquivo de cache do Google Analytics. Não use essa opção se "
"você não entender por que precisa!"
#: admin/pages/ga_cache.php:33
msgid "Local Google Analytics"
msgstr ""
#: admin/pages/ga_cache.php:50
msgid "General"
msgstr "Geral"
#: includes/classes/class.configurate-ga.php:37
msgid "Once Weekly"
msgstr "Uma vez por semana"
#: includes/classes/class.configurate-ga.php:42
msgid "Twice Monthly"
msgstr "Duas vezes por mês"
#: includes/classes/class.configurate-ga.php:47
msgid "Once Monthly"
msgstr "Uma vez por mês"
#: simple_google_analytics.php:32
msgid ""
"We found that you have the \"Clearfy - disable unused features\" plugin "
"installed, this plugin already has Google Analytics cache functions, so you "
"can deactivate plugin \"Google Analytics Cache\"!"
msgstr ""
"Descobrimos que você tem o \"Clearfy - desativar os recursos não utilizados "
"\" plugin instalado, este plugin já tem desativar as funções de comentários, "
"assim você pode desativar o plugin \"Hide Login Page \"!"
#: simple_google_analytics.php:40
msgid ""
"You use the old version of Wordpress to use the <b>Webcraftic Local Google "
"Analytics (Old name: Simple Google Analytics)</b> plugin, you must upgrade "
"your Wordpress to the minimum version 4.2!"
msgstr ""
#: simple_google_analytics.php:65
msgid "Webcraftic Local Google Analytics"
msgstr ""

View File

@@ -0,0 +1,198 @@
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2018-04-17 02:28+0400\n"
"PO-Revision-Date: 2018-04-17 02:35+0400\n"
"Last-Translator: \n"
"Language-Team: \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.0.6\n"
"X-Poedit-Basepath: ga-cache\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: google-analytics-cache.php\n"
"X-Poedit-SearchPath-1: includes/class-rio-plugin.php\n"
"X-Poedit-SearchPath-2: admin/options.php\n"
"X-Poedit-SearchPath-3: includes/classes/class.configurate-ga.php\n"
"X-Poedit-SearchPath-4: admin/pages/class-pages-general-settings.php\n"
#: admin/options.php:23
msgid "<strong>Google Analytics cache</strong>."
msgstr ""
#: admin/options.php:23
msgid ""
"To improve Google Page Speed indicators Analytics caching is needed. "
"However, it can also slightly increase your website loading speed, because "
"Analytics js files will load locally. The second case that you might need "
"these settings is the usual Google Analytics connection to your website. You "
"do not need to do this with other plugins or insert the tracking code into "
"your theme."
msgstr ""
"Кеширование Analytics нужно для улучшения показателей Google Page Speed, но\n"
"это также может незначительно повысить скорость загрузки вашего сайта, \n"
"потому что js файлы Analytics будут подгружаться локально. Второй случай, \n"
"когда вам могут понадобиться эти настройки — обычное подключение Google \n"
"Analytics к сайту. Вам не нужно делать это с помощью других плагинов или \n"
"просто вставлять код отслеживания в вашу тему."
#: admin/options.php:31 admin/pages/ga_cache.php:33 admin/pages/ga_cache.php:49
msgid "Google Analytics Cache"
msgstr ""
#: admin/options.php:33
msgid ""
"If you enable this option, the plugin will begin to save a local copy of "
"Google Analytics to speed up the loading of your website and improve Google "
"Page Speed."
msgstr ""
"Если включить эту опцию, плагин начнет сохранять локальную копию Google \n"
"Analytics, чтобы ускорить загрузку вашего сайта и улучшить показатели "
"Google \n"
"Page speed. ВНИМАНИЕ! Перед использованием этой опции, удалите ранее \n"
"установленный код Google Analytics в вашей теме или плагины, связанные с \n"
"этой функцией!"
#: admin/options.php:33
msgid ""
"ATTENTION! Before using this option, remove the previously installed Google "
"Analytics code inside your theme or plugins associated with this feature!"
msgstr ""
"ВНИМАНИЕ! Перед использованием этой опции, удалите ранее установленный код \n"
"Google Analytics в вашей теме или плагины, связанные с этой функцией!"
#: admin/options.php:51
msgid "Google analytic Code"
msgstr "Код Google аналитики"
#: admin/options.php:53
msgid "Set the Google Analytics tracking code."
msgstr "Установите код отслеживания Google Analytics."
#: admin/options.php:64
msgid "Save GA in"
msgstr "Использовать код аналитики в"
#: admin/options.php:65
msgid "Select location for the Google Analytics code."
msgstr "Выберите местоположение для кода Google Analytics."
#: admin/options.php:72
msgid "Use adjusted bounce rate?"
msgstr "Показатель отказов?"
#: admin/options.php:75
msgid ""
"Essentially, you set up an event which is triggered after a user spends a "
"certain amount of time on the landing page, telling Google Analytics not to "
"count these users as bounces. A user may come to your website, find all of "
"the information they need (a phone number, for example) and then leave the "
"site without visiting another page. Without adjusted bounce rate, such a "
"user would be considered a bounce, even though they had a successful "
"experience. By defining a time limit after which you can consider a user to "
"be \"engaged,\" that user would no longer count as a bounce, and you'd get a "
"more accurate idea of whether they found what they were looking for."
msgstr ""
"По сути, вы настраиваете событие, которое запускается после того, как \n"
"пользователь тратит определенное количество времени на целевую страницу, \n"
"сообщая Google Analytics не считать этих пользователей как отказы. \n"
"Пользователь может зайти на ваш сайт, найти всю необходимую информацию \n"
"(например, номер телефона), а затем покинуть сайт, не посещая другую \n"
"страницу. Без скорректированного коэффициента отказов такой пользователь \n"
"будет считаться отказом, хотя у них был успешный опыт. Определив лимит \n"
"времени, после которого вы можете считать пользователя «включенным», этот \n"
"пользователь больше не будет считаться отказом, и вы получите более точное \n"
"представление о том, нашли ли они то, что искали."
#: admin/options.php:81
msgid "Change enqueue order?"
msgstr "Сортировка скрипта?"
#: admin/options.php:84
msgid ""
"By default, Google Analytics code is loaded before other scripts and "
"javasscript code, but if you set the value to 100, the GA code will be "
"loaded after all other scripts. By changing the priority, you can set code "
"position on the page."
msgstr ""
"По умолчанию код Google Analytics загружается раньше остальных скриптов и \n"
"javasscript кода, но если вы установите к примеру значение 100, то код GA \n"
"будет загружен после всех остальных скриптов. Изменяя приоритет, вы можете \n"
"задавать положение кода на странице."
#: admin/options.php:90
msgid "Disable all display features functionality?"
msgstr "Отключить все функции для контекстно-медийной сети?"
#: admin/options.php:92
#, php-format
msgid "Disable all <a href=\"%s\">display features functionality?</a>"
msgstr "Отключить <a href=\"%s\">все функции для контекстно-медийной сети?</a>"
#: admin/options.php:99
msgid "Use Anonymize IP? (Required by law for some countries)"
msgstr ""
"Использовать анонимный IP-адрес? (Требуется по закону для некоторых стран)"
#: admin/options.php:101
#, php-format
msgid ""
"Use <a href=\"%s\">Anonymize IP?</a> (Required by law for some countries)"
msgstr ""
"Использовать <a href=\"%s\">анонимный IP-адрес?</a> (Требуется по закону "
"для \n"
"некоторых стран)"
#: admin/options.php:108 admin/options.php:110
msgid "Track logged in Administrators?"
msgstr "Отслеживать, если вы авторизованы под администратором?"
#: admin/options.php:117
msgid "Remove script from wp-cron?"
msgstr "Удалить кеширования скрипта из крона?"
#: admin/options.php:119
msgid ""
"Clearfy creates a cron job to daily update Google Analytics cache scripts. "
"After enabling this option, the plugin will not update Google Analytics "
"cache file. Do not use this option if you do not understand why you need it!"
msgstr ""
"Плагин создает cron задание, чтобы ежедневно обновлять кеш скриптов Google \n"
"Analytics. После включения этой опции, плагин не будет обновлять кэш файл \n"
"Google Analytics. Не используйте эту опцию, если вы не понимаете, для чего \n"
"вам это нужно!"
#: admin/pages/ga_cache.php:50
msgid "General"
msgstr "Основные"
#: google-analytics-cache.php:22
msgid ""
"We found that you have the \"Clearfy - disable unused features\" plugin "
"installed, this plugin already has Google Analytics cache functions, so you "
"can deactivate plugin \"Google Analytics Cache\"!"
msgstr ""
"Мы обнаружили, что у вас установлен плагин «Clearfy - отключить \n"
"неиспользуемые функции», этот плагин уже имеет функцию кеширования Google "
"Analytics, поэтому вы можете отключить плагин «Google Analytics Cache»!"
#: google-analytics-cache.php:50
msgid "Webcraftic Google Analytics Cache"
msgstr ""
#: includes/classes/class.configurate-ga.php:40
msgid "Once Weekly"
msgstr ""
#: includes/classes/class.configurate-ga.php:45
msgid "Twice Monthly"
msgstr ""
#: includes/classes/class.configurate-ga.php:50
msgid "Once Monthly"
msgstr ""

View File

@@ -0,0 +1,30 @@
<?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 WGACUpdate030002 extends Wbcr_Factory480_Update {
public function install() {
/**
* Remove the old cron hook
*/
if ( wp_next_scheduled( 'wbcr_clearfy_update_local_ga' ) ) {
wp_clear_scheduled_hook( 'wbcr_clearfy_update_local_ga' );
}
/**
* Add a new cron hook
*/
if ( ! wp_next_scheduled( 'wbcr/gac/update_analytic_library' ) ) {
wp_schedule_event( time(), 'twicedaily', 'wbcr/gac/update_analytic_library' );
}
$disable_display_features = $this->plugin->getPopulateOption( 'ga_caos_disable_display_features', false );
$this->plugin->updatePopulateOption( 'ga_disable_display_features', $disable_display_features );
$this->plugin->deletePopulateOption( 'ga_caos_disable_display_features' );
$this->plugin->deletePopulateOption( 'ga_caos_remove_wp_cron' );
}
}

View File

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

View File

@@ -0,0 +1,177 @@
=== Local Google Analytics for Wordpress - caches external requests ===
Tags: analytics,google analytics,google analytics dashboard,google analytics plugin,google analytics widget,gtag
Contributors: webcraftic, alexkovalevv, JeromeMeyer62, creativemotion
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.4
Stable tag: trunk
License: GPLv2
Plugs in Google Analytics code to your website pages and caches it, so the website loads faster.
== Description ==
This plugin helps to plug in Google Analytics code to the website pages without affecting the theme code. All you have to do is to enter the tracking code. Thats all. Unlike other plugins, this one cares about your website performance and caches Google Analytics scripts.
#### How does plugin cache Google Analytics scripts and why? ####
When you activate and fill in plugin settings, it downloads remote file named analytics.js and places it to the Cache folder on your hosting (server). This file is updated once a day it helps to avoid external requests to the Google remote server and speeds up the website pages.
Also if you want to gain 100 performance rating on Google Pagespeed Insights, then youll definitely need to cache Google Analytics, otherwise youll get a warning.
#### PLUGIN FEATURES ####
* <strong>Helps to place analytics code to the website header or footer.</strong>
* <strong>Monitors bounce rates.</strong> The point is that you set up the event triggered after a user spends a certain amount of time on the landing page, telling Google Analytics not to consider these users as a bounce. The user can visit your website, find all necessary information (for example, phone number), and then simply close the website without visiting other pages. If the bounce rate hasnt been adjusted, then this user is considered as a bounce, even though he had a successful experience. By defining time limits as from when the user should be considered as a bounce, you get more accurate performance of the user experience (for example, whether he's been able to find what he was looking for or not).
* <strong>Define the analytics code position.</strong> Google Analytics code loads prior to other scripts and JavaScript code by default. But if you set up the value 100, for example, then the Google Analytics code will be loaded after all scripts. Adjusting the priority helps to set up the codes position on the page.
* <strong>Disable all Display Network functions.</strong> Find more: https://developers.google.com/analytics/devguides/collection/analyticsjs/display-features
* <strong>Use anonymous IP address (required by the law in some countries).</strong> More details: (https://support.google.com/analytics/answer/2763052)
* <strong>Track administrators.</strong> You can disable tracking for administrators activities and get more accurate statistics.
* <strong>Do not update the analytics.js local script.</strong> Plugin creates cron task to update cache of Google Analytics scripts daily. Once this feature is enabled, the plugin wont update the Google Analytics cache file.
== Translations ==
* English - default, always included
* Russian
If you want to help with the translation, please contact me through this site or through the contacts inside the plugin.
#### THANKS TO THE PLUGINS' AUTHORS ####
We used some plugins functions:
<strong>GA Google Analytics</strong>, <strong>NK Google Analytics</strong>, <strong>Complete Analytics Optimization Suite (CAOS)</strong>, <strong>Clearfy — WordPress optimization plugin and disable ultimate tweaker</strong>, <strong>Enhanced Ecommerce Google Analytics Plugin for WooCommerce</strong>
#### 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/)
* [WordPress Assets manager, dequeue scripts, dequeue styles](https://wordpress.org/plugins/gonzales/ "WordPress Assets manager, dequeue scripts, dequeue styles")
== Installation ==
1. Upload the simple-google-analytics.zip file to the /wp-content/plugins/ directory using wget, curl of ftp.
2. unzip the simple-google-analytics.zip which will create the folder to the directory /wp-content/plugins/simple-google-analytics
3. Activate the plugin through the Plugins menu in WordPress
4. Configure the plugin through Local Google Analytics submenu in the the Settings section of the WordPress admin menu
5. Add your google analytics ID there. An example of Google Analytics ID > UA-0000000-0.
6. Choose if your blog is on a sub-domain or not. This option is defined in your Google Analytics settings page. Do not change if you dont know.
7. Enter the domain where your WordPress is.
8. Save it & your done.
== Screenshots ==
1. Control panel
== Changelog ==
= 3.2.9 (05.12.2024) =
* Added: Compatibility with Wordpress 6.7
* Fixed: Security issue
= 3.2.8 (21.03.2024) =
* Added: Compatibility with Wordpress 6.5
* Added: Compatibility with php 8.3
== Changelog ==
= 3.2.7 (21.11.2023) =
* Added: Compatibility with Wordpress 6.4
* Added: Compatibility with php 8.2
= 3.2.6 (22.03.2023) =
* Fixed: Freemius framework conflict
* Added: Compatibility with Wordpress 6.2
= 3.2.5 (30.05.2022) =
* Added: Compatibility with Wordpress 6.0
= 3.2.4 (24.03.2022) =
* Added: Compatibility with Disable admin notices plugin
= 3.2.3 (23.03.2022) =
* Added: Compatibility with Wordpress 5.9
* Fixed: Minor bugs
= 3.2.2 (20.10.2021) =
* Added: Compatibility with Wordpress 5.8
* Fixed: Minor bugs
= 3.1.3 =
* Added: Subscribe form
* Fixed: Minor bugs
= 3.1.2 =
* Fixed: A bug with creating a local copy of the Google analytics library.
= 3.1.1 =
* Added: Compatibility with Wordpress 4.2 - 5.x
* Added: Multisite support
* Fixed: Minor bugs
= version 3.0.1 =
* Fixed small bugs
= version 3.0.0 =
* The Simple Google Analytics plugin has some major changes. Unfortunately, the old version of the plugin (2.2.2) is no longer supported, but you still can download it from the WordPress repository in case if the new release doesnt work for you.
Weve updated the code and fixed the compatibility issue for the latest WordPress and PHP versions. Weve also added additional feature of the Google Analytics cache this way your website will load faster. The plugins name has been changed to Google Analytics cache, but all features remained the same.
Please, check plugin settings and its performance on your website. We do care about you and want to avoid any problems with the new version.
= version 2.2.3 =
* Author change
= version 2.2.2 =
* Add a comment when the code isn't loaded while being logged
= version 2.2.1 =
* Corrected the analytics code to prevent non-detection from Google
= version 2.2.0 =
* Add the demographic / interests reports
= version 2.1.0 =
* Corrected a bug with wp_enqueue_script
* Change the JS loading method
* Add the external links / downloads tracking
= version 2.0.5 =
* Added the option to not render when logged in
= version 2.0.4 =
* Corrected a bug where the JS file was loading before jQuery. Thanks to MrZebra for finding that.
= version 2.0.3 =
* Corrected a bug that made all settings link on extension page going to Simple Google Analytics settings page.
= version 2.0.2 =
* Google Code has returned to the original. The optimized code have issues with some users having no stats. All should be fine now.
= version 2.0 =
* Code has been fully rewritten.
* Google Analytics code has been rewritten to load faster.
= version 1.1.6 =
* Code is not showing only when logged as Admin.
* Add option to select where you want to place the code (Header or Footer)
= version 1.1.5 =
* Add settings in the extensions page (Thanks to Vladimir Pavlikov)
* Add Russian Translation (Thanks to Vladimir Pavlikov)
= version 1.1.4 =
* Version 1.1.3 doesn't shows in the repository...
= version 1.1.3 =
* Added a translation for 'Simple Google Analytics Settings'
= version 1.1.2 =
* French Translation Bug
= version 1.1.1 =
* Fixed annoying bug
= version 1.1.0 =
* Added new Site Speed setting from Google
= version 1.0.4 =
* Corriged a bug if you use the Papercite plugin
= version 1.0.3 =
* Clean Readme file and clean code
= version 1.0.2 =
* Added French Translation
= version 1.0 =
* Add multi-subdomain option

View File

@@ -0,0 +1,137 @@
<?php
/**
* Plugin Name: Webcraftic Local Google Analytics
* Plugin URI: https://webcraftic.com
* Description: Old plugin name: Simple Google Analytics. To improve Google Page Speed indicators Analytics caching is needed. However, it can also slightly increase your website loading speed, because Analytics js files will load locally. The second case that you might need these settings is the usual Google Analytics connection to your website. You do not need to do this with other plugins or insert the tracking code into your theme.
* Author: Webcraftic <wordpress.webraftic@gmail.com>
* Version: 3.2.9
* Text Domain: simple-google-analytics
* Domain Path: /languages/
* Author URI: http://webcraftic.com
*/
// 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
$plugin_info = [
'prefix' => 'wbcr_gac_',
'plugin_name' => 'wbcr_gac',
'plugin_title' => 'Webcraftic Local Google Analytics',
// PLUGIN SUPPORT
'support_details' => [
'url' => 'https://webcraftic.com',
'pages_map' => [
'support' => 'support', // {site}/support
'docs' => 'docs' // {site}/docs
]
],
// 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)
],
// PLUGIN SUBSCRIBE FORM
'subscribe_widget' => true,
'subscribe_settings' => [ 'group_id' => '105425989' ],
// 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' ]
]
];
$wga_compatibility = new Wbcr_Factory480_Requirements( __FILE__, array_merge( $plugin_info, [
'plugin_already_activate' => defined( 'WGA_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 ( ! $wga_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( 'WGA_PLUGIN_ACTIVE', true );
define( 'WGA_PLUGIN_VERSION', $wga_compatibility->get_plugin_version() );
define( 'WGA_PLUGIN_DIR', dirname( __FILE__ ) );
define( 'WGA_PLUGIN_BASE', plugin_basename( __FILE__ ) );
define( 'WGA_PLUGIN_URL', plugins_url( '', __FILE__ ) );
define( 'WGA_PLUGIN_CACHE_FOLDER', 'wga-cache' );
/**
* -----------------------------------------------------------------------------
* PLUGIN INIT
* -----------------------------------------------------------------------------
*/
require_once( WGA_PLUGIN_DIR . '/libs/factory/core/boot.php' );
require_once( WGA_PLUGIN_DIR . '/includes/class-plugin.php' );
try {
new WGA_Plugin( __FILE__, array_merge( $plugin_info, [
'plugin_version' => WGA_PLUGIN_VERSION,
'plugin_text_domain' => $wga_compatibility->get_text_domain(),
] ) );
} catch ( Exception $e ) {
// Plugin wasn't initialized due to an error
define( 'WGA_PLUGIN_THROW_ERROR', true );
$wga_plugin_error_func = function () use ( $e ) {
$error = sprintf( "The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Local Google Analytics', $e->getMessage(), $e->getCode() );
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action( 'admin_notices', $wga_plugin_error_func );
add_action( 'network_admin_notices', $wga_plugin_error_func );
}
// @formatter:on

View File

@@ -0,0 +1,13 @@
<?php
// if uninstall.php is not called by WordPress, die
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
die;
}
// remove plugin options
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->prefix}options WHERE option_name LIKE 'wbcr_gac%';" );