renderer = $renderer;
}
public function init() {
add_action('adghost_ad', [$this, 'render_named'], 10, 1);
$used = [];
foreach (AdGhost_Helper::units() as $unit) {
if (($unit['placementMode'] ?? 'auto') !== 'manual') {
$used[AdGhost_Helper::get_unit_position($unit)] = true;
}
}
if (isset($used['before_comments']) || get_option('adghost_zone_comments', false)) {
add_filter('comments_template', [$this, 'render_comments_before_template']);
add_action('comment_form_before', [$this, 'render_comments_before']);
}
if (isset($used['after_comments']) || get_option('adghost_zone_comments', false)) {
add_action('comment_form_after', [$this, 'render_comments_after']);
add_action('comment_form_comments_closed', [$this, 'render_comments_after']);
}
if (isset($used['between_comments'])) {
add_filter('comments_array', [$this, 'count_comments'], 99);
add_filter('wp_list_comments_args', [$this, 'wrap_comment_list'], 99);
}
if (isset($used['before_excerpt']) || isset($used['after_excerpt'])) {
add_filter('the_excerpt', [$this, 'render_excerpt'], 20);
add_filter('render_block', [$this, 'render_excerpt_block'], 10, 2);
}
if (isset($used['between_posts']) || get_option('adghost_zone_feed', false)) {
add_action('elementor/frontend/widget/before_render', function () { $this->in_builder_widget++; });
add_action('elementor/frontend/widget/after_render', function () { $this->in_builder_widget = max(0, $this->in_builder_widget - 1); });
add_action('loop_start', [$this, 'reset_feed']);
add_action('the_post', [$this, 'render_feed'], 10, 1);
add_filter('render_block', [$this, 'render_feed_block'], 10, 2);
}
if (isset($used['selector'])) {
add_action('wp_footer', [$this, 'render_selector_units'], 5);
}
if (trim((string) get_option('adghost_zone_selector', '')) !== '') {
add_filter('the_content', [$this, 'render_selector'], 16);
}
}
public function render_named($name) {
$unit = $this->find_by_name((string) $name);
if ($unit === null) {
echo '';
return;
}
echo wp_kses($this->render($unit, 'hook'), AdGhost_Helper::allowed_ads_html());
}
public function render_comments_before_template($template) {
if (is_singular()) {
$this->render_comments_before();
}
return $template;
}
public function render_comments_before() {
if ($this->comments_before_done) {
return;
}
$this->comments_before_done = true;
echo wp_kses($this->zone_html('before_comments', 'comments'), AdGhost_Helper::allowed_ads_html());
}
public function render_comments_after() {
echo wp_kses($this->zone_html('after_comments', 'comments'), AdGhost_Helper::allowed_ads_html());
}
public function render_excerpt($excerpt) {
if (self::block_theme() || !in_the_loop() || !is_main_query()) {
return $excerpt;
}
return $this->around_excerpt((string) $excerpt);
}
public function render_excerpt_block($html, $block) {
if (!self::block_theme() || ($block['blockName'] ?? '') !== 'core/post-excerpt' || trim((string) $html) === '') {
return $html;
}
return $this->around_excerpt((string) $html);
}
private function around_excerpt($excerpt) {
if (is_singular() || is_feed() || is_admin()) {
return $excerpt;
}
$seen = $this->counts['excerpt_seen'] = ($this->counts['excerpt_seen'] ?? 0) + 1;
$before = $this->every_nth('before_excerpt', $seen, 'excerpt');
$after = $this->every_nth('after_excerpt', $seen, 'excerpt');
return $before . $excerpt . $after;
}
private function every_nth($position, $n, $zone) {
foreach ($this->find_all_by_position($position) as $unit) {
$every = max(1, absint($unit['insertionValue'] ?? 3));
$limit = absint($unit['insertionLimit'] ?? 0);
$key = $position . '_placed_' . md5(AdGhost_Helper::gam_code($unit) . ($unit['name'] ?? ''));
if ($n % $every !== 0 || ($limit > 0 && ($this->counts[$key] ?? 0) >= $limit)) {
continue;
}
$html = $this->render($unit, $zone);
if (strpos($html, '
counts[$key] = ($this->counts[$key] ?? 0) + 1;
return wp_kses($html, AdGhost_Helper::allowed_ads_html());
}
return '';
}
return '';
}
public function count_comments($comments) {
$threaded = (bool) get_option('thread_comments');
$top = 0;
foreach ((array) $comments as $comment) {
if (!$threaded || empty($comment->comment_parent)) {
$top++;
}
}
$this->counts['comments_total'] = $top;
return $comments;
}
public function wrap_comment_list($args) {
if (is_admin() || is_feed() || !is_singular() || !empty($args['adghost_between'])) {
return $args;
}
$args['adghost_between'] = true;
$theirs = $args['end-callback'] ?? null;
$args['end-callback'] = function ($comment, $list_args, $depth) use ($theirs) {
if ($theirs && is_callable($theirs)) {
call_user_func($theirs, $comment, $list_args, $depth);
} else {
echo ('div' === ($list_args['style'] ?? 'ul')) ? "
\n" : "\n";
}
$this->after_comment($comment, $list_args);
};
return $args;
}
private function after_comment($comment, $args) {
if (get_option('thread_comments') && !empty($comment->comment_parent)) {
return;
}
$seen = $this->counts['comments_seen'] = ($this->counts['comments_seen'] ?? 0) + 1;
if (isset($this->counts['comments_total']) && $seen >= $this->counts['comments_total']) {
return;
}
$html = $this->every_nth('between_comments', $seen, 'comments');
if ($html === '') {
return;
}
echo ('div' === ($args['style'] ?? 'ul'))
? '' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped by wp_kses in every_nth().
: ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
public function render_feed($post) {
if (is_singular() || !in_the_loop() || !is_main_query() || is_admin() || is_feed() || self::block_theme()) {
return;
}
if ($this->in_builder_widget > 0) {
return;
}
$seen = $this->counts['feed_seen'] = ($this->counts['feed_seen'] ?? 0) + 1;
$after = $seen - 1;
if ($after < 1) {
return;
}
$units = $this->find_all_by_position('between_posts');
if (!$units && get_option('adghost_zone_feed', false)) {
$units = $this->find_all_by_position('feed');
}
foreach ($units as $unit) {
$every = max(1, absint($unit['insertionValue'] ?? get_option('adghost_zone_feed_every', 3)));
$limit = absint($unit['insertionLimit'] ?? 0);
$key = 'feed_placed_' . md5(AdGhost_Helper::gam_code($unit) . ($unit['name'] ?? ''));
if ($after % $every !== 0 || ($limit > 0 && ($this->counts[$key] ?? 0) >= $limit)) {
continue;
}
$html = $this->render($unit, 'feed');
if (strpos($html, 'counts[$key] = ($this->counts[$key] ?? 0) + 1;
echo wp_kses($html, AdGhost_Helper::allowed_ads_html());
}
return;
}
}
public function render_feed_block($html, $block) {
if (($block['blockName'] ?? '') !== 'core/post-template' || is_singular() || is_admin()) {
return $html;
}
if (!preg_match_all('/
]*\bclass="[^"]*\bwp-block-post\b/i', $html, $m, PREG_OFFSET_CAPTURE)) {
return $html;
}
$units = $this->find_all_by_position('between_posts');
if (!$units) {
return $html;
}
$inserts = [];
$placed = [];
foreach ($m[0] as $i => $match) {
$after = $i;
if ($after < 1) {
continue;
}
foreach ($units as $u => $unit) {
$every = max(1, absint($unit['insertionValue'] ?? 3));
$limit = absint($unit['insertionLimit'] ?? 0);
if ($after % $every !== 0 || ($limit > 0 && ($placed[$u] ?? 0) >= $limit)) {
continue;
}
$ad = $this->render($unit, 'feed');
if (strpos($ad, '' . $ad . ''];
}
break;
}
}
foreach (array_reverse($inserts) as [$offset, $ad]) {
$html = substr($html, 0, $offset) . $ad . substr($html, $offset);
}
return $html;
}
private static function block_theme() {
return function_exists('wp_is_block_theme') && wp_is_block_theme();
}
public function reset_feed() {
$this->counts['feed_seen'] = 0;
}
public function render_selector_units() {
if (is_admin() || is_feed() || (class_exists('AdGhost_Targeting') && AdGhost_Targeting::page_exclusion_reason() !== null)) {
return;
}
if (class_exists('AdGhost_AMP') && AdGhost_AMP::is_amp()) {
return;
}
$jobs = [];
foreach ($this->find_all_by_position('selector') as $unit) {
$selector = trim((string) ($unit['selector'] ?? ''));
if ($selector === '') {
continue;
}
$html = $this->render($unit, 'selector');
if ($html === '') {
continue;
}
$place = in_array($unit['selectorPosition'] ?? '', self::SELECTOR_PLACES, true) ? $unit['selectorPosition'] : 'after';
$jobs[] = [
'id' => 'adghost-tpl-' . count($jobs),
'sel' => $selector,
'place' => $place,
'html' => $html,
];
}
if (!$jobs) {
return;
}
foreach ($jobs as $job) {
echo '' . wp_kses($job['html'], AdGhost_Helper::allowed_ads_html()) . '';
}
$spec = array_map(function ($job) {
return ['t' => $job['id'], 's' => $job['sel'], 'p' => $job['place']];
}, $jobs);
wp_print_inline_script_tag('(function(d,j){j.forEach(function(x){try{var t=d.getElementById(x.t),e=d.querySelector(x.s);'
. 'if(!t||!e)return;var n=t.content.firstElementChild;if(!n)return;'
. 'x.p==="before"?e.parentNode.insertBefore(n,e):x.p==="prepend"?e.insertBefore(n,e.firstChild):'
. 'x.p==="append"?e.appendChild(n):e.parentNode.insertBefore(n,e.nextSibling);}catch(r){}});})'
. '(document,' . wp_json_encode($spec, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ');');
}
public function render_selector($content) {
if (!is_singular() || !in_the_loop() || !is_main_query() || strpos($content, '<') === false) {
return $content;
}
$selector = trim((string) get_option('adghost_zone_selector', ''));
if ($selector === '') {
return $content;
}
$html = $this->zone_html('selector', 'selector');
if ($html === '') {
return $content;
}
$offset = $this->selector_offset($content, $selector);
if ($offset === null) {
return $content;
}
return substr($content, 0, $offset) . $html . substr($content, $offset);
}
private function selector_offset($content, $selector) {
$attribute = ($selector[0] === '#') ? 'id' : 'class';
$value = preg_replace('/[^a-z0-9_-]/i', '', substr($selector, 1));
if ($value === '') {
return null;
}
$pattern = $attribute === 'id'
? '/<([a-z0-9]+)\b[^>]*\sid="' . preg_quote($value, '/') . '"[^>]*>/i'
: '/<([a-z0-9]+)\b[^>]*\sclass="(?:[^"]*\s)?' . preg_quote($value, '/') . '(?:\s[^"]*)?"[^>]*>/i';
if (!preg_match($pattern, $content, $m, PREG_OFFSET_CAPTURE)) {
return null;
}
$tag = strtolower($m[1][0]);
$start = $m[0][1];
$cursor = $start + strlen($m[0][0]);
$depth = 1;
if (in_array($tag, ['img', 'hr', 'br', 'input', 'embed', 'source'], true) || substr($m[0][0], -2) === '/>') {
return $cursor;
}
if (preg_match_all('/<(\/?)' . $tag . '\b[^>]*>/i', $content, $tags, PREG_OFFSET_CAPTURE, $cursor)) {
foreach ($tags[0] as $i => $t) {
$depth += ($tags[1][$i][0] === '/') ? -1 : 1;
if ($depth === 0) {
return $t[1] + strlen($t[0]);
}
}
}
return null;
}
private function zone_html($position, $zone) {
if (class_exists('AdGhost_Targeting') && AdGhost_Targeting::page_exclusion_reason() !== null) {
return '';
}
$html = '';
foreach ($this->find_all_by_position($position) as $unit) {
$html .= $this->render($unit, $zone);
}
return $html;
}
private function render(array $unit, $zone) {
if (!AdGhost_Helper::ads_live() || is_admin() || is_feed()) {
return '';
}
if (class_exists('AdGhost_Targeting') && AdGhost_Targeting::page_exclusion_reason() !== null) {
return '';
}
if (class_exists('AdGhost_Targeting')) {
$why = AdGhost_Targeting::unit_exclusion_reason($unit);
if ($why !== null) {
return '';
}
}
if (class_exists('AdGhost_IVT_Manager') && !AdGhost_IVT_Manager::ads_allowed()) {
return '';
}
if ($zone !== 'hook' && !$this->budget_left()) {
return '';
}
$index = $this->counts[$zone] = ($this->counts[$zone] ?? -1) + 1;
$slot = $zone . '_' . $index;
if (AdGhost_Placement_State::is_block_inserted($slot, $zone)) {
return '';
}
AdGhost_Placement_State::mark_block_inserted($slot, $zone, [
'unit_name' => $unit['name'] ?? '',
]);
return (string) call_user_func($this->renderer, $unit, $zone, $index);
}
private function budget_left() {
$max = absint(get_option('adghost_max_ads_per_page', 5));
if ($max <= 0) {
return true;
}
$placed = 0;
foreach (AdGhost_Placement_Engine::CAPPED_ZONES as $zone) {
$placed += AdGhost_Placement_State::get_zone_count($zone);
}
return $placed < $max;
}
private function find_all_by_position($position) {
$out = [];
foreach (AdGhost_Helper::units() as $unit) {
if (($unit['placementMode'] ?? 'auto') === 'manual') {
continue;
}
if (AdGhost_Helper::get_unit_position($unit) === $position) {
$out[] = $unit;
}
}
return $out;
}
private function find_by_name($name) {
$slug = sanitize_title($name);
foreach (AdGhost_Helper::units() as $unit) {
if (sanitize_title($unit['name'] ?? '') === $slug || ($unit['id'] ?? '') === $name) {
return $unit;
}
}
return null;
}
}