<?php //echo'wait 5 sec, unmounted';die;

    // $_админа ещё нет
    //opcache_invalidate(__FILE__, true);



$Dom=explode('.', $_SERVER['SERVER_NAME']);
$member=isset($_GET['member'])? $_GET['member']:strtolower($Dom[0]);
$_Uri=explode('/', trim($_SERVER['REQUEST_URI'],'/'));


if($member=='www'){
	unset($Dom[0]); $s=implode('.', $Dom);
	header("Location: //$s{$_SERVER['REQUEST_URI']}"); exit;
}

if(strstr($member, '_')){
	$s=str_replace('_', '--', $_SERVER['SERVER_NAME']);
	header("Location: //$s{$_SERVER['REQUEST_URI']}", true, 301); exit;
}

$member=preg_replace("/[^a-z0-9\-]/", '', $member);

$renu=user_renamed($member);
if($member!=$renu){
    if(strpos($_SERVER['REQUEST_URI'], $renu)!==false) header("Location: //in.gallerix.ru".strtr($_SERVER['REQUEST_URI'],[$member=>$renu]));
    else header("Location: //in.gallerix.ru/$renu{$_SERVER['REQUEST_URI']}");
    exit;
}

// для главных страниц категорий: member=in + устанавливаем GC
$Cats=['ac','in','graf','digital','crafts','c','icon','sculpt','foto','tog','street','bodyart','int','kids','stihi','proza','embro'];
if($Dom[1]=='gallerix' && in_array($member, $Cats)){
    switch($member){
        case 'ac': $GC=0; break;
        case 'stihi': $GC=0; $GCA=1; break; case 'proza': $GC=0; $GCA=2; break;
        case 'in': $GC=1; break;
        case 'foto': $GC=2; break;
        case 'crafts': $GC=3; break;
        case 'digital': $GC=4; break;
        case 'sculpt': $GC=5; break;
        case 'graf': $GC=6; break;
        case 'bodyart': $GC=7; break;
        case 'icon': $GC=9; break;
        case 'c': $GC=8; break;
        case 'street': $GC=10; break;
        case 'tog': $GC=11; break;
        case 'int': $GC=12; break;
        case 'kids': $GC=13; break;
        case 'embro': $GC=14; break;
    }
    $member='in';
}



$timer1=microtime();
define('_AC',true);
$rut='/var/www/dim/data/www/in.gallerix.ru';
$groot='/var/www/dim/data/www/gallerix.ru';


 // юзерфото>>
if(isset($_GET['ufoto'])) {
    header("Location: https://u.gallerix.ru/ufoto/$member.jpg");
die; }
 // << юзерфото


//// SELECT DB SERVER
if($member=="in" && isset($_GET['visual'])) define('GX2SQL', true); // визуальный поиск в артклубе
//elseif(isset($_GET['expos'])) define('GX2SQL', true); // альбомы и картинки участников



// накрутка
$surfer=array('soaring4traffic.com','easyhits4u.com','proclickexchange.com','lazyhits.com','blue-surf.net','websurf.ru','securityhits.com','clickvoyager.com','dragonsurf.biz','wild4hits.com','autosurfmyth.com','trafficpro.com','trafficgoldrush.com','instantxchange.com','stacks-of-free-traffic.com','freedomtraffic.com','hotflashhits.com','hitswarrior.com','clickfredtraffic.com','traffic4webmasters.com','surfers2u.com','ilovehits.com','freedomtraffic.com','free-website-traffic.com');
$host=explode('/',str_replace('www.','',$_SERVER['HTTP_REFERER'])); $host=$host[2];
if(in_array($host,$surfer)){ $_SESSION['SURFER']=1; }
$_SESSION['MUT']=true; // <-- чтоэто??


include "/var/www/dim/data/www/gallerix.ru/lang.php"; if($en) $lng="en"; else $lng="tdb";

if($_SERVER['SERVER_NAME']=='gallerix.asia') $_host='gallerix.asia';
elseif($_SERVER['SERVER_NAME']=='gallerix.org') $_host='gallerix.org';
else $_host=$clng.'gallerix.ru';

session_set_cookie_params(120960, '/', '.'.$_host);
ini_set('session.cookie_domain', '.'.$_host);
ini_set('session.gc_maxlifetime', 120960);
ini_set('session.cookie_lifetime', 120960);



// загрузка в память - в файле settings/Recache.php
//if(!xcache_isset('RECACHE')){ $A=unserialize(file_get_contents('/var/www/dim/data/www/in.gallerix.ru/settings/cache/recache.zx')); xcache_set('RECACHE', $A); }



if(isset($_GET['expos'])) $_GET['expos']=preg_replace("/[^a-z0-9\-_]/",'',$_GET['expos']);
if(isset($_GET['pict'])) $_GET['pict']=preg_replace("/[^a-z0-9\-_]/",'',$_GET['pict']);
if(isset($_GET['post'])) $_GET['post']=preg_replace("/[^a-z0-9\-_]/",'',$_GET['post']);



/// ======================================================================
/// ======================================================================
///
//todo:  ~~~  DEV NEW DESIGN 2017  ~~~
///
/// ======================================================================

$inc=false; $_Self=false;
$In=($member=='in')? true:false;


if(!$In){
    $renm=user_renamed($member);
    if($member!=$renm){
        header($_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently');
        if(strpos($_SERVER['REQUEST_URI'], $renm)!==false) header('Location: //in.gallerix.ru'.strtr($_SERVER['REQUEST_URI'],[$member=>$renm]));
        else header("Location: //in.gallerix.ru/$renm{$_SERVER['REQUEST_URI']}");
        header('Connection: close');
        exit;
    }
    $_ori=strpos($_SERVER['SERVER_NAME'], '.in.gallerix.')===false? "/$member":''; // ← самое главное - первая точка
} else $_ori='';


/// Запрос с параметрами
if(strpos($_SERVER['REQUEST_URI'], '?')!==false){
    list($req)=explode('?', $_SERVER['REQUEST_URI']);
    if(empty($req) || $req=='/') $isFront=true;
} elseif(!isset($isFront)) $isFront=false;


if($In && $GC==0 && substr($_SERVER['REQUEST_URI'], 0,4)!='/up/') $inc='N_Line';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,6)=='/free/') $inc='N_Free';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,8)=='/albums/') $inc='N_NewAlbums';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,8)=='/autors/') $inc='N_Authors';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,5)=='/vac/') $inc='N_Vac';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,6)=='/days/') $inc='N_AllPOD';
elseif($In && substr($_SERVER['REQUEST_URI'], 0,8)=='/top100/') $inc='N_Top100';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,10)=='/workshop/') $inc='N_Workshop';
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,7)=='/board/') $inc='N_Board';
elseif($In && substr($_SERVER['REQUEST_URI'], 0,4)=='/up/') $inc='N_Uploads';
elseif($In && $GC==13 && substr($_SERVER['REQUEST_URI'], 0,8)=='/avatar/') $inc='N_Avatar';
elseif($In && $GC==13 && substr($_SERVER['REQUEST_URI'], 0,5)=='/com/') $inc='N_Kids';

elseif($In && ($_SERVER['REQUEST_URI']=='/' || $isFront) && isset($_COOKIE['old-ac'])) $inc='N_Front';
elseif($In && ($_SERVER['REQUEST_URI']=='/' || $isFront)) $inc='N_Front23';

elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,7)=='/blogs/'){ $GCA=0; $inc='N_Line'; }
elseif($In && $GC==1 && ($_SERVER['REQUEST_URI']=='/public/' || substr($_SERVER['REQUEST_URI'], 0,9)=='/public/?')){ $GCA=3; $inc='N_Line'; }
elseif($In && $GC==1 && substr($_SERVER['REQUEST_URI'], 0,8)=='/public/' && isset($_GET['fd'])) $inc='N_Public';
elseif($In && $GC==1 && isset($_GET['buy'])) $inc='N_Buy';
elseif($In && $GC==1 && isset($_GET['visual'])) $inc='N_Visual';
elseif($In && isset($_GET['forgotten'])) $inc='U_Forgotten';

// USER PROFILE
elseif(!$In && isset($_GET['blog'])) $inc='N_Line';
elseif(!$In && isset($_GET['awards'])) $inc='U_Awards';
elseif(!$In && isset($_GET['post'])) $inc='U_Post';
elseif(!$In && isset($_GET['shop'])) $inc='U_Shop';
elseif(!$In && isset($_GET['abs'])) $inc='U_Albums';
elseif(!$In && isset($_GET['inter'])) $inc='U_Inter';
elseif(!$In && isset($_GET['expos']) && !isset($_GET['pict'])) $inc='U_Album';
elseif(!$In && isset($_GET['rcls'])) $inc='U_Collection';
elseif(!$In && isset($_GET['expos']) && isset($_GET['pict']) && !isset($_GET['frm'])) $inc='U_Pic';
elseif(!$In && $_Uri==[$member]) $inc='U_Profile';
elseif(!$In && ( // страницы юзера на поддомене
        in_array($_SERVER['REQUEST_URI'], ['/', '/?albums', '']) ||
        (substr($_SERVER['REQUEST_URI'], 0,2)=='/?' && strstr($_SERVER['REQUEST_URI'], 'utm_')) ||
        (substr($_SERVER['REQUEST_URI'], 0,2)=='/?' && strstr($_SERVER['REQUEST_URI'], 'from='))
    )) $inc='U_Profile';
elseif(!$In && isset($_GET['frm'])) include "$rut/engine/framed.php"; // exit inside
elseif(!$In && !isset($_GET['frm']) && !isset($_GET['editimg'])) include "$groot/inc/L_404.php";

// $_SERVER['REMOTE_ADDR']=='79.111.12.53'




if($inc){
    include "$groot/inc/xcache.inc";
    include "$groot/init.php";
    define('DB_PDO', true);
    include "$rut/db.php";
    include "$groot/inc/functions.php";
    include "$groot/inc/template.php";
    $_html = new Template();

    // кука используется только для голосования в артклубе без авторизации
    if(isset($_SESSION['ran'])) $Coo=$_SESSION['ran'];
    if(isset($_COOKIE['ran'])){ $Coo=$_SESSION['ran']=$_COOKIE['ran']; }
    else{
        $Coo=rand(100,999).time(); $_SESSION['ran']=$Coo;
        setcookie('ran', $Coo, time()+86400000, '/', 'gallerix.ru');
        setcookie('ran', $Coo, time()+86400000, '/', '.gallerix.ru');
    }

    if(!$In){
        // Мясо мембера (посещаемой страницы)
        $M=$_db->query("SELECT * FROM `user` WHERE `login`='$member'")->fetch();
        if(!$M || !isset($M['id'])) include "$groot/inc/L_404.php";
        if(!$en) $uname=empty($M['name'])? $member:$M['name'];
        else $uname=empty($M['name_en'])? $member:$M['name_en'];
    }

    if(!isset($_SESSION['auth']) && isset($_COOKIE['auth'])) is_user();

    if(isset($_SESSION['auth'])){
        include "$groot/inc/user.php";
        $_user = new User();
        $_html->usernav(true, $_user, $_SESSION['auth']);
    } else $_html->usernav();

    // БЛЭКЛИСТ
    // Eaas - массив ассетов юзера, существует если юзер авторизован
    if(!$In && isset($_SESSION['uid'])){
        if(adm_bl($M['id'], $_SESSION['uid'])){
            $mirror_ban=<<<EOF
                <div class="font-size-12 mt-30">
                    <p>Доступ к странице временно закрыт администратором</p>
                </div>
EOF;
            include "$groot/inc/L_403.php";
        }
        $Eaas=$_user->assets();
        if(isset($Eaas['blacklist']) && !empty($Eaas['blacklist'])){
            $Blocked_by_user=explode(',', $Eaas['blacklist']);
            if(is_array($Blocked_by_user) && in_array($M['id'], $Blocked_by_user)){
                include "$groot/inc/L_403.php";
            }
        }
        if($member==$_SESSION['auth'] || $_ADMIN) $_Self=true; // юзер посещает свою страницу
    }
    // Maas - массив ассетов мембера, существует только при посещении страниц мемберов юзерами
    if(!$In && isset($_SESSION['uid'])){
        $Maas=$_user->assets($M['id']);
        if(isset($Maas['blacklist']) && !empty($Maas['blacklist'])){
            $Blocked_by_member=explode(',', $Maas['blacklist']);
            if(is_array($Blocked_by_member) && in_array($_SESSION['uid'], $Blocked_by_member)){
                $mirror_ban=<<<EOF
                <div class="font-size-12 mt-30">
                    <span onclick="$('#toblacklist').toggleClass('hide');" class="hovr pointer indigo-600 mr-20">Чёрный список</span>
                    <form action="//in.gallerix.ru/settings/ac_acc.php" method="post" id="toblacklist" class="hide inline-block"><button class="btn btn-xs btn-outline btn-outline-danger">Заблокировать участника</button><input type="hidden" name="blacklist" value="{$M['id']}"></form>
                </div>
EOF;
                include "$groot/inc/L_403.php";
            }
        }
    }

    if($In && $GC==1) $_html->ins(['<!--{META}-->'=>'<!--{META}--><meta name="yandex-verification" content="5c4951915c8ef15d">']);
    elseif($In && $GC==6) $_html->ins(['<!--{META}-->'=>'<!--{META}--><meta name="yandex-verification" content="6d3d3e5d7aa01baf">']);
    $_html->ins(['href="//{DOMAIN}/roster/">'=>'href="//{DOMAIN}/roster/ac/">']);

    /// Lang-Flags
    $_html->ins(['<!--world-->', '<!--/world-->', 0, ''], true);
    $_html->ins(['{WORLDIN}'=>$Dom[0].'.']);

    include "$rut/inc/$inc.inc";

    // Реклама: Workle/RedPencil — бестолковая партнёрка
    //$_html->ins(["<div id='recv'>"=>"<a href='//gallerix.ru/away.php?to=li5.ru/13' target='_blank'><img src='{NAROD}/src/news/2020/Nov/workle_redpencil.png' class='rb3 mb-30'></a><div id='recv'>"]);

    $_html->screen();
    exit;
}

/// ======================================================================
/// ======================================================================





/// дальше только в домене in.gallerix.ru
/// ↓ уже не имеет смысла, всё остальное → 404
//if($In && $GC>1){ header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); exit; }
//if($Dom[3]=='ru' && $Dom[2]=='gallerix' && $Dom[1]!='in'){ header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); exit; }

/// ← Здесь был старый код, теперь 404
include "$groot/inc/L_404.php";


function user_renamed($login){
    global $rut;
    include "$rut/settings/renamed.users.inc";
    if(isset($RenU[$login])) return $RenU[$login];
    else return $login;
}
