<?php



// ENABLE ERROR REPORTING - SHOW ALL ERRORS IN BROWSER


/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */
/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool 1
 */



define('WP_USE_THEMES', true);
/** Для обхода кеша при запросах к API можно добавлять ?rand=2748274 */
if (!defined('EG_CACHE_RAND')) define('EG_CACHE_RAND', '2748274');
$start1 = microtime(true);

$GLOBALS['start1'] = microtime(true);
$GLOBALS['start2'] = microtime(true);

$GLOBALS['profile_log'] ='';

if (!function_exists('myprofile')) {
    function myprofile($name = '')
    {


        $fromstart = microtime(true) - $GLOBALS['start1'];
        $fromstart2 = microtime(true) - $GLOBALS['start2'];
        $GLOBALS['profile_log'] .= "\n $name $fromstart | $fromstart2";
        $GLOBALS['start2'] = microtime(true);

    }
}


if (isset($_GET['debug'])) {
    ini_set('error_reporting', E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
} else {
    ini_set('error_reporting', 0);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);

}


function cleanhtml($html) {
    if (isset($_GET['utm']) && $_GET['utm']=='clean') {
        $clean=$_GET['clean'];

        return preg_replace('/<div class=\''.$clean.' ad_.*?div   >/s','<!--deleted-->',$html);
    } else {
        return $html;
    }
}

if (!isset($_GET['getsitemap']) && preg_match('/\/sitemap-pt-post-(\d+)-(\d+)-(\d+)\.xml/', $_SERVER['REQUEST_URI'], $matches)) {
    if (file_exists('tmp/sitemap' . $matches[0])) {
        Header("Content-Type: text/xml");
        echo file_get_contents('tmp/sitemap' . $matches[0]);

    }

    exit;

}

if (!isset($_GET['getsitemap']) && preg_match('/\/sitemap(.*)\.xml/', $_SERVER['REQUEST_URI'], $matches)) {
    if (file_exists('tmp/sitemap' . $matches[0])) {
        Header("Content-Type: text/xml");
        echo file_get_contents('tmp/sitemap' . $matches[0]);

    }

    exit;

}

$http_host= (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $argv[2]);

if (!in_array($http_host, array('wp1.deveg.local','wp.deveg.local','wp.dev.eg.ru', 'ed.eg.ru')) && (preg_match('/(wp-login|admin)/', str_replace('admini','', $_SERVER['REQUEST_URI'])))) {
    Header("Location:/");
    exit();
}
if (!in_array($http_host, array('wp.dev.eg.ru', 'ed.eg.ru')) && isset($_GET['s'])) {
    Header("Location:/");
    exit();
}
if (in_array($http_host, array('wp.dev.eg.ru', 'ed.eg.ru'))) {
    ini_set('max_execution_time', 180);
    ini_set('upload_max_filesize', '40M');
    ini_set('post_max_size', '40M');
    ini_set("memory_limit", "256M");
}
if (in_array($http_host, array('ed.eg.ru')) && ('/' == $_SERVER['REQUEST_URI'])) {
    Header("Location:/wp-admin");
    exit();
}

if (in_array($http_host, array('www.eg.ru', 'eg.ru', 'ed.eg.ru'))) {
    define('MEMCACHE_SERV', '172.16.69.31');
    define('MEMCACHE_PORT', '11211');
    if (!defined('WP_HOME')) {
        define('WP_HOME', 'https://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $argv[2]));
    }
    $production=true;
} else {
    define('MEMCACHE_SERV', 'localhost');
    define('MEMCACHE_PORT', '11211');
    if (!defined('WP_HOME')) {
        define('WP_HOME', 'https://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $argv[2]));
    }
    $production=false;
    if (in_array($http_host, array('linx.eg.ru'))) {$production=true;}
}
chdir(dirname(__FILE__));
$URIreq = $_SERVER['REQUEST_URI'];

if (strpos($URIreq ,'/category/')!==false ) {
    $url=str_replace('/category/','/',$URIreq);
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:". $url);
    exit();
}



$redir=array("/tags/numbers/"=>"/tag/svezhiy-nomer/","/society/531105/"=>"/","/politics/1107656-zachem-vysokopostavlennyy-chlen-kprf-hodit-k-bdsm-gospoje/"=>"/politics/","/politics/769197-prankery-kupili-kommunistku-shuvalovu-ot-imeni-edinoy-rossii-084157/"=>"/politics/769578-prankery-171kupili187-kommunistku-shuvalovu-ot-imeni-171edinoy-rossii187/","/society/635314/"=>"/society/635314-stalo-izvestno-kak-rossiyane-budut-otdyhat-na-novogodnie-i-mayskie-prazdniki/","/society/63058/"=>"/society/63178/","/showbusiness/66837/"=>"/showbusiness/66833/","/society/63334/"=>"/society/63335/","/society/66540/"=>"/society/66541/","/politics/62702/"=>"/politics/62703/","/society/3950/"=>"/society/3949/","/showbusiness/66224/"=>"/culture/66223/","/politics/64197/"=>"/politics/64198/","/sport/57057/"=>"/sport/57056/","/society/62578/"=>"/society/62577/","/society/62576/"=>"/society/62577/","/showbusiness/58356/"=>"/science/58358/","/showbusiness/58357/"=>"/science/58358/","/politics/67274/"=>"/society/347922/","/politics/60969/"=>"/politics/60970/","/politics/59994/"=>"/politics/59993/","/society/57523/"=>"/society/57524/","/tech/57798/"=>"/tech/57799/","/politics/4224/"=>"/society/4223/","/politics/65972/"=>"/politics/65973/","/society/56679/"=>"/society/56685/","/society/56680/"=>"/society/56685/","/society/56681/"=>"/society/56685/","/society/56682/"=>"/society/56685/","/society/56683/"=>"/society/56685/","/society/395781/"=>"/society/396409/","/society/61781/"=>"/society/61780/","/society/61779/"=>"/society/61780/","/society/61783/"=>"/society/61780/","/society/61782/"=>"/society/61780/","/showbusiness/4112/"=>"/showbusiness/4111/","/society/62415/"=>"/society/62414/","/society/58654/"=>"/society/58668/","/sport/65021/"=>"/sport/65020/","/politics/66644/"=>"/politics/66643/","/politics/64180/"=>"/politics/64179/","/politics/64181/"=>"/politics/64179/","/showbusiness/347925/"=>"/culture/67310/","/tech/61397/"=>"/tech/61368/","/showbusiness/62001/"=>"/showbusiness/62000/","/tech/56265/"=>"/tech/56266/","/politics/62646/"=>"/politics/62647/","/politics/61777/"=>"/politics/61776/","/society/67209/"=>"/society/67208/","/society/67210/"=>"/society/67208/","/society/57165/"=>"/society/57164/","/society/61232/"=>"/society/61233/","/auto/62930/"=>"/auto/62931/","/sport/63846/"=>"/sport/63845/","/index.php"=>"/","//"=>"/","///"=>"/","////"=>"/");

if (isset($redir[$URIreq])) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:".$redir[$URIreq]);
    exit();

}

$rtags=array(623706 =>'igor-zolotovickiy',624720 =>'dmitriy-nagiev',625744 =>'alla-pugacheva',626580 =>'maksim-galkin',628122 =>'olga-buzova',628795 =>'filipp-kirkorov',629979 =>'stas-mihaylov',630405 =>'valeriya',631258 =>'egor-krid',633357 =>'timati',633623 =>'sharl-aznavur',634146 =>'aleksey-vorobev',634410 =>'roman-karcev',635239 =>'polina-gagarina',635488 =>'pelageya',636120 =>'leonid-agutin',636337 =>'valeriy-meladze',637087 =>'lev-leshchenko',637213 =>'dima-bilan',637735 =>'monserrat-kabale',638693 =>'denis-klyaver',638750 =>'natalya-chistyakova-ionova',639418 =>'habib-nurmagomedov',639756 =>'makgregor',640231 =>'aleksandr-kokorin',640600 =>'pavel-mamaev',641130 =>'sergey-shnurov',641411 =>'ivan-urgant',642187 =>'mark-zaharov',642741 =>'basta',643197 =>'ani-lorak',643698 =>'dmitriy-hvorostovskiy',644094 =>'ilya-lagutenko',644566 =>'eminem',645252 =>'konstantin-meladze',645911 =>'sergey-bezrukov',646199 =>'jan-klod-van-damm',646962 =>'katya-gordon',647175 =>'veronika-kastro',647945 =>'tatyana-ovsienko',648702 =>'katrin-denev',649332 =>'arkadiy-raykin',649748 =>'venedikt-erofeev',650381 =>'mihail-galustyan',650825 =>'vlad-topalov',651446 =>'emiliya-klark',651907 =>'tom-hardi',652550 =>'nikolay-karachencov',653219 =>'ivanka-tramp',653448 =>'diego-maradona',653823 =>'regina-todorenko',654273 =>'vladimir-zeldin',654577 =>'mariya-poroshina',654917 =>'ayshvariya-ray',655449 =>'david-cherkasskiy',656243 =>'elena-zaharova',656672 =>'garik-harlamov',657353 =>'evgeniy-plyushchenko',658018 =>'yana-churikova',658150 =>'emma-stoun',658270 =>'pavel-pogrebnyak',659117 =>'oleg-menshikov',660736 =>'mariya-sittel',661802 =>'mihail-efremov',662768 =>'lyudmila-gurchenko',662306 =>'yuliya-kovalchuk',662433 =>'olga-orlova',663643 =>'lolita-milyavskaya',664323 =>'mariya-kojevnikova',664044 =>'anna-semenovich',665398 =>'aleksandr-malinin',666049 =>'anastasiya-volochkova',666628 =>'evgeniya-medvedeva',667388 =>'kseniya-sobchak');



foreach ($rtags as $rid=>$rval) {
    if (strpos($URIreq,'/'.$rid)!==false) {

        Header("HTTP/1.1 301 Moved Permanently\n");
        Header("Location:/tag/".$rval.'/');
        exit();

    }
}

$redir=array("/society/56488/","/society/57212/","/society/65596/","/society/66804/","/economics/377761/","/economics/387408/","/tech/389003/","/society/56910/","/society/57386/","/society/55796/","/society/57095/","/economics/58223/","/economics/59194/","/sport/41216/","/sport/41217/","/sport/41218/","/sport/41219/","/sport/41220/","/sport/41221/","/sport/41476/","/sport/41477/","/sport/41478/","/sport/41479/","/sport/41480/","/sport/41565/","/sport/41566/","/sport/41675/","/sport/41797/","/sport/41798/","/sport/41799/","/sport/41901/","/sport/42068/","/sport/42072/","/sport/42073/","/sport/42074/","/sport/42075/","/sport/42077/","/sport/42080/","/sport/42096/","/sport/42098/","/sport/42113/","/sport/42127/","/sport/42129/","/sport/42130/","/sport/42163/","/sport/42167/","/sport/42178/","/sport/42187/","/sport/42198/","/sport/42199/","/sport/42200/","/sport/42207/","/sport/42218/","/sport/42219/","/sport/42220/","/sport/42235/","/sport/42237/","/sport/42248/","/sport/42254/","/sport/42264/","/sport/42275/","/sport/42287/","/sport/42313/","/sport/42314/","/sport/42323/","/sport/42327/","/sport/42410/","/sport/42436/","/sport/42476/","/sport/42500/","/sport/42501/","/sport/42522/","/sport/42545/","/sport/42581/","/sport/42602/","/sport/42603/","/sport/42617/","/sport/42618/","/sport/42619/","/sport/42653/","/sport/42654/","/sport/42661/","/sport/42737/","/sport/42739/","/sport/42780/","/sport/42822/","/sport/42834/","/sport/43071/","/sport/43072/","/sport/43218/","/sport/43226/","/sport/43231/","/sport/43233/","/sport/43234/","/sport/43250/","/sport/43251/","/sport/43252/","/sport/43253/","/sport/43254/","/sport/43266/","/sport/43269/","/sport/43287/","/sport/43288/","/sport/43289/","/sport/43316/","/sport/43317/","/sport/43333/","/sport/43342/","/sport/43343/","/sport/43344/","/sport/43345/","/sport/43346/","/sport/43368/","/sport/43393/","/sport/43409/","/sport/43410/","/sport/43424/","/sport/43440/","/sport/43466/","/sport/43467/","/sport/43469/","/sport/43471/","/sport/43478/","/sport/43510/","/sport/43514/","/sport/43532/","/sport/43549/","/sport/43573/","/sport/43626/","/sport/43627/","/sport/43628/","/sport/43647/","/sport/43661/","/sport/43662/","/sport/43682/","/sport/43683/","/sport/43684/","/sport/43685/","/sport/43718/","/sport/43719/","/sport/43720/","/sport/43760/","/sport/43813/","/sport/43830/","/sport/43836/","/sport/43851/","/sport/43896/","/sport/43901/","/sport/43903/","/sport/43905/","/sport/43914/","/sport/43944/","/sport/43945/","/sport/43968/","/sport/43978/","/sport/44001/","/sport/44026/","/sport/44042/","/sport/44049/","/sport/44050/","/sport/44072/","/sport/44073/","/sport/44098/","/sport/44127/","/sport/44151/","/sport/44163/","/sport/44165/","/sport/44181/","/sport/44182/","/sport/44243/","/sport/44261/","/sport/44402/","/sport/44415/","/sport/44421/","/sport/44425/","/sport/44426/","/sport/44428/","/sport/44429/","/sport/44454/","/sport/44466/","/sport/44469/","/sport/44486/","/sport/44505/","/sport/44547/","/sport/44548/","/sport/44604/","/sport/44605/","/sport/44615/","/sport/44618/","/sport/44656/","/sport/44664/","/sport/44670/","/sport/44682/","/sport/44722/","/sport/44745/","/sport/44780/","/sport/44815/","/sport/44830/","/sport/44851/","/sport/44857/","/sport/44953/","/sport/44983/","/sport/44984/","/sport/44985/","/sport/44988/","/sport/44989/","/sport/44990/","/sport/44991/","/sport/44992/","/sport/44993/","/sport/44994/","/sport/45067/","/sport/45068/","/sport/45116/","/sport/45125/","/sport/45126/","/sport/45138/","/sport/45637/","/sport/45690/","/showbusiness/53043/","/economics/53870/","/society/55787/","/society/55796/","/society/55961/","/society/56309/","/economics/56310/","/society/56488/","/society/56774/","/society/56910/","/politics/57090/","/society/57092/","/society/57095/","/society/57212/","/society/57386/","/economics/57917/","/economics/58223/","/economics/58291/","/society/58387/","/society/58510/","/society/58649/","/society/58700/","/economics/58745/","/society/58957/","/economics/59019/","/economics/59066/","/economics/59194/","/economics/59313/","/economics/59384/","/economics/59489/","/economics/59577/","/showbusiness/59980/","/society/60149/","/society/60212/","/society/60401/","/society/60504/","/society/65596/","/society/65883/","/society/66227/","/society/66804/","/society/66893/","/society/353023/","/society/354117/","/society/357195/","/society/362887/","/society/366625/","/society/368858/","/society/377536/","/economics/377761/","/culture/381429/","/economics/387408/","/society/388792/","/tech/389003/","/economics/407704/","/economics/412933/","/society/437950/","/society/472804/","/sport/12874/");

if (in_array($URIreq,$redir)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:/news/");
    exit();

}


$redir=array("/634065","/637675","/644738","/639962","/621059","/617923");

foreach ( $redir as $aredir) {

    if (strpos($URIreq, $aredir)) {
        Header("HTTP/1.1 410 Gone\n");
        exit();

    }
}




if (in_array($http_host, array('www.eg.ru', 'eg.ru'))) {
    if (strpos($URIreq, '?') !== false && strpos($URIreq, 'q=') === false && strpos($URIreq, 'utm') === false && strpos($URIreq, 'getsitemap') === false) {
        $link = substr($_SERVER['REQUEST_URI'] . '?', 0, strpos($_SERVER['REQUEST_URI'] . '?', '?'));
        Header("HTTP/1.1 301 Moved Permanently\n");
        Header("Location:$link");
        exit();
    }
}
$URIreq = preg_replace("/\?.*/", '', $URIreq);

// Не редиректить REST API (wp-json) — иначе бесконечный редирект для /wp-json/wp/v2/...
$is_rest = (strpos($URIreq, '/wp-json/') !== false) || (!empty($_GET['rest_route']));
if (!$is_rest && substr_count(str_ireplace(array('tag/','category/','page/','/amp'),'',$URIreq), '/') >6) {


    $URIreq=preg_replace('/^(.*?\/\d+).*/i','$1/',$URIreq);
    header("Location:$URIreq");

    exit();
}


//if ( preg_match('/\.(jpg|jpeg|gif|png|zip|css|js|)/', $URIreq ) ){
if (strpos($URIreq, '.') !== false && !in_array(substr($URIreq, -3, 3), array('rss', 'xml'))) {
    $PathToFileFromRoot = $_SERVER['DOCUMENT_ROOT'] . $URIreq;
    $PathToFileFromRoot = str_replace('//', '/', $PathToFileFromRoot);
    if (!file_exists($PathToFileFromRoot)) {
        header("HTTP/1.x 404 Not Found");
        exit();
    }
}


$new_rubr = array("stars" => "showbusiness", "cadr" => "showbusiness", "worldstars" => "showbusiness", "starsex" => "showbusiness", "ledshow" => "showbusiness", "pugachova" => "showbusiness", "gluhar" => "showbusiness", "latin" => "showbusiness", "evrovid2012" => "culture", "evrovidenie-2011" => "culture", "shooting" => "culture", "ironia" => "culture", "vancouver-2010" => "sport", "olimpiada" => "sport", "football" => "sport", "hockey" => "sport", "tennis" => "sport", "skating" => "sport", "sports" => "sport", "skis" => "sport", "other" => "sport", "crime" => "society", "assorti" => "society", "interview" => "society", "alcohol" => "society", "poetry" => "society", "animal" => "society", "melochi" => "society", "tourism" => "society", "otbor" => "society", "superhoro2012" => "society", "putin" => "society", "vika" => "society", "yurist" => "society", "lifestyle" => "society", "family" => "society", "osetia" => "politics", "russia" => "politics", "world" => "politics", "v2016" => "politics", "finance" => "economics", "money" => "economics", "x-files" => "science", "hitech" => "tech", "drive" => "auto");
if (preg_match('/daily\/(.+?)\/(\d+)/i', $URIreq, $matches)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    if (isset($new_rubr[$matches[1]])) {
        Header("Location:/" . $new_rubr[$matches[1]] . '/' . $matches[2]);
    } else {
        Header("Location:/" . $matches[1] . '/' . $matches[2]);
    }
    exit();
}
if (preg_match('/daily\/gallery\/?$/i', $URIreq, $matches)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:/tag/%D1%84%D0%BE%D1%82%D0%BE");
    exit();
}


if (preg_match('/^\/(\d\d\d+\/?)$/i', $URIreq, $matches)) {



    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:/showbusiness/".$matches[1]);
    exit();
}
if (preg_match('/\/daily\/?$/i', $URIreq, $matches)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:/news/");
    exit();
}
if (preg_match('/daily\/([^\/]*?)\/?$/i', $URIreq, $matches)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    if (isset($new_rubr[$matches[1]])) {
        Header("Location:/" . $new_rubr[$matches[1]] . '/');
    } else {
        Header("Location:/" . $matches[1] . '/');
    }
    exit();
}
if (preg_match('/\/video\/?$/i', $URIreq, $matches)) {
    Header("HTTP/1.1 301 Moved Permanently\n");
    Header("Location:/tag/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE");
    exit();
}
function eg_save($cachefile, $cod, $cachetime, $cli = false)
{
    global $eg_memcache;
    if (false && !isset($eg_memcache)) {
        $eg_memcache = new Memcached();
        $eg_memcache->addServer(MEMCACHE_SERV, MEMCACHE_PORT);
    }
    // if ($cli) $cod .= '<!--cli ' . date('H:i:s') . '-->';
    $expire = time() + $cachetime + rand(0, 60) + ($cli ? 24 * 3600 : 0);
    if (false && $eg_memcache->set($cachefile, $cod, $expire + 24 * 3600)) {
        $ok = true;
        $eg_memcache->set($cachefile . 'EXP', $expire, $expire + 24 * 3600);
    } else {
        $ok = false;
    }
    if (true || $cli) {
        $cached = fopen($cachefile, 'w');
        if (flock($cached, LOCK_EX)) {
            fwrite($cached, $cod);
            fflush($cached);
            flock($cached, LOCK_UN);
        };
        fclose($cached);
    }
}




function egwidget($name, $args = array(), $php = false, $cachetime = 120, $cli = false)
{
    global $eg_memcache;
    $load = sys_getloadavg();
    if ($load[0] > 7) {
        $cachetime = 9999;
    }
    if (false && !isset($args['no_memcache']) && !isset($eg_memcache)) {
        $eg_memcache = new Memcached();
        $memcache_ok = $eg_memcache->addServer(MEMCACHE_SERV, MEMCACHE_PORT);
    } else {
        $memcache_ok = false;
    }
    $file = $name;
    $tmpDIR = str_replace(array('http://','https://'), '', WP_HOME) . '/';
    if ($cli || $tmpDIR == 'eg.ru/' || $tmpDIR == 'www.eg.ru/' || $tmpDIR == 'wp.dev.eg.ru/') {
        $tmpDIR = '';
    }
    if (isset($args['tmpDIR'])) $tmpDIR = $args['tmpDIR'] . '/';
    if ($tmpDIR != '' && !file_exists('tmp/' . $tmpDIR)) {
        mkdir('tmp/' . $tmpDIR);
    };
    if (isset($args['tmpDIR'])) {
        $subdir = substr(md5($file . (isset($args['cache']) ? $args['cache'] : '')), 2, 2);
        if (!file_exists('tmp/' . $tmpDIR . $subdir)) {
            mkdir('tmp/' . $tmpDIR . $subdir);
        };
        $tmpDIR .= $subdir . '/';
    }
    $cachefile = 'tmp/' . $tmpDIR . 'cached-' . $file . (isset($args['cache']) ? $args['cache'] : '') . '.html';
    if (1||isset($_GET['profile'])) {
        $start = microtime(true);
    }
    if ($memcache_ok) {
        $code = $eg_memcache->get($cachefile);
        $code_expire = $eg_memcache->get($cachefile . 'EXP');
    } else {
        $code = false;
    }
    if (!$cli && !isset($_GET['cc']) && (($code && time() < (rand(0, 120)) + $code_expire) || (file_exists($cachefile) && time() - ($cachetime + rand(0, 120)) < filemtime($cachefile)))) {
        // form cache
        if ($code) {
            if ($php) {
                eval('?>' . $code . '<?');
                // echo '<!--memcahed php 1-->';
            } else {
                echo $code;
                //  echo '<!--memcached html 1-->';
            }
        } else {
            if ($php) {
                include($cachefile);
                //echo  "<pre>";print_r($cachefile); die();
                //  echo '<!--file memcached php 1-->';
            } else {
                //echo  "<pre>";print_r($cachefile); die();
                echo file_get_contents($cachefile);
                //   echo '<!--file memcached html 1-->';
            }
        }

        if (1||isset($_GET['profile'])) {
            $start = microtime(true) - $start;
            if ($start>0.03 ) echo "<!-- profile $cachefile $start  -->";
        }

        return true;
    } else {
        if (!isset($args['dont_save'])) {
            ob_start(); //
            include('wp-content/themes/eg/' . $name . '.php');
            $cod = ob_get_contents();
            ob_end_clean();
            if ($cod) {
                if ($php) {
                    $cod = str_replace(array('<!--?', '?-->'), array('<?', '?>'), $cod);
                }
                eg_save($cachefile, $cod, $cachetime, $cli);
            }
            if ($php) {
                eval('?>' . $cod . '<?');
                //  echo '<!--NO memcached php 2-->';
            } else {
                echo $cod;
                //  echo '<!--NO memcached ' . $cachefile . 'html 2    -->';
            }
            if (1||isset($_GET['profile'])) {
                $start = microtime(true) - $start;
                if ($start>0.03) echo "<!-- profile $cachefile $start  -->";
            }
            return true;
        } else {

            return false;
        }
    }

}

function isBot(&$botname = '')
{
    /*                            ,                                                  */

    if (isset($_GET['utmbot'])) return true;

    $bots = array(
        'rambler', 'twitter', 'aport', 'yahoo', 'msnbot', 'turtle', 'mail.ru', 'omsktele',
        'yetibot', 'picsearch', 'sape.bot', 'sape_context', 'gigabot', 'snapbot', 'alexa.com',
        'megadownload.net', 'askpeter.info', 'igde.ru', 'ask.com', 'qwartabot', 'yanga.co.uk',
        'scoutjet', 'similarpages', 'oozbot', 'shrinktheweb.com', 'aboutusbot', 'followsite.com',
        'dataparksearch', 'google-sitemaps', 'appEngine-google', 'feedfetcher-google',
        'liveinternet.ru', 'xml-sitemaps.com', 'agama', 'metadatalabs.com', 'h1.hrn.ru',
        'googlealert.com', 'seo-rus.com', 'yaDirectBot', 'yandeG',
        'yandexSomething', 'Copyscape.com', 'AdsBot-Google', 'domaintools.com',
        'Nigma.ru', 'bing.com', 'dotnetdotcom', 'Relap','yandexbot','googlebot','bot'
    );
    foreach ($bots as $bot)
        if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false) {
            $botname = $bot;
            return true;
        }
    if (file_exists('tmp/topip.txt')) {
        $topip = file_get_contents('tmp/topip.txt');
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strpos($topip, $_SERVER['HTTP_X_FORWARDED_FOR']) !== false) return true;
    }
    return false;
}

//file_put_contents('tmp/ok2.txt',date('Y-m-d H:i:s').' '.$_SERVER['REQUEST_URI']."\n",FILE_APPEND);
$ok = false;
if ($_SERVER['REQUEST_URI'] == '/' || (strpos($_SERVER['REQUEST_URI'], '/?') === 0 && !isset($_GET['main']))) {
    // Обычная главная страница - с полной шапкой
    $ok = egwidget('egindex2019', array('dont_save' => true, 'no_memcache' => true, 'cache' => 'full'));
} elseif (isset($_GET['main'])) {
    // Запросы с параметром ?main=1 для AJAX - только контент без шапки, отдельный кеш
    $ok = egwidget('egindex2019', array('dont_save' => true, 'no_memcache' => true, 'cache' => 'ajax'));
}  elseif (in_array(trim($_SERVER['REQUEST_URI'], '/'), array( 'rss.xml', 'upimg/anews.xml', 'upimg/toprss.xml', 'upimg/mt.xml'))) {
    header('Content-Type: application/rss+xml; charset=utf-8');
    $ok = egwidget('egrss', array('no_memcache' => true, 'dont_save' => true, 'cache' => md5(str_replace('.xml', '', trim($_SERVER['REQUEST_URI'], '/')))));
} elseif (in_array(trim($_SERVER['REQUEST_URI'], '/'), array('yandex.xml'))) {
    header('Content-Type: application/rss+xml; charset=utf-8');
    $ok = egwidget('egrssyandex', array('no_memcache' => true, 'dont_save' => true, 'cache' => 'new'));
}  elseif (in_array(trim($_SERVER['REQUEST_URI'], '/'), array('yandexturbo.xml'))) {
    header('Content-Type: application/rss+xml; charset=utf-8');
    $ok = egwidget('egrssturbo', array('no_memcache' => true, 'dont_save' => true, 'cache' => 'new'));
}

$isBOT=isBot();

if (!$ok) {
    $load = sys_getloadavg();
    $GLOBALS['LOAD'] = $load[0];
    $force_cache_lookup = (isset($_GET['utm']) && $_GET['utm'] == 'cached');
    if (!$force_cache_lookup && $load[0] + rand(0, 1) <10 && ($load[0]<7 || strpos($_SERVER['REQUEST_URI'],'/amp')<1) && !$isBOT  ) {

/*

        if ( $load[0]>10 && file_exists('tmp/topip.txt')) { 
            $topip = file_get_contents('tmp/topip.txt');
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strpos($topip, $_SERVER['HTTP_X_FORWARDED_FOR']) !== false) {
                Header("HTTP/1.1 503 Service Unavailable"); exit();
            };
        }

*/


      //  if ((!($GLOBALS['LOAD'] > 8 || rand(1, 100) < 80) || MEMCACHE_SERV == 'localhost')) {
if (0) {
            ob_start();
            include(dirname(__FILE__) . '/wp-blog-header.php');
            $code = ob_get_contents();
            ob_end_flush();

            $tmpDIR = 'all/';
            $args['tmpDIR'] = 'file';
            $args['cache'] = md5(preg_replace('/\?.*$/','',$_SERVER['REQUEST_URI']));
            if (isset($args['tmpDIR'])) {
                $subdir = substr(md5((isset($args['cache']) ? $args['cache'] : '')), 2, 2);
                if (!file_exists('tmp/' . $tmpDIR . $subdir)) {
                    mkdir('tmp/' . $tmpDIR . $subdir);
                };
                $tmpDIR .= $subdir . '/';
            }



            $cachefile = 'tmp/' . $tmpDIR . 'cached-'  . (isset($args['cache']) ? $args['cache'] : '') . '.html';
           // file_put_contents($cachefile, $code . '<!--load '. $tmpDIR . 'cached-'  . (isset($args['cache']) ? $args['cache'] : '') . '-->');
        } else {


            include(dirname(__FILE__) . '/wp-blog-header.php');


        }
    } else {
        if (preg_match("/\/article\/(\d+)\//", $_SERVER['REQUEST_URI'], $matches)) {
            $subdir = substr(md5('egsinglescroll_' . $matches[1]), 2, 2) . '/';
            if (file_exists('tmp/articles/' . $subdir . 'cached-egsinglescroll_' . $matches[1] . '.html')) {
                print cleanhtml(file_get_contents('tmp/articles/' . $subdir . 'cached-egsinglescroll_' . $matches[1] . '.html'));
                print "<!--load-->";
                exit();
            }
        } elseif (strpos($_SERVER['REQUEST_URI'],'/amp')<1  && preg_match("#^/(?!author/|tag/|editor/).*/(\d+)(?:-[^/]*)?/?(?:\?.*)?$#", $_SERVER['REQUEST_URI'], $matches)) {
            $article_cache_id = $matches[1];
            $subdir = substr(md5('egsingle' . $article_cache_id), 2, 2) . '/';
            $article_cache_file = 'tmp/articles/' . $subdir . 'cached-egsingle' . $article_cache_id . '.html';

            if (isset($_GET['utm']) && in_array($_GET['utm'], array('cached', 'cached-'))) {
                header('Content-Type: text/plain; charset=utf-8');
                echo "article cache debug\n";
                echo "request_uri: " . $_SERVER['REQUEST_URI'] . "\n";
                echo "cache_id: " . $article_cache_id . "\n";
                echo "subdir: " . $subdir . "\n";
                echo "cache_file: " . $article_cache_file . "\n";
                echo "document_root: " . (isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '') . "\n";
                echo "cwd: " . getcwd() . "\n";
                echo "exists: " . (file_exists($article_cache_file) ? 'yes' : 'no') . "\n";
                if (file_exists($article_cache_file)) {
                    echo "mtime: " . date('Y-m-d H:i:s', filemtime($article_cache_file)) . "\n";
                    echo "size: " . filesize($article_cache_file) . "\n";
                }
               
            }

            if (file_exists($article_cache_file)) {
                $html= file_get_contents($article_cache_file);


                echo cleanhtml($html);


                print "<!--load-->";
                exit();
            }
        } elseif (strpos($_SERVER['REQUEST_URI'],'/amp')>1  && preg_match("/\/(.*?)\/(\d+)(-?.*)\//", $_SERVER['REQUEST_URI'], $matches)) {
            $tmpDIR = 'amp/';
            $suff='';
            if (isset($_GET['utm']) && $_GET['utm']=='short') $suff='short';
            $args['tmpDIR'] = 'file';
            $args['cache'] = md5(preg_replace('/\?.*$/','',$_SERVER['REQUEST_URI']));
            if (isset($args['tmpDIR'])) {
                $subdir = substr(md5((isset($args['cache']) ? $args['cache'] : '')), 2, 2);
                $tmpDIR .= $subdir . '/';
            }
            $cachefile = 'tmp/' . $tmpDIR . 'cached-'.$suff  . (isset($args['cache']) ? $args['cache'] : '') . '.html';




            if (file_exists($cachefile) && strpos($URIreq,'online')===false && strpos($URIreq,'.xml')===false) {

                print cleanhtml(file_get_contents($cachefile));
                print "<!--load2-->";
                exit();
            }
        }


        // Не кешируем главную страницу через этот механизм (она кешируется выше с учетом параметра ?main)
        if ($URIreq != '/' && strpos($URIreq, '/?') !== 0) {
            $tmpDIR = 'all/';
            $args['tmpDIR'] = 'file';
            $args['cache'] = md5(preg_replace('/\?.*$/','',$_SERVER['REQUEST_URI']));
            if (isset($args['tmpDIR'])) {
                $subdir = substr(md5((isset($args['cache']) ? $args['cache'] : '')), 2, 2);
                $tmpDIR .= $subdir . '/';
            }
            $cachefile = 'tmp/' . $tmpDIR . 'cached-'  . (isset($args['cache']) ? $args['cache'] : '') . '.html';




            if (file_exists($cachefile) && strpos($URIreq,'/amp')===false && strpos($URIreq,'.xml')===false) {

                print cleanhtml(file_get_contents($cachefile));
                print "<!--load2-->";
                exit();
            }
        }
        if (!$isBOT || $GLOBALS['LOAD']<18) {
            require(dirname(__FILE__) . '/wp-blog-header.php');
        } else {
            Header("HTTP/1.1 503 Service Unavailable");
        }
    }
    //
}

if (1||isset($_GET['profile'])) {
    $start1 = microtime(true) - $start1;
    if ($start1>0 ) echo "<!-- profile all $start1  -->";
}


/** Loads the WordPress Environment and Template */

