plugin_name = $plugin_name;
$this->version = $version;
$this->popup_editor_script_handle = $this->plugin_name . '-popup-block-editor';
}
/**
* Registers popup templates CPT.
*
* @return void
*/
public function register_post_type()
{
$template_lock = $this->is_pro_enabled() ? false : 'all';
$labels = array(
'name' => __('Popups', 'adunblocker'),
'singular_name' => __('Popup', 'adunblocker'),
'add_new' => __('Add Popup', 'adunblocker'),
'add_new_item' => __('Add New Popup', 'adunblocker'),
'edit_item' => __('Edit Popup', 'adunblocker'),
'new_item' => __('New Popup', 'adunblocker'),
'view_item' => __('View Popup', 'adunblocker'),
'search_items' => __('Search Popups', 'adunblocker'),
'not_found' => __('No popups found.', 'adunblocker'),
'not_found_in_trash' => __('No popups found in Trash.', 'adunblocker'),
'all_items' => __('Popups', 'adunblocker'),
'menu_name' => __('Popups', 'adunblocker'),
);
register_post_type('daau_popup', array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => false,
'exclude_from_search' => true,
'show_ui' => true,
'show_in_menu' => $this->plugin_name . '-general-settings-page',
'show_in_rest' => true,
'supports' => array('title', 'editor', 'revisions'),
'template' => $this->get_starter_popup_block_template(),
'template_lock' => $template_lock,
'menu_icon' => 'dashicons-welcome-widgets-menus',
));
}
/**
* Creates one inactive starter popup for installations without popup content.
*
* The state option makes this idempotent across plugin reactivation. Existing
* installations receive the starter only when they have never created a popup.
*
* @return void
*/
public function maybe_create_starter_popup()
{
if (!is_admin() || !current_user_can('manage_options') || !post_type_exists('daau_popup')) {
return;
}
$starter_state = get_option(self::STARTER_STATE_OPTION, 'pending');
if ('pending' !== $starter_state) {
return;
}
$existing_popups = get_posts(array(
'post_type' => 'daau_popup',
'post_status' => array('publish', 'draft', 'pending', 'private', 'future', 'trash'),
'numberposts' => 1,
'fields' => 'ids',
'no_found_rows' => true,
));
if (!empty($existing_popups)) {
update_option(self::STARTER_STATE_OPTION, 'existing', false);
return;
}
$starter_id = wp_insert_post(
array(
'post_type' => 'daau_popup',
'post_status' => 'draft',
'post_title' => __('Starter: Friendly adblock request', 'adunblocker'),
'post_content' => wp_slash($this->get_starter_popup_content()),
'post_author' => get_current_user_id(),
'meta_input' => array(
self::STARTER_META_KEY => '1',
),
),
true
);
if (is_wp_error($starter_id) || $starter_id <= 0) {
return;
}
update_option(self::STARTER_ID_OPTION, absint($starter_id), false);
update_option(self::STARTER_STATE_OPTION, 'created', false);
}
/**
* Keeps Free installations to one published popup while preserving drafts.
*
* @param int $post_id Popup post ID.
* @param WP_Post $post Popup post object.
* @param bool $update Whether this is an existing post update.
* @return void
*/
public function enforce_free_active_popup_limit($post_id, $post, $update)
{
unset($update);
if (
$this->allows_multiple_active_popups() ||
!($post instanceof WP_Post) ||
'publish' !== $post->post_status ||
wp_is_post_revision($post_id) ||
wp_is_post_autosave($post_id)
) {
return;
}
$active_ids = get_posts(array(
'post_type' => 'daau_popup',
'post_status' => 'publish',
'numberposts' => -1,
'fields' => 'ids',
'no_found_rows' => true,
));
$deactivated_count = 0;
foreach ($active_ids as $other_active_id) {
if (absint($other_active_id) === absint($post_id)) {
continue;
}
$result = wp_update_post(array(
'ID' => absint($other_active_id),
'post_status' => 'draft',
), true);
if (!is_wp_error($result)) {
$deactivated_count++;
}
}
if ($deactivated_count > 0 && get_current_user_id() > 0) {
set_transient(
'adunblocker-popup-limit-notice-' . get_current_user_id(),
$deactivated_count,
MINUTE_IN_SECONDS
);
}
}
/**
* Adds an authenticated frontend preview action to each popup row.
*
* @param array $actions Existing row actions.
* @param WP_Post $post Popup post.
* @return array
*/
public function add_popup_row_actions($actions, $post)
{
if (!($post instanceof WP_Post) || 'daau_popup' !== $post->post_type || !current_user_can('edit_post', $post->ID)) {
return $actions;
}
$preview_url = $this->get_popup_preview_url($post->ID);
$actions['daau_preview'] = sprintf(
'%2$s',
esc_url($preview_url),
esc_html__('Preview adblock experience', 'adunblocker')
);
return $actions;
}
/**
* Displays popup editor notice for free users.
*
* @return void
*/
public function maybe_render_upgrade_notice()
{
if (!is_admin() || !function_exists('get_current_screen')) {
return;
}
$screen = get_current_screen();
if (!$screen || 'daau_popup' !== $screen->post_type) {
return;
}
$user_id = get_current_user_id();
$limit_notice_key = 'adunblocker-popup-limit-notice-' . $user_id;
$deactivated_count = $user_id > 0 ? absint(get_transient($limit_notice_key)) : 0;
if ($deactivated_count > 0) {
delete_transient($limit_notice_key);
printf(
'
',
esc_html(
sprintf(
/* translators: %d: number of popups returned to draft status. */
_n(
'Free supports one active popup. %d previously active popup was returned to draft.',
'Free supports one active popup. %d previously active popups were returned to draft.',
$deactivated_count,
'adunblocker'
),
$deactivated_count
)
)
);
}
if ('edit' === $screen->base) {
$this->render_popup_list_notice();
return;
}
if ('post' !== $screen->base || $this->is_pro_enabled()) {
return;
}
$upgrade_url = 'https://digitalapps.com/wordpress-plugins/adunblocker/?utm_source=plugin&utm_medium=web&utm_content=popup-template-editor&utm_campaign=proplugin';
printf(
'',
esc_html__('Build the recovery journey when you are ready.', 'adunblocker'),
esc_html__('Free includes one active popup and unlimited drafts. Pro adds simultaneous campaigns, journey steps, experiments, offers, and advanced recovery analytics.', 'adunblocker'),
esc_url($upgrade_url),
esc_html__('Upgrade to Pro', 'adunblocker')
);
}
/**
* Displays onboarding and plan guidance on the popup list screen.
*
* @return void
*/
private function render_popup_list_notice()
{
$starter_id = absint(get_option(self::STARTER_ID_OPTION, 0));
$starter = $starter_id > 0 ? get_post($starter_id) : null;
if ($starter instanceof WP_Post && 'daau_popup' === $starter->post_type && 'draft' === $starter->post_status) {
printf(
'',
esc_html__('Your starter popup is ready.', 'adunblocker'),
esc_html__('Review the friendly allowlist message, preview the real visitor experience, and publish it when you are ready. Drafts never appear to visitors.', 'adunblocker'),
esc_url(get_edit_post_link($starter_id, 'raw')),
esc_html__('Review starter popup', 'adunblocker'),
esc_url($this->get_popup_preview_url($starter_id)),
esc_html__('Preview experience', 'adunblocker')
);
}
if (!$this->is_pro_enabled()) {
printf(
'',
esc_html__('Free plan:', 'adunblocker'),
esc_html__('Create as many drafts as you need and keep one popup active. Publishing another popup automatically returns the previous active popup to draft.', 'adunblocker')
);
}
}
/**
* Displays a block-editor notice for free users on popup templates.
*
* @return void
*/
public function enqueue_editor_upgrade_notice()
{
if ($this->is_pro_enabled() || !function_exists('get_current_screen')) {
return;
}
$screen = get_current_screen();
if (!$screen || $screen->base !== 'post' || $screen->post_type !== 'daau_popup') {
return;
}
$message = esc_js(__('Free supports one active popup with an editable starter layout. Upgrade to Pro for simultaneous campaigns, recovery journeys, and additional Gutenberg blocks.', 'adunblocker'));
$script = "window.wp&&window.wp.data&&window.wp.data.dispatch&&window.wp.data.dispatch('core/notices').createNotice('info','{$message}',{id:'daau-popup-pro-upgrade',isDismissible:false});";
wp_add_inline_script('wp-block-editor', $script, 'after');
}
/**
* Registers the popup block.
*
* @return void
*/
public function register_block_type()
{
if (! function_exists('register_block_type')) {
return;
}
$block_json_path = $this->get_popup_block_json_path();
if ('' === $block_json_path) {
return;
}
$block_args = array(
'render_callback' => array($this, 'render_popup_block'),
);
$editor_script_handle = $this->register_popup_editor_script();
if ('' !== $editor_script_handle) {
$block_args['editor_script_handles'] = array($editor_script_handle);
}
register_block_type($block_json_path, $block_args);
}
/**
* Registers a minimal editor fallback when popup block assets are unavailable.
*
* @return void
*/
public function enqueue_block_editor_fallback_registration()
{
if (!$this->is_popup_editor_screen()) {
return;
}
$editor_script_handle = $this->register_popup_editor_script();
$message = esc_js(__('AdUnblocker Popup block assets are missing. Basic editing mode is enabled.', 'adunblocker'));
$script = "(function (wp, document) {
if (!wp || !wp.blocks || !wp.element || !wp.blockEditor) { return; }
var registerFallbackBlock = function () {
if (wp.blocks.getBlockType('daau/popup')) { return; }
var createElement = wp.element.createElement;
var InnerBlocks = wp.blockEditor.InnerBlocks;
wp.blocks.registerBlockType('daau/popup', {
apiVersion: 3,
title: 'AdUnblocker Popup',
category: 'design',
icon: 'welcome-widgets-menus',
supports: {
html: false,
reusable: false
},
edit: function () {
return createElement(
'div',
{ className: 'daau-popup-fallback-editor' },
createElement('p', { style: { marginTop: 0 } }, '" . $message . "'),
createElement(InnerBlocks)
);
},
save: function () {
return createElement(InnerBlocks.Content);
}
});
};
if (wp.domReady && typeof wp.domReady === 'function') {
wp.domReady(registerFallbackBlock);
return;
}
if (document && document.readyState === 'loading' && document.addEventListener) {
document.addEventListener('DOMContentLoaded', registerFallbackBlock);
return;
}
registerFallbackBlock();
})(window.wp, document);";
wp_add_inline_script(
'' !== $editor_script_handle ? $editor_script_handle : 'wp-block-editor',
$script,
'after'
);
}
/**
* Returns block.json path, preferring build output.
*
* @return string
*/
private function get_popup_block_json_path()
{
$candidate_paths = array(
ADUNBLOCKER_PLUGIN_PATH . 'blocks/popup/build/block.json',
ADUNBLOCKER_PLUGIN_PATH . 'blocks/popup/block.json',
);
foreach ($candidate_paths as $path) {
if (file_exists($path)) {
return $path;
}
}
return '';
}
/**
* Registers popup editor script from build assets.
*
* @return string
*/
private function register_popup_editor_script()
{
$script_path = ADUNBLOCKER_PLUGIN_PATH . 'blocks/popup/build/index.js';
$asset_path = ADUNBLOCKER_PLUGIN_PATH . 'blocks/popup/build/index.asset.php';
if (!file_exists($script_path) || !file_exists($asset_path)) {
return '';
}
$asset = include $asset_path;
if (!is_array($asset)) {
return '';
}
$dependencies = isset($asset['dependencies']) && is_array($asset['dependencies'])
? $asset['dependencies']
: array();
$version = isset($asset['version']) && is_scalar($asset['version'])
? (string) $asset['version']
: $this->version;
if (!wp_script_is($this->popup_editor_script_handle, 'registered')) {
wp_register_script(
$this->popup_editor_script_handle,
false,
$dependencies,
$version,
true
);
$editor_script = file_get_contents($script_path);
if (is_string($editor_script) && '' !== trim($editor_script)) {
wp_add_inline_script($this->popup_editor_script_handle, $editor_script, 'after');
}
}
return $this->popup_editor_script_handle;
}
/**
* Determines whether current screen is popup template editor.
*
* @return bool
*/
private function is_popup_editor_screen()
{
if (!is_admin() || !function_exists('get_current_screen')) {
return false;
}
$screen = get_current_screen();
return $screen && $screen->base === 'post' && $screen->post_type === 'daau_popup';
}
/**
* Server-side block renderer.
*
* @param array $attributes Block attributes.
* @param string $content Inner block HTML.
*
* @return string
*/
public function render_popup_block($attributes, $content)
{
$defaults = array(
'overlayColor' => 'rgba(0,0,0,0.88)',
'overlayPadding' => 24,
'contentBackgroundColor' => '#ffffff',
'contentMaxWidth' => 680,
'contentPadding' => 28,
'contentBorderRadius' => 10,
'showRefreshButton' => true,
'refreshButtonLabel' => __('I have allowed ads - refresh', 'adunblocker'),
);
$attributes = wp_parse_args(is_array($attributes) ? $attributes : array(), $defaults);
$overlay_color = $this->sanitize_overlay_color($attributes['overlayColor'], $defaults['overlayColor']);
if (
isset($attributes['overlayOpacity']) &&
is_numeric($attributes['overlayOpacity']) &&
strpos($overlay_color, '#') === 0
) {
$legacy_opacity = max(0, min(100, (int) $attributes['overlayOpacity'])) / 100;
$overlay_color = $this->hex_to_rgba($overlay_color, $legacy_opacity);
}
$overlay_padding = max(0, absint($attributes['overlayPadding']));
$content_bg = sanitize_hex_color($attributes['contentBackgroundColor']);
if (empty($content_bg)) {
$content_bg = $defaults['contentBackgroundColor'];
}
$content_max_width = max(280, absint($attributes['contentMaxWidth']));
$content_padding = max(0, absint($attributes['contentPadding']));
$content_border_radius = max(0, absint($attributes['contentBorderRadius']));
$overlay_style = sprintf(
'background-color:%1$s;min-height:100vh;padding:%2$dpx;display:flex;align-items:center;justify-content:center;box-sizing:border-box;',
$overlay_color,
$overlay_padding
);
$content_style = sprintf(
'width:min(100%%,%1$dpx);background-color:%2$s;border-radius:%3$dpx;padding:%4$dpx;box-sizing:border-box;',
$content_max_width,
$content_bg,
$content_border_radius,
$content_padding
);
$content_markup = is_string($content) ? trim($content) : '';
if ('' === $content_markup) {
$content_markup = sprintf('%s
', esc_html__('Add popup content.', 'adunblocker'));
}
if (!empty($attributes['showRefreshButton'])) {
$refresh_button_label = sanitize_text_field((string) $attributes['refreshButtonLabel']);
if ('' === $refresh_button_label) {
$refresh_button_label = $defaults['refreshButtonLabel'];
}
$content_markup .= sprintf(
'',
esc_html($refresh_button_label)
);
}
return sprintf(
'',
esc_attr($overlay_style),
esc_attr($content_style),
$content_markup
);
}
/**
* Converts HEX to RGBA.
*
* @param string $hex Hex color value.
* @param float $alpha Alpha channel from 0 to 1.
*
* @return string
*/
private function hex_to_rgba($hex, $alpha)
{
$hex = ltrim((string) $hex, '#');
if (3 === strlen($hex)) {
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
}
if (6 !== strlen($hex)) {
return 'rgba(0,0,0,0.88)';
}
$red = hexdec(substr($hex, 0, 2));
$green = hexdec(substr($hex, 2, 2));
$blue = hexdec(substr($hex, 4, 2));
$alpha = max(0, min(1, (float) $alpha));
$alpha_string = rtrim(rtrim(sprintf('%.2F', $alpha), '0'), '.');
return sprintf('rgba(%d,%d,%d,%s)', $red, $green, $blue, $alpha_string);
}
/**
* Sanitizes overlay color and allows hex/rgb/rgba formats.
*
* @param mixed $value Color value from block attributes.
* @param string $fallback Fallback color value.
*
* @return string
*/
private function sanitize_overlay_color($value, $fallback)
{
if (!is_string($value)) {
return $fallback;
}
$value = trim($value);
if ($value === '') {
return $fallback;
}
$hex = sanitize_hex_color($value);
if (!empty($hex)) {
return $hex;
}
$pattern = '/^rgba?\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(?:\s*,\s*((?:0|1)(?:\.\d+)?|0?\.\d+))?\s*\)$/i';
if (!preg_match($pattern, $value, $matches)) {
return $fallback;
}
$red = max(0, min(255, absint($matches[1])));
$green = max(0, min(255, absint($matches[2])));
$blue = max(0, min(255, absint($matches[3])));
if (isset($matches[4]) && $matches[4] !== '') {
$alpha = max(0, min(1, (float) $matches[4]));
$alpha_string = rtrim(rtrim(sprintf('%.2F', $alpha), '0'), '.');
return sprintf('rgba(%d,%d,%d,%s)', $red, $green, $blue, $alpha_string);
}
return sprintf('rgb(%d,%d,%d)', $red, $green, $blue);
}
/**
* Returns serialized block content for the onboarding popup.
*
* @return string
*/
private function get_starter_popup_content()
{
$attributes = $this->get_starter_popup_attributes();
return sprintf(
"\n\n%2\$s
\n\n\n\n%3\$s
\n\n\n\n\n- %4\$s
\n\n\n\n- %5\$s
\n\n\n\n- %6\$s
\n
\n\n",
wp_json_encode($attributes),
esc_html__('Ads help keep this site available', 'adunblocker'),
esc_html__('We noticed that an ad blocker is enabled. Advertising supports the work behind this site, so please allow ads here if you can.', 'adunblocker'),
esc_html__('Open your ad blocker from the browser toolbar.', 'adunblocker'),
esc_html__('Choose Pause, Allow, or Disable on this site.', 'adunblocker'),
esc_html__('Use the refresh button below to continue.', 'adunblocker')
);
}
/**
* Returns the starter root block attributes.
*
* @return array
*/
private function get_starter_popup_attributes()
{
return array(
'popupType' => 'dismissible',
'popupTempDelaySeconds' => 2,
'popupScope' => 'session',
'pageTargetMode' => 'all',
'overlayColor' => 'rgba(15,23,42,0.84)',
'overlayPadding' => 24,
'contentBackgroundColor' => '#ffffff',
'contentMaxWidth' => 620,
'contentPadding' => 32,
'contentBorderRadius' => 14,
'showRefreshButton' => true,
'refreshButtonLabel' => __('I have allowed ads - refresh', 'adunblocker'),
);
}
/**
* Returns the complete editor template used for new popup posts.
*
* @return array
*/
private function get_starter_popup_block_template()
{
return array(
array(
'daau/popup',
$this->get_starter_popup_attributes(),
array(
array('core/heading', array(
'level' => 2,
'content' => __('Ads help keep this site available', 'adunblocker'),
)),
array('core/paragraph', array(
'content' => __('We noticed that an ad blocker is enabled. Advertising supports the work behind this site, so please allow ads here if you can.', 'adunblocker'),
)),
array(
'core/list',
array('ordered' => true),
array(
array('core/list-item', array('content' => __('Open your ad blocker from the browser toolbar.', 'adunblocker'))),
array('core/list-item', array('content' => __('Choose Pause, Allow, or Disable on this site.', 'adunblocker'))),
array('core/list-item', array('content' => __('Use the refresh button below to continue.', 'adunblocker'))),
),
),
),
),
);
}
/**
* Builds a nonce-protected preview URL for a popup.
*
* @param int $popup_id Popup post ID.
* @return string
*/
private function get_popup_preview_url($popup_id)
{
$popup_id = absint($popup_id);
return add_query_arg(
array(
'daau_preview_popup' => $popup_id,
'daau_preview_nonce' => wp_create_nonce('daau-preview-popup-' . $popup_id),
),
home_url('/')
);
}
/**
* Determines whether multiple published campaigns are available.
*
* @return bool
*/
private function allows_multiple_active_popups()
{
return (bool) apply_filters('daau_allow_multiple_active_popups', false);
}
/**
* Returns whether Pro features are enabled.
*
* @return bool
*/
private function is_pro_enabled()
{
if (defined('DAAU_PRO_ACTIVE') && DAAU_PRO_ACTIVE) {
return true;
}
return (bool) apply_filters('daau_stats_is_pro', false);
}
}