<?
include_once 'includes/optimize.php';

function redirect_get_param() {
  if (!empty($_GET)) {
      $params = array_map('htmlspecialchars', $_GET);
      $check_params = [
        '*backlinksource*',
        'backlinksource',
        'continue',
        'via_site',
        'fullsiteonly',
        'redirect'
      ];

      foreach ($params as $key => $value) {
        if (in_array($key, $check_params)) {
          exit( wp_redirect( home_url( '/' ) ) );
        }
      }

  }
}
add_action( 'template_redirect', 'redirect_get_param' );

// Function to change email address
function wpb_sender_email( $original_email_address ) {
    return 'site@rush-analytics.ru';
}
 
// Function to change sender name
function wpb_sender_name( $original_email_from ) {
    return 'Rush Analytics';
}
 
// Hooking up our functions to WordPress filters 
add_filter( 'wp_mail_from', 'wpb_sender_email' );
add_filter( 'wp_mail_from_name', 'wpb_sender_name' );

/*
  Ref
*/

/*add_action( 'init', 'ra_set_ref' );
function ra_set_ref() {
  if (isset($_GET['ref'])) {
    $time = time();
    $ref = (int)$_GET['ref'];
    if ($ref > 0 && $user->uid == 0) {
        // user_cookie_save(['referralid' => $ref]);
        setcookie('anonreferralid', $ref);
    }
  }
}*/

/*
  Styles and Scripts
*/

function ra_scripts_styles()
{
  // css
  wp_enqueue_style( 'ra-styles', get_template_directory_uri() . '/assets/css/main.css', array(), '2.9' );
  wp_enqueue_style( 'style', get_stylesheet_uri());
  
  // js
  wp_enqueue_script('shared', get_template_directory_uri() . '/assets/js/shared.js', array(), '1.2', true);
  wp_enqueue_script('builder', get_template_directory_uri() . '/assets/js/scripts.js', array('shared'), '1.5', true);
  wp_enqueue_script('datalayer', get_template_directory_uri() . '/assets/js/datalayer.js', array('jquery'), '1.1', true);
  if ( is_singular('rating') ) {
    wp_enqueue_script('ra-rating', get_template_directory_uri() . '/assets/js/rating.js', array('shared'), '2.2', true);
  }

  wp_localize_script('builder', 'main', array(
    'url' => admin_url('admin-ajax.php')
  ));
}
//add_action( 'wp_enqueue_scripts', 'ra_scripts_styles' );

add_action( 'wp_ajax_get_engine_data', 'get_engine_data_callback' );
add_action( 'wp_ajax_nopriv_get_engine_data', 'get_engine_data_callback' );

function get_engine_data_callback() {
    $engine = isset($_POST['engine']) ? (string) $_POST['engine'] : '';
    $type = isset($_POST['type']) ? (string) $_POST['type'] : '';
    $search = isset($_POST['search']) ? (string) mb_strtolower($_POST['search']) : '';
    $page = isset($_POST['page']) ? (int) $_POST['page'] : 1;
    $regions = '';
    $langs = '';
    $region_city = $engine . '_city';
    $lang = $engine . '_lang';
    $response = [
      'results' => [],
      'pagination' => [
        'more' => false
      ]
    ];

    if (!empty($engine)) {
      
      switch ($type) {
        case 'region':
            $regions = get_option($region_city);

            if (!empty($regions)) {
              //$regions = json_decode($regions, ARRAY_A);
              if ($engine == 'google') {
                  $regions = include_once(get_template_directory() . '/includes/regions-google.php');
              } else {
                  $regions = include_once(get_template_directory() . '/includes/regions-yandex.php');
              }

              $new_regions = [];

//            echo json_encode($regions);
//            die();

              foreach ($regions as $region) {

                if ($engine == 'google') {
                  $text = trim($region['country'] . ' - ' . $region['name']);
                } else {
                  $text = trim($region['name']);
                }
    
                if (!empty($search)) {
                  if (mb_strpos(mb_strtolower($text), $search) !== false) {
                    $new_regions[] = [
                      'id' => $region['id'],
                      'text' => $text
                    ];
                  }
                } else {
                  $new_regions[] = [
                    'id' => $region['id'],
                    'text' => $text
                  ];
                }
              }
    
              $regions_count = count($new_regions);
              $chunk_size = 100;
              $new_regions = array_chunk($new_regions, $chunk_size);
              $page = $page - 1;
              $last_page = count($new_regions) - 1;
    
              if (isset($new_regions[$page]) && $page < $last_page) {
                $response['results'] = $new_regions[$page];
                $response['pagination']['more'] = true;
              } else {
                $response['results'] = $new_regions[$last_page];
              }

              $response = json_encode($response);
            }
            break;
          case 'lang':
            $langs = get_option($lang);
            if (!empty($langs)) {
              $langs = json_decode($langs, ARRAY_A);
              $new_langs = [];
    
              foreach ($langs as $lang) {
                $text = trim($lang['country']);
                if (!empty($search)) {
                  if (mb_strpos(mb_strtolower($text), $search) !== false) {
                    $new_langs[] = [
                      'id' => $lang['code'],
                      'text' => $text
                    ];
                  }
                } else {
                  $new_langs[] = [
                    'id' => $lang['code'],
                    'text' => $text
                  ];
                }
              }
    
              $langs_count = count($new_langs);

              $chunk_size = 100;
              $new_langs = array_chunk($new_langs, $chunk_size);
              $page = $page - 1;
              $last_page = count($new_langs) - 1;

              if (isset($new_langs[$page]) && $page < $last_page) {
                $response['results'] = $new_langs[$page];
                $response['pagination']['more'] = true;
              } else {
                $response['results'] = $new_langs[$last_page];
              }

              $response = json_encode($response);
            }

            break;
        }

    }

    echo $response;

    wp_die();
}

/*
  Custom styles for Gutenberg editor
*/

add_action( 'after_setup_theme', 'gutenberg_setup_theme' );
function gutenberg_setup_theme()
{
	add_theme_support( 'editor-styles' );
	add_editor_style( 'assets/css/editor-style.css' );
}

/*
  Add custom blocks
*/

require get_template_directory() . '/blocks-custom/blocks.php';
require get_template_directory() . '/blocks-acf/blocks.php';

/*
  Add custom functions
*/

require get_template_directory() . '/includes/breadcrumbs.php';
require get_template_directory() . '/includes/custom-walker-menu.php';
require get_template_directory() . '/includes/custom-posts-taxonomies.php';
require get_template_directory() . '/includes/ra-functions.php';
require get_template_directory() . '/includes/postviews.php';
// require get_template_directory() . '/includes/create-ratings.php';
require get_template_directory() . '/includes/ajax-search.php';
require get_template_directory() . '/includes/ajax-ratings.php';


/*
  Add Menu
*/

add_action( 'after_setup_theme', 'theme_register_nav_menu' );
function theme_register_nav_menu()
{
    register_nav_menu( 'main', __( 'Главное меню' ) );
    register_nav_menu( 'socials', __( 'Социальные сети' ) );
    register_nav_menu( 'links_footer_1', __( 'Меню в футере 1' ) );
    register_nav_menu( 'links_footer_2', __( 'Меню в футере 2' ) );
    register_nav_menu( 'links_footer_3', __( 'Меню в футере 3' ) );
}

/*
  Add Widget
*/

function register_casino_widgets() {
  register_sidebar( array(
    'name'          => __( 'Сайдбар' ),
    'description'   => __( 'Выводится на страницах статей блога' ),
    'id'            => 'sidebar',
    'before_widget' => '',
    'after_widget'  => '',
    'before_title'  => '',
    'after_title'   => '',
) );
}
add_action( 'widgets_init', 'register_casino_widgets' );

/*
  Add Option Pages
*/

if( function_exists('acf_add_options_page') ) {
	acf_add_options_page(array(
		'page_title' 	=> __('Общие настройки сайта'),
		'menu_title'	=> __('Rush Analytics'),
		'menu_slug' 	=> 'theme-general-settings',
		'capability'	=> 'edit_posts',
		'redirect'		=> false
	));
}

/*
  Filter and Support
*/

add_theme_support( 'post-thumbnails', array( 'post' ) );

add_filter('excerpt_more', function($more) {
	return '...';
});

add_filter('excerpt_length', function() {
	return 15;
});


/*
  Add Tariffs Options Fields
*/

if( function_exists('acf_add_local_field_group') )
{
  ra_set_tariffs_options_fields();
  ra_set_compare_options_fields();
}

if (file_exists(__DIR__ . '/301.csv')) {
    $file = fopen(__DIR__ . '/301.csv', 'r');
    $data = array();
    while (($buffer = fgets($file, 4096)) !== false) {
        $line = explode(';', $buffer);
        $data[trim($line[0])] = trim($line[1]);

    }
    fclose($file);
    $url = strtok($_SERVER["REQUEST_URI"], '?');

    if(array_key_exists($url, $data)) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: " . $data[$url]);
        exit();
    }

}



function d($data){

    echo "<pre>".print_r($data,true)."</pre>";

}

// pagination base set as 'paged' in parts/pagination.php
// disable redirect for ?paged pagination
function disable_paged_canonical_redirect($redirect_url, $requested_url){
  $page_num = (int)filter_input(INPUT_GET, 'paged');
  
  if ($page_num) {
    return false;
  }
  
  return $redirect_url;
}
add_filter('redirect_canonical','disable_paged_canonical_redirect', 10, 2);

// remove ?paged=1
function remove_pagination_link($link) {
  if(is_paged()){
    $cur_url = explode('paged=', $link);
    $paged = $cur_url[count($cur_url) - 1];

    if (intval($paged) === 1) {
      $link = str_replace('?paged=1', '', $link);
    }
  }

  return $link;
}

add_filter( 'paginate_links', 'remove_pagination_link');

// force 404 if paged value is non numeric
function rr_404_my_event() {
  global $post;

  $cur_url = $_SERVER['REQUEST_URI'];

  if (!is_admin()) {
    if (strpos($cur_url, 'paged') !== false) {
      $cur_url = explode('paged=', $cur_url);
      $paged = $cur_url[count($cur_url) - 1];
      if (!is_numeric($paged)) {
        global $wp_query;
        $wp_query->set_404();
        status_header( 404 );
        nocache_headers();
      } else if ($paged == 1) {
        $clean_url = get_site_url() . str_replace('?', '', $cur_url[0]);
        wp_redirect($clean_url, 301);
        exit;
      }
    }
  }
}
add_action( 'wp', 'rr_404_my_event', 1);

function get_domain($for_cookie = false, $www = false) {
  $urlparts = parse_url(home_url());
  $domain = $urlparts['host'];

  $str_to_replace = 'www.';
  
  if ($for_cookie) {
    $str_to_replace = 'www';
  }

  if ($www) {
    $domain = str_replace($str_to_replace, '', $domain);
  }

  return $domain;
}

function change_next_prev($link) {
  $cur_url = $_SERVER['REQUEST_URI'];

  // убираем rel=next rel=prev на странице поиска
  if (strpos($cur_url, '?s=') !== false) {
    $link = false;
  } else {
    // иначе меняем /page/ на ?paged 
    $link = str_replace('/page/', '/?paged=', $link);
    $link = str_replace('/" />', '" />', $link);
  }


  return $link;
}
add_filter( "rank_math/frontend/next_rel_link", 'change_next_prev');
add_filter( "rank_math/frontend/prev_rel_link", 'change_next_prev');

function set_title_desc_author_page($str) {
	global $paged;
  if (is_author()) {
    $author = get_user_by( 'slug', get_query_var( 'author_name' ) );
    
    if (!empty($author)) {
      $author_id = $author->ID;
      $fields = get_fields('user_'.$author_id);
      
      switch (current_filter()) {
        case 'rank_math/frontend/title':
          $template = get_field('author_title_tmpl', 'option') . ( ($paged > 1) ? ' - страница '.$paged : '');
		 
        break;

        case 'rank_math/frontend/description':
          $template = get_field('author_desc_tmpl', 'option') . ( ($paged > 1) ? ' - страница '.$paged : '');
        break;
      }

      if (!empty($fields) && !empty($template)) {
        foreach ($fields as $name => $value) {
          if (!is_array($value)) {
            $template = str_replace('%'.$name.'%', $value, $template);
          }
        }

        $template = str_replace('%sitename%', get_bloginfo('name'), $template);

        $str = $template;
      }

    }
	
	
	
	
  }

  return $str;
}
add_filter( 'rank_math/frontend/title', 'set_title_desc_author_page');
add_filter( 'rank_math/frontend/description', 'set_title_desc_author_page');

function set_blog_pagination_title($str) {
  global $paged;
  global $wp;
  $obj = get_queried_object();
  $cat_name = '';
  $page_str = '';
  if ( $paged > 1 && !is_author() )
  {	  
	  $page_str = ' - Страница ' . $paged;	
	  if ( strpos(home_url( $wp->request ), '/blog/') !== false ) {
		// $str = 'Блог - ' . $obj->
		if (isset($wp->query_vars)) {
		  if (isset($wp->query_vars['category_name'])) {
			$cat = get_term_by('slug', $wp->query_vars['category_name'], 'category');
			$cat_name = $cat->name;
		  }
		 // $str = 'Блог' . $cat_name . ' - ' . get_bloginfo('name') . ' - Страница ' . $paged;
		}
	  }
	  else
	  {
		  $cat_name = 'Блог Rush Analytics';
		  
	  }
	  
	  
	  $str = $cat_name . $page_str .' | Rush Analytics'; 
	  
  }
 	
  return $str;
}
add_filter( 'rank_math/frontend/title', 'set_blog_pagination_title');

function set_blog_pagination_desc($str) {
	global $paged;
	global $wp;
	$obj = get_queried_object();
	$cat_name = '';
	$page_str = '';	
	if ( $paged > 1 && !is_author() )
	{	 
		$page_str = ' - страница '. $paged;
		if (strpos(home_url( $wp->request ), '/blog/') !== false ) {
		if (isset($wp->query_vars)) {
		  if (isset($wp->query_vars['category_name'])) {
			$cat = get_term_by('slug', $wp->query_vars['category_name'], 'category');
			$cat_name = $cat->name;
		  }
		   
		}
		$str = 'Полезная и актуальная информация из мира интернет-маркетинга от ведущих специалистов Rush Analytics в рубрике '.$cat_name .  $page_str . '.'; 
	}
	else
		$str = 'Полезная и актуальная информация из мира интернет-маркетинга от ведущих специалистов Rush Analytics' .  $page_str . '.';	
	}
	return $str;
}
add_filter( 'rank_math/frontend/description', 'set_blog_pagination_desc');



add_filter('rank_math/frontend/canonical', function($canonical) {
     if (is_paged()) {
        global $wp;
        $canonical = home_url(add_query_arg([], $wp->request));

        // Добавим GET-параметры обратно в canonical
        if (!empty($_GET)) {
            $canonical .= '?' . http_build_query($_GET);
        }


    }
    
    return $canonical;
});

// скрываем поля websites_data и keywords_data в админке
// т.к. они тормозят загрузку страницы редактирования
// и обновляются автоматически, поэтому не будут правиться
// (относится к типу записей "Рейтинг")
function hide_acf_field($field) {
  return false;
}
add_filter("acf/prepare_field/name=websites_data", "hide_acf_field");
add_filter("acf/prepare_field/name=keywords_data", "hide_acf_field");

add_action(
  'after_setup_theme',
  function() {
      add_theme_support( 'html5', [ 'script', 'style' ] );
  }
);

add_filter( 'the_content', 'my_the_content_filter', 20 );
function my_the_content_filter( $content ) {
//  if (get_post_type() == 'land') {
//    $page_link = get_permalink();
//    $page_title = get_the_title();
//
//    $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'utf-8');
//
//    // echo '<pre>';
//    // print_r($content);
//    // echo '</pre>';
//    // die();
//
//    $doc = new DomDocument();
//    @$doc->loadHTML($content);
//
//    $selector = new \DOMXPath( $doc );
//
//    $class = 'hero-title';
//    foreach ( $selector->query( '//div[contains(attribute::class, "' . $class . '")]' ) as $e ) {
//      foreach ($e->childNodes as $child) {
//        if ($child->tagName == 'h1') {
//          $child->setAttribute('itemprop', 'name');
//        }
//      }
//    }
//
//    $class = 'page-hero-wrap';
//    foreach ( $selector->query( '//div[contains(attribute::class, "' . $class . '")]' ) as $e ) {
//      foreach ($e->childNodes as $child) {
//        if ($child->tagName == 'p') {
//          $classes = $child->getAttribute('class');
//
//          if (strpos($classes, 'hero-text') !== false) {
//            $child->setAttribute('itemprop', 'description');
//          }
//        }
//      }
//    }
//
//    $class = 'tariff-brief';
//    foreach ( $selector->query( '//div[@class="' . $class . '"][1]' ) as $e ) {
//      $e->setAttribute('itemscope', '');
//      $e->setAttribute('itemprop', 'offers');
//      $e->setAttribute('itemtype', 'http://schema.org/Offer');
//
//      foreach ($e->childNodes as $child) {
//        if (get_class($child) == 'DOMElement') {
//
//          $classes = $child->getAttribute('class');
//
//          if (strpos($classes, 'tariff-brief-price') !== false) {
//            foreach ($child->childNodes as $c_child) {
//
//              if ($c_child->tagName == 'b') {
//                $price = intval(trim($c_child->textContent));
//              }
//              // die();
//            }
//
//            if (!empty($price)) {
//              $meta = $doc->createElement('meta', '');
//              $meta->setAttribute('itemprop', 'price');
//              $meta->setAttribute('content', $price);
//
//              $e->appendChild($meta);
//
//              $meta = $doc->createElement('meta', '');
//              $meta->setAttribute('itemprop', 'priceCurrency');
//              $meta->setAttribute('content', 'RUB');
//
//              $e->appendChild($meta);
//
//              $link = $doc->createElement('link', '');
//              $link->setAttribute('itemprop', 'availability');
//              $link->setAttribute('href', 'http://schema.org/InStock');
//
//              $e->appendChild($link);
//
//              $ahref = $doc->createElement('meta', '');
//              $ahref->setAttribute('itemprop', 'url');
//              $ahref->setAttribute('content', $page_link);
//
//              $e->appendChild($ahref);
//
//            }
//          }
//        }
//        // die();
//        // echo '<pre>';
//        // print_r($child);
//        // echo '</pre>';
//        // die();
//        // if ($child->tagName == 'h1') {
//        //   $child->setAttribute('itemprop', 'name');
//        // }
//      }
//    }
//
//
//    $rating_set = false;
//    $class = 'case-rating';
//    foreach ( $selector->query( '//div[contains(attribute::class, "' . $class . '")]' ) as $e ) {
//      $e->setAttribute('itemprop', 'aggregateRating');
//      $e->setAttribute('itemtype', 'http://schema.org/AggregateRating');
//      $e->setAttribute('itemscope', '');
//
//      foreach ($e->childNodes as $child) {
//
//          if ($child->tagName == 'span') {
//            foreach ($child->childNodes as $c_child) {
//
//
//                if ($c_child->tagName == 'b') {
//                  $rating_val = str_replace(',','.', $c_child->nodeValue);
//                  $c_child->setAttribute('itemprop', 'ratingValue');
//                  $rating_set = true;
//                  break;
//                }
//
//
//
//              // if (strpos($classes, 'hero-text') !== false) {
//              //   $child->setAttribute('itemprop', 'description');
//              // }
//
//            }
//          }
//      }
//
//      break;
//    }
//
//    $content = $doc->saveHTML();
//  }

	return $content;
}<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="//www.rush-analytics.ru/main-sitemap.xsl"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<sitemap>
		<loc>https://www.rush-analytics.ru/post-sitemap1.xml</loc>
		<lastmod>2026-09-08T15:45:14+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/post-sitemap2.xml</loc>
		<lastmod>2026-09-08T15:41:44+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/post-sitemap3.xml</loc>
		<lastmod>2026-09-08T15:41:01+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/page-sitemap.xml</loc>
		<lastmod>2026-10-22T09:59:29+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/land-sitemap.xml</loc>
		<lastmod>2026-06-23T15:30:55+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/faq-sitemap.xml</loc>
		<lastmod>2026-10-08T12:47:41+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/vacancies-sitemap.xml</loc>
		<lastmod>2023-05-18T14:39:14+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/rating-sitemap.xml</loc>
		<lastmod>2025-05-19T12:36:13+02:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://www.rush-analytics.ru/category-sitemap.xml</loc>
		<lastmod>2026-09-08T15:45:14+02:00</lastmod>
	</sitemap>
</sitemapindex>
<!-- XML Sitemap generated by Rank Math SEO Plugin (c) Rank Math - rankmath.com -->