false, 'error' => 'Invalid nonce')); exit; } header('Content-Type: application/json; charset=utf-8'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Headers: X-WP-Nonce'); header('Access-Control-Allow-Credentials: true'); $propertyID = \wp\AdmiralAdBlockAnalytics::getPropertyID(); $candidateID = sanitize_text_field($_GET[PROTECT_CANDIDATE_ID] ?? ''); $validated = candidate_id_check($candidateID); $tokenResult = null; if ($validated) { $tokenResult = \wp\AdmiralTokenHandler::getTokenForUser($propertyID, get_cookie_name($candidateID)); } else { // temporary legacy cookie handling // this will get replaced with a proper cookie once the frontend starts sending candidateID $tokenResult = \wp\AdmiralTokenHandler::getTokenForUser($propertyID, 'adm_efstok'); } echo json_encode($tokenResult); exit; } if (isset($_GET[PROTECT_GET_POST])) { $propertyID = \wp\AdmiralAdBlockAnalytics::getPropertyID(); // validate post $postID = absint($_GET[PROTECT_GET_POST]); $post = get_post($postID); if ( get_post_status($post) !== 'publish' || !is_post_publicly_viewable($post) || post_password_required($post) ) { status_header(403); echo json_encode(array('success' => false, 'error' => 'Invalid post')); exit; } // validate candidate id $candidateID = sanitize_text_field($_GET[PROTECT_CANDIDATE_ID] ?? ''); $validated = candidate_id_check($candidateID, $postID); if (!$validated) { // legacy token check if (empty($candidateID) && isset($_COOKIE['adm_efstok']) && \wp\AdmiralTokenHandler::verifySignedToken($propertyID, 'adm_efstok')) { $output = apply_filters('the_content', $post->post_content); echo $output; exit; } status_header(403); echo json_encode(array('success' => false, 'error' => 'Invalid request')); exit; } // turned out to not be a protected article if (empty(ProtectState::$requestCandidate['candidateID'] ?? null)) { echo apply_filters('the_content', $post->post_content); exit; } $cookiename = get_cookie_name($candidateID); ProtectState::$requestCookie = $cookiename; if (isset($_COOKIE[$cookiename]) && \wp\AdmiralTokenHandler::verifySignedToken($propertyID, $cookiename)) { $output = apply_filters('the_content', $post->post_content); echo $output; exit; } status_header(403); echo json_encode(array('success' => false, 'error' => 'Invalid request')); exit; } if (isset($_GET[PROTECT_RESET_TOKEN])) { $candidateID = sanitize_text_field($_GET[PROTECT_CANDIDATE_ID] ?? ''); $validated = candidate_id_check($candidateID); if (!$validated) { // reset the legacy cookie setcookie('adm_efstok', '', -1, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); exit; } setcookie(get_cookie_name($candidateID), '', -1, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); exit; } if (isset($_GET[PROTECT_GET_CANDIDATES])) { $version = defined('ADMIRAL_PLUGIN_VERSION') ? ADMIRAL_PLUGIN_VERSION : 'unknown'; $candidates = \wp\AdmiralAdBlockAnalytics::getProtectCandidates(true); $res = array( 'success' => true, 'hasCandidates' => count($candidates) > 0, 'candidateCount' => count($candidates), 'version' => $version, ); echo json_encode($res); exit; } } catch (\Exception $e) { error_log("Error loading init: " . $e->getMessage()); } }); add_action('template_redirect', function() { try { if (!is_single() || is_user_logged_in()) return; initialize(); if (empty(ProtectState::$requestCookie)) return; if (!isset($_COOKIE[ProtectState::$requestCookie])) return; $propertyID = \wp\AdmiralAdBlockAnalytics::getPropertyID(); \wp\AdmiralTokenHandler::verifySignedToken($propertyID, ProtectState::$requestCookie); } catch (\Exception $e) { error_log("Error loading template_redirect: " . $e->getMessage()); } }); function bot_check($useragent) { if (empty($useragent)) { return true; } $t = strtolower($useragent); $t = " " . $t; switch ($t) { case (bool) strpos($t, 'google'): case (bool) strpos($t, 'bing'): case (bool) strpos($t, 'slurp'): case (bool) strpos($t, 'duckduckgo'): case (bool) strpos($t, 'baidu'): case (bool) strpos($t, 'yandex'): case (bool) strpos($t, 'sogou'): case (bool) strpos($t, 'msn'): case (bool) strpos($t, 'naver'): return true; default: return false; } } function detection_check($candidateIDs, $requirement, $benefits = null, $postId = null, $permalink = null) { if ($postId === null) { $postId = get_the_ID(); } if ($permalink === null) { $permalink = get_permalink(); } $tokenUrl = add_query_arg( array( PROTECT_GET_TOKEN => '1', PROTECT_CANDIDATE_ID => $candidateIDs[0], ), $permalink); $retrieveUrl = add_query_arg(array( PROTECT_GET_POST => $postId, PROTECT_CANDIDATE_ID => $candidateIDs[0], ), $permalink); $nonce = wp_create_nonce('wp_rest'); $jsonBenefits = json_encode($benefits); $jsonCandidateIDs = json_encode($candidateIDs); return << var ___admMeasureDetectedRan = false; setTimeout(function() { if (!___admMeasureDetectedRan) { var authMsg = document.getElementById('adm-auth-message'); if (authMsg) { authMsg.innerText = 'There was a problem loading this page. Please ensure JavaScript is enabled on your browser and any ad blockers are disabled.'; } } }, 8000); EOF; } function candidate_id_check($candidateID, $postID = null) { if (empty($candidateID)) { return false; } if (!empty($postID)) { // make sure we've got the right candidate initialize(); ProtectState::$requestCandidate = get_best_candidate(ProtectState::$candidates, $postID); if (ProtectState::$requestCandidate === null || empty(ProtectState::$requestCandidate)) { // not actually protected return true; } if (ProtectState::$requestCandidate['candidateID'] !== $candidateID) { return false; } } return true; } function get_loading_style() { return << .spinner { margin: 10px auto; width: 50px; height: 50px; position: relative; text-align: center; animation: sk-rotate 2.0s infinite linear; } .dot1, .dot2 { width: 60%; height: 60%; display: inline-block; position: absolute; top: 0; background-color: #333; border-radius: 100%; animation: sk-bounce 2.0s infinite ease-in-out; } .dot2 { top: auto; bottom: 0; animation-delay: -1.0s; } @keyframes sk-rotate { 100% { transform: rotate(360deg) }} @keyframes sk-bounce { 0%, 100% { transform: scale(0.0) } 50% { transform: scale(1.0) } } EOF; } function get_loading_message() { return <<
EOF; } function get_best_candidate($candidates, $postID = null) { if (empty($candidates) || count($candidates) == 0) { return null; } $winners = array(); $tags = array(); $fetchTags = null; if ($postID) { $fetchTags = get_the_tags($postID); } else { $fetchTags = get_the_tags(); } if ($fetchTags) { $tags = array_column($fetchTags, "name"); foreach($candidates as $pcand) { if (isset($pcand["payload"]["protect"]["tags"])) { $ctags = $pcand["payload"]["protect"]["tags"]; foreach($ctags as $group) { $hasTags = array_column(array_filter($group, function($tag) { return $tag["shouldNegate"] == false; }), "value"); $notTags = array_column(array_filter($group, function($tag) { return $tag["shouldNegate"] == true; }), "value"); if (count(array_intersect($tags, $hasTags)) == count($hasTags) && count(array_intersect($notTags, $tags)) == 0) { array_push($winners, $pcand); break; } } } else { // case: any/all tags targeted array_push($winners, $pcand); } } } else { // check the other way, does candidate require tags that article lacks foreach($candidates as $pcand) { if (isset($pcand["payload"]["protect"]["tags"])) { $canAdd = false; $ctags = $pcand["payload"]["protect"]["tags"]; foreach($ctags as $group) { $hasTags = array_column(array_filter($group, function($tag) { return $tag["shouldNegate"] == false; }), "value"); if (count($hasTags) == 0) { $canAdd = true; break; } } if ($canAdd) { array_push($winners, $pcand); } } else { // no tag requirements: fine to add array_push($winners, $pcand); } } } if (count($winners) == 0) { return null; } $bestMatch = $winners[0]; if (count($winners) > 1) { usort($winners, function($a,$b) { return $b["weight"] - $a["weight"]; }); $bestMatch = $winners[0]; // if we have multiple applicable candidates with the same weight, prefer non-ABR if ($winners[0]["weight"] == $winners[1]["weight"] && $winners[0]["payload"]["protect"]["requirement"] == "abr") { $highestWeight = $winners[0]["weight"]; foreach($winners as $w) { if ($w["weight"] == $highestWeight && $w["payload"]["protect"]["requirement"] !== "abr"){ return $w; } else if ($w["weight"] != $highestWeight) { break; } } } } return $bestMatch; } function get_cookie_name($candidateID) { return 'adm_efstok_' . hash('crc32b', $candidateID); } function initialize() { try { if (!ProtectState::$didInitialize) { $env = (defined('VIP_GO_APP_ENVIRONMENT') && VIP_GO_APP_ENVIRONMENT) || 'production'; ProtectState::$didInitialize = \wp\AdmiralAdBlockAnalytics::initialize("wp", ADMIRAL_PLUGIN_VERSION, $env); // only try to get candidates if we successfully initialized if (ProtectState::$didInitialize) { ProtectState::$candidates = \wp\AdmiralAdBlockAnalytics::getProtectCandidates(); } } if (!ProtectState::$resolvedCandidate && is_single()) { $postID = get_queried_object_id(); if ($postID > 0 && get_post_type($postID) === 'post') { ProtectState::$resolvedCandidate = true; ProtectState::$requestCandidate = get_best_candidate(ProtectState::$candidates, $postID); if (!empty(ProtectState::$requestCandidate) && ProtectState::$requestCandidate["candidateID"] != null) { ProtectState::$requestCookie = get_cookie_name(ProtectState::$requestCandidate["candidateID"]); } } } } catch (\Exception $e) { error_log("Error initializing protect hooks: " . $e->getMessage()); } } add_filter('wp_headers', function($headers) { try { if (is_single()) { initialize(); // we don't want to set cache-control unless we have Protect candidates if (!empty(ProtectState::$candidates)) { $headers['Cache-Control'] = 'private, must-revalidate, max-age=60'; } } } catch (\Exception $e) { error_log("Error loading wp_headers: " . $e->getMessage()); } return $headers; }); add_filter('wp_head', function() { try { initialize(); if (ProtectState::$didInitialize && is_singular() && !empty(ProtectState::$candidates) && is_main_query() && !is_user_logged_in() && !\wp\AdmiralTokenHandler::getVerifiedEFSToken(ProtectState::$requestCookie)) { define('DONOTCACHEPAGE', true); echo get_loading_style(); } } catch (\Exception $e) { error_log("Error loading wp_head: " . $e->getMessage()); } }); add_filter('the_content', function($content) { try { $useragent = array_key_exists('HTTP_USER_AGENT', $_SERVER) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : null; if (bot_check($useragent)) { return $content; } initialize(); $insideLoopAndIsArticle = in_the_loop() && is_single() && is_main_query(); $protectStateIsValid = ProtectState::$didInitialize && !empty(ProtectState::$candidates) && !empty(ProtectState::$requestCandidate); if ($protectStateIsValid && $insideLoopAndIsArticle && !is_user_logged_in() && !\wp\AdmiralTokenHandler::getVerifiedEFSToken(ProtectState::$requestCookie)) { $postId = get_the_ID(); // only allow the same post to be filtered multiple times if (ProtectState::$contentFilteredPostId !== null && ProtectState::$contentFilteredPostId !== $postId) { return $content; } ProtectState::$contentFilteredPostId = $postId; $embed = \wp\AdmiralAdBlockAnalytics::getEmbed(); if (empty($embed)) { return $content; } $bestMatch = ProtectState::$requestCandidate; if (empty($bestMatch["candidateID"])) { return $content; } // there is no easy way to count paragraphs in wordpress so just trim words for now // avg optimized-for-SEO paragraph is 40-55 words $maxWords = 65; $entitiesFlag = 55; // ENT_HTML5 | ENT_QUOTES | ENT_IGNORE; $excerpt = html_entity_decode(wp_trim_words(htmlentities($content, $entitiesFlag), $maxWords), $entitiesFlag); // if there is an unclosed element at the end, remove it and then balance the tags $excerpt = preg_replace('/<[^>]*$/', '', $excerpt); $excerpt = force_balance_tags($excerpt); $candidateIDs = [$bestMatch["candidateID"]]; $requirement = $bestMatch["payload"]["protect"]["requirement"]; $benefits = isset($bestMatch["payload"]["protect"]["benefits"]) ? $bestMatch["payload"]["protect"]["benefits"] : null; if (isset($bestMatch["transactIDs"])) { $candidateIDs = array_merge($candidateIDs, $bestMatch["transactIDs"]); } $permalink = get_permalink($postId); echo detection_check($candidateIDs, $requirement, $benefits, $postId, $permalink); return $excerpt . "\n" . get_loading_message(); } } catch (\Exception $e) { error_log("Error loading settings: " . $e->getMessage()); } return $content; }, 1);