HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux HTML-DEV-SERVER 5.15.0-173-generic #183-Ubuntu SMP Fri Mar 6 13:29:34 UTC 2026 x86_64
User: www-data (33)
PHP: 8.1.2-1ubuntu2.23
Disabled: NONE
Upload Files
File: //ladev/config-1.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$GVars['dbHost'] = "209.50.49.218";
$GVars['dbUser'] = "webdev";
$GVars['dbPwd'] = "dH4@Tw_bvBK9";
$GVars['dbDB'] = "linkauthority";
$GVars['timenow'] = date("Y-m-d H:i:s");

$host = "209.50.49.218";
$username = "webdev";
$password = "dH4@Tw_bvBK9";
$dbname = "linkauthority";
$conn = mysqli_init();
$conn = $GVars['mysqli'] = new mysqli($GVars['dbHost'], $GVars['dbUser'], $GVars['dbPwd'], $GVars['dbDB']);
mysqli_options($conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
if (!mysqli_real_connect($conn, $host, $username, $password, $dbname)) {
    die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully!";
$proxy = array(
    '141.255.166.195:8800',
    '173.232.7.88:8800',
    '188.208.7.145:8800',
    '88.80.20.218:8800',
    '50.31.104.40:8800',
    '88.80.20.215:8800',
    '88.80.20.152:8800',
    '173.232.7.164:8800',
    '88.80.20.174:8800',
    '188.208.7.148:8800',
    '173.232.7.7:8800',
    '141.255.166.117:8800',
    '88.80.20.208:8800',
    '50.31.104.46:8800',
    '88.80.20.185:8800',
    '188.208.7.162:8800',
    '88.80.20.213:8800',
    '173.232.7.9:8800',
    '141.255.166.35:8800',
    '141.255.166.44:8800',
    '141.255.166.233:8800',
    '188.208.7.246:8800',
    '188.208.7.19:8800',
    '88.80.20.205:8800',
    '50.31.104.65:8800',
    '88.80.20.197:8800',
    '173.232.7.122:8800',
    '173.232.7.43:8800',
    '141.255.166.18:8800',
    '50.31.104.68:8800',
    '173.232.7.90:8800',
    '188.208.7.212:8800',
    '50.31.104.67:8800',
    '141.255.166.5:8800',
    '173.232.7.72:8800',
    '50.31.104.165:8800',
    '141.255.166.10:8800',
    '188.208.7.24:8800',
    '173.232.7.71:8800',
    '188.208.7.56:8800',
    '141.255.166.249:8800',
    '173.232.7.79:8800',
    '141.255.166.250:8800',
    '188.208.7.98:8800',
    '173.232.7.158:8800',
    '173.232.7.124:8800',
    '188.208.7.158:8800',
    '173.232.7.70:8800',
    '88.80.20.191:8800',
    '173.232.7.123:8800',
);

$UserAgentArray = [
    "Mozilla/5.0 (iPad; CPU OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 2025-03-28 12:00:00",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 2025-03-28 12:00:01",
    "Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 2025-03-28 12:00:02",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0 2025-03-28 12:00:03",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_5_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.2 Safari/605.1.15 2025-03-28 12:00:04",
    "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 2025-03-28 12:00:05",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 2025-03-28 12:00:06",
    "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko 2025-03-28 12:00:07",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/118.0.2088.46 Safari/537.36 2025-03-28 12:00:08",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 2025-03-28 12:00:09",
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:118.0) Gecko/20100101 Firefox/118.0 2025-03-28 12:00:10",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.2 Safari/605.1.15 2025-03-28 12:00:11",
    "Mozilla/5.0 (Linux; Android 12; Pixel 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36 2025-03-28 12:00:12",
    "Mozilla/5.0 (Linux; armv8l; rv:109.0) Gecko/20100101 Firefox/118.0 2025-03-28 12:00:13",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Brave/118.0.6026.112 Chrome/118.0.0.0 Safari/537.36 2025-03-28 12:00:14",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 2025-03-28 12:00:15"
];

function microtime_float2() {
    return microtime(true);
}

function checkArticleText(string $text): array {
    // Trim, normalize spaces, and fix anchor tag spacing
    $text = trim($text);
    $text = str_replace("&nbsp;", " ", $text);
    $text = preg_replace('/\s+/', ' ', $text);
    $text = str_ireplace('< a', '<a', $text);

    // Process text content
    $text_stripped = strtolower(strip_tags($text));
    $words = array_filter(explode(" ", $text_stripped)); // Remove empty elements

    // Initialize result array
    $ret_arr = [
        'nwords' => count($words),
        'errors' => 0,
        'error_str' => '',
        'publishable' => 1
    ];

    // Check word count constraints
    if ($ret_arr['nwords'] < 100) {
        $ret_arr['errors']++;
        $ret_arr['error_str'] .= "• Article is too short, only {$ret_arr['nwords']} words (minimum 100 required).<br>";
    } elseif ($ret_arr['nwords'] > 10000) {
        $ret_arr['errors']++;
        $ret_arr['error_str'] .= "• Article is too long, maximum 10,000 words allowed.<br>";
    }

    // Check for disallowed placeholder words
    $disallowedWords = ["%", "%link1%", "%link2%"];
    if (array_intersect($disallowedWords, $words)) {
        $ret_arr['errors']++;
        $ret_arr['error_str'] .= "• Article can't contain certain placeholders.<br>";
    }

    // Check for suspicious symbols
    if (count_suspicious_symbols_in_text($text) > 1) {
        $ret_arr['errors']++;
        $ret_arr['error_str'] .= "• Article contains illegal symbols.<br>";
    }

    // Determine if publishable
    if ($ret_arr['errors'] > 0) {
        $ret_arr['publishable'] = 0;
    }

    return $ret_arr;
}

function count_suspicious_symbols_in_text(string $text): int {
    return substr_count($text, '&#1');
}

function check_for_spun_content(string $text): bool {
    $forbidden_characters = ['{', '}', '[', ']', '|', '~'];

    foreach ($forbidden_characters as $char) {
        if (str_contains($text, $char)) {
            return true; // Return early if any forbidden character is found
        }
    }

    return false; // No forbidden characters found
}

function has_bad_words(string $mystring): array {
    // Ensure forbidden words exist in session before proceeding
    if (empty($_SESSION['global_vars']['forbidden_words'])) {
        return ['n_bad_words' => 0, 'bad_words' => ''];
    }

    // Normalize input string
    $mystring = strtolower($mystring);
    
    // Get forbidden words as an array
    $bad_words = array_map('trim', explode(",", $_SESSION['global_vars']['forbidden_words']));
    
    // Check for bad words
    $found_bad_words = array_filter($bad_words, fn($word) => str_contains($mystring, $word));

    return [
        'n_bad_words' => count($found_bad_words),
        'bad_words' => implode(", ", $found_bad_words)
    ];
}

function getArticleInfoByHash(mysqli $conn, string $aid) {
    $articleInfo = [];

    // Validate hash length
    if (strlen($aid) !== 32) {
        return $articleInfo; // Return empty if invalid
    }

    // Use prepared statement to prevent SQL injection
    $sql = "
        SELECT * FROM articles WHERE id_hash = ?
        UNION
        SELECT * FROM articles_published WHERE id_hash = ?
    ";
    
    $stmt534534 = $conn->prepare($sql);
    if (!$stmt534534) {
        return $articleInfo; // Return empty if statement preparation fails
    }

    $stmt534534->bind_param("ss", $aid, $aid);
    $stmt534534->execute();
    $result = $stmt534534->get_result();

    if ($row = $result->fetch_assoc()) {
        // Map result to array
        $articleInfo = [
            'id' => $row['id'],
            'user_id' => $row['user_id'],
            'project_id' => $row['project_id'],
            'status' => $row['status'],
            'title' => $row['title'],
            'text' => $row['text'],
            'keyword1' => $row['keyword1'],
            'keyword2' => $row['keyword2'],
            'keyword3' => $row['keyword3'],
            'url1' => $row['url1'],
            'url2' => $row['url2'],
            'url3' => $row['url3'],
            'admin_comment' => $row['admin_comment'],
            'user_signed_post' => $row['user_signed_post']
        ];
    }

    // Close statement
    $stmt534534->close();

    return $articleInfo;
}

function rendeFinalText(
    string $f_text, 
    string $f_keyword1, 
    string $f_keyword2, 
    string $f_keyword3, 
    string $f_link1, 
    string $f_link2, 
    string $f_link3, 
    bool $with_link = true
): string {
    
    // Remove tags and count words
    $text_stripped = strip_tags($f_text);
    $word_count = str_word_count($text_stripped);

    // Safely create anchor links if enabled
    $link1 = $with_link ? "<a href='" . htmlspecialchars($f_link1, ENT_QUOTES) . "'>" . htmlspecialchars($f_keyword1) . "</a>" : htmlspecialchars($f_keyword1);
    $link2 = $with_link ? "<a href='" . htmlspecialchars($f_link2, ENT_QUOTES) . "'>" . htmlspecialchars($f_keyword2) . "</a>" : htmlspecialchars($f_keyword2);
    $link3 = htmlspecialchars($f_keyword3); // No link needed for $link3

    // Replace placeholders
    $f_text = str_ireplace("%LINK1%", $link1, $f_text);

    if ($word_count > 300) {
        $f_text = str_ireplace(["%LINK2%", "%LINK3%"], [$link2, $link3], $f_text);
    } else {
        $f_text = str_ireplace(["%LINK2%", "%LINK3%"], [htmlspecialchars($f_keyword2), htmlspecialchars($f_keyword3)], $f_text);
    }

    return nl2br($f_text);
}


function get_32_words_from_top_and_bottom_for_google(string $text): array {
    $n_words = 32;
    $pieces = preg_split('/\s+/', trim($text)); // Split by whitespace and remove extra spaces
    $total_words = count($pieces);

    if ($total_words < $n_words) {
        return [$text, $text]; // If the text has fewer than 32 words, return the full text for both
    }

    // Get first 32 words
    $text1 = implode(' ', array_slice($pieces, 0, $n_words));

    // Get last 32 words
    $text2 = implode(' ', array_slice($pieces, -$n_words));

    return [$text1, $text2];
}

function get_random_words_for_google(string $text, int $n_words = 32): string {
    // Split text into words, removing extra spaces
    $words = preg_split('/\s+/', trim($text));
    $total_words = count($words);

    // If the text has fewer words than required, return the full text
    if ($total_words <= $n_words) {
        return implode(' ', $words);
    }

    // Generate a valid random start index
    $start = rand(0, $total_words - $n_words);

    // Get a slice of words and return as a string
    return implode(' ', array_slice($words, $start, $n_words));
}

function wpRecentPostXMLRPC2(string $title, string $rpcurl, string $username, string $password, bool $proxity = false) {
    global $UserAgentArray, $proxy;
    
    $timeout = 30;
    $params = [0, $username, $password, 20];
    $request = xmlrpc_encode_request('metaWeblog.getRecentPosts', $params);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_POSTFIELDS      => $request,
        CURLOPT_URL             => $rpcurl,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_CONNECTTIMEOUT  => $timeout,
        CURLOPT_USERAGENT       => $UserAgentArray[array_rand($UserAgentArray)],
        CURLOPT_TIMEOUT         => 60,
        CURLOPT_MAXREDIRS       => 5,
    ]);

    if ($proxity) {
        $ch = setupProxy($ch);
    }

    $results = curl_exec($ch);
    curl_close($ch);

    // Retry once with proxy if the first attempt fails
    // if (!$results && !$proxity) {
    //     return wpRecentPostXMLRPC2($title, $rpcurl, $username, $password, true);
    // }

    if (!$results) {
        return false;
    }

    $decoded_results = xmlrpc_decode($results);

    if (!empty($decoded_results) && is_array($decoded_results)) {
        foreach ($decoded_results as $item) {
            if (isset($item['title']) && $item['title'] === $title) {
                return $item;
            }
        }
    }

    return true;
}


function correct_xmlrpc_url(string $url): string {
    // Ensure the URL always ends with 'xmlrpc.php'
    $url = rtrim($url, '/') . '/xmlrpc.php';

    // Convert HTTPS to HTTP (if necessary)
    return str_replace("https://", "http://", $url);
}

function wpPostXMLRPC2(
    string $title, 
    string $body, 
    string $rpcurl, 
    string $username, 
    string $password, 
    array $category = [], 
    string $tags = '', 
    string $encoding = "UTF-8", 
    bool $proxity = false
): array {
    global $UserAgentArray, $proxy;

    $description = '';
    $keywords = '';
    $aiosptitle = '';
    $timeout = 60; // Reduce to reasonable timeout

    // Get categories
    $cats = [];
    $params = [0, $username, $password];
    $request = xmlrpc_encode_request('metaWeblog.getCategories', $params);
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_POSTFIELDS      => $request,
        CURLOPT_URL             => $rpcurl,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_CONNECTTIMEOUT  => $timeout,
        CURLOPT_USERAGENT       => $UserAgentArray[array_rand($UserAgentArray)],
        CURLOPT_TIMEOUT         => $timeout,
        CURLOPT_MAXREDIRS       => 5,
    ]);
    
    if ($proxity) {
        $ch = setupProxy($ch);
    }

    $result = curl_exec($ch);
    curl_close($ch);

    // if (!$result && !$proxity) {
    //     return wpPostXMLRPC2($title, $body, $rpcurl, $username, $password, $category, $tags, $encoding, true);
    // }

    preg_match_all('/<member><name>categoryName<\/name><value><string>(.*?)<\/string><\/value><\/member>/', $result, $matches);
    $cats = $matches[1] ?? [];

    // Find nonexistent categories
    $diff = array_diff($category, $cats);

    // Create nonexistent categories
    $n_cr_cat_errors = 0;
    foreach ($diff as $cat) {
        if (!empty($cat)) {
            $newcat = ['name' => $cat, 'slug' => strtolower($cat), 'description' => $cat];
            $params = [0, $username, $password, $newcat];
            $request = xmlrpc_encode_request('wp.newCategory', $params);

            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_POSTFIELDS      => $request,
                CURLOPT_URL             => $rpcurl,
                CURLOPT_RETURNTRANSFER  => true,
                CURLOPT_CONNECTTIMEOUT  => $timeout,
                CURLOPT_USERAGENT       => $UserAgentArray[array_rand($UserAgentArray)],
                CURLOPT_TIMEOUT         => $timeout,
                CURLOPT_MAXREDIRS       => 5,
            ]);

            if ($proxity) {
                $ch = setupProxy($ch);
            }

            $result = curl_exec($ch);
            curl_close($ch);

            if (strpos($result, 'do not have the right to') !== false) {
                $n_cr_cat_errors++;
            }
        }
    }

    if ($n_cr_cat_errors > 0) {
        return ['', "Please provide admin or editor rights to publish."];
    }

    // Prepare post content
    $title = htmlentities($title, ENT_NOQUOTES, $encoding);
    $tags = htmlentities($tags, ENT_NOQUOTES, $encoding);
    $content = [
        'title'             => $title,
        'description'       => $body,
        'mt_allow_comments' => 1, // 1 to allow comments
        'mt_allow_pings'    => 1, // 1 to allow trackbacks
        'post_type'         => 'post',
        'mt_keywords'       => $tags,
        'categories'        => $category,
        'custom_fields'     => [
            ['key' => '_aioseop_description', 'value' => $description],
            ['key' => '_aioseop_keywords', 'value' => $keywords],
            ['key' => '_aioseop_title', 'value' => $aiosptitle]
        ],
    ];

    $params = [0, $username, $password, $content, true];
    $request = xmlrpc_encode_request('metaWeblog.newPost', $params);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_POSTFIELDS      => $request,
        CURLOPT_URL             => $rpcurl,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_CONNECTTIMEOUT  => $timeout,
        CURLOPT_USERAGENT       => $UserAgentArray[array_rand($UserAgentArray)],
        CURLOPT_TIMEOUT         => $timeout,
        CURLOPT_MAXREDIRS       => 5,
    ]);

    if ($proxity) {
        $ch = setupProxy($ch);
    }

    $results = curl_exec($ch);
    curl_close($ch);
    return [$results, ''];
}

function setupProxy($curl){
    global $proxy;
    if (isset($proxy) && is_array($proxy)) {
        $address = $proxy[array_rand($proxy)];
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_PROXY, $address);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 120);
        curl_setopt($curl, CURLOPT_TIMEOUT, 120);
    }
    return $curl;
}

function XmlRpcGetPermaLink($id, $login, $password, $rpcurl, $proxity = false)
{
    global $UserAgentArray;

    $params = [$id, $login, $password];
    $request = xmlrpc_encode_request('metaWeblog.getPost', $params);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_USERAGENT       => $UserAgentArray[array_rand($UserAgentArray)],
        CURLOPT_TIMEOUT         => 60,
        CURLOPT_MAXREDIRS       => 5,
        CURLOPT_POSTFIELDS      => $request,
        CURLOPT_URL             => $rpcurl,
        CURLOPT_RETURNTRANSFER  => true,
    ]);

    if ($proxity) {
        $ch = setupProxy($ch);
    }

    $result = curl_exec($ch);
    curl_close($ch);

    if (!$result && !$proxity) {
        return XmlRpcGetPermaLink($id, $login, $password, $rpcurl, true);
    }

    $xmlObj = simplexml_load_string($result);
    if (!$xmlObj) {
        return null; // Return null if XML parsing fails
    }

    $arrXml = objectsIntoArray($xmlObj);
    if (!isset($arrXml['params']['param']['value']['struct']['member'])) {
        return null;
    }

    foreach ($arrXml['params']['param']['value']['struct']['member'] as $member) {
        if ($member['name'] === 'permaLink' && isset($member['value']['string'])) {
            return $member['value']['string'];
        }
    }

    return null; // Return null if permalink is not found
}
function objectsIntoArray(object|array $arrObjData, array $arrSkipIndices = []): array
{
    $arrData = [];

    // Convert object to an array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    $skipKeys = array_flip($arrSkipIndices); // Faster lookup

    foreach ($arrObjData as $index => $value) {
        if (isset($skipKeys[$index])) {
            continue; // Skip keys listed in $arrSkipIndices
        }

        $arrData[$index] = is_object($value) || is_array($value) 
            ? objectsIntoArray($value, $arrSkipIndices) // Recursive call
            : $value;
    }

    return $arrData;
}
function mysql__($sql)
{
    global $GVars;
    $_SESSION['lastsql'] = $sql;

    // Use MySQLi connection
    $mysqli = $GVars['mysqli']; // Assuming connection is stored in $GVars['mysqli']

    // Log SQL query (Uncomment if needed)
    /*
    $logFile = $GVars['document_root'] . 'error_log' . $GVars['dir_slash'] . '!_mysql_log_' . date("Y_m_d") . '.txt';
    file_put_contents($logFile, $GVars['timenow'] . "\n" . $sql . "\n\n", FILE_APPEND);
    */

    $result = $mysqli->query($sql);
    
    if (!$result) {
        $i = 1;
        while ($mysqli->errno == 2006 && $i <= 7) { // 2006 = "MySQL server has gone away"
            $i++;
            $mysqli->close();
            sleep(2);
            $mysqli = new mysqli($GVars['dbHost'], $GVars['dbUser'], $GVars['dbPwd'], $GVars['dbDB']);
            
            if ($mysqli->connect_errno) {
                continue;
            }

            $result = $mysqli->query($sql);
            if ($result) {
                return $result;
            } else {
                echo "Error found.";
            }
        }

        echo $sql;
        mysql_die_action($sql . " \n" . $mysqli->error . " [#{$mysqli->errno}]");
        die();
    }

    return $result;
}

function zclvar2($var)
{
    global $GVars;
    
    if (!isset($GVars['mysqli'])) {
        die("Database connection is not initialized!");
    }

    return $GVars['mysqli']->real_escape_string($var);
}

function get_site_info_for_publishing(int $user_id, int $cron_id, int $article_id): array
{
    global $GVars;
    $upgrade = 0;
    $user_dont_publish_on_my_sites = 0;

    // Assuming $mysqli is your MySQLi connection object
    $stmt = $GVars['mysqli']->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($rw = $result->fetch_assoc()) {
        $user_dont_publish_on_my_sites = $rw['dont_publish_on_my_sites'];
        $now = time(); // or your date as well
        $your_date = strtotime($rw['upgrade_time']);
        $datediff = -$now + $your_date + 3 * 60 * 60;
        
        if (floor($datediff / (60 * 60 * 24)) > 0) {
            $upgrade = 1;
        }
    }

    // Fetch sites where articles are published
    $stmt_tr = $GVars['mysqli']->prepare("SELECT DISTINCT site_id FROM log_publish WHERE article_id IN (SELECT id FROM articles_published WHERE user_id = ?) ORDER BY cr_time DESC LIMIT 100");
    $stmt_tr->bind_param("i", $user_id);
    $stmt_tr->execute();
    $result_tr = $stmt_tr->get_result();
    
    $rows = [];
    while ($row = $result_tr->fetch_assoc()) {
        $rows[] = $row['site_id'];
    }

    $condition_lim = "";
    if (count($rows) > 0) {
        $condition_lim = " AND id NOT IN (" . implode(",", $rows) . ")";
    }

    // Check if premium sites are used
    $con = "AND lvl = 0";

    if ($upgrade == 1) {
        $con = "";
    }

    // Construct SQL based on user settings
    if ($user_dont_publish_on_my_sites == 0) {
        $sql = "SELECT * FROM sites WHERE status = 5 $condition_lim $con AND n_articles_can_publish_today > 0 AND user_blocked = 0 AND site_approved = 1 ORDER BY last_publish_time ASC LIMIT 1";
    } else {
        $sql = "SELECT * FROM sites WHERE status = 5 $condition_lim $con AND n_articles_can_publish_today > 0 AND user_blocked = 0 AND user_id <> ? AND site_approved = 1 ORDER BY last_publish_time ASC LIMIT 1";
    }

    $stmt_sql = $GVars['mysqli']->prepare($sql);
    
    if ($user_dont_publish_on_my_sites == 1) {
        $stmt_sql->bind_param("i", $user_id);
    }
    
    $stmt_sql->execute();
    $result_sql = $stmt_sql->get_result();

    $ret_arr = [];
    while ($rw = $result_sql->fetch_assoc()) {
        $ret_arr['site_id'] = $rw['id'];
        $ret_arr['site_url'] = $rw['url'];
        $ret_arr['site_login'] = $rw['login'];
        $ret_arr['site_password'] = $rw['password'];
        $ret_arr['site_pagerank'] = $rw['pagerank'];
        $ret_arr['site_user_id'] = $rw['user_id'];
    }

   

    if ($ret_arr['site_id'] > 0) {
        $stmt_update = $GVars['mysqli']->prepare("UPDATE sites SET last_publish_time = ? WHERE id = ?");
        $stmt_update->bind_param("si", $GVars['timenow'], $ret_arr['site_id']);
        $stmt_update->execute();
    } else {
        
        exit();
    }

    $stmt2 = $GVars['mysqli']->prepare("INSERT INTO log_publish (cron_id, article_id, site_id, errors, notes, post_rez) VALUES (?, ?, ?, 0, ?, ?)");
    $stmt2->bind_param("iiiss", $cron_id, $article_id, $ret_arr['site_id'], $GVars['timenow'], date("Y-m-d H:i:s"));
    $stmt2->execute();

    if ($stmt2->error) {
        die("Error logging publish: " . $stmt2->error);
    }

    return $ret_arr;
}


function render_final_text($f_text, $f_keyword1, $f_keyword2, $f_keyword3, $f_link1, $f_link2, $f_link3, $with_link = true)
{
    $text_stripped = strip_tags($f_text);
    $word_count = str_word_count($text_stripped); // More accurate word count

    // Prevent XSS by escaping URLs
    $f_link1 = htmlspecialchars($f_link1, ENT_QUOTES, 'UTF-8');
    $f_link2 = htmlspecialchars($f_link2, ENT_QUOTES, 'UTF-8');
    $f_link3 = htmlspecialchars($f_link3, ENT_QUOTES, 'UTF-8');

    $link1 = ($with_link) ? "<a href='$f_link1'>$f_keyword1</a>" : "$f_keyword1";
    $link2 = ($with_link) ? "<a href='$f_link2'>$f_keyword2</a>" : "$f_keyword2";
    $link3 = ($with_link) ? "<a href='$f_link3'>$f_keyword3</a>" : "$f_keyword3"; // Fixed missing link

    $f_text = str_ireplace("%LINK1%", $link1, $f_text);

    if ($word_count > 300) {
        $f_text = str_ireplace("%LINK2%", $link2, $f_text);
        $f_text = str_ireplace("%LINK3%", $link3, $f_text);
    } else {
        $f_text = str_ireplace("%LINK2%", $f_keyword2, $f_text);
        $f_text = str_ireplace("%LINK3%", $f_keyword3, $f_text);
    }

    return nl2br($f_text);
}
function zcleantext($text)
{
    // Convert character encoding to fix special character issues
    $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');

    // Fix known character encoding issues
    $replacements = [
        '“' => '"',  // Left double quotation mark
        '”' => '"',  // Right double quotation mark
        '£'   => '£', // Fix Pound symbol encoding
    ];
    $text = str_replace(array_keys($replacements), array_values($replacements), $text);

    // Remove non-ASCII characters
    $text = mb_convert_encoding($text, 'ASCII', 'UTF-8');

    // Reduce multiple spaces to a single space
    $text = preg_replace('/\s+/', ' ', $text);

    return trim($text);
}
$cron_id = microtime_float2() . mt_rand(0, 9999);

$prr_id = '52288';

$sql = "SELECT * FROM articles WHERE status=7 and paused=0 order by id desc LIMIT 5";
$result = $conn->query($sql);

// while ($article_rw = $result->fetch_assoc()) {
//     echo "<br>Article ID: " . $article_rw['id'] . " - Title: " . $article_rw['title'] . "<br>";
// }


while ($article_rw = $result->fetch_assoc()) {
// echo '<pre>';
//    print_r($article_rw);
  
    $article_id = $article_rw['id'];
	$sql33 = "SELECT * FROM articles WHERE id = ?";
	$stmt = $GVars['mysqli']->prepare($sql33);
	$stmt->bind_param("i", $article_id); // "i" means integer
	$stmt->execute();
	$results = $stmt->get_result();
	$article_row = $results->fetch_assoc();
    $stmt->close();
    $id = $article_row['id'];
	
    // $article_id = $article_rw['article_id'];
    $project_id = $article_row['project_id'];
    $keyword1 = $article_row['keyword1'];
    $article_title = $article_row['title'];
    $publish_from_time = $article_row['publish_from_time'];
    $user_id = $article_row['user_id'];
    $id_hash = $article_row['id_hash'];
    $url = $article_row['url1'];
        $type= "publish";

        if(isset($type)) {
            $return_res = array();
            $aid = $id_hash;
            $p_id = $project_id;
            $f_keyword_to_link = trim(zclvar2($keyword1));
        
            $pfromtime  = str_replace(array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'), array('01','02','03','04','05','06','07','08','09','10','11','12'), $publish_from_time);
            $pfromtime .= " 00:00:00";
        
            if ($pfromtime < $GVars['timenow']){
                $pfromtime = date("Y-m-d");
            }
        
            $pfrom = 0;
        
            if($type == 'publish'){
                // echo 'oeoe';
                
					$articleinfo = getArticleInfoByHash($conn, $aid);

                        // echo 'ggg';
                        $rendered_text = rendeFinalText($articleinfo['text'], $articleinfo['keyword1'], $articleinfo['keyword2'], $articleinfo['keyword3'], $articleinfo['url1'], $articleinfo['url2'], $articleinfo['url3']);
                        
                        $rendered_text = strip_tags($rendered_text);
        
        
                        $text_chunks = $text_chunks_orig = get_32_words_from_top_and_bottom_for_google( $rendered_text );
        
                        $i = 0;
                        while (strpos($text_chunks[0], "\"")!==false && $i < 10){
                            $text_chunks[0] = get_random_words_for_google($rendered_text);
                            $i++;
                        }
        
                        $i = 0;
                        while (strpos($text_chunks[1], '"')!==false && $i < 10){
                            $text_chunks[1] = get_random_words_for_google($rendered_text);
                            $i++;
                        }
        
                        $status1 = $status2 = array();
        
                        $original_check_ok1 = 1; $original_check_ok2 = 1;  

                                $new_article_status = 7;
                                
                                $articleId = intval($articleinfo['id']); 
        

                     
											$cronSql = "SELECT * FROM articles WHERE id = ?";
											$stmtnew = $GVars['mysqli']->prepare($cronSql);
											$stmtnew->bind_param("i", $articleId); // "i" means integer
											$stmtnew->execute();
											$resultnew = $stmtnew->get_result();

											while ($rw = $resultnew->fetch_assoc()) {
                //                                 echo 'ee';
                //                                 $row_count = $result->num_rows;
                // echo "Total Articles Found: " . $row_count . "<br>";
                                                // print_r($rw);
                                                $user_has_quota = 0;
                                                $sql2 = "SELECT * FROM users WHERE id = ?";
												$stmt2 = $GVars['mysqli']->prepare($sql2);
												$stmt2->bind_param("i", $rw['user_id']); // "i" means integer
												$stmt2->execute();
												$res2 = $stmt2->get_result();
                                                $stmt2->close();
												while ($row2 = $res2->fetch_assoc()) {
													$user_has_quota = ($row2['quota'] - $row2['n_quota_used_today']);
													$user_has_quota_use_once = $row2['quota_use_once'];
												}
                                            
                                                
                                                
                                                    // Get the count of published articles
													$sql3 = "SELECT COUNT(*) AS published FROM articles_published WHERE user_id = ? AND publish_time >= CURRENT_DATE()";
													$stmt3 = $GVars['mysqli']->prepare($sql3);
													$stmt3->bind_param("i", $rw['user_id']);
													$stmt3->execute();
													$res3 = $stmt3->get_result();
													$row3 = $res3->fetch_assoc();
													$stmt3->close();

													// Update user's quota
													$sqlUpdate = "UPDATE users SET n_quota_used_today = n_quota_used_today + 1 WHERE id = ?";
													$stmtUpdate = $GVars['mysqli']->prepare($sqlUpdate);
													$stmtUpdate->bind_param("i", $rw['user_id']);
													$stmtUpdate->execute();
													$stmtUpdate->close();
                                                
													// Get site info for publishing
													$publish_site_info = get_site_info_for_publishing($rw['user_id'], $cron_id, $rw['id']);
                                                    // print_r($publish_site_info);
                                                    $sql3 = "UPDATE articles SET status = 9 WHERE id = ?";
													$stmt2 = $GVars['mysqli']->prepare($sql3);
													$stmt2->bind_param("i", $rw['id']);
                                                    
													if (!$stmt2->execute()) {
														mysql_die_action($sql3 . " \n" . $stmt2->error);
													}
                                                    
                                                    if ($GVars['mysqli']->affected_rows > 0) {
                                                        // echo 'ieieiiie'; 
														$with_link = (rand(1, 100) > 2);
														
														$text_body = render_final_text($rw['text'], $rw['keyword1'], $rw['keyword2'], 
																					   $rw['keyword3'], $rw['url1'], $rw['url2'], $rw['url3'], $with_link);

														$publish_category = [$static_article_categories[$rw['publish_category']]];
														$publish_title = stripslashes(zcleantext($rw['title']));
														$publish_tags = stripslashes(zcleantext($rw['publish_tags']));
														$text_body = stripslashes(zcleantext($text_body));

														$res = $xml_php_vars = false;

														if ((int)$rw['republish'] === 1) {
															// echo 'fasfdfsd';
															$sql = "SELECT s.* FROM `sites` s 
																	LEFT JOIN log_publish lp ON s.id = lp.site_id 
																	WHERE lp.article_id = ? AND s.status2 <= 1 GROUP BY s.id";
																	
															$stmt4 = $GVars['mysqli']->prepare($sql);
															$stmt4->bind_param("i", $rw['id']);
															$stmt4->execute();
															$rs2 = $stmt4->get_result();

															while ($url = $rs2->fetch_assoc()) {
                                                                $sqlcheck = "SELECT url_perm FROM articles WHERE id = ?";
                                                                $stmtcheck = $GVars['mysqli']->prepare($sqlcheck);
                                                                $stmtcheck->bind_param("i", $rw['id']); // "i" means integer
                                                                $stmtcheck->execute();
                                                                $rescheck = $stmtcheck->get_result();
																// echo $url['url'] . "\n";
																// $res = wpRecentPostXMLRPC2($publish_title,
																// 						   correct_xmlrpc_url($url['url']),
																// 						   $url['login'],
																// 						   $url['password']);
                                                                while ($rowcheck = $rescheck->fetch_assoc()) {
                                                                    $res = wpPostXMLRPC2($publish_title, $text_body,
                                                                    correct_xmlrpc_url($publish_site_info['site_url']),
                                                                    $publish_site_info['site_login'],
                                                                    $publish_site_info['site_password'],
                                                                    $publish_category, $publish_tags, "UTF-8");
                                                                    if (is_array($res)) {
                                                                        $xml_php_vars = $res['postid'] ?? false;
                                                                        if ($xml_php_vars) break;
                                                                    }
                                                                }
                                                                $stmtcheck->close();
															}
															$stmt4->close();
														}

														if (!$xml_php_vars) {
															// echo 'rrrr';
                                                            $sqlchecks = "SELECT url_perm FROM articles WHERE id = ?";
                                                            $stmtchecks = $GVars['mysqli']->prepare($sqlchecks);
                                                            $stmtchecks->bind_param("i", $rw['id']); // "i" means integer
                                                            $stmtchecks->execute();
                                                            $reschecks = $stmtchecks->get_result();
                                                            while ($rowchecks = $reschecks->fetch_assoc()) {
                                                                $post_rez = wpPostXMLRPC2($publish_title, $text_body,
                                                                                        correct_xmlrpc_url($publish_site_info['site_url']),
                                                                                        $publish_site_info['site_login'],
                                                                                        $publish_site_info['site_password'],
                                                                                        $publish_category, $publish_tags, "UTF-8");

                                                                $xml_php_vars = xmlrpc_decode($post_rez[0]);
                                                            }

														}

														if ($xml_php_vars > 0) {
                                                            // echo '37373';
                                                            // if(is_int($xml_php_vars)){
                                                                $permalink = XmlRpcGetPermaLink($xml_php_vars,
                                                                                                $publish_site_info['site_login'],
                                                                                                $publish_site_info['site_password'],
                                                                                                correct_xmlrpc_url($publish_site_info['site_url']));

                                                                $sql5 = "UPDATE articles SET 
                                                                            status = 10, 
                                                                            publish_time = NOW(), 
                                                                            url = ?, 
                                                                            url_perm = ?, 
                                                                            published_site_pr = ? 
                                                                        WHERE id = ?";
                                                                $stmt5 = $GVars['mysqli']->prepare($sql5);
                                                                $url = $publish_site_info['site_url'] . "?p=" . $xml_php_vars;
                                                                $stmt5->bind_param("ssii", $url, $permalink, $publish_site_info['site_pagerank'], $rw['id']);
                                                                $stmt5->execute();
                                                                $stmt5->close();
                                                            // }
														} else {
                                                            // echo 'qwqwqwqwqwqw';
															$error_time = date("Y-m-d H:i:s");
															$xml_error_string = $post_rez[1] ?? $publish_site_info['site_url'];

															$sql6 = "INSERT INTO log_publish (cr_time, cron_id, article_id, site_id, errors, post_rez) 
																	 VALUES (?, ?, ?, ?, 1, ?)";
															$stmt6 = $GVars['mysqli']->prepare($sql6);
															$stmt6->bind_param("siiss", $error_time, $cron_id, $rw['id'], $publish_site_info['site_id'], $xml_error_string);
															$stmt6->execute();
															$stmt6->close();

                                                            $sql309 = "UPDATE articles SET status = 7 WHERE id = ?";
                                                            $stmt266 = $GVars['mysqli']->prepare($sql309);
                                                            $stmt266->bind_param("i", $rw['id']);
                                                            $stmt266->execute();
                                                            $stmt266->close();
														}
													}
                                            }
                                            $stmtnew->close();
            }
        
        }

echo'success';		
}

   



$conn->close();