<?php
//ini_set('display_errors', 0);
//error_reporting(E_ALL);

header('Content-Type: text/html; charset=utf-8');

require get_theme_file_path('clear-functions.php');
require "dirty-functions.php";
require "garbage-functions.php";
require "block-cache-manager.php"; //кешируем долгоживущие блоки
require "inc/cache-cleaner-home.php";
require 'inc/article-rss-feed.php'; //rss ленты статей по датам
require "inc/meta_keywords.php";
require "inc/journal_issue.php"; //номера журналов
require "inc/rank-description.php";

//utils
require "utils/acf-category.php";

//scheduler
require "inc/schedule_async_post_processing.php"; 
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    require "inc/action-scheduler-functions.php"; 
    require "inc/wp-cli-scheduler-commands.php"; 
    require "inc/adfox_on.php";  // управление adfox
}    

include "inc/get_cached_alm.php";
include "inc/graphql.php";

if (is_admin()) {
    require "inc/add_adv_checked.php";  // рекламная статья
    require "inc/admin/auto_check.php";  // помечакм не отправлять в Дзен
    require "inc/admin/lock-terms.php";  // banned и keys
}   



//TODO: Убрать все эти is_yn, is_zen и прочее и внутри плагинов регулировать вывод
//TODO: Убрать все posts_where, переписать в pre_get_posts
//TODO: Убрать все cpt в плагин


// Настройки Redis
//define('WP_REDIS_HOST', '31.129.43.216');  // или IP сервера Redis
//define('WP_REDIS_PORT', 6379);
//define('WP_REDIS_PASSWORD', 'hjl89ukiAsdfkd');
//define('WP_REDIS_TIMEOUT', 1);
//define('WP_REDIS_READ_TIMEOUT', 1);

// Отключаем все автообновления
define( 'AUTOMATIC_UPDATER_DISABLED', true );

// Отключаем только обновления ядра
define( 'WP_AUTO_UPDATE_CORE', false );

//кеш блоков
define('CACHED_TEMPLATE', trailingslashit( wp_upload_dir()['basedir'] ) . 'cached_template/');

// Отключаем обновления плагинов и тем
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );




//debug

/**  
register_shutdown_function(function() {

    global $wpdb;
    
    $logs = [];
    $time = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];

    // Добавляем URL запроса
    $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") 
                 . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $logs[] = "URL: " . $current_url;


    $logs[] = "Время выполнения: " . round($time, 2) . " сек";

    $log_file = ABSPATH . 'wp-content/custom-debug.log';
    
    if (function_exists('get_num_queries')) {
        $logs[] = "SQL-запросов: " . get_num_queries();
    }

    // Добавляем 5 самых медленных запросов (если доступно)
    if (!empty($wpdb->queries)) {
        usort($wpdb->queries, function($a, $b) {
            return $b[1] - $a[1];
        });
        
        $slow_queries = array_slice($wpdb->queries, 0, 5);
        foreach ($slow_queries as $i => $query) {
            $logs[] = "Медленный запрос #" . ($i+1) . ": " . round($query[1], 4) . " сек | " . 
                     substr(str_replace(["\n", "\r"], ' ', $query[0]), 0, 200) . "...";
        }
    }
    

    $message = implode(" | ", $logs);
    file_put_contents($log_file, $message."\n\n", FILE_APPEND | LOCK_EX);

});
*/




add_action('before_rocket_clean_files', function ($urls) {
	

    foreach ($urls as $url) {
        if (str_contains($url, 'g.profile.ru') !== false) {
            return;
        }
    }

    $urls_for_clean = array_map(function ($url) {
        return str_replace('profile.ru', 'g.profile.ru', $url);
    }, $urls);


    \rocket_clean_files($urls_for_clean);

    return $urls;

}, 1, 999);




add_filter('rocket_clean_domain_urls', function ($urls, $lang) {

    $urls = [
        "https://profile.ru",
        "https://g.profile.ru"
    ];

    return $urls;

}, 2, 999);

add_action('before_rocket_clean_domain', function ($root, $lang, $url) {

    if (mb_stripos($url, 'g.profile.ru') !== false) {
        return;
    }

    rocket_clean_files(['https://g.profile.ru/']);
    return;
}, 3, 999);

add_filter('rocket_post_purge_urls', function ($purge_urls, $post) {

    $newurls = [];

    foreach ($purge_urls as $purge_url) {
        $newurls[] = str_replace('admin.profile.ru', 'profile.ru', $purge_url);
        $newurls[] = str_replace('admin.profile.ru', 'g.profile.ru', $purge_url);
    }

    //$newurls[] = 'https://g.profile.ru/';

    return $newurls;

}, 2, 999);

add_action('before_rocket_clean_home', function($root, $lang){

    $root = str_replace('/profile.ru*', '/g.profile.ru', $root);

    $files = glob( $root . '/*', GLOB_NOSORT );

    if ( $files ) {
        foreach ( $files as $file ) {
            if ( preg_match( '#/index(?:-.+\.|\.)html(?:_gzip)?$#', $file ) ) {
                \rocket_direct_filesystem()->delete( $file );
            }
        }
    }
},2,999);

/**********************************************************************************************************************/






















$ver = '2.6.12';

$test_page_id = 216301;


$colors = array (
    "blue" => "Голубой",
    "indigo" => "Индиго",
    "purple" => "Пурпурный",
    "pink" => "Розовый",
    "red" => "Красный",
    "orange" => "Оранжевый",
    "yellow" => "Желтый",
    "green" => "Зеленый",
    "teal" => "Биюзовый",
    "cyan" => "Циан",
    "white" => "Белый",
    "gray" => "Серый",
    "gray-dark" => "Темно-серый",
    "light" => "Магнолия",
    "dark" => "Космос"
);
$termTaxTypes = array (
    "category" => "Рубрика",
    "story" => "Сюжет",
    "branding" => "Спецпроект"
);


//проверка на рсску для Я.Н.
function is_yn(){
    if(mb_strripos(filter_input(INPUT_SERVER,'REQUEST_URI'),get_option('layf_custom_url')) !== false){
        return true;
    }
    return false;
}

//проверка на рсску для Я.Д.
function is_zen(){
    if(mb_strripos(filter_input(INPUT_SERVER,'REQUEST_URI') ,get_option('yzrssname')) !== false && get_option('yzrssname') !== false){
        return true;
    }
    return false;
}



/**
 * Это говно убрать в следующих итерациях
 */

/** 
add_filter('posts_orderby', function($order){
    if((is_post_type_archive() || is_front_page()) && !is_admin() && !is_events()){
        $order = "
                CASE
                    WHEN ( pm123.meta_value = 1 ) THEN
                    1 ELSE 0 
                END DESC, 
                wp_posts.post_date DESC
        ";
    }
    return $order;
});
add_filter('posts_join', function($order){
    if((is_post_type_archive() || is_front_page()) && !is_admin() && !is_events()){
        $order .= "
                left join wp_postmeta pm123 on pm123.post_id = wp_posts.ID and pm123.meta_key = '_breaking'
        ";
    }
    return $order;
});

*/


//добавляем нестандартные типы материалов (новости, статьи)
function add_article_in_main_query( $query ) {
    global $wp;
    if(is_yn()){
        $query->set('tag__not_in', array(7840));
    }
    $query->set('ep_integrate', false);//включили ep
    //var_dump( get_option('layf_custom_url'));
    if (is_admin()){
        if (get_query_var('author_name')){
            $query->set('post_type', array('profile_article','anew','yellow'));
            //echo '<!--'.$query->request.'-->';
        }else if (filter_input(INPUT_GET,'page') == 'wps_authors_page'){
            $query->set('post_type', array('profile_article','anew','yellow'));
            $query->set('posts_per_page', -1);
        }else if (filter_input(INPUT_GET, 'id') == 'tag_request' && filter_input(INPUT_GET, 'post_id') == 103454){
            $query->set('post_type', array('profile_article','anew', 'yellow'));
        }
        if(user_has_role(get_current_user_id(), 'intern')){
            //$query->set('author__in', array(get_current_user_id()));
        }
        return $query;
    }
    else if ($query->is_post_type_archive() && !is_admin()){

        $queried_object = get_queried_object();
        if ($queried_object->name == 'archive'){
            wp_redirect("/?s=");
        }
        $queried_object = ($queried_object->name == 'yellow') ? array($queried_object->name, "anew") : $queried_object->name;
        $query->set('post_type', $queried_object);

    } else {
        if ($query->is_feed()){
            //фиды
            $query->set('post_type', array('profile_article','anew','yellow'));
        }else if(
            ($query->is_main_query() && is_tag() && get_queried_object()->term_id == 103454)
            ||
            (filter_input(INPUT_GET, 'id') == 'tag_request' && filter_input(INPUT_GET, 'post_id') == 103454)
        ){
            $query->set('post_type', array('profile_article', 'anew', 'yellow'));
        }else if ($query->is_main_query() && !is_admin() && is_author()){
            //страница автора
            //$query->set('post_type', array('profile_article'));
            global $coauthors_plus;

            $guest_author_id = $coauthors_plus->get_coauthor_by('user_login', get_query_var( 'author_name' ))->ID;

            $only_articles = get_post_meta($guest_author_id, 'show_only_articles', true);

            if($only_articles){
                $query->set('post_type', array('profile_article'));
            }else{
                $query->set('post_type', array('profile_article','anew','yellow'));
            }
        }else if ($query->is_main_query() && !is_admin() &&  (is_category() || is_search() || is_archive())){
            //страницы рубрик, поиска, архива
            if(is_search() && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) < 5 && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) != 0){
                wp_redirect('/?s=');
            }else if (is_search() && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) == 0){
                //return false;die;
            }
            $query->set('post_type', array('profile_article','anew','yellow'));
            if(get_queried_object_id() == 104418){
                $query->set('posts_per_page', 100);
            }
        }else if ($query->is_main_query() && !is_admin() &&  is_single()){
            //страница материала
            $query->set('post_type', array('profile_article','anew','archive','yellow'));
        }else if ($query->is_main_query() && is_post_type_archive()){
            //страница архива типа материала
            $query->set('post_type', get_query_var('post_type'));
        }else if ($query->is_main_query() && !is_home() && !is_single() && !is_page() && strripos(home_url( $wp->request ).'/', get_option('layf_custom_url')) !== false){
            //фид я.новости
            $query->set('post_type', array('profile_article','anew','archive','yellow'));
        }else if ($query->is_main_query() && !is_home() && !is_single() && !is_page()) {
            //админка
            $query->set('post_type', array('profile_article', 'anew'));
        }else if ($query->is_main_query() && !is_admin()){
            //все остальное
            $query->set('post_type', array('profile_article','page','anew'));
        }
    }

    if(is_tag() && !is_admin()){
        $query->set('posts_per_page', 20);
    }

    return $query;
}
add_action( 'pre_get_posts', 'add_article_in_main_query' );






//обрабатываем вставку картинок в тело статьи
add_filter( 'image_send_to_editor', 'custom_image_send_to_editor', 10, 8 );
function custom_image_send_to_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ){
    $auth = htmlspecialchars($caption);

    $html = str_replace('<img', '<img data-auth="'.$auth.'"', $html);
    //$html = str_replace('<a', '<a class="js-simple-lightbox"', $html);
    return $html;
}
add_filter( 'image_add_caption_text', 'custom_image_add_caption_text', 10, 2 );
function custom_image_add_caption_text( $caption, $id ){
    $desc = str_replace("\n","",strip_tags(apply_filters('the_content', get_post_field('post_content', $id))));
    return $desc;
}





//изменение вывода гарелеи
function profile_gallery_shortcode( $output = '', $atts = null, $instance = null ) {
    if (get_post_format() == 'gallery'){
        $return = '';
        foreach(explode(',', $atts['ids']) as $id){
            $attachment = wp_get_attachment($id);
            $dataphoto = (strlen($attachment['caption']) == 0 ) ? '' : 'Фото: '.str_replace('Фото:','',$attachment['caption']);
            $return .= '<div data-content="'.$attachment['description'].'" data-photo="'.$dataphoto.'">';
            $return .= '<img loading="lazy" src="'.wp_get_attachment_image_url($id,'full').'" />';
            $return .= '</div>';
        }
        return $return;
    }else{
        return $output;
    }
}
add_filter( 'post_gallery', 'profile_gallery_shortcode', 10, 3 );

//собираем все свойства файла
function wp_get_attachment( $attachment_id ) {
    $attachment = get_post( $attachment_id );
    return array(
        'alt' => htmlspecialchars(get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true )),
        'caption' => htmlspecialchars($attachment->post_excerpt),
        'description' => htmlspecialchars($attachment->post_content),
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => htmlspecialchars($attachment->post_title)
    );
}

//добавление копирайта к свойствам объекта изображения
add_filter( 'wp_get_attachment_image_attributes', 'profile_get_attachment_image_attributes', 10, 3 );
function profile_get_attachment_image_attributes( $attr, $attachment, $size ) {
    if (!is_object($attr)) return $attr;
    $attr->copyright = wp_get_attachment_caption($attachment->ID);
    return $attr;
}
//копирайт для галереи
function get_post_gallery_copyright($postID) {
    $gallery = get_post_gallery(get_post($postID), false);
    $attachment = wp_get_attachment(array_shift(explode(',',$gallery['ids'])));
    if (strlen($attachment['caption']) == 0){return;}
    return 'Фото: '.str_replace('Фото:','',$attachment['caption']);
}
//вывод описания для первого снимка галереи
function get_post_gallery_description($postID) {
    $gallery = get_post_gallery(get_post($postID), false);
    $attachment = wp_get_attachment(array_shift(explode(',',$gallery['ids'])));
    return $attachment['description'];
}


//основная категория поста
function get_post_primary_category($post_id, $term='category', $return_all_categories=false){
    $return = array();
    if (class_exists('WPSEO_Primary_Term')){
        $wpseo_primary_term = new WPSEO_Primary_Term( $term, $post_id );
        $primary_term = get_term($wpseo_primary_term->get_primary_term());
        if (!is_wp_error($primary_term)){
            $return['primary_category'] = $primary_term;
        }
    }
    if (empty($return['primary_category']) || $return_all_categories){
        $categories_list = get_the_terms($post_id, $term);
        if (empty($return['primary_category']) && !empty($categories_list)){
            $return['primary_category'] = $categories_list[0];  //get the first category
        }
        if ($return_all_categories){
            $return['all_categories'] = array();
            if (!empty($categories_list)){
                foreach($categories_list as &$category){
                    $return['all_categories'][] = $category->term_id;
                }
            }
        }
    }
    return $return;
}

function get_post_primary_category_id($post_id){

    $term = get_post_primary_category($post_id);
    $term = $term['primary_category'];

    return $term->term_id;

}

function is_branding_page(){
    if (!is_object(get_queried_object())){
        return false;
    }
    $out = get_term_meta(get_queried_object()->term_id,'type',1);
    return $out;
}
//парсинг класса тела сайта


//правильные урлы
function remove_cpt_slug( $post_link, $post, $leavename ) {
    if ( 'profile_article' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }
    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    $post_link = str_replace( '/articles/', '/', $post_link );
    return $post_link;
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
function change_slug_struct( $query ) {
    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }
    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'profile_article', 'page' ) );
    } elseif ( ! empty( $query->query['category_name'] ) && false === strpos( $query->query['category_name'], '/' ) ) {
        $query->set( 'post_type', array( 'post', 'profile_article', 'page' ) );
        $query->set( 'name', $query->query['category_name'] );
    }
}
add_action( 'pre_get_posts', 'change_slug_struct' );

//проверка наличия тега more
function maybe_has_more_link( $post_id ) {
    $post = get_post( $post_id );
    $content = $post->post_content;
    $data_array = get_extended( $content );
    return '' !== $data_array['extended'];
}
//получаем первый абзац
function get_first_paragraph(){
    global $post;
    $str = '';
    $i = 0;
    $content = wpautop( get_the_content() );

    //debug('-'.$content);

    if(mb_strpos( $content, '</p>') === false){
        return $content;
    }

    while($str == ''){
        $i++;
        $str = mb_substr( $content, 0, mb_strpos( $content, '</p>', $i*7 ) + 4 );
        $str = strip_shortcodes(strip_tags($str));
    }




    return $str;
}
//не пробелом единым
function strposa($haystack, $needles=array(), $offset=0) {
    $chr = array();
    foreach($needles as $needle) {
        $res = mb_stripos($haystack, $needle, $offset);
        if ($res !== false) $chr[$needle] = $res;
    }
    if(empty($chr)) return false;
    return min($chr);
}
//генерим анонс со всеми условиями
function the_announce(){
    global $post;
    global $more;
    $more = 1;
    $len = 200;//количество символов
    $end = '...';
    $more = maybe_has_more_link($post->ID);
    $content = get_post_field( 'post_content', $post->ID);
    $content_parts = get_extended( $content );
    if ($more && mb_strlen(strip_tags($content_parts['main'])) < $len){
        if (mb_strlen(strip_tags($content_parts['main'])) > 50){
            echo strip_tags($content_parts['main']).$end;
        }else{
            $p = get_first_paragraph();
            if (mb_strlen($p) < $len){
                echo $p.$end;
            }else{
                $length = strposa($p, array(" ",".",",",";","'","\""),$len);
                echo mb_substr($p, 0, ((int)$length+(int)$len)).$end;
            }
        }
    }else{
        $p = get_first_paragraph();
        if (mb_strlen($p) < $len){
            echo $p.$end;
        }else{
            $length = strposa($p, array(" ",".",",",";","'","\""),$len);
            echo mb_substr($p, 0, ((int)$length+(int)$len)).$end;
        }
    }
}
//убираем лишнее из РСС
function full_text_formatting_rss($content){

    $content = htmlspecialchars(html_entity_decode($content));

    return $content;
}
function test_full_text_formatting_rss($content){
    $content = htmlspecialchars_decode(html_entity_decode($content));
    return $content;
}
add_filter('layf_content_feed', 'full_text_formatting_rss', 20);
add_filter( 'layf_turbo_content_feed', 'full_text_formatting_rss', 20);
apply_filters( 'bloginfo_rss', 'full_text_formatting_rss', 20 );
add_filter('get_the_excerpt', 'full_text_formatting_rss', 20);
add_filter('the_excerpt_rss', 'full_text_formatting_rss', 20);
add_filter( 'layf_turbo_content_feed', 'test_full_text_formatting_rss', 30 );





add_filter("the_content", function($content){
    return str_replace(
            [
                "123.profile.ru",
                "profile.ru:1234",
                "profile.ru:5678"
            ],
        "profile.ru",
        $content
    );
}, 999);



/**
 * Исправляет битые ссылки с одним слэшем после https:/ и добавляет домен.
 *
 * @param string $url   Битая ссылка.
 * @param string $domain Домен (без слэша в конце, например "example.com").
 * @return string Исправленная ссылка.
 */
function fix_broken_url($url, $domain) {
    // Удаляем лишние пробелы
    $url = trim($url);

    // Если ссылка начинается с https:/ и нет второго слэша — исправляем
    if (preg_match('#^https:/([^/].*)#i', $url, $matches)) {
        // Добавляем правильный https:// и домен
        return 'https://' . $domain . '/' . ltrim($matches[1], '/');
    }

    // Если ссылка уже правильная, возвращаем как есть
    return $url;
}





// гутенберг бодрым шагом идет нахер
add_filter('use_block_editor_for_post', '__return_false', 10);



function debug($content){
    
    if(!is_string($content)){
        ob_start();
        var_dump($content);
        $content = ob_get_clean();
    }

    $request = "https://api.telegram.org/bot1184440628:AAE5N10dnzClx3Qce4v1mBD9ax1BsHo98Rs/sendMessage?chat_id=202319661&parse_mode=HTML&text=".urlencode($content);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    curl_setopt($ch, CURLOPT_URL, $request);
    $return = curl_exec($ch);

    return true;


}

add_filter('the_content', function ($content) {

    $allow = [
        "ТАСС",
        "TASS",
        "Профиль",
        "Shutterstock"
    ];



    $preview = wp_is_mobile() ? get_template_directory_uri() . '/assets/img/Profile_lazyload_m.webp' : get_template_directory_uri() . '/assets/img/Profile_lazyload.jpg';
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
        $capt = "";

        $child = $image;
        $wrapper = $image->parentNode;
        if ($wrapper->tagName == 'p') {

            $id = (int)preg_replace('~\D+~','', $image->getAttribute('class'));
            $attachment = get_post($id);

            $figure = $dom->createElement('figure');
            $figure->setAttribute('class', $image->getAttribute('class'));
            if(file_exists($image->getAttribute('src'))){
                $mw = ((int)$image->getAttribute('width')) ? ((int)$image->getAttribute('width')) : (getimagesize($image->getAttribute('src')))[0];
                $figure->setAttribute('style','max-width:'.$mw."px");
            }

            if (!is_feed() && !is_amp_endpoint()) {
                $image->setAttribute('class', 'lazyload');
                $image->removeAttribute('sizes');
                $image->removeAttribute('srcset');
            }

            if(get_queried_object_id() == 1089324 && wp_is_mobile()){
                $image->setAttribute('data-src', $image->getAttribute('src'));
                $image->setAttribute('src', get_template_directory_uri() . '/assets/img/Profile_lazyload_m.webp');
                $image->setAttribute('width', (int)$image->getAttribute('width') . 'px');
                $image->setAttribute('height', (int)$image->getAttribute('height') . 'px');
            }



            $figcaption = $dom->createElement('figcaption');
            $auth = $dom->createElement('span');
            if (strlen($image->getAttribute('data-auth')) !== 0 ) {
                $capt = $image->getAttribute('data-auth');
            }else if(strlen($attachment->post_excerpt) !== 0  && $attachment->post_type == 'attachment' && !strposa($attachment->post_excerpt, ['instag', 'faceb', 'инстаг'])){
                $capt = $attachment->post_excerpt;
            }
            if (mb_strlen($capt) === 0 && mb_strlen($image->getAttribute('alt')) !== 0 ){
                $capt = $image->getAttribute('alt');
            }

            $flag = true;

            if ( in_array( get_post_type(), ['anew', 'yellow'] ) && get_the_date("U") < 1719187200 ) {

                $flag = false;

                foreach ($allow as $c) {

                    if(str_contains($capt, $c)) {

                        $flag = true;

                    }

                }

            }

            if ($flag === false) {

                $figure = $dom->createElement('div');

            }

            $image->parentNode->replaceChild($figure, $image);

            if ($flag === false) {

                continue;

            }

            $figure->appendChild($child);



            $auth->nodeValue = "©".$capt;
            $figcaption->appendChild($auth);
            if(strlen($attachment->post_content) !== 0 && $attachment->post_type == 'attachment'){
                $desc = $dom->createElement('p');
                $desc->nodeValue = $attachment->post_content;
                $figcaption->appendChild($desc);
            }
            $figure->appendChild($figcaption);

        }
    }

    $html = str_replace(['<body>', '</body>'], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
    $html = preg_replace_callback(
        '|<figcaption><span>(.*)</span></figcaption>|Uis',
        function($matches){
            return str_ireplace('depositphotos.com', '<a href="https://depositphotos.com/" target="_blank">depositphotos.com</a>', $matches[0]);
        },
        $html
    );

    libxml_use_internal_errors(false);

    //$html .= '<!------000000------->';

    return $html;
}, 999, 1);
//выебоны с галереей!


function real_img_caption_shortcode( $attr, $content = null ) {//автор и название картинки
    if ( ! isset( $attr['caption'] ) ) {
        if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
            $content = $matches[1];
            $attr['caption'] = trim( $matches[2] );
        }
    } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
        $attr['caption'] = wp_kses( $attr['caption'], 'post' );
    }
    $atts = shortcode_atts( array(
        'id'	  => '',
        'align'	  => 'alignnone',
        'width'	  => '',
        'caption' => '',
        'class'   => '',
    ), $attr, 'caption' );

    $auth = preg_replace("/\".*/","",preg_replace("/.*data-auth=\"/","",$content));

    if(strposa($auth, ['instag', 'faceb', 'инстаг']) > 0) {
        $auth = '';
    }
    $html = '<figure style="max-width:'.$atts['width'].'px" id="' . $atts['id'] .'" class="'.$atts['align'].'">'
        . do_shortcode( $content )
        . '<figcaption><p>' . $atts['caption'] . ' </p>'
        . '<span>' . $auth . '</span></figcaption></figure>';
    return $html;
}

add_shortcode('wp_caption', 'real_img_caption_shortcode');
add_shortcode('caption', 'real_img_caption_shortcode');



//загрузка кастомных стилей
function customStyles(){
    if (is_branding()){
        $file = 'branding-styles';
        if (file_exists(__DIR__.'/'.$file.'.php')){
            get_template_part( $file );
        }
    }
    return true;
}



//это чтобы достать аватарку автора
function coauthors_get_avatar_url( $coauthor, $size = 32, $default = '', $alt = false ) {
    global $coauthors_plus;

    if ( ! is_object( $coauthor ) ) {
        return '';
    }
    if ( isset( $coauthor->type ) && 'guest-author' == $coauthor->type ) {
        $guest_author_thumbnail = $coauthors_plus->guest_authors->get_guest_author_thumbnail( $coauthor, $size );

        if ( $guest_author_thumbnail ) {
            preg_match( '@src="([^"]+)"@' , $guest_author_thumbnail, $match );
            $src = array_pop($match);
            return $src;
        }
    }
    if ( isset( $coauthor->user_email ) ) {
        preg_match( '@src="([^"]+)"@' , get_avatar( $coauthor->user_email, $size, $default, $alt ), $match );
        $src = array_pop($match);
        return $src;
    }
    return '';
}

//Убираем тирешечки
add_action('wp_insert_post_data', 'dashes_replace', 10, 2);
function dashes_replace($data, $postarr){

    $data['post_content'] = str_replace(array(' - ', ' — '), ' – ', $data['post_content'] );
    $data['post_content'] = str_replace(array('—'), '–', $data['post_content'] );

    return $data;
}

//убрал эти стремные яблочные дефисы
add_filter( 'wp_insert_post_data' , 'replace_MACOS_symbols' , 10, 1 );
function replace_MACOS_symbols( $data ) {
    $symbols = array(
        "\u001e" => ""
    );
    $data['post_content'] = json_decode(strtr(json_encode($data['post_content']),$symbols));
    return $data;
}


// хук для регистрации



add_action( 'init', 'create_taxonomy' );
function create_taxonomy(){
    register_taxonomy('archive_category', array('archive'), array(
        'label'                 => '', // определяется параметром $labels->name
        'labels'                => array(
            'name'              => 'Рубрики архива архива',
            'singular_name'     => 'Рубрика архива',
            'search_items'      => 'Поиск по рубрикам архива',
            'all_items'         => 'Все рубрики архива',
            'view_item '        => 'Посмотреть рубрику архива',
            'parent_item'       => 'родительская рубрика архива',
            'parent_item_colon' => 'родительская рубрика архива:',
            'edit_item'         => 'Редактировать рубрику архива',
            'update_item'       => 'Обновить рубрику архива',
            'add_new_item'      => 'Добавить рубрику архива',
            'new_item_name'     => 'Имя новой рубрики архива',
            'menu_name'         => 'Рубрики архива',
        ),
        'description'           => '', // описание таксономии
        'public'                => true,
        'publicly_queryable'    => null, // равен аргументу public
        'show_in_nav_menus'     => true, // равен аргументу public
        'show_ui'               => true, // равен аргументу public
        'show_in_menu'          => true, // равен аргументу show_ui
        'show_tagcloud'         => true, // равен аргументу show_ui
        'show_in_rest'          => null, // добавить в REST API
        'rest_base'             => null, // $taxonomy
        'hierarchical'          => false,
        //'update_count_callback' => '_update_post_term_count',
        'rewrite'               => true,
        //'query_var'             => $taxonomy, // название параметра запроса
        'capabilities'          => array(),
        'meta_box_cb'           => null, // callback функция. Отвечает за html код метабокса (с версии 3.8): post_categories_meta_box или post_tags_meta_box. Если указать false, то метабокс будет отключен вообще
        'show_admin_column'     => false, // Позволить или нет авто-создание колонки таксономии в таблице ассоциированного типа записи. (с версии 3.5)
        '_builtin'              => false,
        'show_in_quick_edit'    => null, // по умолчанию значение show_ui
    ) );
}

add_action( 'init', 'archive_register_post_type_init' );
function archive_register_post_type_init() {
    $labels = array(
        'name' => 'Архив',
        'singular_name' => 'Архивная запись',
        'add_new' => 'Добавить в архив',
        'add_new_item' => 'Добавить в архив',
        'edit_item' => 'Редактировать запись',
        'new_item' => 'Архивная запись',
        'all_items' => 'Все записи архива',
        'view_item' => 'Просмотр архива на сайте',
        'search_items' => 'Искать в архиве',
        'not_found' =>  'В архиве не найдено.',
        'not_found_in_trash' => 'В корзине нет архивных записей.',
        'menu_name' => 'Архив'
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'show_ui' => true,
        'has_archive' => true,
        'supports' => array( 'title', 'subtitle', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
        'taxonomies' => array('post_tag','category'),
        'rewrite' => array('slug' => 'archive','with_front' => true),
        'can_export' => true,
        'show_in_menu' => false,
        'menu_position' => 5,
        'show_in_nav_menus' => false,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'query_var' => true,
        'capability_type' => 'post',
        'rest_base' => 'posts'

    );
    register_post_type('archive', $args);
}




//это чтобы было удобнее писать описание к фоточкам
add_action('admin_head', 'gallery_custom_css');
function gallery_custom_css(){
    echo '
<style>
@media (min-width: 1200px){
    div.media-sidebar {
        /*width:767px!important;*/
    }
    .media-modal-content .media-frame .media-frame-content .attachments-browser .media-toolbar,
    .media-modal-content .media-frame .media-frame-content .attachments-browser .attachments.ui-sortable {
        right:800px!important;
    }
    .attachment-details .setting .value, .attachment-details .setting input[type=email], .attachment-details .setting input[type=number], .attachment-details .setting input[type=password], .attachment-details .setting input[type=search], .attachment-details .setting input[type=tel], .attachment-details .setting input[type=text], .attachment-details .setting input[type=url], .attachment-details .setting textarea, .media-sidebar .setting .value, .media-sidebar .setting input[type=email], .media-sidebar .setting input[type=number], .media-sidebar .setting input[type=password], .media-sidebar .setting input[type=search], .media-sidebar .setting input[type=tel], .media-sidebar .setting input[type=text], .media-sidebar .setting input[type=url], .media-sidebar .setting textarea {
        width:85%!important;
    }
    .attachment-details .setting span, .media-sidebar .setting span {
    min-width:10%!important;
    }
}
</style>';
}



//сохраняем количество символов в посте
function add_post_charcount( $post_id ) {
    $content = get_post_field( 'post_content', $post_id ); // Get the content
    $charcount = strlen( strip_tags( $content ) ); // Count the words
    if ( ! add_post_meta( $post_id, '_post_content_length', $charcount, true ) ) {
        update_post_meta( $post_id, '_post_content_length', $charcount );
    }
}
add_action( 'save_post', 'add_post_charcount' );
add_action( 'post_updated', 'add_post_charcount' );
//счетчик символов

add_filter('mce_external_plugins', 'my_tinymce_plugins');
function my_tinymce_plugins($plugins_array) {
    $plugins_array = array(
        //'charactercount' => get_template_directory_uri()."/assets/js/admin/tinymce.plugin.charcount.js"
        'charactercount' => get_template_directory_uri() . "/assets/js/admin/tinymce.plugin.charcount.js"
    );
    return $plugins_array;
}

function admin_script() {
    wp_enqueue_script('thickbox');
    wp_enqueue_style('thickbox');
}
add_action( 'admin_enqueue_scripts', 'admin_script' );


//оформление счетчика символов!
function admin_style() {
    if(is_user_logged_in()){
        wp_enqueue_style('admin-styles', get_template_directory_uri().'/assets/css/admin/app.css');
    }
}
add_action('admin_enqueue_scripts', 'admin_style');
add_action('wp_enqueue_scripts', 'admin_style');


//дополнительные стили и скрипты 
add_action('wp_enqueue_scripts', function() {
    
    wp_enqueue_script( //добавляем корректор времени
        'moscow-date',
        get_template_directory_uri() . '/assets/js/moscow-date.js',
        array(), // зависимости
        filemtime(get_template_directory() . '/assets/js/moscow-date.js'), // версия
        true // в футере
    );

    // Добавляем стиль

    $css_url = get_template_directory_uri() . '/assets/css/profile-style.css';
    //$css_url = 'https://profile.ru//wp-content/themes/profile/assets/css/profile-style.css';

    wp_enqueue_style(
        'profile-style', // уникальный идентификатор
        $css_url, // путь к файлу
        array(), // зависимости
        filemtime(get_template_directory() . '/assets/css/profile-style.css') // версия
    );


});



add_action('admin_footer', 'my_admin_footer');
function my_admin_footer() {
    get_template_part('admin', 'footer');
}

add_action('admin_head', 'my_admin_header');
function my_admin_header() {
    get_template_part('admin', 'header');
}

add_action( 'init', 'hide_revisions' );
function hide_revisions(){
    if(filter_input(INPUT_GET,'revision',FILTER_VALIDATE_INT) != 0 && !current_user_can('administrator') && !current_user_can('corrector') && !current_user_can('chief_editor')){
        wp_die('Страница не существует. Проверьте URL адрес страницы или обратитесь к администратору.');
    }
}
add_action('admin_footer', 'hide_revisions_style');
function hide_revisions_style() {
    if (!current_user_can('administrator') && !current_user_can('corrector') && !current_user_can('chief_editor')){
        echo '<style>.misc-pub-section.misc-pub-revisions,#last-edit{display:none !important;}</style>';
    }
}





add_action('admin_footer', 'check_content_layout');
function check_content_layout() {
    
    //if(get_current_user_id() == 1 or ){return;}

    $user = wp_get_current_user();
    if (in_array('administrator', $user->roles)) {
        return;
    }

    //if (get_current_user_id() == 53) {
        //echo '<script>console.log("т-c-c-c;")</script>';
        //return;
    //}
    echo <<<EOL
<script>
    document.forms.post.onsubmit = function(e) {
        var content;
        if(tinymce.activeEditor == null){
            content = document.forms.post.elements.content.value;
        }else{
            content = (tinymce.activeEditor.getContent() !== '') ? tinymce.activeEditor.getContent() : document.forms.post.elements.content.value;            
        }
        if(findTags('span:not(.mce_SELRES_start):not(.mce-preview-object):not(.mce-object-iframe):not(.mce-shim):not(.anchor)',content) !== 0 
        || findTags('div:not(.mce-offscreen-selection):not(.mce-content-body):not(.mce-toolbar-grp):not(.mce-statusbar):not(.mce-preview-object):not(.mce-reset):not(.mce-temp)', content) !== 0
        || !checkUnslosedTags(content)){
            console.log('Есть спаны или незакрытые теги');
            alert('В тексте обнаружены недопустимые HTML-теги, несовместимые с форматированием текстов «Профиля». Откройте редактор в режиме «Код» и уберите все ненужные <span>, <div> и др., прежде чем сохранить');
            return false;
        }else{
            console.log('Все ок');
        }
    }
    function findTags(selector,input) {
        var htmlObject = document.createElement('div');
        htmlObject.innerHTML = input;
        
        var elems = htmlObject.querySelectorAll(selector);
        console.log(htmlObject);
        console.log(elems.length+' - Результат поиска спанов');
        if (elems.length !== 0){
            console.log(elems);
        }
        return elems.length;
        
    }
    function isSelfClosingTag(tagName) {
        return tagName.match(/area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr|script/i);
    }
    function checkUnslosedTags(input){
        var tags = [];
        jQuery.each(input.split('\\n'), function (i, line) {
            jQuery.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
                var matches = tag.match(/<\/?([a-z0-9]+)/i);
                if (matches) {
                    tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
                }
            });
        });
        
        if (tags.length == 0) {
            console.log("Текст чист, неплохо!)");
            return true;
        }
        
        var openTags = [];
        var error = false;
        var indent = 0;
        for (var i = 0; i < tags.length; i++) {
            var tag = tags[i];
            if (tag.closing) {
                var closingTag = tag;
                if (isSelfClosingTag(closingTag.name)) {
                    continue;
                }
                if (openTags.length == 0) {
                    console.log("Незакрытых тегов нет! Отлично!");
                    return true;
                }
                var openTag = openTags[openTags.length - 1];
                if (closingTag.name != openTag.name) {
                    console.log('Закрывающий тег ' + closingTag.tag + ' в строке ' + closingTag.line + ' не соответствует открывающему ' + openTag.tag + ' в строке ' + openTag.line + '.');
                    return false;
                } else {
                    openTags.pop();
                }
            } else {
                var openTag = tag;
                if (isSelfClosingTag(openTag.name)) {
                    continue;
                }
                openTags.push(openTag);
            }
        }
        if (openTags.length > 0) {
            var openTag = openTags[openTags.length - 1];
            console.log('Открывающий тег ' + openTag.tag + ' в строке ' + openTag.line + ' не имеет закрывающего тега.');
            return false;
        }
        console.log('Ладно, все окей');
        return true;
    }
</script>
EOL;
}


//фикс вывода авторов в фиде
add_filter( 'the_author', 'zen_real_author' );
function zen_real_author( $display_name ){
    if (is_feed()){
        return implode(", ", array_map(function($a){return $a->display_name;}, get_coauthors()));
    }
    return $display_name;
}

//если есть подзаголовок, то в фиде для Дзена выведется он
//условие с id убрать где-нибудь через полгодика
add_filter( 'the_title_rss', 'subtitle_as_title_for_zen' );
function subtitle_as_title_for_zen( $title ) {
    if (has_secondary_title() && is_feed() && get_query_var('feed') == 'zen' && in_array(get_post_type(),array('profile_article'))){
        $title = get_secondary_title();
    }
    if (has_secondary_title() && is_feed() && get_query_var('feed') == 'googlenews' ){

        //$title = get_secondary_title();
    }
    return $title;
}

add_filter( 'the_title', 'subtitle_as_title_for_googlenews', 10, 2 );
function subtitle_as_title_for_googlenews( $title, $id ) {
    if (has_secondary_title($id) && is_feed() && get_query_var('feed') == 'googlenews'){
        $title = get_secondary_title($id);
    }
    return $title;
}



//отсюда
add_action( 'wp_ajax_wpse_139269_inline_edit_radio_checked_hack', 'wpse_139269_inline_edit_radio_checked_hack' );
add_action( 'wp_ajax_nopriv_wpse_139269_inline_edit_radio_checked_hack', 'wpse_139269_inline_edit_radio_checked_hack' );
function wpse_139269_inline_edit_radio_checked_hack() {
    $terms = wp_get_object_terms(
        $_POST[ 'ajax-post-id' ],
        $_POST[ 'ajax-taxonomy' ],
        array( 'fields' => 'ids' )
    );
    $result = $terms[0];
    echo json_encode($result);
    exit;
    die();
}

add_action( 'admin_enqueue_scripts', 'wpse_139269_inline_edit_radio_checked_hack_enqueue_script' );
function wpse_139269_inline_edit_radio_checked_hack_enqueue_script() {
    wp_enqueue_script(
        'editphp-inline-edit-tax-radio-hack-js',
        get_template_directory_uri() . '/assets/js/admin/editphp-inline-edit-tax-radio-hack.js',
        array( 'jquery' )
    );
}


add_action( 'wp_ajax_inline-save', 'wpse_139269_wp_ajax_inline_save', 0 );
function wpse_139269_wp_ajax_inline_save() {
    global $wp_list_table;

    check_ajax_referer( 'inlineeditnonce', '_inline_edit' );

    if ( ! isset($_POST['post_ID']) || ! ( $post_ID = (int) $_POST['post_ID'] ) )
        wp_die();

    if ( 'page' == $_POST['post_type'] ) {
        if ( ! current_user_can( 'edit_page', $post_ID ) )
            wp_die( __( 'You are not allowed to edit this page.' ) );
    } else {
        if ( ! current_user_can( 'edit_post', $post_ID ) )
            wp_die( __( 'You are not allowed to edit this post.' ) );
    }

    if ( $last = wp_check_post_lock( $post_ID ) ) {
        $last_user = get_userdata( $last );
        $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' );
        printf( $_POST['post_type'] == 'page' ? __( 'Saving is disabled: %s is currently editing this page.' ) : __( 'Saving is disabled: %s is currently editing this post.' ),    esc_html( $last_user_name ) );
        wp_die();
    }

    $data = &$_POST;

    $post = get_post( $post_ID, ARRAY_A );

    // Since it's coming from the database.
    $post = wp_slash($post);

    $data['content'] = $post['post_content'];
    $data['excerpt'] = $post['post_excerpt'];

    // Rename.
    $data['user_ID'] = get_current_user_id();

    if ( isset($data['post_parent']) )
        $data['parent_id'] = $data['post_parent'];

    // Status.
    if ( isset($data['keep_private']) && 'private' == $data['keep_private'] )
        $data['post_status'] = 'private';
    else
        $data['post_status'] = $data['_status'];

    if ( empty($data['comment_status']) )
        $data['comment_status'] = 'closed';
    if ( empty($data['ping_status']) )
        $data['ping_status'] = 'closed';

    // Exclude terms from taxonomies that are not supposed to appear in Quick Edit.
    if ( ! empty( $data['tax_input'] ) ) {
        foreach ( $data['tax_input'] as $taxonomy => $terms ) {
            $tax_object = get_taxonomy( $taxonomy );

            if ( ! apply_filters( 'quick_edit_show_taxonomy', $tax_object->show_in_quick_edit, $taxonomy, $post['post_type'] ) ) {
                unset( $data['tax_input'][ $taxonomy ] );
            }
        }
    }

    // Hack: wp_unique_post_slug() doesn't work for drafts, so we will fake that our post is published.
    if ( ! empty( $data['post_name'] ) && in_array( $post['post_status'], array( 'draft', 'pending' ) ) ) {
        $post['post_status'] = 'publish';
        $data['post_name'] = wp_unique_post_slug( $data['post_name'], $post['ID'], $post['post_status'], $post['post_type'], $post['post_parent'] );
    }

    // Update the post.
    edit_post();

    $wp_list_table = _get_list_table( 'WP_Posts_List_Table', array( 'screen' => $_POST['screen'] ) );

    $level = 0;
    $request_post = array( get_post( $_POST['post_ID'] ) );
    $parent = $request_post[0]->post_parent;

    while ( $parent > 0 ) {
        $parent_post = get_post( $parent );
        $parent = $parent_post->post_parent;
        $level++;
    }

    $wp_list_table->display_rows( array( get_post( $_POST['post_ID'] ) ), $level );

    if( $_POST['post_type'] == 'profile_article' ||  $_POST['post_type'] == 'anew' || $_POST['post_type'] == 'yellow') {
        ?>
        <script>
            document.location.reload(true);
        </script>
        <?php
    }

    wp_die();
}

//досюда - радио для квик едит - позже перекинуть это в плагин

//не показывать картинку в статье
add_action('save_post', 'saveHideThumbnailField');
add_filter( 'admin_post_thumbnail_html', 'filter_admin_post_thumbnail_html', 10, 3 );
function saveHideThumbnailField($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }

    if (!isset($_POST['hide_thumbnail_']) || !wp_verify_nonce($_POST['hide_thumbnail_'], 'hide_thumbnail_'.$post_id)) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['_hide_thumbnail_countdown'])) {
        update_post_meta($post_id, '_hide_thumbnail_countdown', $_POST['_hide_thumbnail_countdown']);
    } else {
        delete_post_meta($post_id, '_hide_thumbnail_countdown');
    }
}

function filter_admin_post_thumbnail_html( $content, $post_id, $thumbnail_id ) {

    $value = get_post_meta($post_id, '_hide_thumbnail_countdown', true);

    ob_start();
    wp_nonce_field('hide_thumbnail_'.$post_id, 'hide_thumbnail_');
    $content .= ob_get_clean();

    $content .= '<div class="misc-pub-section misc-pub-section-last">';
    $content .= '<span style="display:inline-block;padding:8px 8px 4px 0px;">Скрыть через</span>';
    $content .= '<select name="_hide_thumbnail_countdown">';
    $content .= '<option selected="selected" value="-1">&ndash;</option>';
    for($i = 0; $i <= 10; $i++){
        $content .= '<option '.selected($i,$value,false).' value="'.$i.'">'.$i.'</option>';
    }
    $content .= '</select>';
    $content .= '<span style="display:inline-block;padding:8px 0px 4px 8px;"> дней</span>';
    $content .= '</div>';

    return $content;
}

/*function show_thumbnail(){
    $days = ((get_post_meta(get_the_ID(),'_hide_thumbnail_countdown'))[0]);

    if ( $days == NULL ){
        return true;
    }

    $days = (int)$days;

    if ((((date("U") - get_the_date("U")) > 86400*$days && $days >= 0) && count(get_post_meta(get_the_ID(),'_hide_thumbnail_countdown')) !== 0) || $days == 0 ){

        return false;

    }

    return true;
}*/


//проверка наличия роли у пользователя
function user_has_role($user_id, $role){
    $user = get_user_by("id",$user_id);
    if (!is_object($user)){
        return false;
    }
    foreach ($user->roles as $r){
        if ($r === $role){
            return true;
        }
        return false;
    }

}

function hide_publishing_actions(){
    global $post;
    $authors = array_map(function($el){return $el->ID;},get_coauthors());
    if(
        is_object($post) &&
        (
            ($post->post_type == 'profile_article' || $post->post_type == 'anew' || $post->post_type == 'yellow')
            &&
            (!current_user_can('administrator'))
            &&
            (get_current_user_id() != $post->post_author)
            &&
            (!in_array(get_current_user_id(),$authors))
            &&
            (!user_has_role(get_current_user_id(),'managing_editor'))
            &&
            (!user_has_role(get_current_user_id(),'chief_editor'))
            &&
            (!user_has_role(get_current_user_id(),'newsline_editor'))
            &&
            (!user_has_role(get_current_user_id(),'senior_editor'))
            &&
            (!user_has_role(get_current_user_id(),'corrector'))
        ) || user_has_role(get_current_user_id(),'editor')
    ){
        echo '
                <style type="text/css">
                    input[name="publish"] {
                        display:none !important;
                    }
                </style>
            ';
    }
}
add_action('admin_head', 'hide_publishing_actions');




/*if(!function_exists('display_php_error_for_admin')) {
    function display_php_error_for_admin()
    {
        if(get_current_user_id() == 1){
            error_reporting(E_ALL);
            @ini_set('display_errors', 1);
        }else{
            error_reporting(0);
            @ini_set('display_errors', 0);
        }

    }
}
add_action('init','display_php_error_for_admin');*/

add_filter( 'amp_post_template_data', function( $data ) {
    $data['amp_component_scripts'] = array_merge(
        $data['amp_component_scripts'],
        array(
            'amp-auto-ads' => 'https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js',
        )
    );
    return $data;
} );



function print_component() {
    echo '<amp-auto-ads type="adsense" data-ad-client="ca-pub-6584996181587704"></amp-auto-ads>';
}

add_action(
    'wp_footer',
    function() {
        if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
            print_component();
        }
    }
);


function print_amp_counters(){
    get_template_part('counters', 'amp');
}
add_action(
    'amp_post_template_footer',
    function() {
        if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
            print_amp_counters();
        }
    }
);
function print_amp_css() {
    get_template_part('styles', 'amp');
}
add_action(
    'amp_post_template_css',
    function() {
        if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
            print_amp_css();
        }
    }
);








add_filter(
    'amp_post_template_data',
    function( $data ) {
        $data['amp_component_scripts'] = array_merge(
            $data['amp_component_scripts'],
            array(
                'amp-auto-ads' => true,
            )
        );
        return $data;
    }
);
add_action( 'amp_post_template_footer', 'print_component' );






####внимание, костыль, который я поправлю потом####
if (
    get_current_user_id() != 1
    &&
    get_current_user_id() != 2
    &&
    get_current_user_id() != 3
    &&
    get_current_user_id() != 58
){
    add_action('admin_head', 'gurren_dan_menuitems');

}

function gurren_dan_menuitems() {
    echo '
    <style>
        .toplevel_page_wsal-auditlog, .toplevel_page_wsal-auditlog+li,
        #toplevel_page_email-log, #toplevel_page_email-log+li,
        #menu-posts-archive, #wp-admin-bar-delete-cache, #wp-admin-bar-alm-cache,
        #toplevel_page_ajax-load-more, #menu-settings, #toplevel_page_pp-calendar,
        #toplevel_page_email-log, #wp-admin-bar-autoptimize
        {display:none!important;}
    </style>';
}



add_action( 'admin_print_footer_scripts', 'remove_save_button' );
function remove_save_button() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            setInterval(function(){
                if($("input#publish[name='save']").val() != 'Отправить на рассмотрение') {
                    $("input#publish[name='save']").val('Обновить и выйти').prev().val('Обновить и выйти');
                }
                if($("input#publish[name='publish']").val() != 'Отправить на рассмотрение') {
                    $("input#publish[name='publish']").val('Опубликовать и выйти').prev().val('Опубликовать и выйти');
                }
            },1000);
            $("#major-publishing-actions").append('<div style="float:right;padding:10px 0px 0px 0px;"><input type="button" class="preview button" value="Выйти" onclick="if(confirm(\'Изменения не сохранены. Уверен, что хочешь выйти?\')){window.location.href=\'/wp-admin/edit.php?post_type=<?php echo get_post_type(); ?>\'}" /></div><div class="clear"></div>');
            $('.submitdelete.deletion').html('Удалить');
        });
    </script><?php
}

add_filter( 'redirect_post_location', 'redirect_after_update' );
function redirect_after_update( $location ) {
    $user = wp_get_current_user();
    if (
        (!array_intersect($user->roles, array('administrator', 'editor_in_chief')) || in_array(get_current_user_id(), array(58))) &&
        (isset( $_POST['save'] ) || isset( $_POST['publish'] )) && (get_post_status(get_the_ID()) == "publish" || get_post_status(get_the_ID()) == "future")
        &&
        !in_array(get_current_user_id(), array(57))
        &&
        get_post_type(get_post(get_the_ID())) != 'guest-author'
    ){

        $location = "/?post_type=".get_post_type(get_post(get_the_ID()))."&p=".get_the_ID()."&preview=true";

        //debug(get_current_user_id().": ".$location);

        return $location;
    }

    return $location;
}

function empty_excerpt_more( $more ) {
    return '';
}
add_filter('excerpt_more', 'empty_excerpt_more');


add_action( 'wp_print_styles', 'tj_deregister_yarpp_header_styles' );
function tj_deregister_yarpp_header_styles() {
    wp_dequeue_style('yarppWidgetCss');
    wp_deregister_style('yarppRelatedCss');
}

add_action( 'wp_footer', 'tj_deregister_yarpp_footer_styles' );
function tj_deregister_yarpp_footer_styles() {
    wp_dequeue_style('yarppRelatedCss');
}


add_action('admin_head','clear_interface',10);
function get_current_user_role_roles() {
    $user_meta = get_userdata(get_current_user_id());
    $roles = $user_meta->roles;

    return $roles;
}

function clear_interface() {
    $roles = get_current_user_role_roles();

    $remove = array();
    $hide = array();

    if (in_array('editor',$roles)){
        $remove = array(
            "amp-options",
            "tools.php",
            "profile.php"
        );
        $hide = array(
            "#visibility-radio-password",
            "#visibility-radio-password+label",
            "#visibility-radio-password+label+br",
            "#visibility-radio-private",
            "#visibility-radio-private+label",
            "#visibility-radio-private+label+br",
            ".misc-pub-section.misc-amp-status"
        );
    }

    foreach ($remove as $item){
        remove_menu_page( $item );
    }

    echo "<style>".implode(",",$hide)."{display:none!important;}</style>";
}









add_action( 'admin_print_footer_scripts', 'add_title_char_counter' );
function add_title_char_counter(){
    $screen = get_current_screen();
    if(in_array($screen->id, array('edit-yellow', 'edit-profile_article', 'edit-anew'))) { return; }

    $script = <<<EOL
<script>
jQuery.fn.countChars = function() {
    let cc = jQuery(this).val().length;
    let limit =  [60,70];
    let stop =   ["Google уже не поймет", "Теперь не поймет и Яндекс"];
    let container = jQuery(this).siblings(".charcount."+jQuery(this).attr('id'));
    container.find('span').eq(0).html(cc);
    if (cc > limit[1]) {
        container.fadeIn();
        container.removeClass('danger').addClass('warning').find('span').eq(1).html(stop[1]);
    } else if (cc > limit[0]) {
        container.fadeIn();
        container.addClass('danger').removeClass('warning').find('span').eq(1).html(stop[0]);
    } else {
        container.removeClass('danger').removeClass('warning').find('span').eq(1).html();
        container.fadeOut();
    }
    jQuery(container).css({
        "top":jQuery(this).position().top+"px"
    });
}
jQuery(document).ready(function(){
    setTimeout(function(){
    jQuery('input#title').each(function(){
        jQuery(this).before('<div class="clear clearfix"></div><div class="charcount '+jQuery(this).attr('id')+'"><span>'+jQuery(this).val().length+'</span><span></span></div><div class="clear clearfix"></div>');
        jQuery(this).countChars();
    });
    },2000);
    jQuery('#poststuff').on('blur click paste keyup keydown keypress focusin focusout focus','#title',function(e){
        jQuery(this).countChars(e);
    });
});
</script>
<style>
    #secondary-title-input{
        margin:0px;
    }
    #title {
        margin-bottom:8px !important;
    }
    .charcount {
        display:none;
        color:#222;
        width:auto;
        float:right;
        margin:0px;
        padding:0px;
    }
    .charcount.warning {
        background:#bd2130;
        color:#fff;
    }
    .charcount.danger {
        background:#ffc107;
    }
    .charcount span {
        display:inline-block;

    }
    .charcount span {
        font-size: 14px;
        padding:1px 4px 2px 4px;
    }
    #wp-link #link-options .link-nofollow {
        display:none;
    }
</style>
EOL;
    if (in_array(get_post_type(),array('anew','yellow'))){
        $script .= "<script>jQuery('#secondary-title-input').attr('maxlength','230');</script>";
    }
    echo $script;

}

/*if (in_array(get_current_user_id(), array(1,37)) ){
    echo '<pre>';
    var_dump(get_current_user_role_roles());
    echo '</pre>';
}*/
//метаполя в статье
add_action('post_submitbox_misc_actions', 'create_custom_fields_submitbox');
add_action('save_post', 'save_custom_fields');
$fields = array(
    array(//Скрывает пост с главной
        "type" => "checkbox",
        "pt" => array("anew","profile_article"),
        "metabox" => "submitbox",
        "id" => "_hide_on_mainpage",
        "meta_key" => false,
        "label" => "Не показывать на главной",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),
    array(//Скрывает пост с главной
        "type" => "checkbox",
        "pt" => array("anew","profile_article"),
        "metabox" => "submitbox",
        "id" => "_hide_on_website",
        "meta_key" => false,
        "label" => "Не показывать на сайте",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),
    array(//Доступ только по ссылке, отправка в РСС
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "_only_link_access",
        "meta_key" => false,
        "label" => "Доступно только по ссылке",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),
    /*array(//Исключить из РСС для Я.Н. и Г.Н.
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "layf_exclude_from_feed",
        "meta_key" => false,
        "label" => "Исключить из новостных фидов",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),*/
    array(//Исключить из РСС для Я.Н.
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "ynrss_exclude",
        "meta_key" => false,
        "label" => "Исключить из ЯН",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),
    array(//Исключить из РСС для Г.Н.
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "gnrss_exclude",
        "meta_key" => false,
        "label" => "Исключить из GN",
        "value" => "1",
        "echo" => true,
        "roles" => false
    ),
    array(//Исключить из РСС для Я.Дзен
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "yzrssenabled_meta_value",
        "meta_key" => false,
        "label" => "Исключить из Я.Дзен",
        "value" => array(
            0 => "no",
            1 => "yes"
        ),
        "echo" => true,
        "roles" => false
    ),
    array(//Тематика Я.Дзен
        "type" => "checkbox",
        "pt" => array("anew","profile_article"),
        "metabox" => "submitbox",
        "id" => "yzcategory_meta_value",
        "meta_key" => false,
        "label" => "",
        "value" => NULL,
        "echo" => false,
        "roles" => false
    ),
    array(//Событие
        "type" => "checkbox",
        "pt" => array("anew","yellow"),
        "metabox" => "submitbox",
        "id" => "event",
        "meta_key" => false,
        "label" => "Событие",
        "value" => "1",
        "echo" => true,
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "corrector",
            "newsline_editor",
            "senior_editor",
            "chief_editor",
            "editor"
        )
    ),
    array(
        "type" => "date",
        "pt" => array("anew","yellow"),
        "metabox" => "submitbox",
        "id" => "event_date",
        "meta_key" => false,
        "label" => "Дата",
        "echo" => function($post_id){
            return (get_post_meta($post_id, 'event', true) == '1') ? true : false;
        },
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "corrector",
            "chief_editor",
            "senior_editor",
            "newsline_editor"
        )
    ),
    array(
        "type" => "checkbox",
        "pt" => array("guest-author"),
        "metabox" => "author_settings",
        "id" => "show_data",
        "meta_key" => false,
        "label" => "Показывать подробности",
        "value" => "1",
        "echo" => true,
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "chief_editor",
            "managing_editor"
        )
    ),
    array(
        "type" => "checkbox",
        "pt" => array("guest-author"),
        "metabox" => "author_settings",
        "id" => "show_only_articles",
        "meta_key" => false,
        "label" => "Показывать только статьи",
        "value" => "1",
        "echo" => true,
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "chief_editor",
            "managing_editor"
        )
    ),
    array(
        "type" => "select",
        "pt" => array("profile_article"),
        "metabox" => "columnist_category",
        "id" => "mt_category",
        "meta_key" => false,
        "label" => "",
        "value" => array(
            "IT" => "IT",
            "Авто-мото" => "Авто-мото",
            "Бизнес и финансы" => "Бизнес и финансы",
            "В мире животных" => "В мире животных",
            "Военное дело" => "Военное дело",
            "Дети и семья" => "Дети и семья",
            "Дом/Дача" => "Дом/Дача",
            "Игры" => "Игры",
            "История" => "История",
            "Кино" => "Кино",
            "Кулинария" => "Кулинария",
            "Культура и искусство" => "Культура и искусство",
            "Медицина и здоровье" => "Медицина и здоровье",
            "Мода и красота" => "Мода и красота",
            "Наука и технологии" => "Наука и технологии",
            "Общество" => "Общество",
            "Охота и рыбалка" => "Охота и рыбалка",
            "Политика" => "Политика",
            "Работа и карьера" => "Работа и карьера",
            "Реклама" => "Реклама",
            "Религия" => "Религия",
            "Спорт" => "Спорт",
            "Строительство и недвижимость" => "Строительство и недвижимость",
            "Туризм" => "Туризм",
            "Фото" => "Фото",
            "Шоу-бизнес" => "Шоу-бизнес",
            "Юмор и развлечения" => "Юмор и развлечения"
        ),
        "echo" => true,
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "chief_editor",
            "corrector",
            "senior_editor",
            "newsline_editor",
            "editor"
        )
    ),
    array(//Молния
        "type" => "checkbox",
        "pt" => array("anew","yellow"),
        "metabox" => "submitbox",
        "id" => "_breaking",
        "meta_key" => false,
        "label" => "Молния",
        "value" => "1",
        "echo" => true,
        "roles" => array(
            "administrator",
            "editor_in_chief",
            "chief_editor",
            "senior_editor",
            "newsline_editor"
        )
    ),
    array(//Телега
        "type" => "checkbox",
        "pt" => array("anew","profile_article","yellow"),
        "metabox" => "submitbox",
        "id" => "_send_telegram",
        "meta_key" => false,
        "label" => "Отправить в канал",
        "after" => function(){
            return (get_post_meta(get_the_ID(), '_sended_telegram', true)) ? "(отправлено)" : "";
        },
        "value" => "1",
        "echo" => true,
        "roles" => array(
            "corrector",
            "editor_in_chief",
            "administrator",
            "chief_editor",
            "senior_editor",
            "newsline_editor"
        )
    ),
    array(//Телега отправлено
        "type" => "checkbox",
        "pt" => array("anew","profile_article"),
        "metabox" => "submitbox",
        "id" => "_sended_telegram",
        "meta_key" => false,
        "label" => "Отправлено в канал",
        "value" => "1",
        "echo" => false,
        "roles" => array(
            "editor_in_chief",
            "chief_editor",
            "administrator",
            "senior_editor",
            "newsline_editor"
        )
    ),

);
function check_user_meta_access($field){

    $allow = false;

    $user = wp_get_current_user();
    if (!is_array($field["roles"])){
        return true;
    }
    if( array_intersect($field["roles"], $user->roles) || $field["roles"] === false ) {
        $allow = true;
    }
    if (array_key_exists("users", $field)) {
        if (in_array($user->ID, $field["users"]["allow"])) {
            $allow = true;
        }
        if (in_array($user->ID, $field["users"]["deny"])) {
            $allow = false;
        }
    }

    return $allow;

}

function create_custom_fields_submitbox() {//создаем кастомные чекбоксы
    global $fields;
    $post_id = get_the_ID();
    $post_type = get_post_type();
    foreach ($fields as $field) {
        //hr(check_user_meta_access($field));
        if (in_array($post_type,$field["pt"]) && $field['metabox'] == 'submitbox'){
            create_custom_field($field);
        }
    }
}
function create_custom_fields($post, $params) {//создаем кастомные чекбоксы

    global $fields;
    $post_id = get_the_ID();
    $post_type = get_post_type();
    foreach ($fields as $field) {
        //hr(check_user_meta_access($field));
        if (in_array($post_type,$field["pt"]) && $field['metabox'] == $params['id']){
            create_custom_field($field);
        }
    }
}
function create_custom_field($field) {//создаем кастомный чекбокс
    global $fields;
    $post_id = get_the_ID();
    $gpm = get_post_meta($post_id, $field['id'], true);

    foreach ($fields as $f){
        if ($f["id"] !== $field["id"]) { continue; }
        $value = (is_array($f["value"])) ? array_search($gpm,$f["value"]) : $gpm;
    }

    $write = (is_callable($field['echo'])) ? $field['echo']($post_id) : $field['echo'];

    wp_nonce_field('nonce_'.$field['id'].'_'.$post_id, 'nonce_'.$field['id']);

    if ($write):
        $display = check_user_meta_access($field) ? "d-block" : "d-none";
        ?>
        <div class="misc-pub-section misc-pub-section-last <?php echo $display; ?>">
            <label>
                <?php _e(custom_field_html($field)) ?>
                <?php (is_callable($field['after'])) ? _e($field['after']()) : _e($field['after']); ?>
            </label>
        </div>
    <?php
    endif;

}
function custom_field_html($field){
    global $fields;
    $html = '';
    $post_id = get_the_ID();
    $gpm = get_post_meta($post_id, $field['id'], true);
    foreach ($fields as $f){
        if ($f["id"] !== $field["id"]) { continue; }
        $value = (is_array($f["value"])) ? array_search($gpm,$f["value"]) : $gpm;
    }
    switch($field['type']) {
        case("checkbox"):
            //' . checked($value, true, false) . '
            $html = '
                <input
                    type="checkbox"
                    value="'.$field['value'].'"
                    name="' . $field['id'] . '"
                    ' . checked((bool)$value, true, false) . '
                />
                ' . _e($field['label']);
            break;
        case("checkbox_option"):
            $html = '
                <input
                    type="checkbox"
                    value="'.$field['value'].'"
                    name="' . $field['id'] . '"
                    ' . ((get_option($field['id']) == get_the_ID()) ? "checked" : "") . '
                />
                ' . _e($field['label']);
            break;
        case('date'):
            $html = '
                <input
                    type="date"
                    value="'.$value.'"
                    name="' . $field['id'] . '"
                />
                ' . _e($field['label']);
            break;
        case('select'):
            $html = '<select name="' . $field['id'] . '" id="' . $field['id'] . '">';
            foreach($field['value'] as $key => $val){
                $html .= '<option value="'.$key.'" '.(($key == $value) ? 'selected' : '').'>'.$val.'</option>';
            }
            $html .= '</select>';
            break;
        case('text'):
            $txt_val = is_closure($field['value']) ? $field['value']() : $field['value'];
            $html = _e($field['label']) . '<input name="' . $field['id'] . '" id="' . $field['id'] . '" value="'.$txt_val.'" >';
            //$html = '';
            break;
        default:
            $html = '';
    }
    return $html;
}
function is_closure($t) {
    return $t instanceof \Closure;
}
function save_custom_fields() {//сохраняем кастомные чекбоксы
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }
    global $fields;
    $post_id = get_the_ID();
    foreach ($fields as $field) {
        save_custom_field($post_id, $field);
    }
}
function save_custom_field($post_id, $field) {//сохраняем кастомный чекбокс
    global $fields;
    $value = $_POST[$field['id']];

    if (is_callable($field["onsave"])){
        if(!$field["onsave"]()){
            return;
        }
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }
    if (!isset($_POST['nonce_'.$field['id']]) || !wp_verify_nonce($_POST['nonce_'.$field['id']], 'nonce_'.$field['id'].'_'.$post_id)) { return; }
    if (!current_user_can('edit_post', $post_id)) { return; }

    if (isset($_POST[$field['id']])) {
        foreach ($fields as $f) {
            if ($f["id"] !== $field["id"]) { continue; }
            $value = is_array($f["value"]) ? (isset($_POST[$field['id']])) ? $f["value"][1] : $f["value"][0] : $_POST[$field["id"]];
            $field['id'] = ($f['meta_key']) ? $f['meta_key'] : $field['id'];
            $value = $f['type'] == 'select' ? $_POST[$field['id']] : $value;
        }
        update_post_meta($post_id, $field['id'], $value);
    } else {
        if ($field['echo'] === true){
            delete_post_meta($post_id, $field['id']);
        }
    }
}
add_action( 'add_meta_boxes' , 'remove_post_custom_fields',99 );
function remove_post_custom_fields() {//убираем ненужные мета
    $context = array('normal','advanced','side');
    $screen = array('anew','profile_article','yellow');
    $id = array(
        'layf_related_links',
        'yzen_meta_box'
    );
    foreach ($context as $c){
        foreach ($screen as $s){
            foreach ($id as $i){
                remove_meta_box( $i , $s , $c );
            }
        }
    }
}
add_action( 'add_meta_boxes', 'yzen_meta_boxx' );
function yzen_meta_boxx(){//Добавляем свой метабокс для тематик дзена взамен стандартного
    add_meta_box('yzen_category', 'Тематика Яндекс.Дзен', 'yzen_categories', array('profile_article','anew','yellow'), 'normal' , 'high');
}
function yzen_categories(){//создаем селект в своем метабоксе дзена

    $meta_name = 'yzcategory_meta_value';
    $categories = array("Происшествия", "Политика", "Война", "Общество", "Экономика", "Спорт", "Технологии", "Наука", "Игры", "Музыка", "Литература", "Кино", "Культура", "Мода", "Знаменитости", "Психология", "Здоровье", "Авто", "Дом", "Хобби", "Еда", "Дизайн", "Фотографии", "Юмор", "Природа", "Путешествия");
    $meta_value = get_post_meta(get_the_ID(),$meta_name,true);

    $html = '<select name="'.$meta_name.'">';
    foreach ($categories as $cat){
        $selected = ($meta_value == $cat) ? 'selected="selected"' : '';
        $html .= '<option value="'.$cat.'" '.$selected.' >'.$cat.'</option>';
    }
    $html .= '</select>';
    $html .= wp_nonce_field('nonce_yzcategory_meta_value_'.get_the_ID(), 'nonce_yzcategory_meta_value');
    echo $html;

}






//добавляем свои колонки в таблицу-список статей
add_filter('manage_yellow_posts_columns', 'add_custom_columns');
add_filter('manage_anew_posts_columns', 'add_custom_columns');
add_filter('manage_profile_article_posts_columns', 'add_custom_columns');
function add_custom_columns($columns){
    $arr = array('thumb' => 'Фото');
    return $columns+$arr;
}


//добавляем в таблицу содержимое для ячеек кастомных колонок
add_action( 'manage_yellow_posts_custom_column', 'add_custom_columns_column');
add_action( 'manage_anew_posts_custom_column', 'add_custom_columns_column');
add_action( 'manage_profile_article_posts_custom_column', 'add_custom_columns_column');
function add_custom_columns_column( $column_name ) {
    if ($column_name === 'thumb') {
        if (has_post_thumbnail()) {
            ?>
            <a class="wpseo-score-icon good" target="_blank" href="<?php echo get_the_post_thumbnail_url(); ?>"></a>
            <?php
        } else {
            ?>
            <div class="wpseo-score-icon na"></div>
            <?php
        }
    }
}


//удаляем скрипты медиаплеера
add_action('wp_enqueue_scripts', 'remove_mediaplayer_scripts');
function remove_mediaplayer_scripts() {
    wp_deregister_script('jquery');
    wp_deregister_script('jquery-core');
    wp_deregister_script('jquery-migrate');
    wp_deregister_script('mediaelement');
    wp_deregister_script('mediaelement-core');
    wp_deregister_script('mediaelement-migrate');
}



//удаляем параметр высоты видео фрейма, пусть подстраивается сам
add_filter( 'wp_video_shortcode', 'rewrite_video_shortcode', 10, 5 );
function rewrite_video_shortcode( $output, $atts, $video, $post_id, $library  ) {

    $output = preg_replace('/(<[^>]+) height=".*?"/i', '$1', $output);
    $output = preg_replace('/(<[^>]+) width=".*?"/i', '$1', $output);
    $output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $output);


    return $output;

}

//упорядочиваем загрузку новостей при бесконечном скролле


// убираем ссылку на ленту комментариев для каждого поста
function pr_disable_feed() {
    wp_redirect(get_option('siteurl'));
}
add_action('do_feed', 'pr_disable_feed', 1);
add_action('do_feed_rdf', 'pr_disable_feed', 1);
add_action('do_feed_rss', 'pr_disable_feed', 1);
add_action('do_feed_rss2', 'pr_disable_feed', 1);
add_action('do_feed_atom', 'pr_disable_feed', 1);
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'rsd_link' );


//делаем opengraph для постов без фото
add_action('wp_head', function() {

    if (!is_singular()) return;
    
    $post_id = get_the_ID();
    $default_image = 'https://cdn.profile.ru/wp-content/uploads/2023/07/profile_lazyload_hq.jpg'; // Заглушка в папке темы
    
    $og_image = esc_url($default_image);
    
    if (!has_post_thumbnail($post_id) or !show_thumbnail($post_id)) {

        echo '<meta property="og:image" content="' . $og_image . '" />' . "\n";
        echo '<meta property="og:image:width" content="1200" />' . "\n";
        echo '<meta property="og:image:height" content="630" />' . "\n";
        echo '<meta name="twitter:image" content="' . $og_image . '" />';
        
    //} else {
    //    $og_image = get_the_post_thumbnail_url($post_id, 'large');
    }
    
    

});


//Добавили к ссылкам nofollow
add_action( 'after_wp_tiny_mce', function(){

    ?>
    <script>

        var originalWpLink;

        if ( typeof tinymce !== 'undefined' && typeof _ !== 'undefined' && typeof wpLink !== 'undefined' ) {

            if ( tinymce.$('#link-options').length ) {

                tinymce.$('#link-options').append(<?php echo json_encode( '<div class="link-redirect"><label><span></span><input type="checkbox" id="wp-link-redirect" /> Редирект с задержкой</label></div>' ); ?>);

                originalWpLink = _.clone( wpLink );
                wpLink.addRedirect = tinymce.$('#wp-link-redirect');

                wpLink = _.extend( wpLink, {
                    getAttrs: function() {
                        var attrs = originalWpLink.getAttrs();
                        attrs.redirect = wpLink.addRedirect.prop( 'checked' ) ? 'true' : false;
                        return attrs;
                    },
                    buildHtml: function( attrs ) {
                        var html = '<a href="' + attrs.href + '"';
                        if ( attrs.target ) {
                            html += ' target="' + attrs.target + '"';
                        }
                        if ( attrs.redirect ) {
                            html += ' redirect="' + attrs.redirect + '"';
                        }
                        return html + '>';
                    },
                    mceRefresh: function( searchStr, text ) {
                        originalWpLink.mceRefresh( searchStr, text );
                        var editor = window.tinymce.get( window.wpActiveEditor )
                        if ( typeof editor !== 'undefined' && ! editor.isHidden() ) {
                            var linkNode = editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
                            if ( linkNode ) {
                                wpLink.addRedirect.prop( 'checked', 'true' === editor.dom.getAttrib( linkNode, 'redirect' ) );
                            }
                        }
                    }
                });
            }
        }
    </script>
    <style>
        #wp-link #link-options .link-nofollow {
            padding: 3px 0 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        #wp-link #link-options .link-nofollow label span {
            width: 83px;
        }
        .has-text-field #wp-link .query-results {
            top: 223px;
        }
    </style>
    <?php
});

add_filter( 'the_title', 'archive_title_filter', 10, 2 );
function archive_title_filter( $title, $id ) {
    $title = (get_post_type($id) == 'archive') ? "Архивная публикация ".get_the_date("Y", $id)." года: \"".$title."\"" : $title;
    return $title;
}
remove_filter( 'the_title', 'wptexturize' );
add_filter('the_title', 'remove_dashes_from_title', 100, 2);
function remove_dashes_from_title($title, $id){
    $title = str_replace(array(' - ', ' — '), ' – ', $title );
    $title = str_replace(array('—'), '–', $title );
    return $title;
}

add_filter('the_title', 'remove_nbsp', 100, 2);
add_filter('the_secondary_title', 'remove_nbsp', 100, 2);
add_filter('get_secondary_title', 'remove_nbsp', 100, 2);
function remove_nbsp ($title, $id){
    $string = htmlentities($title, null, 'utf-8');
    $title = str_replace("&nbsp;", " ", $string);
    $title = html_entity_decode($title);
    return $title;
}

foreach( [ 'post', 'page', 'yellow', 'post_type'] as $type ) {
    add_filter( $type . '_link', function ( $url, $post_id, $sample ) use ( $type )
    {
        return apply_filters( 'wpse_link', $url, $post_id, $sample, $type );
    }, 9999, 3 );
}

add_filter( 'wpse_link', function(  $url, $post_id, $sample, $type )
{

    $url = str_replace('/gregator/', '/news/', $url);

    return $url;
}, 10, 4 );



//Получаем темплейт без вывода




//Ссылки на желтуху в фиде
function filter_wpseo_xml_sitemap_post_url( $get_permalink, $post ) {

    $get_permalink = (get_post_type($post) == 'yellow') ? str_replace('/gregator/', '/news/', $get_permalink) : $get_permalink;

    return $get_permalink;
}
add_filter( 'wpseo_xml_sitemap_post_url', 'filter_wpseo_xml_sitemap_post_url', 10, 2 );

//Редиректы на правильные ссылки желтухи
add_action( 'template_redirect', 'agregator_to_news_redirect' );
function agregator_to_news_redirect() {
    if ( is_single() && get_post_type(get_the_ID()) == 'yellow' && strripos(filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING), 'gregator/') !== false && !(is_user_logged_in())) {
        wp_redirect( str_replace('gregator/', 'news/', filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING)), 301 );
        exit;
    }
}
//Запрет показа баннера в брендированных рубриках
function deny_branding(){
    $ids = array();
    return false;
    foreach (get_the_category() as $crnt_cat) {
        array_push($ids, $crnt_cat->term_id);
        array_push($ids, $crnt_cat->category_parent);
    }

    if (is_home()){
        return true;
    }

    if (in_array(91781, $ids)){
        return true;
    }

    foreach ($ids as $id){
        if(get_term_meta( $id, 'type', 1 ) == "branding"){
            return false;
        }
    }
    return true;

}


//Удалил лишние колонки из таблицы WP
/*add_filter('manage_yellow_posts_columns', 'remove_columns_for_user', 10);
add_filter('manage_anew_posts_columns', 'remove_columns_for_user', 10);
add_filter('manage_profile_article_posts_columns', 'remove_columns_for_user', 10);
add_filter( 'manage_edit-yellow_columns', 'remove_columns_for_user', 10);
add_filter( 'manage_edit-anew_columns', 'remove_columns_for_user', 10);
add_filter( 'manage_edit-profile_article_columns', 'remove_columns_for_user', 10);*/
function remove_columns_for_user($columns) {

    /*if (!in_array(get_current_user_id(), array(57, 37))) {
        return $columns;
    }

    $unset = array("secondary_title", "cb", "coauthors", "tags", "comments", "thumb", "wpseo-score", "wpseo-score-readability", "wpseo-title", "wpseo-metadesc", "wpseo-focuskw", "wpseo-links", "wpseo-linked");
    foreach ($unset as $key) {
        //unset($columns[$key]);
    }*/

    return $columns;
}


add_action( 'admin_head', 'admin_head_styles' );
function admin_head_styles(){
    ?>
    <style>
        .d-block {
            display:block;
        }
        .d-none {
            display:none;
        }
    </style>
    <?php
    return;
}

add_action('wp_enqueue_scripts', function() {
    // Подключаем CSS-файл
    wp_enqueue_style(
        'app-paginator', // Уникальный идентификатор
        get_theme_file_uri('/assets/css/app-paginator.css'), // Путь относительно темы
        [], // Зависимости (например, ['bootstrap'])
        '1.0.1', // Версия по дате изменения
        'all' // Медиа-тип
    );
});


add_action( 'after_setup_theme', 'my_theme_add_editor_styles' );
function my_theme_add_editor_styles() {
    add_theme_support( 'editor-style' );
    add_editor_style( 'assets/css/admin/editor-styles.css' );

}



add_filter( 'oembed_request_post_id', 'post_id_for_oembed', 10, 2 );
function post_id_for_oembed( $post_id, $url ) {
    if(parse_url($url)['host'] == 'profile.ru'){
        $url = str_replace("/","",$url);
        $post_id = array_pop(explode("-",$url));
        $post_id = (int)$post_id;
    }else{
        $post_id = false;
    }
    return $post_id;
}



function get_current_page_category() {
    $cat = get_the_category();
    $id = ($cat[0]->parent == 0) ? $cat[0]->cat_ID : $cat[0]->parent;

    return $id;
}



//Добавление дополнительных интервалов в крон
add_filter('cron_schedules','my_cron_schedules');
function my_cron_schedules($schedules){
    if(!isset($schedules["5min"])){
        $schedules["5min"] = array(
            'interval' => 5*60,
            'display' => __('Once every 5 minutes'));
    }
    if(!isset($schedules["2min"])){
        $schedules["2min"] = array(
            'interval' => 2*60,
            'display' => __('Once every 2 minutes'));
    }
    if(!isset($schedules["30min"])){
        $schedules["30min"] = array(
            'interval' => 30*60,
            'display' => __('Once every 30 minutes'));
    }
    if(!isset($schedules["1min"])){
        $schedules["1min"] = array(
            'interval' => 1*60,
            'display' => __('Once every 1 minute'));
    }
    if(!isset($schedules["10sec"])){
        $schedules["10sec"] = array(
            'interval' => 10,
            'display' => __('Once every 10 seconds'));
    }
    if(!isset($schedules["1week"])){
        $schedules["1week"] = array(
            'interval' => 60*60*24*7,
            'display' => __('Once every 1 week'));
    }
    return $schedules;
}

//Проверка, выбрана ли рубрика в quick-edit
add_action('admin_footer', 'quick_edit_category_required');
function quick_edit_category_required(){
    $script = <<<JS
    <script>
        (function($){
            $('.save', $('#inline-edit')).click(function(e){
                console.log(e);
                if(!checkFields(this, $)){
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    alert('Сначала выберите рубрику!');
                }
            })
        })(jQuery);
        
        function checkFields(el,$) {
            
            var elems = $(el).parents('tr').find('input[name="post_category[]"]:checked, input[name="radio_tax_input[category][]"]:checked');
            
            return (elems.length == 0) ? false : true;
            
        }
    </script>
JS;
    $screen = get_current_screen();
    if($screen->base == 'edit'){
        echo $script;
    }
}


//если создаем новую желтую, надо сразу ее помечать как желтую
add_action('admin_footer', 'mark_new_yellow');
function mark_new_yellow(){
    $screen = get_current_screen();
    if (is_edit_page('new')  && $screen->id == 'yellow'){
        echo <<<JS
    <script>
        (function($){
            $('input[name="_yellow"]').prop('checked',true);
        })(jQuery);
    </script>
JS;
    }
}


//Фильтр для отсеивания материалов, доступных только по ссылке
add_filter( 'posts_where', 'only_link_access_request_filter', 99, 1 );
function only_link_access_request_filter($where){
    if (!is_single() && !is_admin() || filter_input(INPUT_GET, 'action') == 'alm_get_posts'){
        $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_only_link_access' and `meta_value` = '1') ";
        //$where .= " AND '".esc_sql($_SERVER['REQUEST_URI'])."' = '".esc_sql($_SERVER['REQUEST_URI'])."' ";
    }
    return $where;
}

//Фильтр для отсеивания материалов дзен
add_filter( 'posts_where', 'only_link_access_request_filter', 99, 1 );
function dzen_request_filter($where){
	if(str_contains($_SERVER["REQUEST_URI"], "feed/zen")){
		$where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'yzrssenabled_meta_value' and `meta_value` = 'yes') ";
	}
	return $where;
}
add_filter( 'posts_where', 'dzen_request_filter', 99, 1 );

add_filter( 'posts_where', 'hide_on_website_request_filter', 99, 1 );
function hide_on_website_request_filter($where){
    if((is_admin() || is_feed() || is_single() || is_yn()) && filter_input(INPUT_GET, 'action') != 'alm_get_posts'){
        return $where;
    }else {
        $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') ";
    }
    return $where;
}

//Фильтр для добавления тега милитари в рубрику милитари
add_filter( 'posts_where', 'military_posts_appending' );
function military_posts_appending($where){
    if((filter_input(INPUT_GET, 'slug') == 'military' || get_queried_object_id() == 8529) && !is_feed()){
        $where .= " OR `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 103464) ";
    }
    return $where;
}
add_filter( 'posts_where', 'persona_posts_appending' );
function persona_posts_appending($where){
    if((filter_input(INPUT_GET, 'slug') == 'persona' || get_queried_object_id() == 105049) && !is_feed()){
        $where .= " OR `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 105047) ";
    }
    return $where;
}
//Фильтр для добавления импортозамещение милитари в рубрику "знай наших"
add_filter( 'posts_where', 'import_posts_appending' );
function import_posts_appending($where){
    if((filter_input(INPUT_GET, 'slug') == 'znaj-nashih' || get_queried_object_id() == 104807) && !is_feed() && !is_admin()){
        //$where .= " OR (`ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 17548) AND `post_status` = 'publish'  AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') ) ";
        $where .= " AND ID != 1067204 OR (`post_status` = 'publish' AND `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 17548 AND `object_id` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') ) )";
    }
    return $where;
}


//Фильтр для отсеивания на главной публикаций с чеком "Не показывать на главной"
add_action ('posts_where', 'mainpage_request_filter');
function mainpage_request_filter($where){
    if (is_home() || filter_input(INPUT_GET, 'id') == 'home_page'){
        $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_mainpage' and `meta_value` = '1')  ";
    }
    return $where;
}
add_action ('posts_where', function($where){
    if (filter_input(INPUT_GET, 'id') == 'mainpage_request'){
        $where .= " AND `ID` NOT IN (".implode(",", json_decode(get_option('mainpage_ids'))).") ";
    }
    return $where;
},999,1);

//Фильтр для отсеивания в рекомендациях публикаций с чеком "Не показывать в рекомендуемом"
add_filter('posts_where', 'related_request_filter', 10, 2);
function related_request_filter($where, $wp_query) {
    global $wpdb;
    if(!mb_strrpos($wpdb->last_query,'yarpp')){ return $where; }
    $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_from_related' AND `meta_value` = '1') AND `post_type` ";
    return $where;
}

//Фильтр для отсеивания из фида Дзена публикаций с чеком "Не отправлять в Дзен"
add_filter( 'posts_where', 'zen_feed_request_filter', 10, 2 );
function zen_feed_request_filter($where, $query){
    //$yzen_options = get_option('yzen_options');
    //if (array_values(array_filter(explode('/', esc_sql($_SERVER['REQUEST_URI']))))[1] == $yzen_options['yzrssname'] && $query->query['posts_per_page'] == $yzen_options['yznumber']){
    if(is_zen() && is_feed()){
        $where = " AND `wp_posts`.`ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` where `meta_key` = 'yzrssenabled_meta_value' AND `meta_value` = 'yes' ) ";
        $where .= " AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id') ";
        $where .= " AND `post_type` IN ('anew','profile_article','yellow') ";
        $where .= " AND ( ( wp_posts.post_status = 'publish' ) ) ";
    }
    return $where;
}



//Фильтр для фида избранных материалов
add_filter( 'posts_where', 'featured_feed_request_filter', 10, 2 );
function featured_feed_request_filter($where, $query){
    if(array_key_exists('feed',$query->query)){
        if ($query->query['feed'] == get_option('ff_options', false)['url']){
            $where .= " AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'featured_teaser') ";
        }
    }
    return $where;
}




add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' );
function prefix_filter_canonical_example( $canonical ) {
    if(
        strpos(filter_input(INPUT_SERVER, 'REQUEST_URI'), '/events/') === false
        ||
        strlen(str_replace('events','',preg_replace('/[0-9\-\/]/', '', filter_input(INPUT_SERVER, 'REQUEST_URI')))) !== 0
    ) {
        return $canonical;
    } else {

        $canonical = 'https://profile.ru/events/';

    }


    return $canonical;
}



































function filter_by_the_author() {
    $params = array(
        'name' => 'author', // this is the "name" attribute for filter <select>
        'show_option_all' => 'Все авторы' // label for all authors (display posts without filter)
    );

    if ( isset($_GET['user']) )
        $params['selected'] = $_GET['user']; // choose selected user by $_GET variable

    wp_dropdown_users( $params ); // print the ready author list
}

add_action('restrict_manage_posts', 'filter_by_the_author');



//add_filter( 'posts_where', 'hide_cars_from_feed', 10, 1 );
function hide_cars_from_feed($where) {
    if(is_feed() || is_yn()){
        $where .= " AND `wp_posts`.`ID` NOT IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 3386 AND `object_id` <= 194172 ) ";
    }
    return $where;
}

add_filter ('posts_where', 'ynrss_exclude', 10, 1);
function ynrss_exclude($where){
    if(is_yn()){
        $where .= " AND `wp_posts`.`ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'ynrss_exclude' AND `meta_value` = 1) ";
    }
    return $where;
}

add_filter ('posts_where', 'gnrss_exclude', 10, 1);
function gnrss_exclude($where){
    $options = get_option('gnf_options');
    $array = explode("/", $_SERVER['REQUEST_URI']);
    if((is_feed() && $options['url'] == array_pop($array)) || stripos($_SERVER['REQUEST_URI'], '/feed/gn') !== false){
        $where .= " AND `wp_posts`.`ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'gnrss_exclude' AND `meta_value` = 1) ";
    }
    return $where;
}






//Когда будешь делать нормальный фильтр по авторам, убери нахуй этот ебаный костыль
add_filter('posts_where', 'legolas_where');
function legolas_where($where){
    if (!in_array(get_current_user_id(),array(1,58))){return $where;}
    if(filter_input(INPUT_GET, 'guest_author') == "profile" && is_admin()){
        $where .= ' AND ID in (SELECT object_id FROM wp_term_relationships where term_taxonomy_id in (7511, 3520)) ';
    }

    return $where;
}



function legolas_add_taxonomy_filters() {
    if (!in_array(get_current_user_id(),array(1,58))){return;}
    echo '<input type="button" value="Автор: Профиль" class="button" onclick="window.location.replace(document.URL+\'&guest_author=profile\')" />';
}
add_action( 'restrict_manage_posts', 'legolas_add_taxonomy_filters' );

function datesort_add_default_filter(){
    echo '<input type="hidden" name="orderby" value="date" />';
    echo '<input type="hidden" name="order" value="desc" />';
}
add_action( 'restrict_manage_posts', 'datesort_add_default_filter' );






//Кобзев не загружает картинки больше 500КБ (хотя и это слишком много)
add_filter('upload_size_limit', 'upload_size_lim', 10, 3);
function upload_size_lim($size, $u_bytes, $p_bytes){
    if (in_array(get_current_user_id(), array(17))){
        $size = 512000;
    }
    return $size;
}
//Ресайз фреймов с врезами
add_filter( 'the_content', 'responsive_embeds' );
function responsive_embeds( $content ) {
    $content = str_replace('sandbox="allow-scripts"', 'sandbox="allow-same-origin allow-top-navigation allow-scripts"', $content);
    return $content;
}


//Отключили сжатие картинок
add_filter( 'jpeg_quality', function( $quality ){
    return 100;
});

//Настройки автора!
function author_settings_meta_box() {
    $screens = array( 'guest-author' );
    foreach ( $screens as $screen ) {
        add_meta_box(
            'author_settings',
            __( 'Настройки', 'author_settings' ),
            'create_custom_fields',
            $screen
        );
    }
}
add_action( 'add_meta_boxes', 'author_settings_meta_box' );




add_filter('layf_content_feed', 'remove_blockquotes');
function remove_blockquotes($content){
    $content = preg_replace('~<blockquote(.*?)</blockquote>~Usi', "", $content);
    return $content;
}

add_filter('the_content', 'remove_blockquotes_from_feed');
function remove_blockquotes_from_feed($content){
    if(is_feed()) {
        $content = preg_replace('~<blockquote(.*?)</blockquote>~Usi', "", $content);
        $content = preg_replace('~<p><iframe class(.*?)</iframe></p>~Usi', "", $content);
    }
    return $content;
}

add_filter( 'mce_external_plugins', 'quot_add_buttons' );
add_filter( 'mce_buttons', 'quot_register_buttons' );
function quot_add_buttons( $plugin_array ) {
    $plugin_array['add_quotes'] = get_stylesheet_directory_uri().'/assets/js/vendor/tinymce/tinymce_quotebutton.js';
    return $plugin_array;
}
function quot_register_buttons( $buttons ) {
    array_push( $buttons, 'open_quote' );
    array_push( $buttons, 'close_quote' );
    return $buttons;
}




function is_turbo(){
    if(strripos(filter_input(INPUT_SERVER,'REQUEST_URI'),get_option('mytf_options')['url']) !== false){
        return true;
    }
    return false;
}

add_filter('the_content', 'clear_dom',100000);
function clear_dom($content){
    $content = str_replace(
        array(
            '<html><head><meta http-equiv="Content-Type" content="charset=utf-8">',
            '</head><body>',
            '</body></html>'
        ),
        '',
        $content
    );

    return $content;

}

//TODO: Перенести в темплейты
add_filter('the_content', 'ad_inread_archive',20);
function ad_inread_archive($content) {
    if ((int)get_option('show_ad') == 1) {
        if (get_post_type() == 'archive') {
            $ps = explode("\n", $content);
            $ps[2] .= "
            <!--montemedia-->
            <!--Площадка: profile.ru / desktop / 785x desktop-->
            <!--Категория: <не задана>-->
            <!--Тип баннера: Перетяжка 100%-->
            <div id=\"adfox_163361840755876626\"></div>
            <script>
                window.yaContextCb.push(()=>{
                    Ya.adfoxCode.create({
                        ownerId: 242477,
                        containerId: 'adfox_163361840755876626',
                        params: {
                            p1: 'cjhzz',
                            p2: 'y'
                        }
                    })
                })
            </script>
        ";
            $content = implode("<p>", $ps);
        }
    }
    return $content;
}


add_action( 'wp_insert_post', 'send_telegram', 10, 1 );
function send_telegram($post) {
    
    $post = get_post($post);

    $post_id = $post->ID;


    if(
        (!in_array(get_post_type($post_id), array('anew', 'yellow', 'profile_article'))) || ((bool)(get_post_meta($post_id,'_sended_telegram', true))) || (get_post_status($post_id) !== 'publish')){
        return;
    }

    $bot_id = "1108783670:AAGm7_vdXQAte25OGUa5gWJNXhy5-v6d_hU";
    $post_id = (is_object($post_id)) ? $post_id->ID : $post_id;

    // Получаем и проверяем ссылку
    $curr_url = get_permalink($post_id);
    if (empty($curr_url)) {
        error_log('Telegram bot: Empty permalink for post ID ' . $post_id);
        return;
    }

    $curr_url = fix_broken_url($curr_url, 'profile.ru'); //корректируем ссылку с ошиюбками



    if(has_tag(103565, $post_id)){
        $chat_id = "-1001241573514";//идентификатор канала profile_lifestyle


        $text = '<a href="' . $curr_url . '?utm_from=telegram">' . get_the_title($post_id) . '</a>';
        $text = str_replace('admin.', '', $text);
        $request = "https://api.telegram.org/bot" . $bot_id . "/sendMessage?chat_id=" . $chat_id . "&parse_mode=HTML&text=" . urlencode($text);

        update_post_meta($post_id, '_sended_telegram', '1');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
            

    }else{
        if(
            (((bool)filter_input(INPUT_POST,'_send_telegram'))
                ||
                ((bool)get_post_meta($post_id,'_send_telegram', true)))
        ){

            $chat_id = "-1001365682276";//идентификатор канала profile_news

            $text = '<a href="'.$curr_url.'?utm_from=telegram">'.get_the_title($post_id).'</a>';
            $text = str_replace('admin.', '', $text);
            $request = "https://api.telegram.org/bot".$bot_id."/sendMessage?chat_id=".$chat_id."&parse_mode=HTML&text=".urlencode($text);

            update_post_meta( $post_id, '_sended_telegram', '1' );
            update_option('last_telegram_message', date("U"));

            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL, $request);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);

        }
    }

    return true;


}




add_filter('pre_get_posts', 'hide_posts_from_editor', 10, 1);
function hide_posts_from_editor($query){
    if(is_admin() && in_array(get_current_user_id(), array(57) ) ){
        $notinArray = array();
        foreach((array)json_decode(get_option('ppp_options')) as $item){
            if($item->count > 100){
                array_push($notinArray, $item->id);
            }
        }
        $query->set('post__not_in', $notinArray);
    }
    return $query;
}


//другу
add_action( 'wp_login', 'auth_fn', 10, 2 );
function auth_fn( $user_login, $user ){
    if (in_array($user->data->ID, array(17)) && !wp_is_mobile()){
        $meta = (int)get_user_meta($user->data->ID, 'has_cookie', true);
        update_post_meta($user->data->ID, 'has_cookie', ($meta+1));
    }
}




function profile_custom_fields( $item_id, $item ) {

    wp_nonce_field( 'menu_item_color_nonce', '_menu_item_color_nonce_name' );
    $menu_item_color = get_post_meta( $item_id, '_menu_item_color', true );

    $colors = array(
        "black" => "Черный",
        "yellow" => "Желтый",
        "blue" => "Синий",
        "green" => "Зеленый",
        "red" => "Красный",
        "orange" => "Оранжевый",
        "gray" => "Серый",
        "indigo" => "Индиго",
        "purple" => "Пурпурный",
        "pink" => "Розовый",
        "teal" => "Биюзовый",
        "cyan" => "Циан",
        "white" => "Белый",
        "gray-dark" => "Темно-серый",
        "light" => "Магнолия",
        "dark" => "Космос"
    );

    ?>

    <input type="hidden" name="custom-menu-meta-nonce" value="<?php echo wp_create_nonce( 'custom-menu-meta-name' ); ?>" />

    <div class="field-menu_item_color description-wide" style="margin: 5px 0;">
        <span class="description"><?php _e( "Цвет пункта меню", 'custom-menu-meta' ); ?></span>
        <br />

        <input type="hidden" class="nav-menu-id" value="<?php echo $item_id ;?>" />

        <div class="logged-input-holder">
            <select name="menu_item_color[<?php echo $item_id ;?>]" id="custom-menu-meta-for-<?php echo $item_id ;?>" value="<?php echo esc_attr( $menu_item_color ); ?>" >
                <?php
                foreach ($colors as $value => $text){
                    $selected = $menu_item_color == $value ? " selected " : "";
                    echo '<option value="'.$value.'"'.$selected.'>'.$text.'</option>';
                }
                ?>
            </select>
        </div>

    </div>

    <?php
}
add_action( 'wp_nav_menu_item_custom_fields', 'profile_custom_fields', 10, 2 );



function profile_nav_update( $menu_id, $menu_item_db_id ) {

    // Verify this came from our screen and with proper authorization.
    if ( ! isset( $_POST['_menu_item_color_nonce_name'] ) || ! wp_verify_nonce( $_POST['_menu_item_color_nonce_name'], 'menu_item_color_nonce' ) ) {
        return $menu_id;
    }

    if ( isset( $_POST['menu_item_color'][$menu_item_db_id]  ) ) {
        $sanitized_data = sanitize_text_field( $_POST['menu_item_color'][$menu_item_db_id] );
        update_post_meta( $menu_item_db_id, '_menu_item_color', $sanitized_data );
    } else {
        delete_post_meta( $menu_item_db_id, '_menu_item_color' );
    }
}
add_action( 'wp_update_nav_menu_item', 'profile_nav_update', 10, 2 );

function profile_custom_menu_title( $title, $item ) {

    if( is_object( $item ) && isset( $item->ID ) ) {

        $menu_item_color = get_post_meta( $item->ID, '_menu_item_color', true );

        if ( ! empty( $menu_item_color ) ) {
            $title .= ' - ' . $menu_item_color;
        }
    }
    return $title;
}
add_filter( 'nav_menu_item_title', 'profile_custom_menu_title', 10, 2 );



function hex2rgba($color, $opacity = false) {

    $default = 'rgb(0,0,0)';

    //Return default if no color provided
    if(empty($color))
        return $default;

    //Sanitize $color if "#" is provided
    if ($color[0] == '#' ) {
        $color = substr( $color, 1 );
    }

    //Check if color has 6 or 3 characters and get values
    if (strlen($color) == 6) {
        $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
    } elseif ( strlen( $color ) == 3 ) {
        $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
    } else {
        return $default;
    }

    //Convert hexadec to rgb
    $rgb =  array_map('hexdec', $hex);

    //Check if opacity is set(rgba or rgb)
    if($opacity !== false){
        if(abs($opacity) > 1)
            $opacity = 1.0;
        $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
    } else {
        $output = 'rgb('.implode(",",$rgb).')';
    }

    //Return rgb(a) color string
    return $output;
}


function ml_upload_image(){

    if ( !current_user_can('edit_posts') ) return;

    $mime = !empty( $_POST['imgMime'] ) ? $_POST['imgMime'] : null;
    if ( 'null' === $mime ) $mime = null;

    $name = !empty( $_POST['imgName'] ) ? $_POST['imgName'] : null;
    if ( 'null' === $name ) $name = null;

    $parentId = isset( $_POST['imgParent'] ) ? intval($_POST['imgParent']) : 0;
    $ref = isset( $_POST['imgRef'] ) ? $_POST['imgRef'] : false;

    if ( empty($mime) ) {
        if ( !empty( $_POST['file'] ) && preg_match('/image\/[a-z0-9]+/', $_POST['file'], $matches) ) {
            $mime = $matches[0];
        } else {
            factory_325_json_error('Unable to get mime type of the file.');
        }
    }

    // gets extension
    $parts = explode('/', $mime);
    $ext = empty( $parts[1] ) ? 'png' : $parts[1];

    if ( !in_array( $ext, array('png', 'jpeg', 'jpg', 'gif', 'tiff', 'bmp') ) ) {
        factory_325_json_error('Sorry, only following types of images allowed to paste: png, jpeg, jpg, gif, tiff, bmp');
    }

    // check the path to upload
    $uploadInfo = wp_upload_dir();
    $targetPath = $uploadInfo['path'];
    if ( !is_dir($targetPath) ) mkdir($targetPath, 0777, true);

    // move the uploaded file to the upload path
    $imageName = ( !empty($name) && $name !== 'undefined' )
        ? factory_325_filename_without_ext($name)
        : 'img_' . uniqid();

    $target = $targetPath . '/' . $imageName . '.' . $ext;

    if ( isset( $_FILES['file'] ) ) {

        if ( empty( $_FILES['file']['size'] ) ) {
            factory_325_json_error('[A] Sorry, the error of reading image data occured. May be the image is empty or has incorrect format.');
        }

        $source = $_FILES['file']['tmp_name'];

        $image = imagecreatefrompng($source);
        imagejpeg($image, $target, 75);
        imagedestroy($image);

        //move_uploaded_file($source, $target);

    } else {
        if ( preg_match('/base64,(.*)/', $_POST['file'], $matches) ) {
            $img = str_replace(' ', '+', $matches[1]);
            $data = base64_decode($img);

            if ( empty($data) ) {
                factory_325_json_error('[B] Sorry, the error of reading image data occured. May be the image is empty or has incorrect format.');
            }

            if ( !is_dir($targetPath) ) {
                factory_325_json_error("Unable to save the image. Unable to create the folder '$targetPath'.");
            }

            if ( !is_writable($targetPath) ) {
                factory_325_json_error("Unable to save the image. The folder '$targetPath' is not writable.");
            }

            if ( is_file($target) ) {
                factory_325_json_error("Unable to save the image. The file '$target' already exists.");
            }

            $success = file_put_contents($target, $data);
            if ( !$success ) {

                if ( is_file( $target ) ) {

                    $filesize = filesize( $target );
                    if ( $filesize == 0 ) {
                        factory_325_json_error('Unable to save the image. The file is not writable');
                    } else {
                        // looks everything is fine O_o
                    }

                } else {
                    factory_325_json_error('Unable to save the image.');
                }
            }

        } else {
            factory_325_json_error('Incorrect file format (base64).');
        }
    }

    $media = array();
    $media['base'] = array(
        'guid' => $uploadInfo['url'] . '/' . $imageName . '.' . $ext,
        'path' => $target,
        'name' => $imageName
    );

    $resizingEnabled = false;
    $compressionEnabled = false;



    // for the function wp_generate_attachment_metadata() to work
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    foreach( $media as $key => $item ) {

        $attachment = array(
            'guid' => $item['guid'],
            'post_mime_type' => $mime,
            'post_title' => $item['name'],
            'post_name' => $item['name'],
            'post_content' => '',
            'post_status' => 'inherit',
        );

        $media[$key]['id'] = wp_insert_attachment( $attachment, $item['path'], $parentId );

        $attach_data = wp_generate_attachment_metadata( $media[$key]['id'], $item['path'] );
        wp_update_attachment_metadata( $media[$key]['id'], $attach_data );
    }

    $id = $media['base']['id'];
    $cssClasses = ' ' . trim( get_option( 'imgevr_css_class', '' ) );

    if ( !empty( $id ) ) {
        $html = "<img loading='lazy' alt='' class='alignnone size-full wp-image-" . $id . $cssClasses . "' src='" . $media['base']['guid'] . "' />";
    } else {
        $html = "<img loading='lazy' alt='' class='alignnone size-full" . $cssClasses . "' src='" . $media['base']['guid'] . "' />";
    }

    $linksEnabled = get_option( 'imgevr_links_enable', false );
    if ( $linksEnabled ) {
        $saveOriginal = get_option('imgevr_resizing_save_original', false);

        if ( $resizingEnabled && $saveOriginal ) {
            $html = "<a href='" . $media['original']['guid'] . "'>" . $html . '</a>';
        } else {
            $html = "<a href='" . $media['base']['guid'] . "'>" . $html . '</a>';
        }
    }

    $result = array(
        'html' => $html
    );

    echo json_encode($result);
    exit;
}

add_action('wp_ajax_ml_insert_upload', 'ml_upload_image', 1);





function my_prepare_attachment_for_js($response, $attachment, $meta) {
    //debug($_POST);

    $sizes = array();

    $post = filter_input_array(INPUT_POST);
    $get = filter_input_array(INPUT_GET);
    $server = filter_input_array(INPUT_SERVER);
    $screen = get_current_screen();

    foreach($meta['sizes'] as $key => $size){
        $sizes[str_replace('-', '_', $key)] = $size;
    }

    $response['all_sizes'] = $sizes;
    $response['apply_filter'] = (strripos(explode('?', filter_input(INPUT_SERVER, 'HTTP_REFERER'))[0], 'upload.php') !== false || ($post['action'] == 'query-attachments' && $post['post_id'] > 0 && $post['query']['post_mime_type'] == 'image')) ? true : false;


    //return false;
    //debug($array);
    return $response;
};

// add the action
add_filter('wp_prepare_attachment_for_js', 	'my_prepare_attachment_for_js', 11, 3);




function custom_print_media_templates() {
    remove_action( 'admin_footer', 'wp_print_media_templates' );
    remove_action( 'wp_footer', 'wp_print_media_templates' );
    remove_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );

    add_action( 'admin_footer', 'my_print_media_templates' );
    add_action( 'wp_footer', 'my_print_media_templates' );
    add_action( 'customize_controls_print_footer_scripts', 'my_print_media_templates' );
}
add_action( 'wp_enqueue_media', 'custom_print_media_templates' );






function my_print_media_templates() {
    global $is_IE;
    $class = 'media-modal wp-core-ui';
    if ( $is_IE && strpos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 7' ) !== false ) {
        $class .= ' ie7';
    }

    $alt_text_description = sprintf(
    /* translators: 1: Link to tutorial, 2: Additional link attributes, 3: Accessibility text. */
        __( '<a href="%1$s" %2$s>Describe the purpose of the image%3$s</a>. Leave empty if the image is purely decorative.' ),
        esc_url( 'https://www.w3.org/WAI/tutorials/images/decision-tree' ),
        'target="_blank" rel="noopener noreferrer"',
        sprintf(
            '<span class="screen-reader-text"> %s</span>',
            /* translators: Accessibility text. */
            __( '(opens in a new tab)' )
        )
    );
    ?>

    <?php // Template for the media frame: used both in the media grid and in the media modal. ?>
    <script type="text/html" id="tmpl-media-frame">
        <div class="media-frame-title" id="media-frame-title"></div>
        <h2 class="media-frame-menu-heading"><?php _ex( 'Actions', 'media modal menu actions' ); ?></h2>
        <button type="button" class="button button-link media-frame-menu-toggle" aria-expanded="false">
            <?php _ex( 'Menu', 'media modal menu' ); ?>
            <span class="dashicons dashicons-arrow-down" aria-hidden="true"></span>
        </button>
        <div class="media-frame-menu"></div>
        <div class="media-frame-tab-panel">
            <div class="media-frame-router"></div>
            <div class="media-frame-content"></div>
        </div>
        <h2 class="media-frame-actions-heading screen-reader-text">
            <?php
            /* translators: Accessibility text. */
            _e( 'Selected media actions' );
            ?>
        </h2>
        <div class="media-frame-toolbar"></div>
        <div class="media-frame-uploader"></div>
    </script>

    <?php // Template for the media modal. ?>
    <script type="text/html" id="tmpl-media-modal">
        <div tabindex="0" class="<?php echo $class; ?>" role="dialog" aria-labelledby="media-frame-title">
            <# if ( data.hasCloseButton ) { #>
            <button type="button" class="media-modal-close"><span class="media-modal-icon"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></span></button>
            <# } #>
            <div class="media-modal-content" role="document"></div>
        </div>
        <div class="media-modal-backdrop"></div>
    </script>

    <?php // Template for the window uploader, used for example in the media grid. ?>
    <script type="text/html" id="tmpl-uploader-window">
        <div class="uploader-window-content">
            <div class="uploader-editor-title"><?php _e( 'Drop files to upload' ); ?></div>
        </div>
    </script>

    <?php // Template for the editor uploader. ?>
    <script type="text/html" id="tmpl-uploader-editor">
        <div class="uploader-editor-content">
            <div class="uploader-editor-title"><?php _e( 'Drop files to upload' ); ?></div>
        </div>
    </script>

    <?php // Template for the inline uploader, used for example in the Media Library admin page - Add New. ?>
    <script type="text/html" id="tmpl-uploader-inline">
        <# var messageClass = data.message ? 'has-upload-message' : 'no-upload-message'; #>
        <# if ( data.canClose ) { #>
        <button class="close dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Close uploader' ); ?></span></button>
        <# } #>
        <div class="uploader-inline-content {{ messageClass }}">
            <# if ( data.message ) { #>
            <h2 class="upload-message">{{ data.message }}</h2>
            <# } #>
            <?php if ( ! _device_can_upload() ) : ?>
                <div class="upload-ui">
                    <h2 class="upload-instructions"><?php _e( 'Your browser cannot upload files' ); ?></h2>
                    <p>
                        <?php
                        printf(
                        /* translators: %s: https://apps.wordpress.org/ */
                            __( 'The web browser on your device cannot be used to upload files. You may be able to use the <a href="%s">native app for your device</a> instead.' ),
                            'https://apps.wordpress.org/'
                        );
                        ?>
                    </p>
                </div>
            <?php elseif ( is_multisite() && ! is_upload_space_available() ) : ?>
                <div class="upload-ui">
                    <h2 class="upload-instructions"><?php _e( 'Upload Limit Exceeded' ); ?></h2>
                    <?php
                    /** This action is documented in wp-admin/includes/media.php */
                    do_action( 'upload_ui_over_quota' );
                    ?>
                </div>
            <?php else : ?>
                <div class="upload-ui">
                    <h2 class="upload-instructions drop-instructions"><?php _e( 'Drop files to upload' ); ?></h2>
                    <p class="upload-instructions drop-instructions"><?php _ex( 'or', 'Uploader: Drop files here - or - Select Files' ); ?></p>
                    <button type="button" class="browser button button-hero"><?php _e( 'Select Files' ); ?></button>
                </div>

                <div class="upload-inline-status"></div>

                <div class="post-upload-ui">
                    <?php
                    /** This action is documented in wp-admin/includes/media.php */
                    do_action( 'pre-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
                    /** This action is documented in wp-admin/includes/media.php */
                    do_action( 'pre-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

                    if ( 10 === remove_action( 'post-plupload-upload-ui', 'media_upload_flash_bypass' ) ) {
                        /** This action is documented in wp-admin/includes/media.php */
                        do_action( 'post-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
                        add_action( 'post-plupload-upload-ui', 'media_upload_flash_bypass' );
                    } else {
                        /** This action is documented in wp-admin/includes/media.php */
                        do_action( 'post-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
                    }

                    $max_upload_size = wp_max_upload_size();
                    if ( ! $max_upload_size ) {
                        $max_upload_size = 0;
                    }
                    ?>

                    <p class="max-upload-size">
                        <?php
                        printf(
                        /* translators: %s: Maximum allowed file size. */
                            __( 'Maximum upload file size: %s.' ),
                            esc_html( size_format( $max_upload_size ) )
                        );
                        ?>
                    </p>

                    <# if ( data.suggestedWidth && data.suggestedHeight ) { #>
                    <p class="suggested-dimensions">
                        <?php
                        /* translators: 1: Suggested width number, 2: Suggested height number. */
                        printf( __( 'Suggested image dimensions: %1$s by %2$s pixels.' ), '{{data.suggestedWidth}}', '{{data.suggestedHeight}}' );
                        ?>
                    </p>
                    <# } #>

                    <?php
                    /** This action is documented in wp-admin/includes/media.php */
                    do_action( 'post-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
                    ?>
                </div>
            <?php endif; ?>
        </div>
    </script>

    <?php // Template for the view switchers, used for example in the Media Grid. ?>
    <script type="text/html" id="tmpl-media-library-view-switcher">
        <a href="<?php echo esc_url( add_query_arg( 'mode', 'list', $_SERVER['REQUEST_URI'] ) ); ?>" class="view-list">
            <span class="screen-reader-text"><?php _e( 'List View' ); ?></span>
        </a>
        <a href="<?php echo esc_url( add_query_arg( 'mode', 'grid', $_SERVER['REQUEST_URI'] ) ); ?>" class="view-grid current" aria-current="page">
            <span class="screen-reader-text"><?php _e( 'Grid View' ); ?></span>
        </a>
    </script>

    <?php // Template for the uploading status UI. ?>
    <script type="text/html" id="tmpl-uploader-status">
        <h2><?php _e( 'Uploading' ); ?></h2>
        <button type="button" class="button-link upload-dismiss-errors"><span class="screen-reader-text"><?php _e( 'Dismiss Errors' ); ?></span></button>

        <div class="media-progress-bar"><div></div></div>
        <div class="upload-details">
			<span class="upload-count">
				<span class="upload-index"></span> / <span class="upload-total"></span>
			</span>
            <span class="upload-detail-separator">&ndash;</span>
            <span class="upload-filename"></span>
        </div>
        <div class="upload-errors"></div>
    </script>

    <?php // Template for the uploading status errors. ?>
    <script type="text/html" id="tmpl-uploader-status-error">
        <span class="upload-error-filename">{{{ data.filename }}}</span>
        <span class="upload-error-message">{{ data.message }}</span>
    </script>

    <?php // Template for the Attachment Details layout in the media browser. ?>
    <script type="text/html" id="tmpl-edit-attachment-frame">
        <div class="edit-media-header">
            <button class="left dashicons"<# if ( ! data.hasPrevious ) { #> disabled<# } #>><span class="screen-reader-text"><?php _e( 'Edit previous media item' ); ?></span></button>
            <button class="right dashicons"<# if ( ! data.hasNext ) { #> disabled<# } #>><span class="screen-reader-text"><?php _e( 'Edit next media item' ); ?></span></button>
            <button type="button" class="media-modal-close"><span class="media-modal-icon"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></span></button>
        </div>
        <div class="media-frame-title"></div>
        <div class="media-frame-content"></div>
    </script>

    <?php // Template for the Attachment Details two columns layout. ?>
    <script type="text/html" id="tmpl-attachment-details-two-column">
        <div class="attachment-media-view {{ data.orientation }}">
            <h2 class="screen-reader-text"><?php _e( 'Attachment Preview' ); ?></h2>
            <div class="thumbnail thumbnail-{{ data.type }}">
                <# if ( data.uploading ) { #>
                <div class="media-progress-bar"><div></div></div>
                <# } else if ( data.sizes && data.sizes.large ) { #>
                <img class="details-image" src="{{ data.sizes.large.url }}" draggable="false" alt="" />
                <# } else if ( data.sizes && data.sizes.full ) { #>
                <img class="details-image" src="{{ data.sizes.full.url }}" draggable="false" alt="" />
                <# } else if ( -1 === jQuery.inArray( data.type, [ 'audio', 'video' ] ) ) { #>
                <img class="details-image icon" src="{{ data.icon }}" draggable="false" alt="" />
                <# } #>

                <# if ( 'audio' === data.type ) { #>
                <div class="wp-media-wrapper">
                    <audio style="visibility: hidden" controls class="wp-audio-shortcode" width="100%" preload="none">
                        <source type="{{ data.mime }}" src="{{ data.url }}"/>
                    </audio>
                </div>
                <# } else if ( 'video' === data.type ) {
                var w_rule = '';
                if ( data.width ) {
                w_rule = 'width: ' + data.width + 'px;';
                } else if ( wp.media.view.settings.contentWidth ) {
                w_rule = 'width: ' + wp.media.view.settings.contentWidth + 'px;';
                }
                #>
                <div style="{{ w_rule }}" class="wp-media-wrapper wp-video">
                    <video controls="controls" class="wp-video-shortcode" preload="metadata"
                    <# if ( data.width ) { #>width="{{ data.width }}"<# } #>
                    <# if ( data.height ) { #>height="{{ data.height }}"<# } #>
                    <# if ( data.image && data.image.src !== data.icon ) { #>poster="{{ data.image.src }}"<# } #>>
                    <source type="{{ data.mime }}" src="{{ data.url }}"/>
                    </video>
                </div>
                <# } #>

                <div class="attachment-actions">
                    <# if ( 'image' === data.type && ! data.uploading && data.sizes && data.can.save ) { #>
                    <button type="button" class="button edit-attachment"><?php _e( 'Edit Image' ); ?></button>
                    <# } else if ( 'pdf' === data.subtype && data.sizes ) { #>
                    <p><?php _e( 'Document Preview' ); ?></p>
                    <# } #>
                </div>
            </div>
        </div>
        <div class="attachment-info">
			<span class="settings-save-status" role="status">
				<span class="spinner"></span>
				<span class="saved"><?php esc_html_e( 'Saved.' ); ?></span>
			</span>
            <div class="details">
                <# let fDate = new Date(data.date); fDate.setHours( fDate.getHours() + 0 ); #>
                <# data.dateF = ("00" + fDate.getDate()).slice(-2)+'.'+("00" + (fDate.getMonth() + 1)).slice(-2)+'.'+fDate.getFullYear()+' '+("00" + fDate.getHours()).slice(-2)+':'+("00" + fDate.getMinutes()).slice(-2)+':'+("00" + fDate.getSeconds()).slice(-2) #>
                <h2 class="screen-reader-text"><?php _e( 'Details' ); ?></h2>
                <div class="filename"><strong><?php _e( 'File name:' ); ?></strong> {{ data.filename }}</div>
                <div class="filename"><strong><?php _e( 'File type:' ); ?></strong> {{ data.mime }}</div>
                <div class="uploaded"><strong><?php _e( 'Uploaded on:' ); ?></strong> {{ data.dateF }}</div>


                <div class="file-size"><strong><?php _e( 'File size:' ); ?></strong> {{ data.filesizeHumanReadable }}</div>
                <# if ( 'image' === data.type && ! data.uploading ) { #>
                <# if ( data.width && data.height ) { #>
                <div class="dimensions"><strong><?php _e( 'Dimensions:' ); ?></strong>
                    <?php
                    /* translators: 1: A number of pixels wide, 2: A number of pixels tall. */
                    printf( __( '%1$s by %2$s pixels' ), '{{ data.width }}', '{{ data.height }}' );
                    ?>
                </div>
                <# } #>

                <# if ( data.originalImageURL && data.originalImageName ) { #>
                <?php _e( 'Original image:' ); ?>
                <a href="{{ data.originalImageURL }}">{{data.originalImageName}}</a>
                <# } #>
                <# } #>

                <# if ( data.fileLength && data.fileLengthHumanReadable ) { #>
                <div class="file-length"><strong><?php _e( 'Length:' ); ?></strong>
                    <span aria-hidden="true">{{ data.fileLength }}</span>
                    <span class="screen-reader-text">{{ data.fileLengthHumanReadable }}</span>
                </div>
                <# } #>

                <# if ( 'audio' === data.type && data.meta.bitrate ) { #>
                <div class="bitrate">
                    <strong><?php _e( 'Bitrate:' ); ?></strong> {{ Math.round( data.meta.bitrate / 1000 ) }}kb/s
                    <# if ( data.meta.bitrate_mode ) { #>
                    {{ ' ' + data.meta.bitrate_mode.toUpperCase() }}
                    <# } #>
                </div>
                <# } #>

                <div class="compat-meta">
                    <# if ( data.compat && data.compat.meta ) { #>
                    {{{ data.compat.meta }}}
                    <# } #>
                </div>
            </div>

            <div class="settings">
                <# var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly'; #>
                <# if ( 'image' === data.type ) { #>
                <span class="setting has-description" data-setting="alt">
						<label for="attachment-details-two-column-alt-text" class="name"><?php _e( 'Alternative Text' ); ?></label>
						<input type="text" id="attachment-details-two-column-alt-text" value="{{ data.alt }}" aria-describedby="alt-text-description" {{ maybeReadOnly }} />
					</span>
                <p class="description" id="alt-text-description"><?php echo $alt_text_description; ?></p>
                <# } #>
                <?php if ( post_type_supports( 'attachment', 'title' ) ) : ?>
                    <span class="setting" data-setting="title">
					<label for="attachment-details-two-column-title" class="name">Название</label>
					<input type="text" id="attachment-details-two-column-title" value="{{ data.title }}" {{ maybeReadOnly }} />
				</span>
                <?php endif; ?>
                <# if ( 'audio' === data.type ) { #>
                <?php
                foreach ( array(
                              'artist' => __( 'Artist' ),
                              'album'  => __( 'Album' ),
                          ) as $key => $label ) :
                    ?>
                    <span class="setting" data-setting="<?php echo esc_attr( $key ); ?>">
					<label for="attachment-details-two-column-<?php echo esc_attr( $key ); ?>" class="name"><?php echo $label; ?></label>
					<input type="text" id="attachment-details-two-column-<?php echo esc_attr( $key ); ?>" value="{{ data.<?php echo $key; ?> || data.meta.<?php echo $key; ?> || '' }}" />
				</span>
                <?php endforeach; ?>
                <# } #>
                <span class="setting" data-setting="caption">
					<label for="attachment-details-two-column-caption" class="name">Copyright</label>
					<textarea id="attachment-details-two-column-caption" {{ maybeReadOnly }}>{{ data.caption }}</textarea>
				</span>
                <span class="setting" data-setting="description">
					<label for="attachment-details-two-column-description" class="name">Подпись</label>
					<textarea id="attachment-details-two-column-description" {{ maybeReadOnly }}>{{ data.description }}</textarea>
				</span>
                <span class="setting">
					<span class="name"><?php _e( 'Uploaded By' ); ?></span>
					<span class="value">{{ data.authorName }}</span>
				</span>
                <# if ( data.uploadedToTitle ) { #>
                <span class="setting">
						<span class="name"><?php _e( 'Uploaded To' ); ?></span>
						<# if ( data.uploadedToLink ) { #>
							<span class="value"><a href="{{ data.uploadedToLink }}">{{ data.uploadedToTitle }}</a></span>
						<# } else { #>
							<span class="value">{{ data.uploadedToTitle }}</span>
						<# } #>
					</span>
                <# } #>
                <span class="setting" data-setting="url">
					<label for="attachment-details-two-column-copy-link" class="name"><?php _e( 'Copy Link' ); ?></label>
					<input type="text" id="attachment-details-two-column-copy-link" value="{{ data.url }}" readonly />
				</span>
                <div class="attachment-compat"></div>
            </div>

            <div class="actions">
                <a class="view-attachment" href="{{ data.link }}"><?php _e( 'View attachment page' ); ?></a>
                <# if ( data.can.save ) { #> |
                <a href="{{ data.editLink }}"><?php _e( 'Edit more details' ); ?></a>
                <# } #>
                <# if ( ! data.uploading && data.can.remove ) { #> |
                <?php if ( MEDIA_TRASH ) : ?>
                    <# if ( 'trash' === data.status ) { #>
                    <button type="button" class="button-link untrash-attachment"><?php _e( 'Restore from Trash' ); ?></button>
                    <# } else { #>
                    <button type="button" class="button-link trash-attachment"><?php _e( 'Move to Trash' ); ?></button>
                    <# } #>
                <?php else : ?>
                    <button type="button" class="button-link delete-attachment"><?php _e( 'Delete Permanently' ); ?></button>
                <?php endif; ?>
                <# } #>
            </div>
        </div>
    </script>

    <?php // Template for the Attachment "thumbnails" in the Media Grid. ?>
    <script type="text/html" id="tmpl-attachment">
        <div class="attachment-preview js--select-attachment type-{{ data.type }} subtype-{{ data.subtype }} {{ data.orientation }}">
            <div class="thumbnail">
                <# if(typeof data.all_sizes !== "undefined") { #>
                <# if(typeof data.all_sizes.post_thumbnail !== "undefined") { #>
                <# if(Math.abs((data.all_sizes.post_thumbnail.width/data.all_sizes.post_thumbnail.height)/(1.777777777777777777777/100)-100) > 5 && data.apply_filter){ #>
                <div style="position:absolute;left:0;top:30%:0;width:100%;text-align:center;fint-size:10px;z-index:3;">
                    Не подходит в качестве заходного
                </div>
                <# } #>
                <# } #>
                <# } #>
                <# if ( data.uploading ) { #>
                <div class="media-progress-bar"><div style="width: {{ data.percent }}%"></div></div>
                <# } else if ( 'image' === data.type && data.sizes ) { #>
                <# if ( data.apply_filter ) { #>
                <div class="centered" <# if(typeof data.all_sizes !== "undefined") { #><# if(typeof data.all_sizes.post_thumbnail !== "undefined") { #><# if(Math.abs((data.all_sizes.post_thumbnail.width/data.all_sizes.post_thumbnail.height)/(1.777777777777777777777/100)-100) > 5){ #> style="opacity:0.2"<# } #><# } #><# } #>>
                <img src="{{ data.size.url }}" draggable="false" alt="" />
            </div>
            <# } else { #>
            <div class="centered">
                <img src="{{ data.size.url }}" draggable="false" alt="" />
            </div>
            <# } #>
            <# } else { #>
            <div class="centered">
                <# if ( data.image && data.image.src && data.image.src !== data.icon ) { #>
                <img src="{{ data.image.src }}" class="thumbnail" draggable="false" alt="" />
                <# } else if ( data.sizes && data.sizes.medium ) { #>
                <img src="{{ data.sizes.medium.url }}" class="thumbnail" draggable="false" alt="" />
                <# } else { #>
                <img src="{{ data.icon }}" class="icon" draggable="false" alt="" />
                <# } #>
            </div>
            <div class="filename">
                <div>{{ data.filename }}</div>
            </div>
            <# } #>
        </div>
        <# if ( data.buttons.close ) { #>
        <button type="button" class="button-link attachment-close media-modal-icon"><span class="screen-reader-text"><?php _e( 'Remove' ); ?></span></button>
        <# } #>
        </div>
        <# if ( data.buttons.check ) { #>
        <button type="button" class="check" tabindex="-1"><span class="media-modal-icon"></span><span class="screen-reader-text"><?php _e( 'Deselect' ); ?></span></button>
        <# } #>
        <#
        var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly';
        if ( data.describe ) {
        if ( 'image' === data.type ) { #>
        <input type="text" value="{{ data.caption }}" class="describe" data-setting="caption"
               aria-label="<?php esc_attr_e( 'Caption' ); ?>"
               placeholder="<?php esc_attr_e( 'Caption&hellip;' ); ?>" {{ maybeReadOnly }} />
        <# } else { #>
        <input type="text" value="{{ data.title }}" class="describe" data-setting="title"
        <# if ( 'video' === data.type ) { #>
        aria-label="<?php esc_attr_e( 'Video title' ); ?>"
        placeholder="<?php esc_attr_e( 'Video title&hellip;' ); ?>"
        <# } else if ( 'audio' === data.type ) { #>
        aria-label="<?php esc_attr_e( 'Audio title' ); ?>"
        placeholder="<?php esc_attr_e( 'Audio title&hellip;' ); ?>"
        <# } else { #>
        aria-label="<?php esc_attr_e( 'Media title' ); ?>"
        placeholder="<?php esc_attr_e( 'Media title&hellip;' ); ?>"
        <# } #> {{ maybeReadOnly }} />
        <# }
        } #>
    </script>

    <?php // Template for the Attachment details, used for example in the sidebar. ?>
    <script type="text/html" id="tmpl-attachment-details">
        <h2>
            <?php _e( 'Attachment Details' ); ?>
            <span class="settings-save-status" role="status">
				<span class="spinner"></span>
				<span class="saved"><?php esc_html_e( 'Saved.' ); ?></span>
			</span>
        </h2>
        <div class="attachment-info">
            <div class="thumbnail thumbnail-{{ data.type }}">
                <# if ( data.uploading ) { #>
                <div class="media-progress-bar"><div></div></div>
                <# } else if ( 'image' === data.type && data.sizes ) { #>
                <img src="{{ data.size.url }}" draggable="false" alt="" />
                <# } else { #>
                <img src="{{ data.icon }}" class="icon" draggable="false" alt="" />
                <# } #>
            </div>
            <div class="details">
                <div class="filename">{{ data.filename }}</div>
                <div class="uploaded">{{ data.dateFormatted }}</div>

                <div class="file-size">{{ data.filesizeHumanReadable }}</div>
                <# if ( 'image' === data.type && ! data.uploading ) { #>
                <# if ( data.width && data.height ) { #>
                <div class="dimensions">
                    <?php
                    /* translators: 1: A number of pixels wide, 2: A number of pixels tall. */
                    printf( __( '%1$s by %2$s pixels' ), '{{ data.width }}', '{{ data.height }}' );
                    ?>
                </div>
                <# } #>

                <# if ( data.originalImageURL && data.originalImageName ) { #>
                <?php _e( 'Original image:' ); ?>
                <a href="{{ data.originalImageURL }}">{{data.originalImageName}}</a>
                <# } #>

                <# if ( data.can.save && data.sizes ) { #>
                <a class="edit-attachment" href="{{ data.editLink }}&amp;image-editor" target="_blank"><?php _e( 'Edit Image' ); ?></a>
                <# } #>
                <# } #>

                <# if ( data.fileLength && data.fileLengthHumanReadable ) { #>
                <div class="file-length"><?php _e( 'Length:' ); ?>
                    <span aria-hidden="true">{{ data.fileLength }}</span>
                    <span class="screen-reader-text">{{ data.fileLengthHumanReadable }}</span>
                </div>
                <# } #>

                <# if ( ! data.uploading && data.can.remove ) { #>
                <?php if ( MEDIA_TRASH ) : ?>
                    <# if ( 'trash' === data.status ) { #>
                    <button type="button" class="button-link untrash-attachment"><?php _e( 'Restore from Trash' ); ?></button>
                    <# } else { #>
                    <button type="button" class="button-link trash-attachment"><?php _e( 'Move to Trash' ); ?></button>
                    <# } #>
                <?php else : ?>
                    <button type="button" class="button-link delete-attachment"><?php _e( 'Delete Permanently' ); ?></button>
                <?php endif; ?>
                <# } #>

                <div class="compat-meta">
                    <# if ( data.compat && data.compat.meta ) { #>
                    {{{ data.compat.meta }}}
                    <# } #>
                </div>
            </div>
        </div>
        <# var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly'; #>
        <# if ( 'image' === data.type ) { #>
        <span class="setting has-description" data-setting="alt">
				<label for="attachment-details-alt-text" class="name"><?php _e( 'Alt Text' ); ?></label>
				<input type="text" id="attachment-details-alt-text" value="{{ data.alt }}" aria-describedby="alt-text-description" {{ maybeReadOnly }} />
			</span>
        <p class="description" id="alt-text-description"><?php echo $alt_text_description; ?></p>
        <# } #>
        <?php if ( post_type_supports( 'attachment', 'title' ) ) : ?>
            <span class="setting" data-setting="title">
			<label for="attachment-details-title" class="name">Название</label>
			<input type="text" id="attachment-details-title" value="{{ data.title }}" {{ maybeReadOnly }} />
		</span>
        <?php endif; ?>
        <# if ( 'audio' === data.type ) { #>
        <?php
        foreach ( array(
                      'artist' => __( 'Artist' ),
                      'album'  => __( 'Album' ),
                  ) as $key => $label ) :
            ?>
            <span class="setting" data-setting="<?php echo esc_attr( $key ); ?>">
			<label for="attachment-details-<?php echo esc_attr( $key ); ?>" class="name"><?php echo $label; ?></label>
			<input type="text" id="attachment-details-<?php echo esc_attr( $key ); ?>" value="{{ data.<?php echo $key; ?> || data.meta.<?php echo $key; ?> || '' }}" />
		</span>
        <?php endforeach; ?>
        <# } #>
        <span class="setting" data-setting="caption">
			<label for="attachment-details-caption" class="name">Copyright</label>
			<textarea id="attachment-details-caption" {{ maybeReadOnly }}>{{ data.caption }}</textarea>
		</span>
        <span class="setting" data-setting="description">
			<label for="attachment-details-description" class="name">Подпись</label>
			<textarea id="attachment-details-description" {{ maybeReadOnly }}>{{ data.description }}</textarea>
		</span>
        <span class="setting" data-setting="url">
			<label for="attachment-details-copy-link" class="name"><?php _e( 'Copy Link' ); ?></label>
			<input type="text" id="attachment-details-copy-link" value="{{ data.url }}" readonly />
		</span>
    </script>

    <?php // Template for the Selection status bar. ?>
    <script type="text/html" id="tmpl-media-selection">
        <div class="selection-info">
            <span class="count"></span>
            <# if ( data.editable ) { #>
            <button type="button" class="button-link edit-selection"><?php _e( 'Edit Selection' ); ?></button>
            <# } #>
            <# if ( data.clearable ) { #>
            <button type="button" class="button-link clear-selection"><?php _e( 'Clear' ); ?></button>
            <# } #>
        </div>
        <div class="selection-view"></div>
    </script>

    <?php // Template for the Attachment display settings, used for example in the sidebar. ?>
    <script type="text/html" id="tmpl-attachment-display-settings">
        <h2><?php _e( 'Attachment Display Settings' ); ?></h2>

        <# if ( 'image' === data.type ) { #>
        <span class="setting align">
				<label for="attachment-display-settings-alignment" class="name"><?php _e( 'Alignment' ); ?></label>
				<select id="attachment-display-settings-alignment" class="alignment"
                        data-setting="align"
					<# if ( data.userSettings ) { #>
						data-user-setting="align"
					<# } #>>

					<option value="left">
						<?php esc_html_e( 'Left' ); ?>
					</option>
					<option value="center">
						<?php esc_html_e( 'Center' ); ?>
					</option>
					<option value="right">
						<?php esc_html_e( 'Right' ); ?>
					</option>
					<option value="none" selected>
						<?php esc_html_e( 'None' ); ?>
					</option>
            </select>
			</span>
        <# } #>

        <span class="setting">
			<label for="attachment-display-settings-link-to" class="name">
				<# if ( data.model.canEmbed ) { #>
                <?php _e( 'Embed or Link' ); ?>
                <# } else { #>
                <?php _e( 'Link To' ); ?>
                <# } #>
			</label>
			<select id="attachment-display-settings-link-to" class="link-to"
                    data-setting="link"
				<# if ( data.userSettings && ! data.model.canEmbed ) { #>
					data-user-setting="urlbutton"
				<# } #>>

			<# if ( data.model.canEmbed ) { #>
				<option value="embed" selected>
					<?php esc_html_e( 'Embed Media Player' ); ?>
				</option>
				<option value="file">
			<# } else { #>
				<option value="none" selected>
					<?php esc_html_e( 'None' ); ?>
				</option>
				<option value="file">
			<# } #>
				<# if ( data.model.canEmbed ) { #>
                    <?php esc_html_e( 'Link to Media File' ); ?>
                    <# } else { #>
                    <?php esc_html_e( 'Media File' ); ?>
                    <# } #>
				</option>
				<option value="post">
				<# if ( data.model.canEmbed ) { #>
                    <?php esc_html_e( 'Link to Attachment Page' ); ?>
                    <# } else { #>
                    <?php esc_html_e( 'Attachment Page' ); ?>
                    <# } #>
				</option>
			<# if ( 'image' === data.type ) { #>
				<option value="custom">
					<?php esc_html_e( 'Custom URL' ); ?>
				</option>
			<# } #>
            </select>
		</span>
        <span class="setting">
			<label for="attachment-display-settings-link-to-custom" class="name"><?php _e( 'URL' ); ?></label>
			<input type="text" id="attachment-display-settings-link-to-custom" class="link-to-custom" data-setting="linkUrl" />
		</span>

        <# if ( 'undefined' !== typeof data.sizes ) { #>
        <span class="setting">
				<label for="attachment-display-settings-size" class="name"><?php _e( 'Size' ); ?></label>
				<select id="attachment-display-settings-size" class="size" name="size"
                        data-setting="size"
					<# if ( data.userSettings ) { #>
						data-user-setting="imgsize"
					<# } #>>
            <?php
            /** This filter is documented in wp-admin/includes/media.php */
            $sizes = apply_filters(
                'image_size_names_choose',
                array(
                    #'thumbnail' => __( 'Thumbnail' ),
                    #'medium'    => __( 'Medium' ),
                    #'large'     => __( 'Large' ),
                    'full'      => __( 'Full Size' ),
                )
            );

            foreach ( $sizes as $value => $name ) :
                ?>
                <#
                var size = data.sizes['<?php echo esc_js( $value ); ?>'];
                if ( size ) { #>
                <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'full' ); ?>>
								<?php echo esc_html( $name ); ?> &ndash; {{ size.width }} &times; {{ size.height }}
							</option>
                <# } #>
            <?php endforeach; ?>
            </select>
			</span>
        <# } #>
    </script>

    <?php // Template for the Gallery settings, used for example in the sidebar. ?>
    <script type="text/html" id="tmpl-gallery-settings">
        <h2><?php _e( 'Gallery Settings' ); ?></h2>

        <span class="setting">
			<label for="gallery-settings-link-to" class="name"><?php _e( 'Link To' ); ?></label>
			<select id="gallery-settings-link-to" class="link-to"
                    data-setting="link"
				<# if ( data.userSettings ) { #>
					data-user-setting="urlbutton"
				<# } #>>

				<option value="post" <# if ( ! wp.media.galleryDefaults.link || 'post' == wp.media.galleryDefaults.link ) {
					#>selected="selected"<# }
				#>>
            <?php esc_html_e( 'Attachment Page' ); ?>
            </option>
            <option value="file" <# if ( 'file' == wp.media.galleryDefaults.link ) { #>selected="selected"<# } #>>
            <?php esc_html_e( 'Media File' ); ?>
            </option>
            <option value="none" <# if ( 'none' == wp.media.galleryDefaults.link ) { #>selected="selected"<# } #>>
            <?php esc_html_e( 'None' ); ?>
            </option>
            </select>
		</span>

        <span class="setting">
			<label for="gallery-settings-columns" class="name select-label-inline"><?php _e( 'Columns' ); ?></label>
			<select id="gallery-settings-columns" class="columns" name="columns"
                    data-setting="columns">
				<?php for ( $i = 1; $i <= 9; $i++ ) : ?>
                    <option value="<?php echo esc_attr( $i ); ?>" <#
						if ( <?php echo $i; ?> == wp.media.galleryDefaults.columns ) { #>selected="selected"<# }
					#>>
						<?php echo esc_html( $i ); ?>
					</option>
                <?php endfor; ?>
			</select>
		</span>

        <span class="setting">
			<input type="checkbox" id="gallery-settings-random-order" data-setting="_orderbyRandom" />
			<label for="gallery-settings-random-order" class="checkbox-label-inline"><?php _e( 'Random Order' ); ?></label>
		</span>

        <span class="setting size">
			<label for="gallery-settings-size" class="name"><?php _e( 'Size' ); ?></label>
			<select id="gallery-settings-size" class="size" name="size"
                    data-setting="size"
				<# if ( data.userSettings ) { #>
					data-user-setting="imgsize"
				<# } #>
				>
            <?php
            /** This filter is documented in wp-admin/includes/media.php */
            $size_names = apply_filters(
                'image_size_names_choose',
                array(
                    'thumbnail' => __( 'Thumbnail' ),
                    'medium'    => __( 'Medium' ),
                    'large'     => __( 'Large' ),
                    'full'      => __( 'Full Size' ),
                )
            );

            foreach ( $size_names as $size => $label ) :
                ?>
                <option value="<?php echo esc_attr( $size ); ?>">
						<?php echo esc_html( $label ); ?>
					</option>
            <?php endforeach; ?>
            </select>
		</span>
    </script>

    <?php // Template for the Playlists settings, used for example in the sidebar. ?>
    <script type="text/html" id="tmpl-playlist-settings">
        <h2><?php _e( 'Playlist Settings' ); ?></h2>

        <# var emptyModel = _.isEmpty( data.model ),
        isVideo = 'video' === data.controller.get('library').props.get('type'); #>

        <span class="setting">
			<input type="checkbox" id="playlist-settings-show-list" data-setting="tracklist" <# if ( emptyModel ) { #>
				checked="checked"
			<# } #> />
			<label for="playlist-settings-show-list" class="checkbox-label-inline">
				<# if ( isVideo ) { #>
                <?php _e( 'Show Video List' ); ?>
                <# } else { #>
                <?php _e( 'Show Tracklist' ); ?>
                <# } #>
			</label>
		</span>

        <# if ( ! isVideo ) { #>
        <span class="setting">
			<input type="checkbox" id="playlist-settings-show-artist" data-setting="artists" <# if ( emptyModel ) { #>
				checked="checked"
			<# } #> />
			<label for="playlist-settings-show-artist" class="checkbox-label-inline">
				<?php _e( 'Show Artist Name in Tracklist' ); ?>
			</label>
		</span>
        <# } #>

        <span class="setting">
			<input type="checkbox" id="playlist-settings-show-images" data-setting="images" <# if ( emptyModel ) { #>
				checked="checked"
			<# } #> />
			<label for="playlist-settings-show-images" class="checkbox-label-inline">
				<?php _e( 'Show Images' ); ?>
			</label>
		</span>
    </script>

    <?php // Template for the "Insert from URL" layout. ?>
    <script type="text/html" id="tmpl-embed-link-settings">
        <span class="setting link-text">
			<label for="embed-link-settings-link-text" class="name"><?php _e( 'Link Text' ); ?></label>
			<input type="text" id="embed-link-settings-link-text" class="alignment" data-setting="linkText" />
		</span>
        <div class="embed-container" style="display: none;">
            <div class="embed-preview"></div>
        </div>
    </script>

    <?php // Template for the "Insert from URL" image preview and details. ?>
    <script type="text/html" id="tmpl-embed-image-settings">
        <div class="wp-clearfix">
            <div class="thumbnail">
                <img src="{{ data.model.url }}" draggable="false" alt="" />
            </div>
        </div>

        <span class="setting alt-text has-description">
			<label for="embed-image-settings-alt-text" class="name"><?php _e( 'Alternative Text' ); ?></label>
			<input type="text" id="embed-image-settings-alt-text" data-setting="alt" aria-describedby="alt-text-description" />
		</span>
        <p class="description" id="alt-text-description"><?php echo $alt_text_description; ?></p>

        <?php
        /** This filter is documented in wp-admin/includes/media.php */
        if ( ! apply_filters( 'disable_captions', '' ) ) :
            ?>
            <span class="setting caption">
				<label for="embed-image-settings-caption" class="name"><?php _e( 'Caption' ); ?></label>
				<textarea id="embed-image-settings-caption" data-setting="caption" />
			</span>
        <?php endif; ?>

        <fieldset class="setting-group">
            <legend class="name"><?php _e( 'Align' ); ?></legend>
            <span class="setting align">
				<span class="button-group button-large" data-setting="align">
					<button class="button" value="left">
						<?php esc_html_e( 'Left' ); ?>
					</button>
					<button class="button" value="center">
						<?php esc_html_e( 'Center' ); ?>
					</button>
					<button class="button" value="right">
						<?php esc_html_e( 'Right' ); ?>
					</button>
					<button class="button active" value="none">
						<?php esc_html_e( 'None' ); ?>
					</button>
				</span>
			</span>
        </fieldset>

        <fieldset class="setting-group">
            <legend class="name"><?php _e( 'Link To' ); ?></legend>
            <span class="setting link-to">
				<span class="button-group button-large" data-setting="link">
					<button class="button" value="file">
						<?php esc_html_e( 'Image URL' ); ?>
					</button>
					<button class="button" value="custom">
						<?php esc_html_e( 'Custom URL' ); ?>
					</button>
					<button class="button active" value="none">
						<?php esc_html_e( 'None' ); ?>
					</button>
				</span>
			</span>
            <span class="setting">
				<label for="embed-image-settings-link-to-custom" class="name"><?php _e( 'URL' ); ?></label>
				<input type="text" id="embed-image-settings-link-to-custom" class="link-to-custom" data-setting="linkUrl" />
			</span>
        </fieldset>
    </script>

    <?php // Template for the Image details, used for example in the editor. ?>
    <script type="text/html" id="tmpl-image-details">
        <div class="media-embed">
            <div class="embed-media-settings">
                <div class="column-settings">
					<span class="setting alt-text has-description">
						<label for="image-details-alt-text" class="name"><?php _e( 'Alternative Text' ); ?></label>
						<input type="text" id="image-details-alt-text" data-setting="alt" value="{{ data.model.alt }}" aria-describedby="alt-text-description" />
					</span>
                    <p class="description" id="alt-text-description"><?php echo $alt_text_description; ?></p>

                    <?php
                    /** This filter is documented in wp-admin/includes/media.php */
                    if ( ! apply_filters( 'disable_captions', '' ) ) :
                        ?>
                        <span class="setting caption">
							<label for="image-details-caption" class="name"><?php _e( 'Caption' ); ?></label>
							<textarea id="image-details-caption" data-setting="caption">{{ data.model.caption }}</textarea>
						</span>
                    <?php endif; ?>

                    <h2><?php _e( 'Display Settings' ); ?></h2>
                    <fieldset class="setting-group">
                        <legend class="legend-inline"><?php _e( 'Align' ); ?></legend>
                        <span class="setting align">
							<span class="button-group button-large" data-setting="align">
								<button class="button" value="left">
									<?php esc_html_e( 'Left' ); ?>
								</button>
								<button class="button" value="center">
									<?php esc_html_e( 'Center' ); ?>
								</button>
								<button class="button" value="right">
									<?php esc_html_e( 'Right' ); ?>
								</button>
								<button class="button active" value="none">
									<?php esc_html_e( 'None' ); ?>
								</button>
							</span>
						</span>
                    </fieldset>

                    <# if ( data.attachment ) { #>
                    <# if ( 'undefined' !== typeof data.attachment.sizes ) { #>
                    <span class="setting size">
								<label for="image-details-size" class="name"><?php _e( 'Size' ); ?></label>
								<select id="image-details-size" class="size" name="size"
                                        data-setting="size"
									<# if ( data.userSettings ) { #>
										data-user-setting="imgsize"
									<# } #>>
                        <?php
                        /** This filter is documented in wp-admin/includes/media.php */
                        $sizes = apply_filters(
                            'image_size_names_choose',
                            array(
                                'thumbnail' => __( 'Thumbnail' ),
                                'medium'    => __( 'Medium' ),
                                'large'     => __( 'Large' ),
                                'full'      => __( 'Full Size' ),
                            )
                        );

                        foreach ( $sizes as $value => $name ) :
                            ?>
                            <#
                            var size = data.sizes['<?php echo esc_js( $value ); ?>'];
                            if ( size ) { #>
                            <option value="<?php echo esc_attr( $value ); ?>">
												<?php echo esc_html( $name ); ?> &ndash; {{ size.width }} &times; {{ size.height }}
											</option>
                            <# } #>
                        <?php endforeach; ?>
                        <option value="<?php echo esc_attr( 'custom' ); ?>">
										<?php _e( 'Custom Size' ); ?>
									</option>
                        </select>
							</span>
                    <# } #>
                    <div class="custom-size wp-clearfix<# if ( data.model.size !== 'custom' ) { #> hidden<# } #>">
								<span class="custom-size-setting">
									<label for="image-details-size-width"><?php _e( 'Width' ); ?></label>
									<input type="number" id="image-details-size-width" aria-describedby="image-size-desc" data-setting="customWidth" step="1" value="{{ data.model.customWidth }}" />
								</span>
                        <span class="sep" aria-hidden="true">&times;</span>
                        <span class="custom-size-setting">
									<label for="image-details-size-height"><?php _e( 'Height' ); ?></label>
									<input type="number" id="image-details-size-height" aria-describedby="image-size-desc" data-setting="customHeight" step="1" value="{{ data.model.customHeight }}" />
								</span>
                        <p id="image-size-desc" class="description"><?php _e( 'Image size in pixels' ); ?></p>
                    </div>
                    <# } #>

                    <span class="setting link-to">
						<label for="image-details-link-to" class="name"><?php _e( 'Link To' ); ?></label>
						<select id="image-details-link-to" data-setting="link">
						<# if ( data.attachment ) { #>
							<option value="file">
								<?php esc_html_e( 'Media File' ); ?>
							</option>
							<option value="post">
								<?php esc_html_e( 'Attachment Page' ); ?>
							</option>
						<# } else { #>
							<option value="file">
								<?php esc_html_e( 'Image URL' ); ?>
							</option>
						<# } #>
							<option value="custom">
								<?php esc_html_e( 'Custom URL' ); ?>
							</option>
							<option value="none">
								<?php esc_html_e( 'None' ); ?>
							</option>
						</select>
					</span>
                    <span class="setting">
						<label for="image-details-link-to-custom" class="name"><?php _e( 'URL' ); ?></label>
						<input type="text" id="image-details-link-to-custom" class="link-to-custom" data-setting="linkUrl" />
					</span>

                    <div class="advanced-section">
                        <h2><button type="button" class="button-link advanced-toggle"><?php _e( 'Advanced Options' ); ?></button></h2>
                        <div class="advanced-settings hidden">
                            <div class="advanced-image">
								<span class="setting title-text">
									<label for="image-details-title-attribute" class="name"><?php _e( 'Image Title Attribute' ); ?></label>
									<input type="text" id="image-details-title-attribute" data-setting="title" value="{{ data.model.title }}" />
								</span>
                                <span class="setting extra-classes">
									<label for="image-details-css-class" class="name"><?php _e( 'Image CSS Class' ); ?></label>
									<input type="text" id="image-details-css-class" data-setting="extraClasses" value="{{ data.model.extraClasses }}" />
								</span>
                            </div>
                            <div class="advanced-link">
								<span class="setting link-target">
									<input type="checkbox" id="image-details-link-target" data-setting="linkTargetBlank" value="_blank" <# if ( data.model.linkTargetBlank ) { #>checked="checked"<# } #>>
									<label for="image-details-link-target" class="checkbox-label"><?php _e( 'Open link in a new tab' ); ?></label>
								</span>
                                <span class="setting link-rel">
									<label for="image-details-link-rel" class="name"><?php _e( 'Link Rel' ); ?></label>
									<input type="text" id="image-details-link-rel" data-setting="linkRel" value="{{ data.model.linkRel }}" />
								</span>
                                <span class="setting link-class-name">
									<label for="image-details-link-css-class" class="name"><?php _e( 'Link CSS Class' ); ?></label>
									<input type="text" id="image-details-link-css-class" data-setting="linkClassName" value="{{ data.model.linkClassName }}" />
								</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="column-image">
                    <div class="image">
                        <img src="{{ data.model.url }}" draggable="false" alt="" />
                        <# if ( data.attachment && window.imageEdit ) { #>
                        <div class="actions">
                            <input type="button" class="edit-attachment button" value="<?php esc_attr_e( 'Edit Original' ); ?>" />
                            <input type="button" class="replace-attachment button" value="<?php esc_attr_e( 'Replace' ); ?>" />
                        </div>
                        <# } #>
                    </div>
                </div>
            </div>
        </div>
    </script>

    <?php // Template for the Image Editor layout. ?>
    <script type="text/html" id="tmpl-image-editor">
        <div id="media-head-{{ data.id }}"></div>
        <div id="image-editor-{{ data.id }}"></div>
    </script>

    <?php // Template for an embedded Audio details. ?>
    <script type="text/html" id="tmpl-audio-details">
        <# var ext, html5types = {
        mp3: wp.media.view.settings.embedMimes.mp3,
        ogg: wp.media.view.settings.embedMimes.ogg
        }; #>

        <?php $audio_types = wp_get_audio_extensions(); ?>
        <div class="media-embed media-embed-details">
            <div class="embed-media-settings embed-audio-settings">
                <?php wp_underscore_audio_template(); ?>

                <# if ( ! _.isEmpty( data.model.src ) ) {
                ext = data.model.src.split('.').pop();
                if ( html5types[ ext ] ) {
                delete html5types[ ext ];
                }
                #>
                <span class="setting">
					<label for="audio-details-source" class="name"><?php _e( 'URL' ); ?></label>
					<input type="text" id="audio-details-source" readonly data-setting="src" value="{{ data.model.src }}" />
					<button type="button" class="button-link remove-setting"><?php _e( 'Remove audio source' ); ?></button>
				</span>
                <# } #>
                <?php

                foreach ( $audio_types as $type ) :
                    ?>
                    <# if ( ! _.isEmpty( data.model.<?php echo $type; ?> ) ) {
                    if ( ! _.isUndefined( html5types.<?php echo $type; ?> ) ) {
                    delete html5types.<?php echo $type; ?>;
                    }
                    #>
                    <span class="setting">
					<label for="audio-details-<?php echo $type . '-source'; ?>" class="name"><?php echo strtoupper( $type ); ?></label>
					<input type="text" id="audio-details-<?php echo $type . '-source'; ?>" readonly data-setting="<?php echo $type; ?>" value="{{ data.model.<?php echo $type; ?> }}" />
					<button type="button" class="button-link remove-setting"><?php _e( 'Remove audio source' ); ?></button>
				</span>
                    <# } #>
                <?php endforeach ?>

                <# if ( ! _.isEmpty( html5types ) ) { #>
                <fieldset class="setting-group">
                    <legend class="name"><?php _e( 'Add alternate sources for maximum HTML5 playback' ); ?></legend>
                    <span class="setting">
						<span class="button-large">
						<# _.each( html5types, function (mime, type) { #>
							<button class="button add-media-source" data-mime="{{ mime }}">{{ type }}</button>
						<# } ) #>
						</span>
					</span>
                </fieldset>
                <# } #>

                <fieldset class="setting-group">
                    <legend class="name"><?php _e( 'Preload' ); ?></legend>
                    <span class="setting preload">
						<span class="button-group button-large" data-setting="preload">
							<button class="button" value="auto"><?php _ex( 'Auto', 'auto preload' ); ?></button>
							<button class="button" value="metadata"><?php _e( 'Metadata' ); ?></button>
							<button class="button active" value="none"><?php _e( 'None' ); ?></button>
						</span>
					</span>
                </fieldset>

                <span class="setting-group">
					<span class="setting checkbox-setting autoplay">
						<input type="checkbox" id="audio-details-autoplay" data-setting="autoplay" />
						<label for="audio-details-autoplay" class="checkbox-label"><?php _e( 'Autoplay' ); ?></label>
					</span>

					<span class="setting checkbox-setting">
						<input type="checkbox" id="audio-details-loop" data-setting="loop" />
						<label for="audio-details-loop" class="checkbox-label"><?php _e( 'Loop' ); ?></label>
					</span>
				</span>
            </div>
        </div>
    </script>

    <?php // Template for an embedded Video details. ?>
    <script type="text/html" id="tmpl-video-details">
        <# var ext, html5types = {
        mp4: wp.media.view.settings.embedMimes.mp4,
        ogv: wp.media.view.settings.embedMimes.ogv,
        webm: wp.media.view.settings.embedMimes.webm
        }; #>

        <?php $video_types = wp_get_video_extensions(); ?>
        <div class="media-embed media-embed-details">
            <div class="embed-media-settings embed-video-settings">
                <div class="wp-video-holder">
                    <#
                    var w = ! data.model.width || data.model.width > 640 ? 640 : data.model.width,
                    h = ! data.model.height ? 360 : data.model.height;

                    if ( data.model.width && w !== data.model.width ) {
                    h = Math.ceil( ( h * w ) / data.model.width );
                    }
                    #>

                    <?php wp_underscore_video_template(); ?>

                    <# if ( ! _.isEmpty( data.model.src ) ) {
                    ext = data.model.src.split('.').pop();
                    if ( html5types[ ext ] ) {
                    delete html5types[ ext ];
                    }
                    #>
                    <span class="setting">
					<label for="video-details-source" class="name"><?php _e( 'URL' ); ?></label>
					<input type="text" id="video-details-source" readonly data-setting="src" value="{{ data.model.src }}" />
					<button type="button" class="button-link remove-setting"><?php _e( 'Remove video source' ); ?></button>
				</span>
                    <# } #>
                    <?php
                    foreach ( $video_types as $type ) :
                        ?>
                        <# if ( ! _.isEmpty( data.model.<?php echo $type; ?> ) ) {
                        if ( ! _.isUndefined( html5types.<?php echo $type; ?> ) ) {
                        delete html5types.<?php echo $type; ?>;
                        }
                        #>
                        <span class="setting">
					<label for="video-details-<?php echo $type . '-source'; ?>" class="name"><?php echo strtoupper( $type ); ?></label>
					<input type="text" id="video-details-<?php echo $type . '-source'; ?>" readonly data-setting="<?php echo $type; ?>" value="{{ data.model.<?php echo $type; ?> }}" />
					<button type="button" class="button-link remove-setting"><?php _e( 'Remove video source' ); ?></button>
				</span>
                        <# } #>
                    <?php endforeach ?>
                </div>

                <# if ( ! _.isEmpty( html5types ) ) { #>
                <fieldset class="setting-group">
                    <legend class="name"><?php _e( 'Add alternate sources for maximum HTML5 playback' ); ?></legend>
                    <span class="setting">
						<span class="button-large">
						<# _.each( html5types, function (mime, type) { #>
							<button class="button add-media-source" data-mime="{{ mime }}">{{ type }}</button>
						<# } ) #>
						</span>
					</span>
                </fieldset>
                <# } #>

                <# if ( ! _.isEmpty( data.model.poster ) ) { #>
                <span class="setting">
					<label for="video-details-poster-image" class="name"><?php _e( 'Poster Image' ); ?></label>
					<input type="text" id="video-details-poster-image" readonly data-setting="poster" value="{{ data.model.poster }}" />
					<button type="button" class="button-link remove-setting"><?php _e( 'Remove poster image' ); ?></button>
				</span>
                <# } #>

                <fieldset class="setting-group">
                    <legend class="name"><?php _e( 'Preload' ); ?></legend>
                    <span class="setting preload">
						<span class="button-group button-large" data-setting="preload">
							<button class="button" value="auto"><?php _ex( 'Auto', 'auto preload' ); ?></button>
							<button class="button" value="metadata"><?php _e( 'Metadata' ); ?></button>
							<button class="button active" value="none"><?php _e( 'None' ); ?></button>
						</span>
					</span>
                </fieldset>

                <span class="setting-group">
					<span class="setting checkbox-setting autoplay">
						<input type="checkbox" id="video-details-autoplay" data-setting="autoplay" />
						<label for="video-details-autoplay" class="checkbox-label"><?php _e( 'Autoplay' ); ?></label>
					</span>

					<span class="setting checkbox-setting">
						<input type="checkbox" id="video-details-loop" data-setting="loop" />
						<label for="video-details-loop" class="checkbox-label"><?php _e( 'Loop' ); ?></label>
					</span>
				</span>

                <span class="setting" data-setting="content">
					<#
					var content = '';
					if ( ! _.isEmpty( data.model.content ) ) {
						var tracks = jQuery( data.model.content ).filter( 'track' );
						_.each( tracks.toArray(), function( track, index ) {
							content += track.outerHTML; #>
						<label for="video-details-track-{{ index }}" class="name"><?php _e( 'Tracks (subtitles, captions, descriptions, chapters, or metadata)' ); ?></label>
						<input class="content-track" type="text" id="video-details-track-{{ index }}" aria-describedby="video-details-track-desc-{{ index }}" value="{{ track.outerHTML }}" />
						<span class="description" id="video-details-track-desc-{{ index }}">
						<?php
                        printf(
                        /* translators: 1: "srclang" HTML attribute, 2: "label" HTML attribute, 3: "kind" HTML attribute. */
                            __( 'The %1$s, %2$s, and %3$s values can be edited to set the video track language and kind.' ),
                            'srclang',
                            'label',
                            'kind'
                        );
                        ?>
						</span>
						<button type="button" class="button-link remove-setting remove-track"><?php _ex( 'Remove video track', 'media' ); ?></button><br/>
						<# } ); #>
					<# } else { #>
					<span class="name"><?php _e( 'Tracks (subtitles, captions, descriptions, chapters, or metadata)' ); ?></span><br />
					<em><?php _e( 'There are no associated subtitles.' ); ?></em>
					<# } #>
					<textarea class="hidden content-setting">{{ content }}</textarea>
				</span>
            </div>
        </div>
    </script>

    <?php // Template for a Gallery within the editor. ?>
    <script type="text/html" id="tmpl-editor-gallery">
        <# if ( data.attachments.length ) { #>
        <div class="gallery gallery-columns-{{ data.columns }}">
            <# _.each( data.attachments, function( attachment, index ) { #>
            <dl class="gallery-item">
                <dt class="gallery-icon">
                    <# if ( attachment.thumbnail ) { #>
                    <img src="{{ attachment.thumbnail.url }}" width="{{ attachment.thumbnail.width }}" height="{{ attachment.thumbnail.height }}" alt="{{ attachment.alt }}" />
                    <# } else { #>
                    <img src="{{ attachment.url }}" alt="{{ attachment.alt }}" />
                    <# } #>
                </dt>
                <# if ( attachment.caption ) { #>
                <dd class="wp-caption-text gallery-caption">
                    {{{ data.verifyHTML( attachment.caption ) }}}
                </dd>
                <# } #>
            </dl>
            <# if ( index % data.columns === data.columns - 1 ) { #>
            <br style="clear: both;">
            <# } #>
            <# } ); #>
        </div>
        <# } else { #>
        <div class="wpview-error">
            <div class="dashicons dashicons-format-gallery"></div><p><?php _e( 'No items found.' ); ?></p>
        </div>
        <# } #>
    </script>

    <?php // Template for the Crop area layout, used for example in the Customizer. ?>
    <script type="text/html" id="tmpl-crop-content">
        <img class="crop-image" src="{{ data.url }}" alt="<?php esc_attr_e( 'Image crop area preview. Requires mouse interaction.' ); ?>">
        <div class="upload-errors"></div>
    </script>

    <?php // Template for the Site Icon preview, used for example in the Customizer. ?>
    <script type="text/html" id="tmpl-site-icon-preview">
        <h2><?php _e( 'Preview' ); ?></h2>
        <strong aria-hidden="true"><?php _e( 'As a browser icon' ); ?></strong>
        <div class="favicon-preview">
            <img src="<?php echo esc_url( admin_url( 'images/' . ( is_rtl() ? 'browser-rtl.png' : 'browser.png' ) ) ); ?>" class="browser-preview" width="182" height="" alt="" />

            <div class="favicon">
                <img id="preview-favicon" src="{{ data.url }}" alt="<?php esc_attr_e( 'Preview as a browser icon' ); ?>"/>
            </div>
            <span class="browser-title" aria-hidden="true"><# print( '<?php bloginfo( 'name' ); ?>' ) #></span>
        </div>

        <strong aria-hidden="true"><?php _e( 'As an app icon' ); ?></strong>
        <div class="app-icon-preview">
            <img id="preview-app-icon" src="{{ data.url }}" alt="<?php esc_attr_e( 'Preview as an app icon' ); ?>"/>
        </div>
    </script>

    <?php

    /**
     * Fires when the custom Backbone media templates are printed.
     *
     * @since 3.5.0ь
     */
    do_action( 'print_media_templates' );
}








add_action( 'admin_bar_menu', 'customize_my_wp_admin_bar', 80 );
function customize_my_wp_admin_bar( $wp_admin_bar ) {
    $new_content_node = $wp_admin_bar->get_node('new-content');

    $new_content_node->href = '#';
    $wp_admin_bar->add_node($new_content_node);
    $wp_admin_bar->remove_menu('new-post');
    $wp_admin_bar->add_menu( array(
            'id'    => 'new-custom-menu',
            'title' => 'Custom Menu',
            'parent'=> 'new-content',
            'href'  => '#custom-menu-link',)
    );

}



// add_filter( 'pre_insert_term', 'deny_term_creation', 10, 2 );
function deny_term_creation( $term, $taxonomy ) {
    // Таксономия будет 'post_tag'
    if ( $taxonomy === 'post_tag' ) {
        if ( !user_has_role(get_current_user_id(),'administrator') && !user_has_role(get_current_user_id(),'chief_editor') ) {
            return new WP_Error( 'error', 'НЕЛЬЗЯ СОЗДАВАТЬ МЕТКИ!' );
        }
    }
    return $term;
}
add_filter( 'pre_insert_term', 'deny_term_creation', 10, 2 );





add_action('current_screen', 'hide_mainpage_for_bild');
function hide_mainpage_for_bild(){
    $screen = get_current_screen();
    if(current_user_can('bild') && is_admin()){
        if(!in_array($screen->id, array('upload', 'attachment', 'media', 'async-upload'))){
            wp_redirect('/wp-admin/upload.php');
        }
    }
    if(!current_user_can('administrator') && $screen->id == 'post'){
        wp_redirect('/wp-admin/post-new.php?post_type=anew');
    }

}
add_action( 'add_term_relationship', 'deny_category_change', 10, 3 );
function deny_category_change( $object_id, $tt_id, $taxonomy ){
    if($taxonomy == 'category') {
        $id = filter_input(INPUT_POST, 'post_ID', FILTER_SANITIZE_NUMBER_INT);
        $category = get_the_category($id);
        if ($category[0]->term_id != NULL && $category[0]->term_id != $tt_id && in_array(get_current_user_id(), array(17)) && get_post_status($id) == 'publish') {
            wp_redirect('/?p=' . $id);
            die;
        }
    }
}



//Отключение автосохранения на новостях и желтухе для кобзева
add_action( 'admin_init', 'disable_autosave' );
function disable_autosave() {
    if((in_array(get_post_type(get_queried_object_id()), array('anew', 'yellow')) || in_array(filter_input(INPUT_GET, 'post_type'), array('anew', 'yellow'))) && in_array(get_current_user_id(), array(17))){
        wp_deregister_script( 'autosave' );
    }
}



//add_filter('autoptimize_filter_noptimize','my_ao_noptimize',10,0);
function my_ao_noptimize() {
    if (is_single() && wp_is_mobile()) {
        return true;
    } else {
        return false;
    }
}

//add_action( 'wp_print_scripts', 'localize_alm_script_to_footer', 100 );
function localize_alm_script_to_footer(){
    if (wp_is_mobile() && is_single() && !is_amp_endpoint() && posts_to_promote() && !use_new_template()) {
        $alm_localize_variable = array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'alm_nonce' => wp_create_nonce( "ajax_load_more_nonce" ),
            'rest_api' => esc_url_raw( rest_url() ),
            'rest_nonce' => wp_create_nonce( 'wp_rest' ),
            'pluginurl' => ALM_URL,
            'scrolltop' => 100,
            'speed' => apply_filters('alm_speed', 200),
            'ga_debug' => apply_filters('alm_ga_debug', 'false'),
            'results_text' => apply_filters('alm_display_results', __('Viewing {post_count} of {total_posts} results.', 'ajax-load-more')),
            'no_results_text' => apply_filters('alm_no_results_text', __('No results found.', 'ajax-load-more')),
            'alm_debug' => apply_filters('alm_debug', false),
            'a11y_focus' => apply_filters('alm_a11y_focus', true)
        );
        echo "<script>var alm_localize = ".json_encode($alm_localize_variable)."</script>";
    }
}


//rel для ссылок
add_filter('the_content', 'links_rel_attr', 200 );
function links_rel_attr($content){
    if(mb_stripos($content, '<a') === false){
        return $content;
    }else{
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
        $links = $dom->getElementsByTagName('a');
        foreach($links as $link){
            $href = parse_url($link->getAttribute('href'));
            if(is_array($href) && array_key_exists('host', $href)){
                if($href['host'] != 'profile.ru'){
                    $link->setAttribute('rel', 'false noopener');
                }
            }
        }
        libxml_use_internal_errors(false);
        return str_replace(['<body>', '</body>'], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
    }
}







add_action( 'set_object_terms', 'set_author_term_as_meta', 10, 6 );
function set_author_term_as_meta( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ){
    if($taxonomy == 'author') {
        $term = get_term($tt_ids[0]);
        update_post_meta($object_id, 'post_author-1', explode("@", $term->description)[0]);//todo доработать
    }
}


add_filter('pre_get_posts', 'ep_search_filter', 100, 1);
function ep_search_filter($query){
    if($query->is_search()){
        $query->set('ep_integrate', true);//включили ep

        //$query->set('post_type', array('profile_article','anew', 'yellow'));//ограничили типы записей для поиска

        $query->set('search_fields',//добавили мету с автором в поиск
            array(
                'post_title',
                'post_content',
                'post_excerpt',
                'meta' =>
                    array(
                        'post_author-1',
                        'post_author-2'
                    ),
            )
        );

        $query->set('orderby', 'date');
        $query->set('order', 'DESC');

        if(filter_input(INPUT_GET, 'period', FILTER_SANITIZE_NUMBER_INT) > 0) {//если установлено ограничение по дате, добавили дату
            $query->set('date_query',
                array(
                    array(
                        'after' => date("Y-m-d", strtotime('-' . filter_input(INPUT_GET, 'period', FILTER_SANITIZE_NUMBER_INT) . ' days')),
                        'inclusive' => true,
                    ),
                )
            );
        }

        if(strlen(filter_input(INPUT_GET, 'category')) != 0 && filter_input(INPUT_GET, 'category') != 'all'){//если установлено ограничение по рубрике, добавили рубрику
            $query->set('category_name', filter_input(INPUT_GET, 'category'));
        }
    }
    return $query;
}

//add_action('init','updateallposts', 200);
/*function updateallposts(){
    if(filter_input(INPUT_GET, 'variable_for_update', FILTER_SANITIZE_NUMBER_INT) == 37809412 ) {
        $posts = get_posts(
            array(
                'post_type' => array('profile_article', 'anew', 'yellow'),
                'posts_per_page' => -1
            )
        );

        foreach ($posts as $post) {
            $terms = get_the_terms($post->ID, 'author');
            foreach ($terms as $i => $term) {
                //delete_post_meta($post->ID, 'post_author-' . ($i + 1));
                update_post_meta($post->ID, 'post_author-' . ($i + 1), explode("@", $term->description)[0]);
            }
        }
        die('done');
    }
}*/

add_filter('ep_highlighting_class', 'highlight_search_class');
function highlight_search_class($class){
    $class = 'highlight';
    return $class;
}

add_filter( 'wp_insert_post_data' , 'remove_noref' , 999, 2 );
function remove_noref( $data , $postarr ) {
    $data['post_content'] = str_replace('noreferrer', '', $data['post_content']);
    return $data;
}






add_shortcode('hide', 'text_hide');
function text_hide($atts) {
    if(is_feed() || is_yn() || is_admin() || !is_single() || is_amp_endpoint()){
        return false;
    } else {
        return '<p><script>document.write(JSON.parse(\''.json_encode(addslashes(str_replace("\n", "", $atts['code'])), JSON_HEX_QUOT | JSON_HEX_TAG).'\'));</script></p>';
    }
}

add_filter('the_guid', 'guid_function_filter', 99, 2);
function guid_function_filter($guid, $id){
    return get_the_permalink($id);
}



add_action('save_post', 'clear_feed_cache', 999, 1 );
add_action('draft_to_publish', 'clear_feed_cache', 999, 1 );
add_action('future_to_publish', 'clear_feed_cache', 999, 1 );

function clear_feed_cache($post_id){

    $post_id = (is_object($post_id)) ? $post_id->ID : $post_id;
    if (
        (get_post_status($post_id) !== 'publish')
        ||
        defined('DOING_AUTOSAVE') && DOING_AUTOSAVE
    ) {
        return;
    }

    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/feed ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/uploads/rank-math/* ');

    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/rss ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/articles ');

    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/news/index-mobile-https.html ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/news/index-https.html ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/news/index-mobile-https.html_gzip ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/news/index-https.html_gzip ');

    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/index-mobile-https.html ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/index-https.html ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/index-mobile-https.html_gzip ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/cache/wp-rocket/profile.ru/index-https.html_gzip ');

    execInBackground('rm -rf /var/www/profile/html/wp-content/uploads/alm-cache/000001 ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/uploads/alm-cache/000101 ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/uploads/alm-cache/010001 ');
    execInBackground('rm -rf /var/www/profile/html/wp-content/uploads/alm-cache/010101 ');

}





function get_micro_desc($post_id = 0){

    if($post_id === 0){
        return false;
    }

    $content = get_the_content(null, false, $post_id);
    $content = strip_tags($content);
    $content = mb_substr($content, 0, 160);
    $content = str_replace('"', '\"', $content);
    $dot = mb_strripos($content, '.');
    return mb_substr($content, 0, $dot).".";
}



add_filter( 'post_row_actions', 'expand_quick_edit_link', 10, 2 );
function expand_quick_edit_link( $actions, $post ) {
    if(!current_user_can('administrator')) {
        unset($actions['trash']);
        return $actions;
    }
    return $actions;
}








remove_filter('the_content', 'wptexturize');
remove_filter('the_title', 'wptexturize');



add_filter('the_content', 'amp_links', 100, 1);
function amp_links($content){
    if(!is_amp_endpoint()){
        return $content;
    }

    $dom = new DomDocument('1.0', 'utf-8');
    $dom->loadHTML('<meta http-equiv="Content-Type" content="charset=utf-8" />'.$content);

    $links = $dom->getElementsByTagName('a');
    if(count($links) > 0) {
        foreach ($links as $key => $a) {
            $link = parse_url($a->getAttribute('href'));
            if(mb_strripos($link['host'], 'profile.ru') !== false){
                $a->setAttribute('href', $a->getAttribute('href').'?amp');
            }
        }
    }


    $content = $dom->saveHTML($dom->getElementsByTagName('body')->item(0));

    return $content;

}



function execInBackground($cmd) {
    exec($cmd . " > /dev/null &");
    return true;
}



add_filter( 'ep_elasticpress_enabled', function ( $enabled, $query ) {

    //return true;

    if(get_current_user_id() == 1) {
/*
        var_dump(
                $query->query["post_type"]
        );
        if(!in_array( $query->query["post_type"], [
            "acf-taxonomy",
            "acf-post-type",
            NULL
        ] )) {
            die;
        }
*/

        /*if($query->query["post_type"] === "attachment" || $_POST["action"] === "query-attachments" || $_GET["_fs_blog_admin"] === true || $_GET["_fs_blog_admin"] === "true"){
            die("000");
        }*/

    }

    if($query->query["post_type"] === "attachment" || $_POST["action"] === "query-attachments" || $_GET["_fs_blog_admin"] === true || $_GET["_fs_blog_admin"] === "true" ) {
        return false;
    }

    return $enabled;

}, PHP_INT_MAX, 2 );






/*add_filter( 'ep_elasticpress_enabled', function ( $enabled, $query ) {
    if(is_admin() && filter_input(INPUT_GET, 's') == ''){
        return false;
    }
    if (property_exists($query, 'query_vars') && is_array($query->query_vars) && array_key_exists('post_type', $query->query_vars) && 'attachment' === $query->query_vars['post_type']) {
        return false;
    }
    return $enabled;//
}, 11, 2 );*/


add_action( 'current_screen', 'newsline_editor_redirect' );
function newsline_editor_redirect(){
    $screen = get_current_screen();
    if((user_has_role(get_current_user_id(), 'newsline_editor') || user_has_role(get_current_user_id(), 'senior_editor')) && $screen->id == 'dashboard'){
        wp_redirect('/wp-admin/edit.php?post_type=anew');
    }
}



function artabr_opengraph_fix_yandex($lang) {
    $lang_prefix = 'prefix="og: https://ogp.me/ns# article: https://ogp.me/ns/article#  profile: https://ogp.me/ns/profile# fb: https://ogp.me/ns/fb#"';
    $lang_fix = preg_replace('!prefix="(.*?)"!si', $lang_prefix, $lang);
    return $lang_fix;
}
add_filter( 'language_attributes', 'artabr_opengraph_fix_yandex',200,1);



add_action('admin_footer', 'load_logged_in_footer_template');
add_action('wp_footer', 'load_logged_in_footer_template');

function load_logged_in_footer_template(){
    if(is_user_logged_in()) {
        get_template_part('user', 'footer');
    }
}


add_filter( 'rank_math/frontend/description', function( $description ) {
    if (get_queried_object_id() == 104418){
        $description = "Юрий Витальевич Мамлеев (1931–2015) — один из интереснейших и самобытных русских писателей второй половины ХХ века. Прославился он благодаря необычному языку, насыщенности прозы философской проблематикой (его жанр даже получил определение «метафизический реализм»), а также пугающим, порой просто чернушным образам и персонажам, населяющим его книги.";
    }

    return $description;
}, 97);

add_filter( 'rank_math/frontend/description', function( $description ) {
    $post_id = get_queried_object_id();

    if (is_single() && get_post_type($post_id) == 'profile_article' && (has_tag(105047, $post_id) || has_category(105049, $post_id))) {
        $description = 'Персона – журнал Профиль: ' . get_the_title($post_id);
    }
    return $description;
}, 98);




add_filter( 'post_gallery', 'turbo_gallery_layout', 900, 2);
function turbo_gallery_layout($output, $attr) {
    if(!is_feed()) {
        return $output;
    }
    global $post, $wp_locale;

    if (get_post_format($post) != false){
        return $output;
    }

    $attachments = get_posts( array('include' => $attr['ids'], 'posts_per_page' => -1, 'post_type' => 'attachment') );

    $output = '';

    foreach ( $attachments as $i => $attachment ) {
        $img = wp_get_attachment_image_src($attachment->ID,'full');

        $output .= '<figure>';
        $output .= '<img loading="lazy" src="'.$img[0].'" />';
        $output .= '<figcaption>';
        if(strlen($attachment->post_excerpt && !strposa($attachment->post_excerpt, ['instag', 'faceb', 'инстаг'])) > 0){
            $output .= '<span>© '.$attachment->post_excerpt.'</span>';
        }
        if(strlen($attachment->post_content) > 0){
            $output .= '<p>'.$attachment->post_content.'</p>';
        }
        $output .= '</figcaption>';
        $output .= '</figure>';

    }
    return $output;
}





add_filter( 'post_gallery', 'new_gallery_layout', 998, 2);
function new_gallery_layout($output, $attr) {
    if(in_array(get_queried_object_id(), array(978599, 978610))){
        //return $output;
    }
    if ((is_feed() || is_yn() || is_zen())){
        //$output .= "<!----**** " . filter_input(INPUT_GET, 'action') . " ****---->";
        //return $output;
    }

    //global $post, $wp_locale;

    if (get_post_format($post) != false){
        //return $output;
    }

    if(is_yn()){
        $output = "\n";
        //return $output;
    }

    if(in_array(get_post_type(), ["anew", "yellow"]) && get_the_date("U") < 1719187200 ) {
        return "";
    }

    $title = get_the_title(get_queried_object_id());
    $link = get_permalink(get_queried_object_id());

    $attachments = get_posts( array('include' => $attr['ids'], 'posts_per_page' => -1, 'post_type' => 'attachment') );

    $output = '<div class="swiper-container-bg">';
    $output .= '<div class="swiper-container js-gallery-top">';

    $output .= '<div class="swiper-pagination-custom"></div>';

    $output .= '<div class="swiper-wrapper">';
    //→
    $thumbs = '';
    $images = '';
    $captions = '';
    /**/
    $att_ids = explode(",", $attr['ids']);
    foreach ($att_ids as $i => $att_id) {
        foreach ($attachments as $attachment) {
            if ($attachment->ID == $att_id) {

                $data_auth = $attachment->post_excerpt;
                $data_capt = $attachment->post_content;

                $img = wp_get_attachment_image_src($attachment->ID, 'full');
                $images .= '
                                        <div class="swiper-slide">
                                            <img loading="lazy" src="' . $img[0] . '" width="' . $img[1] . '" height="' . $img[2] . '" data-url="?image=' . $attachment->ID . '" alt="'.$data_capt.'" data-auth="'. $data_auth .'" />
                                        </div>';

                $thumbs .= '
                                        <div class="swiper-slide">
                                            <img loading="lazy" class="img-fluid w-100" data-tg-display="no" src="' . $img[0] . '" data-type="gallery-nav" />
                                        </div>';
                $captions .= '
                            <div class="swiper-slide">
                                <div class="swiper-slide-text">
                                    <span>';
                if (strlen($attachment->post_excerpt) > 0) {
                    $captions .= '©' . $attachment->post_excerpt;
                }
                $captions .= '</span>
                                    <p>
                                        ' . $attachment->post_content . '
                                    </p>
                                </div>
                            </div>';

                if ($i == 1) {
                    if ((int)get_option('show_ad') == 1) {
                        $images .= '<div class="swiper-slide swiper-slide-adfox">';
                        $images .= '<div id="adfox" class="adfox"></div>';
                        if (wp_is_mobile()) {
                            $output .= "<script>window.yaContextCb.push(()=>{Ya.adfoxCode.create({ownerId: 242477,containerId: 'adfox',params: {p1: 'cgvth',p2: 'gket'}})})</script>";
                        } else {
                            $output .= "<script>window.yaContextCb.push(()=>{Ya.adfoxCode.create({ownerId: 242477,containerId: 'adfox',params: {p1: 'ciwck',p2: 'gkel'}})})</script>";
                        }
                        $images .= '</div>';

                        $captions .= '<div class="swiper-slide">';
                        $captions .= '<div class="swiper-slide-text">';
                        $captions .= '<p>Листайте дальше, впереди еще много интересного';
                        $captions .= '<svg class="fill-white" viewBox="0 0 24 25" width="12" height="12" class="align-baseline svg-icon">';
                        $captions .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#arrow-right"></use>';
                        $captions .= '</svg>';
                        $captions .= '</p>';
                        $captions .= '</div>';
                        $captions .= '</div>';
                    }
                }
            }
        }
    }
    /**/
    $output .= $images;
    $output .= '<div class="swiper-slide swiper-slide-adfox">';
    $output .= '<div id="adfox-second" class="adfox-second"></div>';
    if ((int)get_option('show_ad') == 1) {
        if (wp_is_mobile()) {
            $output .= "<script>window.yaContextCb.push(()=>{Ya.adfoxCode.create({ownerId: 242477,containerId: 'adfox-second',params: {p1: 'cgvth',p2: 'gket'}})})</script>";
        } else {
            $output .= "<script>window.yaContextCb.push(()=>{Ya.adfoxCode.create({ownerId: 242477,containerId: 'adfox-second',params: {p1: 'ciwck',p2: 'gkel'}})})</script>";
        }
    }
    $output .= '</div>';
    //←
    $output .= '</div>';

    $output .= '<div class="swiper-button-next swiper-button-white"></div>';
    $output .= '<div class="swiper-button-prev swiper-button-white"></div>';

    $output .= '<div class="swiper-buttons">';

    $output .= '<span class="cursor-pointer swiper-social-links js-button" data-toggle="collapse" data-target="#collapseSocial" aria-expanded="false" aria-controls="collapseSocial">';
    $output .= '<svg width="21" height="23">';
    $output .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#social-links"></use>';
    $output .= '</svg>';
    $output .= '</span>';

    $output .= '<div class="collapse" id="collapseSocial">';
    $output .= '<div class="ya-share2__list position-absolute d-flex flex-column">';
    $output .= '<a rel="noopener" class="ya-share2__item vk" href="https://vk.com/share.php?url='.urlencode($link.'?utm_from=vk_share').'&title='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>';
    $output .= '<a rel="noopener" class="ya-share2__item twitter" href="https://twitter.com/intent/tweet?text=&'.urlencode($title).'&url='.urlencode($link.'?utm_from=t_share').'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>';
    $output .= '<a rel="noopener" class="ya-share2__item telegram" href="tg://msg_url?url='.urlencode($link.'?utm_from=tg_share').'&text='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>';
    $output .= '<a rel="noopener" class="ya-share2__item ok" href="https://connect.ok.ru/offer?url='.urlencode($link.'?utm_from=ok_share').'&title='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>';
    $output .= '</div>';
    $output .= '</div>';

    $output .= '<span class="cursor-pointer js-full-screen">';
    $output .= '<svg width="23" height="23">';
    $output .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#full-screen"></use>';
    $output .= '</svg>';
    $output .= '<svg width="23" height="23">';
    $output .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#full-screen-close"></use>';
    $output .= '</svg>';
    $output .= '</span>';

    $output .= '</div>';

    $output .= '</div>';

    $output .= '<div class="swiper-container js-gallery-thumbs">';

    $output .= '<div class="swiper-wrapper">';
    //→
    $output .= $thumbs;
    //←
    $output .= '</div>';

    $output .= '</div>';
    $output .= '<div class="swiper-container js-gallery-text close">';
    $output .= '<div class="swiper-wrapper">';
    //→
    $output .= $captions;
    //←
    $output .= '<div class="swiper-slide">';
    $output .= '<div class="swiper-slide-text">';
    $output .= '<p>Листайте дальше, впереди еще много интересного';
    $output .= '<svg class="fill-white" viewBox="0 0 24 25" width="12" height="12" class="align-baseline svg-icon">';
    $output .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#arrow-right"></use>';
    $output .= '</svg>';
    $output .= '</p>';
    $output .= '</div>';
    $output .= '</div>';
    $output .= '</div>';
    $output .= '<span class="js-gallery-text-close">';
    $output .= '<svg width="21" height="23">';
    $output .= '<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#arrow-down"></use>';
    $output .= '</svg>';
    $output .= '</span>';
    $output .= '</div>';
    $output .= '</div>';


    return $output;
}


function remove_empty_lines( $content ){

    $content = preg_replace("/&nbsp;/", " ", $content);

    return $content;
}
add_action('content_save_pre', 'remove_empty_lines');














add_action('admin_bar_menu', 'add_toolbar_items', 100);
function add_toolbar_items($admin_bar){
    if(in_array(get_current_user_id(), array(1, 3))){
        $show_ad = (int)get_option('show_ad');
        if(filter_input(INPUT_GET, 'toggle_ad') === 'true') {
            $show_ad = $show_ad == 1 ? 0 : 1;
            update_option( 'show_ad', $show_ad);
        }
        $title = $show_ad ? "Выключить рекламу" : "Включить рекламу";
        $admin_bar->add_menu(array(
            'id' => 'toggle_ad',
            'title' => $title,
            'href' => '/wp-admin?toggle_ad=true',
            'meta' => array(
                'title' => __($title),
            ),
        ));
    }
}

add_action('admin_footer', 'clear_cache_ad');
function clear_cache_ad() {
    if(in_array(get_current_user_id(), array(1, 3))){
        if (filter_input(INPUT_GET, 'toggle_ad') === 'true') {
            $html = "
                <script>
                    /*(function($){
                        window.location = $('#wp-admin-bar-delete-cache').find('a').eq(0).attr('href');
                    })(jQuery);*/
                </script>
            ";
            echo $html;
        }
    }
}

function remove_spaces( $content ){

    $content = str_replace(array("&nbsp;", " "), " ", $content);

    return $content;
}
add_action('content_save_pre', 'remove_spaces');
add_action('the_content', 'remove_spaces');



add_filter( 'the_content', 'renderDisclaimers', 200 );
function renderDisclaimers($content){
    if(
        ( function_exists('is_turbo') && is_turbo() )
        ||
        ( function_exists('amp_is_request') && amp_is_request() )
    ){
        if(get_post_primary_category_id(get_queried_object_id()) == 3358 || has_tag(17542, get_queried_object_id()) || has_tag(52905, get_queried_object_id())){
            //$disclaimer .= "Информация носит ознакомительный характер, необходимо проконсультироваться со специалистом/врачом";
        }

            //$content .= '<p style="border-left: 2px solid #b51d1d;margin: 0 0 8px;padding: 0 0 0 8px;line-height: 1.2;font-size: 14px;font-style: italic;">Предупреждение об ограничении ответственности: Все приведенные прогнозы носят оценочный характер, прогнозируемая доходность не гарантирует действительной доходности в процессе вашей инвестиционной деятельности. Любые решения, основанные на опубликованной информации, вы принимаете на свой риск.</p>';

    }
    return $content;
}

function add_admin_column($column_title, $post_type, $cb){
    add_filter('manage_' . $post_type . '_posts_columns', function ($columns) use ($column_title) {
        $columns[sanitize_title($column_title)] = $column_title;
        return $columns;
    });

    add_action('manage_' . $post_type . '_posts_custom_column', function ($column, $post_id) use ($column_title, $cb) {
        if (sanitize_title($column_title) === $column) {
            $cb($post_id);
        }
    }, 10, 2);
}

add_admin_column(__('Последнее изменение'), 'anew', function($post_id){
    $user = get_user_by("id", get_post_meta($post_id, '_edit_last', true));
    echo $user->display_name . " в " . get_the_modified_date("H:i d.m.Y", $post_id);
});
add_admin_column(__('Последнее изменение'), 'profile_article', function($post_id){
    $user = get_user_by("id", get_post_meta($post_id, '_edit_last', true));
    echo $user->display_name . " в " . get_the_modified_date("H:i d.m.Y", $post_id);
});
add_admin_column(__('Последнее изменение'), 'yellow', function($post_id){
    $user = get_user_by("id", get_post_meta($post_id, '_edit_last', true));
    echo $user->display_name . " в " . get_the_modified_date("H:i d.m.Y", $post_id);
});





function remove_comments_column( $columns ) {
    unset($columns['comments']);
    unset($columns['parent']);
    unset($columns['tiny-compress-images']);
    return $columns;
}

function remove_column_init() {
    add_filter('manage_media_columns', 'remove_comments_column');

}
//add_action( 'admin_init' , 'remove_column_init' );





add_action( 'admin_init' , 'media_request_init' );
function media_request_init(){
    //if(get_current_user_id() == 1) {
    //add_filter('posts_where', 'media_request', 100);
    //}
}

function media_request($where) {
    if(is_admin()) {
        $screen = get_current_screen();
        if ($screen->id == 'upload' || $screen->id == NULL) {
            $where .= ' and post_date <= now() ';
        }
    }
    return $where;
}










//Это позволит убрать лишние новости
function limit_test($where){
    $screen = get_current_screen();
    if(1==2 && is_admin() && in_array($screen->id, array('edit-anew', 'edit-yellow', 'edit-profile_article', 'anew', 'yellow', 'profile_article'))){
        $where .= " AND `wp_posts`.`ID` IN (
            SELECT post_id from wp_postmeta where meta_key = 'is_actual' and meta_value = '1'
        ) ";
    }
    return $where;
}
function limit_test_init(){
    if(get_current_user_id() == 1) {
        add_filter('posts_where', 'limit_test', 999);
    }
}
add_action( 'admin_init' , 'limit_test_init' );




































function fake_test_init(){
    if(is_user_logged_in()){

        add_action('save_post', 'save_fake_status',999,1);
        add_action('post_updated', 'save_fake_status',999,1);

        add_action( 'add_meta_boxes', "remove_customized_metabox", 10 );

        add_filter('posts_where', 'remove_fake_draft',10,1);

        add_filter( 'display_post_states', 'remove_draft_state', 10, 2 );
        function remove_draft_state( $post_states, $post ){
            if(get_post_meta($post->ID, 'is_fake', true) == '1'){
                return array();
            }
            return $post_states;
        }

        add_filter( 'post_class', function( $classes ) {
            global $post;
            if(get_post_meta($post->ID, 'is_fake', true) == '1'){
                $classes[] = 'seo';
                $classes[] = 'status-publish';
            }
            return $classes;
        });

        add_filter( 'get_post_status', 'fake_post_status', 10, 2 );
        function fake_post_status( $post_status, $post ){
            if(get_post_meta($post->ID, 'is_fake', true) == '1'){
                $post_status = 'publish';
            }
            return $post_status;
        }


    }
}
add_action( 'admin_init' , 'fake_test_init' );

function remove_fake_draft($where){
    if(is_admin()) {
        if (filter_input(INPUT_GET, 'post_status') == 'draft') {
            $where .= " and wp_posts.vsp != 'IsFake' ";
        }
        if(filter_input(INPUT_GET, 'post_status') == 'publish'){
            $where .= " and (wp_posts.vsp = 'IsFake' or wp_posts.post_status = 'publish' ) ";
        }
    }
    return $where;
}

function remove_customized_metabox(){
    if(get_post_meta(filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT), 'is_fake', true) == '1') {
        remove_meta_box('submitdiv', 'anew', 'side');
        add_meta_box(
            "_submitdiv",
            __("Publish"),
            "omfgtest",
            'anew',
            'side',
            'high',
            ['show_draft_button' => false]
        );
    }
}

function save_fake_status($post_id){
    if(get_post_meta($post_id, 'is_fake', true) == '1' && get_post_status($post_id) == 'publish') {
        wp_update_post(array(
            'ID'    =>  $post_id,
            'post_status'   =>  'draft'
        ));
    }
}



function omfgtest(  ) {
    global $action, $post;

    $post_id = (int) $post->ID;
    if(get_post_meta(filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT), 'is_fake', true) == '1') {
        $post->post_status = 'publish';
    }
    ob_start();
    post_submit_meta_box($post);
    $cache = ob_get_clean();
    if(get_post_meta(filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT), 'is_fake', true) == '1') {
        echo '<div id="submitdiv">' . $cache . '</div>';
    }else{
        echo $cache;
    }

}

add_action( 'init', 'wordfence_cancel_loading' );
function wordfence_cancel_loading(){
    if(filter_input(INPUT_GET, 'wordfence_syncAttackData', FILTER_SANITIZE_NUMBER_INT)){
        exit;
    }
}


if( !function_exists('index_post_now') ){

    add_action('future_to_publish', 'index_post_now');
    add_action('post_updated', 'index_post_now');

    function index_post_now($post_id): bool {

        $post_id = (is_object($post_id)) ? $post_id->ID : $post_id;

        if (get_post_status($post_id) !== 'publish'){
            return true;
        }

        $params = array(
            "key" => "VCujf3mXZaBsHnkenAW2VUv03CDTJaLpkg4CeQbuSgF73ODaAMThUcuZKpcdTmPWWZ0G7EDZ2FmmN74hMmcjeUwOh5ZbGSLKPAo",
            "url" => get_permalink($post_id)
        );

        $url = "https://yandex.com/indexnow?" . http_build_query( $params );

        file_get_contents($url);

        $url = "https://www.bing.com/indexnow?" . http_build_query( $params );

        file_get_contents($url);

        return true;

    }
}






//Ссылки на КП

add_filter('the_content', function($content) {
    $content = preg_replace('/<a(.*)href="([^"]*)\/kp\.ru([^"]*)"(.*)>/', '<a$1href="' . get_site_url() . '/go/$2/kp.ru$3"$4>', $content);
    $content = preg_replace('/<a(.*)href="([^"]*)\.kp\.ru([^"]*)"(.*)>/', '<a$1href="' . get_site_url() . '/go/$2.kp.ru$3"$4>', $content);
    $content = preg_replace('/<a(.*)href="([^"]*)novostivl\.ru([^"]*)"(.*)>/', '<a$1href="' . get_site_url() . '/go/$2novostivl.ru$3"$4>', $content);
    return $content;

}, 999);



//Возрастное ограничение
add_filter('the_content', function($content){

    if(!preg_match('/[0-9]\+/', $content) && get_post_meta(get_the_ID(), 'event', true) == 1){
        $age = get_post_meta(get_the_ID(), 'age', true);
        $age = $age ? $age : 16;
        $content = $content . "<p>Возрастное ограничение: " . $age . "+</p>";
    }

    return $content;

}, 999);






add_filter( 'wp_video_shortcode', 'video_micromarking_filter_function', 999, 5 );
function video_micromarking_filter_function( $output, $atts, $video, $post_id, $library ){

    $attachment_id = attachment_url_to_postid($atts['mp4']);
    $metadata = wp_get_attachment_metadata($attachment_id);
    $attachmentdata = get_post($attachment_id);


    if($attachment_id == 0){
        return $output;
    }


    $length = explode(":", $metadata['length_formatted']);
    $duration = "PT" . $length[0] . "M" . $length[1]."S";

    $html = '<div itemscope itemtype="https://schema.org/VideoObject">';

    //$html .= '<span itemprop="name" class="d-none">'.get_the_title(get_the_ID()).'</span>';
    $html .= '<meta itemprop="duration" content="'.$duration.'"/>';
    $html .= '<meta itemprop="uploadDate" content="'.date("c", strtotime($attachmentdata->post_date)).'" />';

    if($atts['poster'] != '') {
        $html .= '<meta itemprop="thumbnail" content="' . $atts['poster'] . '"/>';
    }
    if(get_the_excerpt(get_the_ID()) != ''){
        //$html .= '<span itemprop="description" class="d-none">'.get_the_excerpt(get_the_ID()).'</span>';
    }

    $html .= "<!--[if lt IE 9]><script>document.createElement(\'video\');</script><![endif]-->";
    $html .= '<meta itemprop="contentUrl" content="'.$atts['mp4'].'" />';
    $html .= '<video class="wp-video-shortcode" id="video-'.$attachment_id.'-'.$post_id.'" preload="metadata" controls="controls">';
    $html .= '<source type="'.$attachmentdata->post_mime_type.'" src="'.$atts['mp4'].'?_=1" />';
    $html .= '<a href="'.$atts['mp4'].'">'.$atts['mp4'].'</a>';
    $html .= '</video>';

    $html .= '</div>';

    return $html;
}


add_filter('posts_where', function($where){
    if(!is_user_logged_in()) {
        if (
            (filter_input(INPUT_GET, 'id') == 'post_type_archive' && filter_input(INPUT_GET, 'post_id') == 'anew')
            ||
            (is_post_type_archive() && get_queried_object()->name == 'anew' && !is_admin())
        ) {
            //$where .= " AND `wp_posts`.`ID` NOT IN (SELECT `object_id` from `wp_term_relationships` where `term_taxonomy_id` = 103565) ";
        }
    }
    return $where;
},999);




function use_new_template(){
    return false;
    if(
        get_current_user_id() == 1
        &&
        wp_is_mobile()
    ){
        return true;
    }
    return false;
}

function use_new_banner(){
    if(
        get_current_user_id() == 1
        &&
        wp_is_mobile()
    ){
        return true;
    }
    return false;
}





add_action( 'init', 'no_access_to_edit_posts' );
function no_access_to_edit_posts(){
    if(
        is_admin()
        &&
        is_user_logged_in()
        &&
        in_array(filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT), [1027239])
        &&
        !in_array(get_current_user_id(), [58, 3, 1])
    ){
        wp_die('Вам запрещено редактировать этот материал');
    }
}



add_filter( 'get_the_tags', 'remove_agregator_front', PHP_INT_MAX );
function remove_agregator_front( $terms ){
    if(get_current_user_id() != 1){
        //return $terms;
    }
    if(!is_admin()) {
        foreach ($terms as $i => $term) {
            if($term->term_id == 103565){
                unset($terms[$i]);
            }
        }
    }
    return $terms;
}
add_filter( 'posts_where', function($where){
    if(is_feed()){
        //$where .= " AND wp_posts.post_date < (NOW() - INTERVAL 1 MINUTE) ";
    }
    return $where;
}, PHP_INT_MAX );







add_filter('ep_index_name', function($index_name, $blog_id, $indexable){
    $index_name = str_replace('admin', '', $index_name);
    return $index_name;
},99,3);

add_action('the_content', 'remove_admin');
add_action('the_permalink', 'remove_admin');
function remove_admin($content){
    $content = str_replace('admin.profile.ru', 'profile.ru', $content);
    return $content;
}



add_filter( 'rank_math/instant_indexing/publish_url', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );
add_filter( 'rank_math/instant_indexing/submit_url', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );
add_filter( 'rank_math/instant_indexing/indexnow_key_location', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );

add_filter( 'rank_math/indexing_api/publish_url', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );
add_filter( 'rank_math/indexing_api/submit_url', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );
add_filter( 'rank_math/indexing_api/indexnow_key_location', function( $url ) {
    return str_replace( 'admin.profile.ru', 'profile.ru', $url );
}, PHP_INT_MAX, 1 );

add_filter( 'http_request_args',
    function ( $parsed_args, $url ){
        if($url === 'https://api.indexnow.org/indexnow/'){
            foreach ($parsed_args as $i => $arg){
                if(is_string($arg) && mb_stripos($arg, 'admin') !== false){
                    $parsed_args[$i] = preg_replace('/admin(.*)profile\.ru\"/i', 'profile.ru"', $parsed_args[$i]);
                }
            }
        }
        return $parsed_args;
    }, 10, 2 );












































































add_filter('posts_where', function($where){
    if(is_admin()){
        if(is_user_logged_in() && !in_array(get_current_user_id(),[1,3])){
            $where .= " AND `wp_posts`.`ID` NOT IN (SELECT object_id FROM wp_term_relationships where term_taxonomy_id = 104862) AND 111 = 111  ";
        }
    }else{
        if(is_single()){
            if(is_user_logged_in() && !in_array(get_current_user_id(),[1,3])){
                $where .= " AND `wp_posts`.`ID` NOT IN (SELECT object_id FROM wp_term_relationships where term_taxonomy_id = 104862) AND 222 = 222   ";
            }
        }else{
            if(!is_yn()) {
                $where .= " AND `wp_posts`.`ID` NOT IN (SELECT object_id FROM wp_term_relationships where term_taxonomy_id = 104862) AND 333 = 333 ";
            }
        }
    }
    if(filter_input(INPUT_GET, 'action') == 'alm_get_posts'){
        $where .= " AND `wp_posts`.`ID` NOT IN (SELECT object_id FROM wp_term_relationships where term_taxonomy_id = 104862) AND 444 = 444  ";
    }
    return $where;
},999,1);

add_filter( 'ep_index_posts_args', function( $args ) {
    //if(is_user_logged_in() && !in_array(get_current_user_id(),[1,3])) {
        $exclude = get_posts( [
            'fields'           => 'ids',
            'numberposts'      => -1,
            'category'         => 104862,
            'post_type'        => ['profile_article','anew','yellow'],
            'suppress_filters' => true,
        ] );



        $args['post__not_in'] = $exclude;
    //}
    return $args;
});


add_filter( 'get_terms', function ( $terms, $taxonomies, $args, $term_query ){
    if(is_user_logged_in() && !in_array(get_current_user_id(), [1,3])){

        $exclude = ['profil'];

        foreach ($terms as $key => $term) {
            if (in_array($term->slug, $exclude)) {
                unset($terms[$key]);
            }
        }

    }

    return $terms;
}, 999, 4 );

add_filter('get_the_terms', 'hide_categories_terms', 999, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
    if(is_user_logged_in() && !in_array(get_current_user_id(), [1,3])){

        $exclude = ['profil'];

        foreach ($terms as $key => $term) {
            if (in_array($term->slug, $exclude)) {
                unset($terms[$key]);
            }
        }

    }

    return $terms;
}




/**
 * Filters WP_Query arguments for initial ElasticPress indexing.
 * Searches for posts with 'do_not_index' and adds those post IDs to 'posts__not_in' argument.
 * @param array $args
 * @return array
 */
function my_ep_filter( $args ) {
    $query   = new WP_Query( [
        'fields'           => 'ids',
        'numberposts'      => -1,
        'category'         => 104862,
        'post_type'        => ['profile_article','anew','yellow'],
        'suppress_filters' => true,
    ] );
    if ( 0 != $query->post_count ) {
        $args[ 'post__not_in' ] = $query->posts;
    }
    return $args;
}

add_filter( 'ep_index_posts_args', 'my_ep_filter' );

/**
 * Filter to determine if a post should not be indexed.
 * @param bool $return_val Default is false.
 * @param array $post_args
 * @param int $post_id
 * @return boolean
 */
/*function my_ep_stop_sync( $return_val, $post_args, $post_id ) {

    $to_index = has_category(104862, $post_id);

    if ( true === boolval( $to_index ) ) {
        return false;
    }

    if ( function_exists( 'ep_delete_post' ) ) {
        ep_delete_post( $post_id );
    }

    return true;
}

add_filter( 'ep_post_sync_kill', 'my_ep_stop_sync', 10, 3 );*/





add_action('wp_insert_post', 'news_telegram_log', 10, 1 );

//хук для запланированных
add_action('transition_post_status', function($new_status, $old_status, $post) {
    if ($new_status == 'publish' && $old_status == 'future') {
       news_telegram_log($post);
    }
}, 10, 3);

function news_telegram_log($post){

    $post = get_post($post);

    $post_id = $post->ID;

    if(
        get_post_status($post_id) !== 'publish'
        ||
        !in_array(get_post_type($post_id), array('anew', 'yellow', 'profile_article'))
        ||
        get_post_meta($post_id, 'telegram_log', true)
    ){
        return;
    }

    if(wp_get_post_categories($post_id)[0] == 104862){
        return;
    }

    // Получаем и проверяем ссылку
    $curr_link = get_permalink($post_id);
    if (empty($curr_link)) {
        error_log('Telegram bot: Empty permalink for post ID ' . $post_id);
        return;
    }

    $curr_link = fix_broken_url($curr_link, 'profile.ru'); //корректируем ссылку с ошиюбками

    $content = '<a href="'.$curr_link.'?utm_from=telegram">'.get_the_title($post_id).'</a>';
    $content = str_replace('admin.', '', $content);
    $request = "https://api.telegram.org/bot1184440628:AAE5N10dnzClx3Qce4v1mBD9ax1BsHo98Rs/sendMessage?chat_id=-1001588455134&parse_mode=HTML&text=".urlencode($content);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    curl_setopt($ch, CURLOPT_URL, $request);
    $return = curl_exec($ch);

    update_post_meta($post_id, 'telegram_log', 1);

    return true;

}




























function show_thumbnail($id = false) : bool
{

    if(!$id){
        $id = get_the_ID();
    }

    // НОВОЕ УСЛОВИЕ: Амнистия для постов, опубликованных после 1 августа 2025 года
    $amnestyDate = strtotime('2025-08-01');

    if (get_the_date("U", $id) > $amnestyDate) {
        return true;
    }

    $days = ((get_post_meta($id,'_hide_thumbnail_countdown'))[0]);

    if ( $days == NULL ){
        return true;
    }

    if ($days === 0 || $days === '0') {
        return true;
    }

    $days = (int)$days;

    if ((((date("U") - get_the_date("U")) > 86400*$days && $days >= 0) && count(get_post_meta($id,'_hide_thumbnail_countdown')) !== 0) || $days == 0 ){

        return false;

    }
    if((is_single() || is_turbo()) && in_array(get_post_type($id), ['anew', 'yellow'])) {

        if (date("U") - get_the_date("U", $id) > 24 * 60 * 60 * 10) {

            $term = get_the_category($id)[0];
            if($term->category_parent == 11430 || $term->term_id == 11430) {
                return true;
            }

            if(get_post_meta($id, 'event', true) == 1) {
                return true;
            }

            if (get_the_date("U", $id) < 1483228800) {
                return true;
            }

            $allow = [
                "Global Look Press",
                "ТАСС",
                "TASS",
                "AFP",
                "«Профиль»",
                "kremlin.ru",
                "president.gov.ua",
                "president.gov.by",
                "NASA",
                "АГН «Москва»",
                "АГН Москва",
                "Агентство «Москва»",
                "Авгурова",
                "mil.ru",
                "roscosmos.ru",
                "mid.ru",
                "vostock photo",
                "duma.gov.ru",
                "Пресс-служба"
            ];



            $copyright = wp_get_attachment_caption( get_post_thumbnail_id($id) );

            foreach ($allow as $substr){
                if(mb_stripos($copyright, $substr)){
                    return true;
                }
            }

            return false;
        }
    }

    return true;
}






add_filter( 'post_gallery', function($output, $attr) {

    if(is_single() && in_array(get_post_type(), ['anew', 'yellow'])) {
        if (date("U") - get_the_date("U") > 24 * 60 * 60 * 10) {
            $output = " ";
        }
    }

    return $output;

}, 999, 2);






function is_in_dk() : bool
{

    if (is_single()) {
        $category = array_shift(get_the_category());
        if($category->term_id === 11430 || $category->parent === 11430){
            return true;
        }
    }

    if (is_category()) {
        $category = get_category( get_query_var( 'cat' ) );
        if($category->term_id === 11430 || $category->parent === 11430){
            return true;
        }
    }

    return false;

}


add_filter( 'wp_redirect',function  ( $location, $status ) {

    $location = str_replace("g.profile.ru", "profile.ru", $location);

    return $location;

}, 10, 2 );


/**
 * Экспорт в знай наших
 */
/*
add_action('save_post', function($post_id) {

    if (!defined('DOING_AUTOSAVE') && (has_category("104807", $post_id) || get_post_type() === "guest-author")) {

        wp_schedule_single_event( time() + 60, 'export_import_zn_hook', [ $post_id ] );

    }

});

add_action('export_import_zn_hook', 'export_import_zn');

function export_import_zn($post_id) {

    debug($post_id);

    $thumb = (int)get_post_meta($post_id, "_thumbnail_id", true);

    if($thumb > 0){
        exec(" /var/www/exports/scripts/export-import.sh " . $thumb . " > /dev/null &");
    }

    if($post_id > 0){
        exec(" /var/www/exports/scripts/export-import.sh " . $post_id . " > /dev/null &");
    }


}


//Трансляция в телеграм Знай Наших
add_action("save_post", function($post_id) {

    if(
        !defined('DOING_AUTOSAVE') &&
        in_array( get_post_type($post_id), ["anew", "profile_article"] ) &&
        get_post_status($post_id) === "publish" &&
        has_category("104807", $post_id) &&
        !get_post_meta($post_id, "_zn_tg_channel_posted")
    )
    {

        $bot_id = "1108783670:AAGm7_vdXQAte25OGUa5gWJNXhy5-v6d_hU";
        $chat_id = "-1001960709397";

        $text = '<a href="' . get_the_permalink($post_id) . '?utm_from=telegram">' . get_the_title($post_id) . '</a>';
        $text = str_replace('admin.', '', $text);

        $request = "https://api.telegram.org/bot" . $bot_id . "/sendMessage?chat_id=" . $chat_id . "&parse_mode=HTML&text=" . urlencode($text);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ( curl_exec($ch) ) {
            update_post_meta($post_id, '_zn_tg_channel_posted', 1);
        }

    }

}, 999, 1 );
*/

add_filter( 'sanitize_file_name', function($filename){

    return strtolower( $filename );

}, 10 );






add_action("transition_post_status", "mainpage_producer_wpcli", 10, 3);
function mainpage_producer_wpcli($new_status, $old_status, $post) {

    if ($post->post_type === "profile_article" && $new_status === "publish") {

        wp_schedule_single_event( time() + 30, 'mainpage_producer_update' );

    }

}

/*
add_action('save_post', 'mainpage_producer_user', 999, 1 );
function mainpage_producer_user($post_id){

    if(get_post_type($post_id) == 'profile_article' && get_post_status($post_id) == 'publish') {

        mainpage_producer_requests();

    }

}

*/

add_filter( 'rank_math/frontend/robots', function( $robots ) {

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    if(1 != $paged) {
        $robots = ["noindex", "nofollow"];
    }

    return $robots;
});





function rewrite_post_slug(int $post_id, string $slug) : ?bool
{


    add_action("init", function() use ($post_id, $slug) {

        add_rewrite_rule( '^' . $slug . '(.*)', 'index.php?p='.$post_id, 'top' );

    });


    add_filter("the_permalink", function($permalink, $post) use ($post_id, $slug) {

        $post = get_post($post);
        $id = $post->ID;

        if($post_id == $id) {
            $permalink = "/" . $slug;
        }

        return $permalink;

    }, 10, 2);

    add_filter( 'rank_math/sitemap/entry', function( $url, $type, $object ) use ($post_id, $slug) {

        $id = $object->ID;

        if($post_id == $id) {

            $url["loc"] = "https://profile.ru/" . $slug;

        }

        return $url;
    }, 10, 3 );

    add_filter( 'rank_math/frontend/canonical', function( $canonical ) use ($post_id, $slug) {

        if($canonical == get_permalink($post_id)) {

            $canonical = "/" . $slug;

        }

        return $canonical;

    }, 10, 1);

    add_action("template_redirect", function() use ($post_id, $slug) {

        $id = get_queried_object_id();

        if($id == $post_id) {

            if (get_permalink($id) ==  'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) {

                wp_redirect("/" . $slug);

            }

        }

    }, 10);

    return true;
}

rewrite_post_slug(1328478, "profil/maksim-barskij-sibantracit");






function first_sentence (string $content) : string
{

    $dom = new DOMDocument("1.0", "UTF-8");

    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);

    $xpath = new DOMXPath($dom);

    $first_el = $xpath->query("//html/body/*")->item(0);

    $arr = explode(".", $first_el->nodeValue);
    $sentence = array_shift($arr);
    if($first_el->nodeName == "p"){
        $sentence .= ".";
    }

    foreach( ["\"" => "\"", "'" => "'", "«" => "»"] as $open => $close ) {



        if(mb_strripos($sentence, $open) !== false && mb_strripos($first_el->nodeValue, $close) > mb_strpos($first_el->nodeValue, ".")){

            $arr = explode($close, $first_el->nodeValue);
            $sentence = array_shift($arr) . $close. ".";

        }

    }

    $output_el = $dom->createElement( $first_el->nodeName );
    $output_el->nodeValue = $sentence;



    $a =  $dom->saveXML($output_el);

    return $a;

}


add_filter("the_content", function ($content){

    

    if(is_single() && in_array(get_post_type(get_queried_object_id()), ["anew","profile_article","yellow"])){

        $paragraphs = explode("</p>", $content);

        array_shift($paragraphs);

        $content = implode("</p>", $paragraphs);



    }
    return $content;
},999);


function first_paragraph(){

    $content = wpautop( get_the_content() );

    $paragraphs = explode("</p>", $content);

    return $paragraphs[0] . "</p>";

}


function is_edit_page($new_edit = null) {
    global $pagenow;
    if (!is_admin()) return false;


    if($new_edit == "edit")
        return in_array( $pagenow, array( 'post.php',  ) );
    elseif($new_edit == "new") //check for new post page
        return in_array( $pagenow, array( 'post-new.php' ) );
    else //check for either new or edit
        return in_array( $pagenow, array( 'post.php', 'post-new.php' ) );
}


/**
 * Это позже довести до ума
 * @param string $output
 * @param array $attr
 * @param int $instance
 * @return void
 */
function override_gallery_html_site(string $output, array $attr, int $instance )// : string
{

    if(is_feed() || is_amp_endpoint()){
        //return $output;
    }

    if(in_array(get_post_type(), ["anew", "yellow"]) && get_the_date("U") < 1719187200 ) {
        $output = "<div></div>";

        return $output;
    }

    $attachments_query = new WP_Query(
        [
            "post_type" => ["attachment"],
            "post_status" => ["inherit", "publish"],
            "post__in" => explode(",", $attr["ids"]),
            "orderby" => "post__in",
            "ignore_sticky" => true,
            "suppress_filters" => true,
            "posts_per_page" => -1
        ]
    );

    $images = "";
    $thumbs = "";
    $descs = "";

    if ( $attachments_query->have_posts() ) {


        while ( $attachments_query->have_posts() ) {

            $attachments_query->the_post();



            $images .= "
                <div class=\"swiper-slide col-12 p-0\">
				    <img src=\"" . wp_get_attachment_image_url( get_the_ID(), "large" ) . "\" data-url=\"?image=" . $attachments_query->current_post . "\" alt=\"". get_the_content( get_the_ID() ) ."\" data-auth=\"". wp_get_attachment_caption( get_the_ID() ) ."\" />
			    </div>
                ";

            $thumbs .= "
                <div class=\"swiper-slide gallery-mini-slide\">
                    <img src=\"" . wp_get_attachment_image_url( get_the_ID(), "medium" ) . "\" data-url=\"?image=" . $attachments_query->current_post . "\" alt=\"\" data-type=\"gallery-nav\" />
                </div>
            ";

            $descs .= "
                <div class=\"swiper-slide gallery-text-slide d-flex flex-column\">
                    <span> ". get_the_content( get_the_ID() ) ." </span>
                    <p>
                        ". wp_get_attachment_caption( get_the_ID() ) ."
                    </p>
                </div>
            ";

            wp_reset_postdata();

        }

        $html = "
<div class=\"swiper-block\">
	<div class=\"gallery\">

		<div class=\"swiper-wrapper d-flex flex-row\">

";
$html .= $images;
$html .= "
		</div>
		<div class=\"gallery-prev\"></div>
		<div class=\"gallery-next\"></div>
		<div class=\"gallery-pagination\"></div>
	</div>
	<div thumbsSlider=\"\" class=\"gallery-mini\">
	<div class=\"swiper-wrapper gallery-mini-wrapper d-flex flex-row\">
";
$html .= $thumbs;

$html .= "		</div>
	</div>
	<div thumbsSlider=\"\" class=\"gallery-text\">
		<div class=\"swiper-wrapper gallery-text-wrapper d-flex flex-row\">";
$html .= $descs;
$html .= "		</div>
	</div>

</div>";
        $output = $html;
        return $output;
    }

    wp_reset_postdata();
    wp_reset_query();


    return $output;

}


function override_gallery_html_api(string $output, array $attr, int $instance )// : string
{

    if(is_feed() || is_amp_endpoint()){
        //return $output;
    }

    $attachments_query = new WP_Query(
        [
            "post_type" => ["attachment"],
            "post_status" => ["inherit", "publish"],
            "post__in" => explode(",", $attr["ids"]),
            "orderby" => "post__in",
            "ignore_sticky" => true,
            "suppress_filters" => true,
            "posts_per_page" => -1
        ]
    );



    if ( $attachments_query->have_posts() ) {


        while ($attachments_query->have_posts()) {

            $attachments_query->the_post();


            $output .= "
                <p>
				    <img src=\"" . wp_get_attachment_image_url(get_the_ID(), "large") . "\" data-url=\"?image=" . $attachments_query->current_post . "\" alt=\"" . htmlspecialchars(get_the_content(get_the_ID())) . "\" data-auth=\"" . wp_get_attachment_caption(get_the_ID()) . "\" />
			    </p>
                ";

        }

    }

    return $output;

}

function override_gallery_html(string $output, array $attr, int $instance )// : string
{

    if( defined('REST_REQUEST') ){

        return override_gallery_html_api($output, $attr, $instance);

    }

    return override_gallery_html_site($output, $attr, $instance);
}

add_filter("post_gallery", "override_gallery_html", 9999, 3);







function main_photo_caption( $str ){

    $str = str_ireplace('depositphotos.com', '<a target="_blank" href="https://depositphotos.com/">depositphotos.com</a>', $str);

    return $str;

}



function m_debug_log($content){
    error_log(
        sprintf("%s Error: %s\n", date("Y-m-d h:i:s"), $content),
        3,
        \WP_CONTENT_DIR . "/debug.log"
    );
}



//Костыль для отображения бОльшего количества меток при поиске из материала
add_filter("get_terms_args", function($args){

    if( $_GET["action"] === "ajax-tag-search" ) {

        $args["number"] = 0;

    }


    return $args;


}, 999, 1);






/**
 * Исправление ошибки с тайтлами на странице автора
 * @param string $title
 * @return string
 */
function author_page_title(string $title) : string
{

    if( is_author() && is_archive() ) {

        $title = str_contains($title, get_queried_object()->display_name) ? $title : get_queried_object()->display_name . $title;

    }

    return $title;

}
add_filter( "rank_math/frontend/title", "author_page_title", 99);



add_action("save_post", function($post_id){

    if(get_post_status($post_id) === "publish"){

        if (function_exists ('rocket_clean_files' ) ){

            rocket_clean_files(['https://g.profile.ru/author']);
            rocket_clean_files(['https://profile.ru/author']);
        
        }    

    }


},999);


//
add_action('acf/save_post', 'mark_url_chatgpt');
function mark_url_chatgpt( $post_id ) {

    if(
        !in_array(
            get_post_type( $post_id ),
            ["profile_article", "anew"]
        )
    ) {

        return;

    }

    $gpt_marker = get_field('chatgpt', $post_id);
    $gpt_str_marker = "a999";

    $post_name = get_post_field( 'post_name', $post_id );
    $post_title = get_post_field( 'post_title', $post_id );
    $post_status = get_post_field( 'post_status', $post_id );
    $post_type = get_post_field( 'post_type', $post_id );

    if($gpt_marker && !str_ends_with($post_name, $gpt_str_marker)) {

        wp_update_post(
            [
                'ID' => $post_id,
                'post_name' => wp_unique_post_slug( sanitize_title( $post_title ), $post_id, $post_status, $post_type, 0 ) . "-" . $gpt_str_marker
            ]
        );

    }


}













/**
 *
 * Allow using any attributes and any tags in tinymce
 *
 */
add_action("tiny_mce_before_init", function ( $mce_init, $editor_id ){

    $mce_init["extended_valid_elements"] = "*[*]";
    $mce_init["valid_elements"] = "*[*]";
    $mce_init["paste_as_text"] = true;

    return $mce_init;

},99,2);

add_filter("the_content", function($content){

        $dom = new DOMDocument();
        $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);

        $links = $dom->getElementsByTagName('a');

        foreach ($links as $link) {

            if ($link->getAttribute("redirect") == "true" && mb_strlen($link->getAttribute("href")) > 0) {

                $link->setAttribute("href", 'https://profile.ru/redirection?url=' . urlencode($link->getAttribute("href")));
                $link->setAttribute("target", '_blank');

            }

        }

        return str_replace(['<body>', '</body>'], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0)));


}, 11, 1);



function is_night():bool {

    if((int)date("H") < 5) return true;

    return false;
}





function update_attachment_date( int $post_id )
{
    /*$postdate = '2010-02-23 18:57:33';

    $my_args = array(
        'ID' => $post_id,
        'post_date' => $postdate
    );*/



    if(get_current_user_id() != 1) {
        return;
    }

    if ( ! wp_is_post_revision( $post_id ) ){

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'update_attachment_date');

        // update the post, which calls save_post again
        //wp_update_post( $my_args );

        debug($_POST);die;

        // re-hook this function
        add_action('save_post', 'update_attachment_date');
    }
}
add_action('save_post', 'update_attachment_date');


//выводит ссылку на сайт автора
function get_profile_website_link( $url ) {
    
    if ( ! $url ) {
        return '';
    }

    // Удаляем протокол и www для текста ссылки
    $display_url = preg_replace('#^https?://(www\.)?#', '', rtrim($url, '/'));

    // Генерируем HTML-ссылку
    return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($display_url) . '</a>';
}
